Ghidra is a software reverse engineering (SRE) framework
Print symbol namespace paths in context
caheckmanf7a8e264aa69
diff --git a/Ghidra/Features/Decompiler/src/decompile/cpp/database.cc b/Ghidra/Features/Decompiler/src/decompile/cpp/database.ccindex 4f1cb2c140..2d42613a5c 100644--- a/Ghidra/Features/Decompiler/src/decompile/cpp/database.cc+++ b/Ghidra/Features/Decompiler/src/decompile/cpp/database.cc@@ -295,18 +295,32 @@ int4 Symbol::getMapEntryPosition(const SymbolEntry *entry) constreturn -1;}-/// A value of 0 means the base Symbol name is visible and not overridden in the given use scope.+/// For a given context scope where \b this Symbol is used, determine how many elements of+/// the full namespace path need to be printed to correctly distinguish it.+/// A value of 0 means the base symbol name is visible and not overridden in the context scope./// A value of 1 means the base name may be overridden, but the parent scope name is not.-/// The minimual number of names that distinguishes \b this Symbol uniquely within the+/// The minimal number of names that distinguishes the symbol name uniquely within the/// use scope is returned.-/// \param useScope is the given scope where \b this Symbol is being used-/// \return the number of (extra) names needed to distinguish \b this Symbol+/// \param useScope is the given scope where the symbol is being used+/// \return the number of (extra) names needed to distinguish the symbolint4 Symbol::getResolutionDepth(const Scope *useScope) const{if (scope == useScope) return 0; // Symbol is in scope where it is used+ if (useScope == (const Scope *)0) { // Treat null useScope as resolving the full path+ const Scope *point = scope;+ int4 count = 0;+ while(point != (const Scope *)0) {+ count += 1;+ point = point->getParent();+ }+ return count-1; // Don't print global scope+ }+ if (depthScope == useScope)+ return depthResolution;+ depthScope = useScope;const Scope *distinguishScope = scope->findDistinguishingScope(useScope);- int4 depth = 0;+ depthResolution = 0;string distinguishName;const Scope *terminatingScope;if (distinguishScope == (const Scope *)0) { // Symbol scope is ancestor of use scope@@ -317,15 +331,15 @@ int4 Symbol::getResolutionDepth(const Scope *useScope) constdistinguishName = distinguishScope->getName();const Scope *currentScope = scope;while(currentScope != distinguishScope) { // For any scope up to the distinguishing scope- depth += 1; // Print its name+ depthResolution += 1; // Print its namecurrentScope = currentScope->getParent();}- depth += 1; // Also print the distinguishing scope name+ depthResolution += 1; // Also print the distinguishing scope nameterminatingScope = distinguishScope->getParent();}if (useScope->isNameUsed(distinguishName,terminatingScope))- depth += 1; // Name was overridden, we need one more distinguishing name- return depth;+ depthResolution += 1; // Name was overridden, we need one more distinguishing name+ return depthResolution;}/// \param s is the output stream@@ -564,7 +578,7 @@ Funcdata *FunctionSymbol::getFunction(void){if (fd != (Funcdata *)0) return fd;SymbolEntry *entry = getFirstWholeMap();- fd = new Funcdata(name,scope,entry->getAddr());+ fd = new Funcdata(name,scope,entry->getAddr(),this);return fd;}@@ -586,7 +600,7 @@ void FunctionSymbol::restoreXml(const Element *el){if (el->getName() == "function") {- fd = new Funcdata("",scope,Address());+ fd = new Funcdata("",scope,Address(),this);symbolId = fd->restoreXml(el);name = fd->getName();if (consumeSize < fd->getSize()) {@@ -1377,20 +1391,19 @@ void Scope::getNameSegments(vector<string> &vec) const}/// Put the parent scopes of \b this into an array in order, starting with the global scope.-/// This scope itself will not be in the array./// \param vec is storage for the array of scopes-void Scope::getScopePath(vector<Scope *> &vec) const+void Scope::getScopePath(vector<const Scope *> &vec) const{int4 count = 0;- Scope *cur = parent;- while(cur != (Scope *)0) { // Count number of elements in path+ const Scope *cur = this;+ while(cur != (const Scope *)0) { // Count number of elements in pathcount += 1;cur = cur->parent;}vec.resize(count);- cur = parent;- while(cur != (Scope *)0) {+ cur = this;+ while(cur != (const Scope *)0) {count -= 1;vec[count] = cur;cur = cur->parent;@@ -1407,7 +1420,7 @@ bool Scope::isNameUsed(const string &nm,const Scope *op2) const{const Scope *currentScope = this;while(currentScope != op2) {- if (currentScope->isNameUsed(name))+ if (currentScope->isNameUsed(nm))return true;currentScope = currentScope->parent;}@@ -1422,12 +1435,12 @@ bool Scope::isNameUsed(const string &nm,const Scope *op2) constconst Scope *Scope::findDistinguishingScope(const Scope *op2) const{- if (this == op2) return (Scope *)0; // Quickly check most common cases+ if (this == op2) return (const Scope *)0; // Quickly check most common casesif (parent == op2) return this;- if (op2->parent == this) return op2;+ if (op2->parent == this) return (const Scope *)0;if (parent == op2->parent) return this;- vector<Scope *> thisPath;- vector<Scope *> op2Path;+ vector<const Scope *> thisPath;+ vector<const Scope *> op2Path;getScopePath(thisPath);op2->getScopePath(op2Path);int4 min = thisPath.size();@@ -1440,7 +1453,7 @@ const Scope *Scope::findDistinguishingScope(const Scope *op2) constif (min < thisPath.size())return thisPath[min]; // thisPath matches op2Path but is longerif (min < op2Path.size())- return (Scope *)0; // op2Path matches thisPath but is longer+ return (const Scope *)0; // op2Path matches thisPath but is longerreturn this; // ancestor paths are identical (only base scopes differ)}@@ -1453,7 +1466,7 @@ Symbol *Scope::addSymbol(const string &name,Datatype *ct){Symbol *sym;- sym = new Symbol(this,name,ct);+ sym = new Symbol(owner,name,ct);addSymbolInternal(sym); // Let this scope lay claim to the new objectreturn sym;}@@ -1474,7 +1487,7 @@ SymbolEntry *Scope::addSymbol(const string &name,Datatype *ct,{Symbol *sym;- sym = new Symbol(this,name,ct);+ sym = new Symbol(owner,name,ct);addSymbolInternal(sym);return addMapPoint(sym,addr,usepoint);}@@ -1509,19 +1522,19 @@ Symbol *Scope::addMapSym(const Element *el)Symbol *sym;const string &symname( subel->getName() );if (symname == "symbol")- sym = new Symbol(this);+ sym = new Symbol(owner);else if (symname == "dynsymbol")- sym = new Symbol(this);+ sym = new Symbol(owner);else if (symname == "equatesymbol")- sym = new EquateSymbol(this);+ sym = new EquateSymbol(owner);else if (symname == "function")- sym = new FunctionSymbol(this,glb->min_funcsymbol_size);+ sym = new FunctionSymbol(owner,glb->min_funcsymbol_size);else if (symname == "functionshell")- sym = new FunctionSymbol(this,glb->min_funcsymbol_size);+ sym = new FunctionSymbol(owner,glb->min_funcsymbol_size);else if (symname == "labelsym")- sym = new LabSymbol(this);+ sym = new LabSymbol(owner);else if (symname == "externrefsymbol")- sym = new ExternRefSymbol(this);+ sym = new ExternRefSymbol(owner);elsethrow LowlevelError("Unknown symbol type: "+symname);try { // Protect against duplicate scope errors@@ -1563,7 +1576,7 @@ FunctionSymbol *Scope::addFunction(const Address &addr,const string &nm)errmsg += " overlaps object: "+overlap->getSymbol()->getName();glb->printMessage(errmsg);}- sym = new FunctionSymbol(this,nm,glb->min_funcsymbol_size);+ sym = new FunctionSymbol(owner,nm,glb->min_funcsymbol_size);addSymbolInternal(sym);// Map symbol to base address of function// there is no limit on the applicability of this map within scope@@ -1584,7 +1597,7 @@ ExternRefSymbol *Scope::addExternalRef(const Address &addr,const Address &refadd{ExternRefSymbol *sym;- sym = new ExternRefSymbol(this,refaddr,nm);+ sym = new ExternRefSymbol(owner,refaddr,nm);addSymbolInternal(sym);// Map symbol to given address// there is no limit on applicability of this map within scope@@ -1612,7 +1625,7 @@ LabSymbol *Scope::addCodeLabel(const Address &addr,const string &nm)errmsg += " overlaps object: "+overlap->getSymbol()->getName();glb->printMessage(errmsg);}- sym = new LabSymbol(this,nm);+ sym = new LabSymbol(owner,nm);addSymbolInternal(sym);addMapPoint(sym,addr,Address());return sym;@@ -1632,7 +1645,7 @@ Symbol *Scope::addDynamicSymbol(const string &nm,Datatype *ct,const Address &cad{Symbol *sym;- sym = new Symbol(this,nm,ct);+ sym = new Symbol(owner,nm,ct);addSymbolInternal(sym);RangeList rnglist;if (!caddr.isInvalid())@@ -1832,12 +1845,17 @@ list<SymbolEntry>::iterator ScopeInternal::endDynamic(void)/// \param nm is the name of the Scope/// \param g is the Architecture it belongs toScopeInternal::ScopeInternal(const string &nm,Architecture *g)- : Scope(nm,g)+ : Scope(nm,g,this)+{+ nextUniqueId = 0;+ maptable.resize(g->numSpaces(),(EntryMap *)0);+}++ScopeInternal::ScopeInternal(const string &nm,Architecture *g, Scope *own)+ : Scope(nm,g,own){nextUniqueId = 0;- int4 numspaces = g->numSpaces();- for(int4 i=0;i<numspaces;++i)- maptable.push_back((EntryMap *)0);+ maptable.resize(g->numSpaces(),(EntryMap *)0);}ScopeInternal::~ScopeInternal(void)diff --git a/Ghidra/Features/Decompiler/src/decompile/cpp/database.hh b/Ghidra/Features/Decompiler/src/decompile/cpp/database.hhindex fb524ac6e9..4ec0aacc5f 100644--- a/Ghidra/Features/Decompiler/src/decompile/cpp/database.hh+++ b/Ghidra/Features/Decompiler/src/decompile/cpp/database.hh@@ -167,6 +167,8 @@ protected:uint2 catindex; ///< Index within categoryuint8 symbolId; ///< Unique id, 0=unassignedvector<list<SymbolEntry>::iterator> mapentry; ///< List of storage locations labeled with \b this Symbol+ mutable const Scope *depthScope; ///< Scope associated with current depth resolution+ mutable int4 depthResolution; ///< Number of namespace elements required to resolve symbol in current scopeuint4 wholeCount; ///< Number of SymbolEntries that map to the whole Symbolvirtual ~Symbol(void) {} ///< Destructorvoid setDisplayFormat(uint4 val); ///< Set the display format for \b this Symbol@@ -183,13 +185,9 @@ public:isolate = 16, ///< Symbol should not speculatively merge automaticallymerge_problems = 32 ///< Set if some SymbolEntrys did not get merged};- /// \brief Construct given a name and data-type- Symbol(Scope *sc,const string &nm,Datatype *ct)- { scope=sc; name=nm; nameDedup=0; type=ct; flags=0; dispflags=0; category=-1; symbolId=0; wholeCount=0; }-- /// \brief Construct for use with restoreXml()- Symbol(Scope *sc) { scope=sc; nameDedup=0; flags=0; dispflags=0; category=-1; symbolId = 0; wholeCount=0; }+ Symbol(Scope *sc,const string &nm,Datatype *ct); ///< Construct given a name and data-type+ Symbol(Scope *sc); ///< Construct for use with restoreXml()const string &getName(void) const { return name; } ///< Get the local name of the symbolDatatype *getType(void) const { return type; } ///< Get the data-typeuint8 getId(void) const { return symbolId; } ///< Get a unique id for the symbol@@ -214,7 +212,7 @@ public:int4 numEntries(void) const { return mapentry.size(); } ///< Return the number of SymbolEntrysSymbolEntry *getMapEntry(int4 i) const { return &(*mapentry[i]); } ///< Return the i-th SymbolEntry for \b this Symbolint4 getMapEntryPosition(const SymbolEntry *entry) const; ///< Position of given SymbolEntry within \b this multi-entry Symbol- int4 getResolutionDepth(const Scope *useScope) const; ///< Get the number of scope names to print to resolve symbol in given context+ int4 getResolutionDepth(const Scope *useScope) const; ///< Get number of scope names needed to resolve \b this symbolvoid saveXmlHeader(ostream &s) const; ///< Save basic Symbol properties as XML attributesvoid restoreXmlHeader(const Element *el); ///< Restore basic Symbol properties from XMLvoid saveXmlBody(ostream &s) const; ///< Save details of the Symbol to XML@@ -415,6 +413,7 @@ class Scope {friend class ScopeCompare;RangeList rangetree; ///< Range of data addresses \e owned by \b this scopeScope *parent; ///< The parent scope+ Scope *owner; ///< Scope using \b this as a cacheScopeMap children; ///< Sorted list of child scopesvoid attachScope(Scope *child); ///< Attach a new child Scope to \b thisvoid detachScope(ScopeMap::iterator iter); ///< Detach a child Scope from \b this@@ -502,8 +501,8 @@ public:void turnOffDebug(void) const { debugon = false; }#endif/// \brief Construct an empty scope, given a name and Architecture- Scope(const string &nm,Architecture *g) {- name = nm; glb = g; parent = (Scope *)0; fd = (Funcdata *)0; uniqueId = 0;+ Scope(const string &nm,Architecture *g,Scope *own) {+ name = nm; glb = g; parent = (Scope *)0; fd = (Funcdata *)0; uniqueId = 0; owner=own;#ifdef OPACTION_DEBUGdebugon = false;#endif@@ -694,7 +693,7 @@ public:bool isSubScope(const Scope *scp) const; ///< Is this a sub-scope of the given Scopestring getFullName(void) const; ///< Get the full name of \b this Scopevoid getNameSegments(vector<string> &vec) const; ///< Get the fullname of \b this in segments- void getScopePath(vector<Scope *> &vec) const; ///< Get the ordered list of parent scopes to \b this+ void getScopePath(vector<const Scope *> &vec) const; ///< Get the ordered list of scopes up to \b thisbool isNameUsed(const string &nm,const Scope *op2) const; ///< Is the given name in use within given scope pathconst Scope *findDistinguishingScope(const Scope *op2) const; ///< Find first ancestor of \b this not shared by given scopeArchitecture *getArch(void) const { return glb; } ///< Get the Architecture associated with \b this@@ -735,6 +734,7 @@ protected:uint8 nextUniqueId; ///< Next available symbol idpublic:ScopeInternal(const string &nm,Architecture *g); ///< Construct the Scope+ ScopeInternal(const string &nm,Architecture *g, Scope *own); ///< Construct as a cachevirtual void clear(void);virtual void categorySanity(void); ///< Make sure Symbol categories are sanevirtual void clearCategory(int4 cat);@@ -870,4 +870,41 @@ public:void restoreXmlScope(const Element *el,Scope *new_scope); ///< Register and fill out a single Scope from XML};+/// \param sc is the scope containing the new symbol+/// \param nm is the local name of the symbol+/// \param ct is the data-type of the symbol+inline Symbol::Symbol(Scope *sc,const string &nm,Datatype *ct)++{+ scope=sc;+ name=nm;+ nameDedup=0;+ type=ct;+ flags=0;+ dispflags=0;+ category=-1;+ catindex = 0;+ symbolId=0;+ wholeCount=0;+ depthScope = (const Scope *)0;+ depthResolution = 0;+}++/// \param sc is the scope containing the new symbol+inline Symbol::Symbol(Scope *sc)++{+ scope=sc;+ nameDedup=0;+ type = (Datatype *)0;+ flags=0;+ dispflags=0;+ category=-1;+ catindex = 0;+ symbolId = 0;+ wholeCount=0;+ depthScope = (const Scope *)0;+ depthResolution = 0;+}+#endifdiff --git a/Ghidra/Features/Decompiler/src/decompile/cpp/database_ghidra.cc b/Ghidra/Features/Decompiler/src/decompile/cpp/database_ghidra.ccindex 165fd087e3..49257ff216 100644--- a/Ghidra/Features/Decompiler/src/decompile/cpp/database_ghidra.cc+++ b/Ghidra/Features/Decompiler/src/decompile/cpp/database_ghidra.cc@@ -18,10 +18,10 @@/// \param g is the Architecture and connection to the Ghidra clientScopeGhidra::ScopeGhidra(ArchitectureGhidra *g)- : Scope("",g)+ : Scope("",g,this){ghidra = g;- cache = new ScopeInternal("",g);+ cache = new ScopeInternal("",g,this);cacheDirty = false;}diff --git a/Ghidra/Features/Decompiler/src/decompile/cpp/funcdata.cc b/Ghidra/Features/Decompiler/src/decompile/cpp/funcdata.ccindex 87c9f82499..a2390354a9 100644--- a/Ghidra/Features/Decompiler/src/decompile/cpp/funcdata.cc+++ b/Ghidra/Features/Decompiler/src/decompile/cpp/funcdata.cc@@ -20,7 +20,7 @@/// \param scope is Symbol scope associated with the function/// \param addr is the entry address for the function/// \param sz is the number of bytes (of code) in the function body-Funcdata::Funcdata(const string &nm,Scope *scope,const Address &addr,int4 sz)+Funcdata::Funcdata(const string &nm,Scope *scope,const Address &addr,FunctionSymbol *sym,int4 sz): baseaddr(addr),funcp(),vbank(scope->getArch(),@@ -31,6 +31,7 @@ Funcdata::Funcdata(const string &nm,Scope *scope,const Address &addr,int4 sz){ // Initialize high-level properties of// function by giving address and size+ functionSymbol = sym;flags = 0;clean_up_index = 0;high_level_index = 0;diff --git a/Ghidra/Features/Decompiler/src/decompile/cpp/funcdata.hh b/Ghidra/Features/Decompiler/src/decompile/cpp/funcdata.hhindex 71504ec713..ed54dca411 100644--- a/Ghidra/Features/Decompiler/src/decompile/cpp/funcdata.hh+++ b/Ghidra/Features/Decompiler/src/decompile/cpp/funcdata.hh@@ -63,9 +63,10 @@ class Funcdata {uint4 high_level_index; ///< Creation index of first Varnode created after HighVariables are createduint4 cast_phase_index; ///< Creation index of first Varnode created after ActionSetCastsuint4 minLanedSize; ///< Minimum Varnode size to check as LanedRegister+ int4 size; ///< Number of bytes of binary data in function bodyArchitecture *glb; ///< Global configuration data+ FunctionSymbol *functionSymbol; ///< The symbol representing \b this functionstring name; ///< Name of function- int4 size; ///< Number of bytes of binary data in function bodyAddress baseaddr; ///< Starting code address of binary dataFuncProto funcp; ///< Prototype of this functionScopeLocal *localmap; ///< Local variables (symbols in the function scope)@@ -119,12 +120,13 @@ class Funcdata {static PcodeOp *findPrimaryBranch(PcodeOpTree::const_iterator iter,PcodeOpTree::const_iterator enditer,bool findbranch,bool findcall,bool findreturn);public:- Funcdata(const string &nm,Scope *conf,const Address &addr,int4 sz=0); ///< Constructor+ Funcdata(const string &nm,Scope *conf,const Address &addr,FunctionSymbol *sym,int4 sz=0); ///< Constructor~Funcdata(void); ///< Destructorconst string &getName(void) const { return name; } ///< Get the function's local symbol nameconst Address &getAddress(void) const { return baseaddr; } ///< Get the entry point addressint4 getSize(void) const { return size; } ///< Get the function body size in bytes- Architecture *getArch(void) const { return glb; } ///< Get the program/architecture owning the function+ Architecture *getArch(void) const { return glb; } ///< Get the program/architecture owning \b this function+ FunctionSymbol *getSymbol(void) const { return functionSymbol; } ///< Return the symbol associated with \b this functionbool isHighOn(void) const { return ((flags&highlevel_on)!=0); } ///< Are high-level variables assigned to Varnodesbool isProcStarted(void) const { return ((flags&processing_started)!=0); } ///< Has processing of the function startedbool isProcComplete(void) const { return ((flags&processing_complete)!=0); } ///< Is processing of the function completediff --git a/Ghidra/Features/Decompiler/src/decompile/cpp/funcdata_block.cc b/Ghidra/Features/Decompiler/src/decompile/cpp/funcdata_block.ccindex fbcb1e48cc..61c406b489 100644--- a/Ghidra/Features/Decompiler/src/decompile/cpp/funcdata_block.cc+++ b/Ghidra/Features/Decompiler/src/decompile/cpp/funcdata_block.cc@@ -495,7 +495,7 @@ int4 Funcdata::stageJumpTable(JumpTable *jt,PcodeOp *op,FlowInfo *flow)s1 << name << "@@jump@";op->getAddr().printRaw(s1);- Funcdata partial(s1.str(),localmap->getParent(),baseaddr);+ Funcdata partial(s1.str(),localmap->getParent(),baseaddr,(FunctionSymbol *)0);partial.flags |= jumptablerecovery_on; // Mark that this Funcdata object is dedicated to jumptable recoverypartial.truncatedFlow(this,flow);diff --git a/Ghidra/Features/Decompiler/src/decompile/cpp/printc.cc b/Ghidra/Features/Decompiler/src/decompile/cpp/printc.ccindex d916c0f74b..3e35c3d063 100644--- a/Ghidra/Features/Decompiler/src/decompile/cpp/printc.cc+++ b/Ghidra/Features/Decompiler/src/decompile/cpp/printc.cc@@ -38,6 +38,7 @@ OpToken PrintC::binary_plus = { "+", 2, 50, true, OpToken::binary, 1, 0, (OpTokeOpToken PrintC::binary_minus = { "-", 2, 50, false, OpToken::binary, 1, 0, (OpToken *)0 };OpToken PrintC::shift_left = { "<<", 2, 46, false, OpToken::binary, 1, 0, (OpToken *)0 };OpToken PrintC::shift_right = { ">>", 2, 46, false, OpToken::binary, 1, 0, (OpToken *)0 };+OpToken PrintC::shift_sright = { ">>", 2, 46, false, OpToken::binary, 1, 0, (OpToken *)0 };OpToken PrintC::less_than = { "<", 2, 42, false, OpToken::binary, 1, 0, (OpToken *)0 };OpToken PrintC::less_equal = { "<=", 2, 42, false, OpToken::binary, 1, 0, (OpToken *)0 };OpToken PrintC::greater_than = { ">", 2, 42, false, OpToken::binary, 1, 0, (OpToken *)0 };@@ -167,6 +168,48 @@ void PrintC::pushPrototypeInputs(const FuncProto *proto)}}+/// Calculate what elements of a given symbol's namespace path are necessary to distinguish+/// it within the current scope. Then print these elements.+/// \param symbol is the given symbol+void PrintC::pushSymbolScope(const Symbol *symbol)++{+ int4 scopedepth = symbol->getResolutionDepth(curscope);+ if (scopedepth != 0) {+ vector<const Scope *> scopeList;+ const Scope *point = symbol->getScope();+ for(int4 i=0;i<scopedepth;++i) {+ scopeList.push_back(point);+ point = point->getParent();+ pushOp(&scope, (PcodeOp *)0);+ }+ for(int4 i=scopedepth-1;i>=0;--i) {+ pushAtom(Atom(scopeList[i]->getName(),syntax,EmitXml::global_color,(PcodeOp *)0,(Varnode *)0));+ }+ }+}++/// Emit the elements of the given function's namespace path that distinguish it within+/// the current scope.+/// \param fd is the given function+void PrintC::emitSymbolScope(const Symbol *symbol)++{+ int4 scopedepth = symbol->getResolutionDepth(curscope);+ if (scopedepth != 0) {+ vector<const Scope *> scopeList;+ const Scope *point = symbol->getScope();+ for(int4 i=0;i<scopedepth;++i) {+ scopeList.push_back(point);+ point = point->getParent();+ }+ for(int4 i=scopedepth-1;i>=0;--i) {+ emit->print(scopeList[i]->getName().c_str(), EmitXml::global_color);+ emit->print(scope.print, EmitXml::no_color);+ }+ }+}+/// Store off array sizes for printing after the identifier/// \param ct is the data-type to push/// \param noident is \b true if an identifier will not be pushed as part of the declaration@@ -453,8 +496,12 @@ void PrintC::opCall(const PcodeOp *op)string name = genericFunctionName(fc->getEntryAddress());pushAtom(Atom(name,functoken,EmitXml::funcname_color,op,(const Funcdata *)0));}- else+ else {+ Funcdata *fd = fc->getFuncdata();+ if (fd != (Funcdata *)0)+ pushSymbolScope(fd->getSymbol());pushAtom(Atom(fc->getName(),functoken,EmitXml::funcname_color,op,(const Funcdata *)0));+ }}else {clear();@@ -718,8 +765,10 @@ void PrintC::opPtrsub(const PcodeOp *op)int4 newoff;const TypeField *fld = ((TypeStruct *)ct)->getField((int4)suboff,0,&newoff);if (fld == (const TypeField *)0) {- if (ct->getSize() <= suboff)+ if (ct->getSize() <= suboff) {+ clear();throw LowlevelError("PTRSUB out of bounds into struct");+ }// Try to match the Ghidra's default field name from DataTypeComponent.getDefaultFieldNameostringstream s;s << "field_0x" << hex << suboff;@@ -1577,7 +1626,7 @@ void PrintC::pushSymbol(const Symbol *sym,const Varnode *vn,const PcodeOp *op)tokenColor = EmitXml::param_color;elsetokenColor = EmitXml::var_color;- // FIXME: resolve scopes+ pushSymbolScope(sym);if (sym->hasMergeProblems() && vn != (Varnode *)0) {HighVariable *high = vn->getHigh();if (high->isUnmerged()) {@@ -1934,6 +1983,8 @@ void PrintC::resetDefaults(void)void PrintC::adjustTypeOperators(void){+ scope.print = "::";+ shift_right.print = ">>";TypeOp::selectJavaOperators(glb->inst,false);}@@ -2179,12 +2230,14 @@ void PrintC::emitFunctionDeclaration(const Funcdata *fd)}}int4 id1 = emit->openGroup();+ emitSymbolScope(fd->getSymbol());emit->tagFuncName(fd->getName().c_str(),EmitXml::funcname_color,fd,(PcodeOp *)0);emit->spaces(function_call.spacing,function_call.bump);int4 id2 = emit->openParen('(');emit->spaces(0,function_call.bump);+ pushScope(fd->getScopeLocal()); // Enter the function's scope for parametersemitPrototypeInputs(proto);emit->closeParen(')',id2);emit->closeGroup(id1);@@ -2241,7 +2294,7 @@ void PrintC::docFunction(const Funcdata *fd)int4 id1 = emit->beginFunction(fd);emitCommentFuncHeader(fd);emit->tagLine();- emitFunctionDeclaration(fd);+ emitFunctionDeclaration(fd); // Causes us to enter function's scopeemit->tagLine();emit->tagLine();int4 id = emit->startIndent();@@ -2251,6 +2304,7 @@ void PrintC::docFunction(const Funcdata *fd)emitBlockGraph(&fd->getBasicBlocks());elseemitBlockGraph(&fd->getStructure());+ popScope(); // Exit function's scopeemit->stopIndent(id);emit->tagLine();emit->print("}");diff --git a/Ghidra/Features/Decompiler/src/decompile/cpp/printc.hh b/Ghidra/Features/Decompiler/src/decompile/cpp/printc.hhindex 5426790072..431cbdedf7 100644--- a/Ghidra/Features/Decompiler/src/decompile/cpp/printc.hh+++ b/Ghidra/Features/Decompiler/src/decompile/cpp/printc.hh@@ -82,6 +82,7 @@ protected:static OpToken binary_minus; ///< The \e binary \e subtraction operatorstatic OpToken shift_left; ///< The \e left \e shift operatorstatic OpToken shift_right; ///< The \e right \e shift operator+ static OpToken shift_sright; ///< The signed \e right \e shift operatorstatic OpToken less_than; ///< The \e less \e than operatorstatic OpToken less_equal; ///< The \e less \e than \e or \e equal operatorstatic OpToken greater_than; ///< The \e greater \e than operator@@ -124,6 +125,8 @@ protected:// Routines that are specific to C/C++void buildTypeStack(const Datatype *ct,vector<const Datatype *> &typestack); ///< Prepare to push components of a data-type declarationvoid pushPrototypeInputs(const FuncProto *proto); ///< Push input parameters+ void pushSymbolScope(const Symbol *symbol); ///< Push tokens resolving a symbol's scope+ void emitSymbolScope(const Symbol *symbol); ///< Emit tokens resolving a symbol's scopevirtual void pushTypeStart(const Datatype *ct,bool noident); ///< Push part of a data-type declaration onto the RPN stack, up to the identifiervirtual void pushTypeEnd(const Datatype *ct); ///< Push the tail ends of a data-type declaration onto the RPN stackvoid pushBoolConstant(uintb val,const TypeBase *ct,const Varnode *vn,@@ -251,7 +254,7 @@ public:virtual void opIntOr(const PcodeOp *op) { opBinary(&bitwise_or,op); }virtual void opIntLeft(const PcodeOp *op) { opBinary(&shift_left,op); }virtual void opIntRight(const PcodeOp *op) { opBinary(&shift_right,op); }- virtual void opIntSright(const PcodeOp *op) { opBinary(&shift_right,op); }+ virtual void opIntSright(const PcodeOp *op) { opBinary(&shift_sright,op); }virtual void opIntMult(const PcodeOp *op) { opBinary(&multiply,op); }virtual void opIntDiv(const PcodeOp *op) { opBinary(÷,op); }virtual void opIntSdiv(const PcodeOp *op) { opBinary(÷,op); }diff --git a/Ghidra/Features/Decompiler/src/decompile/cpp/printjava.cc b/Ghidra/Features/Decompiler/src/decompile/cpp/printjava.ccindex c6cf5d5f25..eb8a91ae02 100644--- a/Ghidra/Features/Decompiler/src/decompile/cpp/printjava.cc+++ b/Ghidra/Features/Decompiler/src/decompile/cpp/printjava.cc@@ -99,6 +99,8 @@ void PrintJava::pushTypeEnd(const Datatype *ct)void PrintJava::adjustTypeOperators(void){+ scope.print = ".";+ shift_right.print = ">>>";TypeOp::selectJavaOperators(glb->inst,true);}diff --git a/Ghidra/Features/Decompiler/src/decompile/cpp/printlanguage.cc b/Ghidra/Features/Decompiler/src/decompile/cpp/printlanguage.ccindex 2d11add68c..b486b8386d 100644--- a/Ghidra/Features/Decompiler/src/decompile/cpp/printlanguage.cc+++ b/Ghidra/Features/Decompiler/src/decompile/cpp/printlanguage.cc@@ -105,6 +105,16 @@ void PrintLanguage::setCommentDelimeter(const string &start,const string &stop,b}}+void PrintLanguage::popScope(void)++{+ scopestack.pop_back();+ if (scopestack.empty())+ curscope = (Scope *)0;+ else+ curscope = scopestack.back();+}+/// This generally will recursively push an entire expression onto the RPN stack,/// up to Varnode objects marked as \e explicit, and will decide token order/// and parenthesis placement. As the ordering gets resolved,@@ -658,10 +668,8 @@ void PrintLanguage::clear(void)mods = modstack.front();modstack.clear();}- if (!scopestack.empty()) {- curscope = scopestack.front();- scopestack.clear();- }+ scopestack.clear();+ curscope = (const Scope *)0;revpol.clear();pending = 0;diff --git a/Ghidra/Features/Decompiler/src/decompile/cpp/printlanguage.hh b/Ghidra/Features/Decompiler/src/decompile/cpp/printlanguage.hhindex 933b266638..f2bad7f287 100644--- a/Ghidra/Features/Decompiler/src/decompile/cpp/printlanguage.hh+++ b/Ghidra/Features/Decompiler/src/decompile/cpp/printlanguage.hh@@ -230,8 +230,7 @@ public:private:string name; ///< The name of the high-level languagevector<uint4> modstack; ///< Printing modification stack- vector<Scope *> scopestack; ///< The symbol scope stack- Scope *curscope; ///< The current symbol scope+ vector<const Scope *> scopestack; ///< The symbol scope stackvector<ReversePolish> revpol; ///< The Reverse Polish Notation (RPN) token stackvector<NodePending> nodepend; ///< Data-flow nodes waiting to be pushed onto the RPN stackint4 pending; ///< Number of data-flow nodes waiting to be pushed@@ -240,6 +239,7 @@ private:string commentend; ///< Delimiter characters (if any) for the end of a commentprotected:Architecture *glb; ///< The Architecture owning the language emitter+ const Scope *curscope; ///< The current symbol scopeCastStrategy *castStrategy; ///< The strategy for emitting explicit \e case operationsEmitXml *emit; ///< The low-level token emitteruint4 mods; ///< Currently active printing modifications@@ -251,8 +251,8 @@ protected:#endif// Routines that are probably consistent across languagesbool isSet(uint4 m) const { return ((mods & m)!=0); } ///< Is the given printing modification active- void pushScope(Scope *sc) { scopestack.push_back(sc); curscope = sc; } ///< Push a new symbol scope- void popScope(void) { scopestack.pop_back(); curscope = scopestack.back(); } ///< Pop to the previous symbol scope+ void pushScope(const Scope *sc) { scopestack.push_back(sc); curscope = sc; } ///< Push a new symbol scope+ void popScope(void); ///< Pop to the previous symbol scopevoid pushMod(void) { modstack.push_back(mods); } ///< Push current printing modifications to the stackvoid popMod(void) { mods = modstack.back(); modstack.pop_back(); } ///< Pop to the previous printing modificationsvoid setMod(uint4 m) { mods |= m; } ///< Activate the given printing modification@@ -405,7 +405,6 @@ public:CastStrategy *getCastStrategy(void) const { return castStrategy; } ///< Get the casting strategy for the languageostream *getOutputStream(void) const { return emit->getOutputStream(); } ///< Get the output stream being emitted tovoid setOutputStream(ostream *t) { emit->setOutputStream(t); } ///< Set the output stream to emit to- void setScope(Scope *sc) { curscope = sc; } ///< Set the current Symbol scopevoid setMaxLineSize(int4 mls) { emit->setMaxLineSize(mls); } ///< Set the maximum number of characters per linevoid setIndentIncrement(int4 inc) { emit->setIndentIncrement(inc); } ///< Set the number of characters to indent per level of code nestingvoid setLineCommentIndent(int4 val); ///< Set the number of characters to indent comment lines