Ghidra is a software reverse engineering (SRE) framework
GP-7080 Nearby symbol search
caheckman792e529e7ab3
diff --git a/Ghidra/Features/Decompiler/certification.manifest b/Ghidra/Features/Decompiler/certification.manifestindex ee6bc9ca79..899dd6ef50 100644--- a/Ghidra/Features/Decompiler/certification.manifest+++ b/Ghidra/Features/Decompiler/certification.manifest@@ -83,6 +83,7 @@ src/decompile/datatests/retstruct.xml||GHIDRA||||END|src/decompile/datatests/revisit.xml||GHIDRA||||END|src/decompile/datatests/sbyte.xml||GHIDRA||||END|src/decompile/datatests/skipnext2.xml||GHIDRA||||END|+src/decompile/datatests/stackcorner.xml||GHIDRA||||END|src/decompile/datatests/stackreturn.xml||GHIDRA||||END|src/decompile/datatests/stackspill.xml||GHIDRA||||END|src/decompile/datatests/stackstring.xml||GHIDRA||||END|diff --git a/Ghidra/Features/Decompiler/src/decompile/cpp/address.cc b/Ghidra/Features/Decompiler/src/decompile/cpp/address.ccindex 3a3d33a2a0..1d3136926f 100644--- a/Ghidra/Features/Decompiler/src/decompile/cpp/address.cc+++ b/Ghidra/Features/Decompiler/src/decompile/cpp/address.cc@@ -481,7 +481,10 @@ bool RangeList::inRange(const Address &addr,int4 size) const// if (iter == tree.end()) // iter can't be end if non-empty// return false;if ((*iter).spc != addr.getSpace()) return false;- if ((*iter).last >= addr.getOffset()+size-1)+ uintb end = addr.getOffset()+size-1;+ if (end < addr.getOffset())+ return false; // size causes overflow+ if ((*iter).last >= end)return true;return false;}@@ -504,6 +507,37 @@ const Range *RangeList::getRange(AddrSpace *spaceid,uintb offset) constreturn (const Range *)0;}+/// If \b this contains no Range in the given address space, null is returned.+/// If a range contains \b offset, it is returned.+/// Otherwise the range with a boundary point closest to \b offset is returned.+/// If two ranges are equidistant to \b offset, the earlier Range is returned.+/// \param spaceid is the given address space+/// \param offset is the given offset+/// \return the nearest Range in the same address space or null+const Range *RangeList::getNearestRange(AddrSpace *spaceid,uintb offset) const++{+ if (tree.empty()) return (const Range *)0;++ set<Range>::const_iterator iter = tree.upper_bound(Range(spaceid,offset,offset));+ const Range *after = (const Range *)0;+ if (iter != tree.end()) {+ after = &(*iter);+ if (after->spc != spaceid)+ after = (const Range *)0;+ }++ if (iter == tree.begin()) return after; // nothing earlier, after is closest+ --iter;+ const Range *before = &(*iter);+ if (before->spc != spaceid) return after;+ if (after == (const Range *)0) return before;+ if (before->last >= offset) return before; // Range contains offset, it is closest+ uint8 distafter = after->first - offset;+ uint8 distbefore = offset - before->last;+ return (distafter < distbefore) ? after : before;+}+/// Return the size of the biggest contiguous sequence of addresses in/// \b this RangeList which contain the given address/// \param addr is the given addressdiff --git a/Ghidra/Features/Decompiler/src/decompile/cpp/address.hh b/Ghidra/Features/Decompiler/src/decompile/cpp/address.hhindex 6fdc9a5478..8836e913c1 100644--- a/Ghidra/Features/Decompiler/src/decompile/cpp/address.hh+++ b/Ghidra/Features/Decompiler/src/decompile/cpp/address.hh@@ -244,6 +244,7 @@ public:const Range *getLastRange(void) const; ///< Get the last Rangeconst Range *getLastSignedRange(AddrSpace *spaceid) const; ///< Get the last Range viewing offsets as signedconst Range *getRange(AddrSpace *spaceid,uintb offset) const; ///< Get Range containing the given byte+ const Range *getNearestRange(AddrSpace *spaceid,uintb offset) const; ///< Get the nearest Range to the given bytevoid insertRange(AddrSpace *spc,uintb first,uintb last); ///< Insert a range of addressesvoid removeRange(AddrSpace *spc,uintb first,uintb last); ///< Remove a range of addressesvoid merge(const RangeList &op2); ///< Merge another RangeList into \b thisdiff --git a/Ghidra/Features/Decompiler/src/decompile/cpp/coreaction.cc b/Ghidra/Features/Decompiler/src/decompile/cpp/coreaction.ccindex 2a4af3462b..15648f9663 100644--- a/Ghidra/Features/Decompiler/src/decompile/cpp/coreaction.cc+++ b/Ghidra/Features/Decompiler/src/decompile/cpp/coreaction.cc@@ -4916,30 +4916,190 @@ int4 ActionPrototypeTypes::apply(Funcdata &data)return 0;}+/// Sort by address, then by data-type size, then by data-type ordering.+/// \param op2 is the reference to compare with+/// \return \b true if \b this should be ordered before \b op2+bool ActionInputPrototype::InputRef::operator<(const InputRef &op2) const++{+ if (addr != op2.addr)+ return (addr < op2.addr);+ if (dataType == op2.dataType)+ return false;+ if (dataType->getSize() != op2.dataType->getSize())+ return (op2.dataType->getSize() < dataType->getSize()); // Bigger data-types first+ return (dataType->typeOrder(*op2.dataType) <= 0);+}++/// Remove the later reference of any pairs that overlap.+/// \param refs is the list of references+void ActionInputPrototype::InputRef::dedup(list<InputRef> &refs)++{+ list<InputRef>::const_iterator iter=refs.begin();+ if (iter == refs.end()) return;+ Address lastAddr = (*iter).addr;+ int4 size = (*iter).dataType->getSize();+ ++iter;+ while(iter != refs.end()) {+ if ((*iter).addr.overlap(0, lastAddr, size) >= 0)+ iter = refs.erase(iter);+ else {+ lastAddr = (*iter).addr;+ size = (*iter).dataType->getSize();+ ++iter;+ }+ }+}++/// \brief Gather references into the region of the stack reserved for parameters+///+/// Look for PTRSUBs and PTRADDs off of the \e spacebase pointer for the local scope.+/// Calculate the base address being referenced, and if it is a possible parameter,+/// store the address and data-type associated with the reference. Sort and deup the references.+/// \param refs will hold any collected parameter references+/// \param data is the function+void ActionInputPrototype::gatherParamSpacebaseRefs(list<InputRef> &refs,Funcdata &data)++{+ AddrSpace *spcid = data.getScopeLocal()->getSpaceId();+ Varnode *spcvn = data.findSpacebaseInput(spcid);+ if (spcvn == (Varnode *)0) return;+ Datatype *spctype = spcvn->getType();+ if (spctype->getMetatype() != TYPE_PTR) return;+ spctype = ((TypePointer *)spctype)->getPtrTo();+ if (spctype->getMetatype() != TYPE_SPACEBASE) return;+ TypeSpacebase *sbtype = (TypeSpacebase *)spctype;+ const RangeList ¶mRange(data.getFuncProto().getParamRange());+ list<PcodeOp *>::const_iterator iter;+ Address addr;+ Datatype *dt;++ for(iter=spcvn->beginDescend();iter!=spcvn->endDescend();++iter) {+ PcodeOp *op = *iter;+ Varnode *vn;+ OpCode opc = op->code();+ if (opc == CPUI_PTRSUB) {+ vn = op->getIn(1);+ addr = sbtype->getAddress(vn->getOffset(),vn->getSize(),op->getAddr());+ }+ else if (opc == CPUI_PTRADD) {+ vn = op->getIn(1);+ if (vn->isConstant()) {+ uintb off = vn->getOffset() * op->getIn(2)->getOffset();+ addr = sbtype->getAddress(off,vn->getSize(),op->getAddr());+ }+ else+ continue;+ }+ else+ continue;+ if (paramRange.inRange(addr, 1)) {+ dt = op->getOut()->getTypeDefFacing();+ if (dt->getMetatype() == TYPE_PTR) {+ dt = ((TypePointer *)dt)->getPtrTo();+ if (dt->getSize() == 0)+ dt = data.getArch()->types->getBase(1,TYPE_UNKNOWN);+ }+ else+ dt = data.getArch()->types->getBase(1,TYPE_UNKNOWN);+ if (!data.getFuncProto().possibleInputParam(addr, dt->getSize())) {+ VarnodeData vData;+ if (data.getFuncProto().unjustifiedInputParam(addr, dt->getSize(), vData)) {+ if (vData.getAddr() == addr && vData.size > dt->getSize()) {+ // If the address range is unjustified but can be justified by just changing the size (big endian case)+ // Change the data-type to be the justified size+ dt = data.getArch()->types->getBase(vData.size,TYPE_UNKNOWN);+ }+ }+ }+ refs.push_back(InputRef(addr,dt));+ }+ }+ refs.sort();+ InputRef::dedup(refs);+}++/// \brief Add an active parameter trial for any reference that is a possible input and doesn't intersect a Varnode+///+/// \param active is the container accumulating parameter trials+/// \param refs is the list of references+/// \param typeList accumulates a data-type per parameter trial+/// \param data is the function+void ActionInputPrototype::markActiveInputRefs(ParamActive &active,list<InputRef> &refs,vector<Datatype *> &typeList,+ Funcdata &data)++{+ for(list<InputRef>::const_iterator iter=refs.begin();iter!=refs.end();++iter) {+ if (data.hasInputIntersection((*iter).dataType->getSize(), (*iter).addr))+ continue;+ if (!data.getFuncProto().possibleInputParam((*iter).addr, (*iter).dataType->getSize()))+ continue;+ int4 slot = active.getNumTrials();+ active.registerTrial((*iter).addr,(*iter).dataType->getSize());+ typeList.push_back((*iter).dataType);+ ParamTrial &trial(active.getTrial(slot));+ trial.markActive();+ }+}++/// \brief Add a Symbol for any reference that doesn't intersect an existing input Varnode+///+/// \param refs is the list of references+/// \param data is the function+void ActionInputPrototype::addRefOnlySymbols(list<InputRef> &refs,Funcdata &data)++{+ for(list<InputRef>::const_iterator iter=refs.begin();iter!=refs.end();++iter) {+ if (data.getScopeLocal()->findOverlap((*iter).addr, (*iter).dataType->getSize()))+ continue;+ data.getScopeLocal()->addSymbol("", (*iter).dataType, (*iter).addr, Address());+ }+}+int4 ActionInputPrototype::apply(Funcdata &data){- vector<Varnode *> triallist;+ vector<Datatype *> typeList;ParamActive active(false);Varnode *vn;+ list<InputRef> inputRefs;data.getScopeLocal()->clearCategory(Symbol::fake_input);data.getFuncProto().clearUnlockedInput();+ if (data.getScopeLocal()->hasOpenParamRefs())+ gatherParamSpacebaseRefs(inputRefs, data);if (!data.getFuncProto().isInputLocked()) {VarnodeDefSet::const_iterator iter,enditer;iter = data.beginDef(Varnode::input);enditer = data.endDef(Varnode::input);+ bool useHigh = data.isHighOn();while(iter != enditer) {vn = *iter;++iter;if (data.getFuncProto().possibleInputParam(vn->getAddr(),vn->getSize())) {int4 slot = active.getNumTrials();- active.registerTrial(vn->getAddr(),vn->getSize());+ if (vn->isPersist()) {+ int4 sz;+ Address addr = data.findDisjointCover(vn, sz);+ Datatype *ct;+ if (sz == vn->getSize())+ ct = useHigh ? vn->getHigh()->getType() : vn->getType();+ else+ ct = data.getArch()->types->getBase(sz, TYPE_UNKNOWN);+ active.registerTrial(addr,sz);+ typeList.push_back(ct);+ }+ else {+ active.registerTrial(vn->getAddr(),vn->getSize());+ Datatype *ct = useHigh ? vn->getHigh()->getType() : vn->getType();+ typeList.push_back(ct);+ }if (!vn->hasNoDescend())active.getTrial(slot).markActive(); // Mark as active if it has descendants- triallist.push_back(vn);}}+ markActiveInputRefs(active, inputRefs, typeList, data);data.getFuncProto().resolveModel(&active);data.getFuncProto().deriveInputMap(&active); // Derive the correct prototype from trials// Create any unreferenced input varnodes@@ -4951,19 +5111,15 @@ int4 ActionInputPrototype::apply(Funcdata &data)paramtrial.markNoUse();}else {- vn = data.newVarnode(paramtrial.getSize(),paramtrial.getAddress());- vn = data.setInputVarnode(vn);- int4 slot = triallist.size();- triallist.push_back(vn);+ int4 slot = typeList.size();+ typeList.push_back(data.getArch()->types->getBase(paramtrial.getSize(), TYPE_UNKNOWN));paramtrial.setSlot(slot + 1);}}}- if (data.isHighOn())- data.getFuncProto().updateInputTypes(data,triallist,&active);- else- data.getFuncProto().updateInputNoTypes(data,triallist,&active);+ data.getFuncProto().updateInputTypes(data,typeList,&active);}+ addRefOnlySymbols(inputRefs, data);data.clearDeadVarnodes();#ifdef OPACTION_DEBUGif ((flags&rule_debug)==0) return 0;diff --git a/Ghidra/Features/Decompiler/src/decompile/cpp/coreaction.hh b/Ghidra/Features/Decompiler/src/decompile/cpp/coreaction.hhindex a676275cb5..0faf1a7f6d 100644--- a/Ghidra/Features/Decompiler/src/decompile/cpp/coreaction.hh+++ b/Ghidra/Features/Decompiler/src/decompile/cpp/coreaction.hh@@ -905,6 +905,18 @@ public:/// If the prototype wasn't originally known, the discovered input Varnodes are analyzed/// to determine a prototype based on the prototype model.class ActionInputPrototype : public Action {+ /// \brief A reference into the stack+ class InputRef {+ public:+ Address addr; ///< Address of region being referenced+ Datatype *dataType; ///< Data-type associated with the region+ InputRef(Address &ad,Datatype *dt) : addr(ad) { dataType = dt; } ///< Constructor+ bool operator<(const InputRef &op2) const; ///< Compare \b this with another reference+ static void dedup(list<InputRef> &refs); ///< Deduplicate a (sorted) list of references+ };+ void gatherParamSpacebaseRefs(list<InputRef> &refs,Funcdata &data);+ void markActiveInputRefs(ParamActive &active,list<InputRef> &refs,vector<Datatype *> &typeList,Funcdata &data);+ void addRefOnlySymbols(list<InputRef> &refs,Funcdata &data);public:ActionInputPrototype(const string &g) : Action(rule_onceperfunc,"inputprototype",g) {} ///< Constructorvirtual Action *clone(const ActionGroupList &grouplist) const {diff --git a/Ghidra/Features/Decompiler/src/decompile/cpp/database.cc b/Ghidra/Features/Decompiler/src/decompile/cpp/database.ccindex 26b68a62af..1d3dc214ea 100644--- a/Ghidra/Features/Decompiler/src/decompile/cpp/database.cc+++ b/Ghidra/Features/Decompiler/src/decompile/cpp/database.cc@@ -2498,6 +2498,39 @@ MapEntry *ScopeInternal::findOverlap(const Address &addr,int4 size) constreturn (MapEntry *)0;}+MapEntry *ScopeInternal::findSymbolBefore(const Address &addr,const Address &usepoint) const++{+ EntryMap *rangemap = maptable[ addr.getSpace()->getIndex() ];+ if (rangemap != (EntryMap *)0) {+ EntryMap::const_iterator iter = rangemap->find_last_before(addr.getOffset());+ if (iter != rangemap->end()) {+ for(;;) {+ if ((*iter).entry->inUse(usepoint))+ return (*iter).entry;+ if (iter == rangemap->begin()) break;+ --iter;+ }+ }+ }+ return (MapEntry *)0;+}++MapEntry *ScopeInternal::findSymbolAfter(const Address &addr,const Address &usepoint) const++{+ EntryMap *rangemap = maptable[ addr.getSpace()->getIndex() ];+ if (rangemap != (EntryMap *)0) {+ EntryMap::const_iterator iter = rangemap->find_first_after(addr.getOffset());+ while (iter != rangemap->end()) {+ if ((*iter).entry->inUse(usepoint))+ return (*iter).entry;+ ++iter;+ }+ }+ return (MapEntry *)0;+}+void ScopeInternal::findByName(const string &nm,vector<Symbol *> &res) const{diff --git a/Ghidra/Features/Decompiler/src/decompile/cpp/database.hh b/Ghidra/Features/Decompiler/src/decompile/cpp/database.hhindex 1ea7b84ce8..95bf119464 100644--- a/Ghidra/Features/Decompiler/src/decompile/cpp/database.hh+++ b/Ghidra/Features/Decompiler/src/decompile/cpp/database.hh@@ -707,6 +707,20 @@ public:/// \return an overlapping SymbolEntry or NULL if none existsvirtual MapEntry *findOverlap(const Address &addr,int4 size) const=0;+ /// \brief Find the last Symbol whose range ends before the given address+ ///+ /// \param addr is the given address+ /// \param usepoint is the point at which the Symbol is being accessed+ /// \return the matching MapEntry or NULL+ virtual MapEntry *findSymbolBefore(const Address &addr,const Address &usepoint) const=0;++ /// \brief Find the first Symbol whose range begins after the given address+ ///+ /// \param addr is the given address+ /// \param usepoint is the point at which the Symbol is being accessed+ /// \return the matching MapEntry or NULL+ virtual MapEntry *findSymbolAfter(const Address &addr,const Address &usepoint) const=0;+/// \brief Find a Symbol by name within \b this Scope////// If there are multiple Symbols with the same name, all are passed back.@@ -789,6 +803,7 @@ public:const string &getDisplayName(void) const { return displayName; } ///< Get name displayed in outputuint8 getId(void) const { return uniqueId; } ///< Get the globally unique idbool isGlobal(void) const { return (fd == (Funcdata *)0); } ///< Return \b true if \b this scope is global+ Funcdata *getFunction(void) const { return fd; } ///< Get function \b this is attached to, or null// The main global querying routinesvoid queryByName(const string &nm,vector<Symbol *> &res) const; ///< Look-up symbols by name@@ -884,6 +899,8 @@ public:virtual ExternRefSymbol *findExternalRef(const Address &addr) const;virtual LabSymbol *findCodeLabel(const Address &addr) const;virtual MapEntry *findOverlap(const Address &addr,int4 size) const;+ virtual MapEntry *findSymbolBefore(const Address &addr,const Address &usepoint) const;+ virtual MapEntry *findSymbolAfter(const Address &addr,const Address &usepoint) const;virtual void findByName(const string &nm,vector<Symbol *> &res) const;virtual bool isNameUsed(const string &nm,const Scope *op2) const;diff --git a/Ghidra/Features/Decompiler/src/decompile/cpp/database_ghidra.cc b/Ghidra/Features/Decompiler/src/decompile/cpp/database_ghidra.ccindex 03515cec8f..46cc03cc5b 100644--- a/Ghidra/Features/Decompiler/src/decompile/cpp/database_ghidra.cc+++ b/Ghidra/Features/Decompiler/src/decompile/cpp/database_ghidra.cc@@ -353,6 +353,39 @@ Funcdata *ScopeGhidra::resolveExternalRefFunction(ExternRefSymbol *sym) constreturn resFd;}+MapEntry *ScopeGhidra::findSymbolBefore(const Address &addr,const Address &usepoint) const++{+ uintb off = addr.getOffset();+ MapEntry *res = findContainer(addr, 1, usepoint);+ if (res != (MapEntry *)0)+ off = res->getAddr().getOffset();+ if (off == 0)+ return (MapEntry *)0;+ if ((off & 7) == 0)+ off -= 8;+ else+ off -= off & 7;+ Address curAddr(addr.getSpace(),off);+ return findContainer(curAddr,1,usepoint);+}++MapEntry *ScopeGhidra::findSymbolAfter(const Address &addr,const Address &usepoint) const++{+ uintb off = addr.getOffset();+ MapEntry *res = findContainer(addr, 1, usepoint);+ if (res != (MapEntry *)0)+ off = res->getAddr().getOffset() + res->getSize() - 1;+ if ((off & 7) != 0)+ off -= off & 7;+ off += 8;+ if (off < addr.getOffset() || off > addr.getSpace()->getHighest())+ return (MapEntry *)0;+ Address curAddr(addr.getSpace(),off);+ return findContainer(curAddr,1,usepoint);+}+MapEntry *ScopeGhidra::addSymbol(const string &nm,Datatype *ct,const Address &addr,const Address &usepoint){diff --git a/Ghidra/Features/Decompiler/src/decompile/cpp/database_ghidra.hh b/Ghidra/Features/Decompiler/src/decompile/cpp/database_ghidra.hhindex 60f4e08627..eb36ef35ed 100644--- a/Ghidra/Features/Decompiler/src/decompile/cpp/database_ghidra.hh+++ b/Ghidra/Features/Decompiler/src/decompile/cpp/database_ghidra.hh@@ -88,6 +88,8 @@ public:virtual Funcdata *resolveExternalRefFunction(ExternRefSymbol *sym) const;virtual MapEntry *findOverlap(const Address &addr,int4 size) const { throw LowlevelError("findOverlap unimplemented"); }+ virtual MapEntry *findSymbolBefore(const Address &addr,const Address &usepoint) const;+ virtual MapEntry *findSymbolAfter(const Address &addr,const Address &usepoint) const;virtual void findByName(const string &nm,vector<Symbol *> &res) const { throw LowlevelError("findByName unimplemented"); }virtual bool isNameUsed(const string &nm,const Scope *op2) const { throw LowlevelError("isNameUsed unimplemented"); }diff --git a/Ghidra/Features/Decompiler/src/decompile/cpp/fspec.cc b/Ghidra/Features/Decompiler/src/decompile/cpp/fspec.ccindex 5752fa72d1..ddf488d7d8 100644--- a/Ghidra/Features/Decompiler/src/decompile/cpp/fspec.cc+++ b/Ghidra/Features/Decompiler/src/decompile/cpp/fspec.cc@@ -2269,22 +2269,17 @@ void ProtoModel::defaultLocalRange(void)if (stackgrowsnegative) { // This the normal stack convention// Default locals are negative offsets off the stacklast = spc->getHighest();- if (spc->getAddrSize()>=4)- first = last - 999999;- else if (spc->getAddrSize()>=2)- first = last - 9999;- else- first = last - 99;+ uintb size = last >> 1;+ if (size > 0x7fffffff)+ size = 0x7fffffff;+ first = last - size;localrange.insertRange(spc,first,last);}else { // This is the flipped stack conventionfirst = 0;- if (spc->getAddrSize()>=4)- last = 999999;- else if (spc->getAddrSize()>=2)- last = 9999;- else- last = 99;+ last = spc->getHighest() >> 1;+ if (last > 0x7fffffff)+ last = 0x7fffffff;localrange.insertRange(spc,first,last);}}@@ -2298,22 +2293,17 @@ void ProtoModel::defaultParamRange(void)if (stackgrowsnegative) { // This the normal stack convention// Default parameters are positive offsets off the stackfirst = 0;- if (spc->getAddrSize()>=4)- last = 511;- else if (spc->getAddrSize()>=2)- last = 255;- else- last = 15;+ last = spc->getHighest() >> 2;+ if (last > 0x7fffffff)+ last = 0x7fffffff;paramrange.insertRange(spc,first,last);}else { // This is the flipped stack conventionlast = spc->getHighest();- if (spc->getAddrSize()>=4)- first = last - 511;- else if (spc->getAddrSize()>=2)- first = last - 255;- else- first = last - 15;+ uintb size = last >> 2;+ if (size > 0x7fffffff)+ size = 0x7fffffff;+ first = last - size;paramrange.insertRange(spc,first,last); // Parameters are negative offsets}}@@ -4042,93 +4032,33 @@ void FuncProto::cancelInjectId(void)flags &= ~((uint4)is_inline);}-/// \brief Update input parameters based on Varnode trials+/// \brief Update input parameters based on active trials///-/// If the input parameters are locked, don't do anything. Otherwise,-/// given a list of Varnodes and their associated trial information,-/// create an input parameter for each trial in order, grabbing data-type-/// information from the Varnode. Any old input parameters are cleared.+/// Create an input parameter for each trial in order, grabbing data-type information from the+/// list provided, linked by trial \e slot. Any old input parameters are cleared./// \param data is the function containing the trial Varnodes-/// \param triallist is the list of Varnodes+/// \param typeList is the list of data-types/// \param activeinput is the trial container-void FuncProto::updateInputTypes(Funcdata &data,const vector<Varnode *> &triallist,ParamActive *activeinput)+void FuncProto::updateInputTypes(Funcdata &data,const vector<Datatype *> &typeList,ParamActive *activeinput){- if (isInputLocked()) return; // Input is locked, do no updatingstore->clearAllInputs();int4 count = 0;int4 numtrials = activeinput->getNumTrials();for(int4 i=0;i<numtrials;++i) {ParamTrial &trial(activeinput->getTrial(i));if (trial.isUsed()) {- Varnode *vn = triallist[trial.getSlot()-1];- if (vn->isMark()) continue;ParameterPieces pieces;- if (vn->isPersist()) {- int4 sz;- pieces.addr = data.findDisjointCover(vn, sz);- if (sz == vn->getSize())- pieces.type = vn->getHigh()->getType();- else- pieces.type = data.getArch()->types->getBase(sz, TYPE_UNKNOWN);- pieces.flags = 0;- }- else {- pieces.addr = trial.getAddress();- pieces.type = vn->getHigh()->getType();- pieces.flags = 0;- }+ pieces.addr = trial.getAddress();+ pieces.type = typeList[trial.getSlot()-1];+ pieces.flags = 0;store->setInput(count,"",pieces);count += 1;- vn->setMark();}}- for(int4 i=0;i<triallist.size();++i)- triallist[i]->clearMark();updateThisPointer();}-/// \brief Update input parameters based on Varnode trials, but do not store the data-type-///-/// This is accomplished in the same way as if there were data-types but instead of-/// pulling a data-type from the Varnode, only the size is used.-/// Undefined data-types are pulled from the given TypeFactory-/// \param data is the function containing the trial Varnodes-/// \param triallist is the list of Varnodes-/// \param activeinput is the trial container-void FuncProto::updateInputNoTypes(Funcdata &data,const vector<Varnode *> &triallist,ParamActive *activeinput)-{- if (isInputLocked()) return; // Input is locked, do no updating- store->clearAllInputs();- int4 count = 0;- int4 numtrials = activeinput->getNumTrials();- TypeFactory *factory = data.getArch()->types;- for(int4 i=0;i<numtrials;++i) {- ParamTrial &trial(activeinput->getTrial(i));- if (trial.isUsed()) {- Varnode *vn = triallist[trial.getSlot()-1];- if (vn->isMark()) continue;- ParameterPieces pieces;- if (vn->isPersist()) {- int4 sz;- pieces.addr = data.findDisjointCover(vn, sz);- pieces.type = factory->getBase(sz, TYPE_UNKNOWN);- pieces.flags = 0;- }- else {- pieces.addr = trial.getAddress();- pieces.type = factory->getBase(vn->getSize(),TYPE_UNKNOWN);- pieces.flags = 0;- }- store->setInput(count,"",pieces);- count += 1;- vn->setMark(); // Make sure vn is used only once- }- }- for(int4 i=0;i<triallist.size();++i)- triallist[i]->clearMark();-}-/// \brief Update the return value based on Varnode trials////// If the output parameter is locked, don't do anything. Otherwise,diff --git a/Ghidra/Features/Decompiler/src/decompile/cpp/fspec.hh b/Ghidra/Features/Decompiler/src/decompile/cpp/fspec.hhindex 6d1615b449..922c1a799e 100644--- a/Ghidra/Features/Decompiler/src/decompile/cpp/fspec.hh+++ b/Ghidra/Features/Decompiler/src/decompile/cpp/fspec.hh@@ -1524,8 +1524,7 @@ public:bool checkInputSplit(const Address &loc,int4 size,int4 splitpoint) const {return model->checkInputSplit(loc,size,splitpoint); }- void updateInputTypes(Funcdata &data,const vector<Varnode *> &triallist,ParamActive *activeinput);- void updateInputNoTypes(Funcdata &data,const vector<Varnode *> &triallist,ParamActive *activeinput);+ void updateInputTypes(Funcdata &data,const vector<Datatype *> &typeList,ParamActive *activeinput);void updateOutputTypes(const vector<Varnode *> &triallist);void updateOutputNoTypes(const vector<Varnode *> &triallist,TypeFactory *factory);void updateAllTypes(const PrototypePieces &proto);diff --git a/Ghidra/Features/Decompiler/src/decompile/cpp/funcdata.cc b/Ghidra/Features/Decompiler/src/decompile/cpp/funcdata.ccindex da9ecd6e97..9d21071611 100644--- a/Ghidra/Features/Decompiler/src/decompile/cpp/funcdata.cc+++ b/Ghidra/Features/Decompiler/src/decompile/cpp/funcdata.cc@@ -240,7 +240,7 @@ void Funcdata::spacebase(void)for(i=0;i<numspace;++i) {const VarnodeData &point(spc->getSpacebase(i));// Find input varnode at this size and location- Datatype *ct = glb->types->getTypeSpacebase(spc,getAddress());+ Datatype *ct = glb->types->getTypeSpacebase(spc,localmap->getId());Datatype *ptr = glb->types->getTypePointer(point.size,ct,spc->getWordSize());iter = vbank.beginLoc(point.size,Address(point.space,point.offset));@@ -313,7 +313,7 @@ Varnode *Funcdata::constructSpacebaseInput(AddrSpace *id)if (id->numSpacebase() == 0)throw LowlevelError("Unable to construct pointer into space: "+id->getName());const VarnodeData &point(id->getSpacebase(0));- Datatype *ct = glb->types->getTypeSpacebase(id,getAddress());+ Datatype *ct = glb->types->getTypeSpacebase(id,localmap->getId());Datatype *ptr = glb->types->getTypePointer(point.size,ct,id->getWordSize());spacePtr = newVarnode(point.size, point.getAddr(), ptr);spacePtr = setInputVarnode(spacePtr);@@ -330,7 +330,7 @@ Varnode *Funcdata::constructSpacebaseInput(AddrSpace *id)Varnode *Funcdata::constructConstSpacebase(AddrSpace *id){- Datatype *ct = glb->types->getTypeSpacebase(id,Address());+ Datatype *ct = glb->types->getTypeSpacebase(id,0);Datatype *ptr = glb->types->getTypePointer(id->getAddrSize(),ct,id->getWordSize());Varnode *spacePtr = newConstant(id->getAddrSize(),0);spacePtr->updateType(ptr,true,true);@@ -360,7 +360,7 @@ void Funcdata::spacebaseConstant(PcodeOp *op,int4 slot,MapEntry *entry,const Add{int4 sz = rampoint.getAddrSize();AddrSpace *spaceid = rampoint.getSpace();- Datatype *sb_type = glb->types->getTypeSpacebase(spaceid,Address());+ Datatype *sb_type = glb->types->getTypeSpacebase(spaceid,entry->getSymbol()->getScope()->getId());sb_type = glb->types->getTypePointer(sz,sb_type,spaceid->getWordSize());Varnode *spacebase_vn,*outvn,*newconst;diff --git a/Ghidra/Features/Decompiler/src/decompile/cpp/rangemap.hh b/Ghidra/Features/Decompiler/src/decompile/cpp/rangemap.hhindex ba29f9886f..b4e2c38b6c 100644--- a/Ghidra/Features/Decompiler/src/decompile/cpp/rangemap.hh+++ b/Ghidra/Features/Decompiler/src/decompile/cpp/rangemap.hh@@ -4,9 +4,9 @@* Licensed under the Apache License, Version 2.0 (the "License");* you may not use this file except in compliance with the License.* You may obtain a copy of the License at- *+ ** http://www.apache.org/licenses/LICENSE-2.0- *+ ** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.@@ -99,6 +99,7 @@ public:/// may be visited multiple times by the iterator, depending on how much it overlaps other/// \b recordtypes. The sub-ranges are sorted in linear order, then depending on the \b subsorttype.class PartIterator {+ friend class rangemap<_recordtype>;typename std::multiset<AddrRange>::const_iterator iter; ///< The underlying multiset iteratorpublic:PartIterator(void) {} ///< Constructor@@ -158,6 +159,12 @@ public:/// \brief Find first record overlapping given intervalconst_iterator find_overlap(linetype point,linetype end) const;+ /// \brief Find first record whose range begins after the given point+ const_iterator find_first_after(linetype point) const;++ /// \brief Find last record whose range ends before the given point+ const_iterator find_last_before(linetype point) const;+/// \brief Insert a new record into the containertypename std::list<_recordtype>::iterator insert(const inittype &data,linetype a,linetype b);@@ -422,5 +429,37 @@ rangemap<_recordtype>::find_overlap(linetype point,linetype end) constreturn tree.end();}+/// \param point is the given boundary point+/// \return iterator to the first sub-range of a record not containing \b point, or end()+template<typename _recordtype>+typename rangemap<_recordtype>::const_iterator+rangemap<_recordtype>::find_first_after(linetype point) const++{+ const_iterator iter = find_end(point); // First subrange after point+ while (iter != end()) {+ if (point < (*iter.iter).a) // Skip records whose full range contains point (a <= point)+ return iter;+ ++iter;+ }+ return iter;+}++/// \param point is the given boundary point+/// \return iterator to the last sub-range of a record not containing \b point, or end()+template<typename _recordtype>+typename rangemap<_recordtype>::const_iterator+rangemap<_recordtype>::find_last_before(linetype point) const++{+ const_iterator iter = find_begin(point); // Earliest subrange that contains point+ while (iter != begin()) {+ --iter; // Move backwards to latest subranges not containing point+ if ((*iter.iter).b < point) // Skip records whose full range contains point (b >= point)+ return iter;+ }+ return end();+}+} // End namespace ghidra#endifdiff --git a/Ghidra/Features/Decompiler/src/decompile/cpp/ruleaction.cc b/Ghidra/Features/Decompiler/src/decompile/cpp/ruleaction.ccindex a9db3b8008..accecb0904 100644--- a/Ghidra/Features/Decompiler/src/decompile/cpp/ruleaction.cc+++ b/Ghidra/Features/Decompiler/src/decompile/cpp/ruleaction.cc@@ -6071,64 +6071,6 @@ AddTreeState::AddTreeState(Funcdata &d,PcodeOp *op,int4 slot)isDegenerate = (baseType->getAlignSize() <= unitsize && baseType->getAlignSize() > 0);}-/// \brief Given an offset into the base data-type and array hints find sub-component being referenced-///-/// An explicit offset should target a specific sub data-type,-/// but array indexing may confuse things. This method passes-/// back the offset of the best matching component, searching among components-/// that are \e nearby the given offset, preferring a matching array element size-/// and a component start that is nearer to the offset.-/// \param off is the given offset into the data-type-/// \param arrayHint if non-zero indicates array access, where the value is the element size-/// \param newoff is used to pass back the actual offset of the selected component-/// \return \b true if a good component match was found-bool AddTreeState::hasMatchingSubType(int8 off,uint4 arrayHint,int8 *newoff) const--{- if (arrayHint == 0)- return (baseType->getSubType(off,newoff) != (Datatype *)0);-- int8 elSizeBefore;- int8 offBefore;- int8 typeBefore = baseType->nearestArrayedComponentBackward(off, 128, &offBefore, &elSizeBefore);- int8 elSizeAfter;- int8 offAfter;- int8 typeAfter = baseType->nearestArrayedComponentForward(off, 128, &offAfter, &elSizeAfter);- if (typeBefore < 0 && typeAfter < 0)- return (baseType->getSubType(off,newoff) != (Datatype *)0);- if (typeBefore < 0) {- *newoff = offAfter; // Only array is after- return true;- }- if (typeAfter < 0) {- *newoff = offBefore; // Only array is before- return true;- }- if (offAfter == offBefore) {- *newoff = offAfter;- return true;- }- // Reaching here we know there is an array before and an array after the offset point- if (arrayHint != 1 && elSizeBefore != elSizeAfter) { // element sizes are different, try to distinguish by arrayHint- if (elSizeBefore == arrayHint) {- *newoff = offBefore;- return true;- }- if (elSizeAfter == arrayHint) {- *newoff = offAfter;- return true;- }- }- if (baseType->getSubType(off,newoff) != (Datatype *)0) {- if (*newoff == offBefore || *newoff == offAfter)- return true; // Offset is contained in one of the arrayed components. Return it.- }- uint8 distBefore = (offBefore < 0) ? -offBefore : offBefore;- uint8 distAfter = (offAfter < 0) ? -offAfter : offAfter;- *newoff = (distAfter < distBefore) ? offAfter : offBefore;- return true;-}-/// Examine a CPUI_INT_MULT element in the middle of the add tree. Determine if we treat/// the output simply as a leaf, or if the multiply needs to be distributed to an/// additive subtree. If the Varnode is a leaf of the tree, return \b true if@@ -6310,7 +6252,14 @@ void AddTreeState::calcSubtype(void)int8 offsetbytes = AddrSpace::addressToByteInt(offset,ct->getWordSize()); // Convert to bytesint8 extra;// Get offset into mapped variable- if (!hasMatchingSubType(offsetbytes, biggestNonMultCoeff, &extra)) {+ bool foundSymbol = false;+ if (biggestNonMultCoeff != 0)+ foundSymbol = baseType->nearestArrayedComponent(offsetbytes, biggestNonMultCoeff, &extra);+ if (!foundSymbol)+ foundSymbol = (baseType->getSubType(offsetbytes,&extra) != (Datatype *)0);+ if (!foundSymbol && biggestNonMultCoeff == 0)+ foundSymbol = baseType->nearestArrayedComponent(offsetbytes, 1, &extra);+ if (!foundSymbol) {valid = false; // Cannot find mapped variable but nonmult is non-emptyreturn;}@@ -6324,7 +6273,12 @@ void AddTreeState::calcSubtype(void)int8 offsetbytes = AddrSpace::addressToByteInt(soffset,ct->getWordSize()); // Convert to bytesint8 extra;// Get offset into field in structure- if (!hasMatchingSubType(offsetbytes, biggestNonMultCoeff, &extra)) {+ bool foundField = false;+ if (biggestNonMultCoeff != 0)+ foundField = baseType->nearestArrayedComponent(offsetbytes, biggestNonMultCoeff, &extra);+ if (!foundField)+ foundField = (baseType->getSubType(offsetbytes,&extra) != (Datatype *)0);+ if (!foundField) {if (offsetbytes < 0 || offsetbytes >= baseType->getSize()) { // Compare as bytes! not address unitsvalid = false; // Out of structure's boundsreturn;diff --git a/Ghidra/Features/Decompiler/src/decompile/cpp/ruleaction.hh b/Ghidra/Features/Decompiler/src/decompile/cpp/ruleaction.hhindex 5b8c80d2d0..5a39b7aaae 100644--- a/Ghidra/Features/Decompiler/src/decompile/cpp/ruleaction.hh+++ b/Ghidra/Features/Decompiler/src/decompile/cpp/ruleaction.hh@@ -66,7 +66,6 @@ class AddTreeState {bool isSubtype; ///< Is there a sub-type (using CPUI_PTRSUB)bool valid; ///< Set to \b true if the whole expression can be transformedbool isDegenerate; ///< Set to \b true if pointer to unitsize or smaller- bool hasMatchingSubType(int8 off,uint4 arrayHint,int8 *newoff) const;bool checkMultTerm(Varnode *vn,PcodeOp *op,uint8 treeCoeff); ///< Accumulate details of INT_MULT term and continue traversal if appropriatebool checkTerm(Varnode *vn,uint8 treeCoeff); ///< Accumulate details of given term and continue tree traversalbool spanAddTree(PcodeOp *op,uint8 treeCoeff); ///< Walk the given sub-tree accumulating detailsdiff --git a/Ghidra/Features/Decompiler/src/decompile/cpp/type.cc b/Ghidra/Features/Decompiler/src/decompile/cpp/type.ccindex 5b5bbf83fe..0a1f22168a 100644--- a/Ghidra/Features/Decompiler/src/decompile/cpp/type.cc+++ b/Ghidra/Features/Decompiler/src/decompile/cpp/type.cc@@ -200,32 +200,25 @@ Datatype *Datatype::getSubType(int8 off,int8 *newoff) const}/// If \b this data-type is (or contains) an array starting after the given-/// offset, return the distance in bytes to the start of the array,-/// and pass back the difference between the component's start and the given offset.+/// offset, pass back information about the component and its distance./// \param off is the given offset into \b this data-type-/// \param max is the maximum distance, in bytes, to search-/// \param newoff is used to pass back the offset difference-/// \param elSize is used to pass back the array element size-/// \return the distance to the array or -1 otherwise-int8 Datatype::nearestArrayedComponentForward(int8 off,int8 max,int8 *newoff,int8 *elSize) const+/// \param res is filled in with component and distance info+/// \return \b true if a component is found+bool Datatype::nearestArrayedComponentForward(int8 off,Nearest &res) const{- return -1;+ return false;}/// If \b this data-type is (or contains) an array starting before the given-/// offset, return the distance in bytes to the end of the array,-/// and pass back the difference between the component's start and the given offset.-/// Return the component data-type or null if no array is found.+/// offset, pass back information about the component and its distance./// \param off is the given offset into \b this data-type-/// \param max is the maximum distance, in bytes, to search-/// \param newoff is used to pass back the offset difference-/// \param elSize is used to pass back the array element size-/// \return the distance to the array or -1 otherwise-int8 Datatype::nearestArrayedComponentBackward(int8 off,int8 max,int8 *newoff,int8 *elSize) const+/// \param res is filled in with component and distance info+/// \return \b true if a component is found+bool Datatype::nearestArrayedComponentBackward(int8 off,Nearest &res) const{- return -1;+ return false;}/// Order \b this with another data-type, in a way suitable for the type propagation algorithm.@@ -536,6 +529,66 @@ bool Datatype::isPrimitiveWhole(void) constreturn false;}+/// \brief Find the \e array subcomponent nearest to the given offset+///+/// This method passes back the offset of the best component, preferring an array closer+/// to the offset and matching the preferred element size. The start of the array must+/// be within \b max bytes of the offset, or \b false is returned.+/// \param off is the given offset into the data-type+/// \param arrayHint if non-zero indicates the preferred element size+/// \param newoff is used to pass back the actual offset of the selected component+/// \return \b true if a good component match was found+bool Datatype::nearestArrayedComponent(int8 off,uint4 arrayHint,int8 *newoff) const++{+ Nearest before;+ Nearest after;+ bool typeBefore = nearestArrayedComponentBackward(off, before);+ bool typeAfter = nearestArrayedComponentForward(off, after);+ if (!typeBefore && !typeAfter)+ return false;+ if (!typeBefore) {+ *newoff = after.offset; // Only array is after+ return true;+ }+ if (!typeAfter) {+ *newoff = before.offset; // Only array is before+ return true;+ }+ // Reaching here we know there is an array before and an array after the offset point+ if (arrayHint != 1 && before.elSize != after.elSize) { // element sizes are different, try to distinguish by arrayHint+ if (before.elSize == arrayHint) {+ *newoff = before.offset;+ return true;+ }+ if (after.elSize == arrayHint) {+ *newoff = after.offset;+ return true;+ }+ }+ if (getSubType(off,newoff) != (Datatype *)0) {+ if (*newoff == before.offset || *newoff == after.offset)+ return true; // Offset is contained in one of the arrayed components. Return it.+ }+ *newoff = (after.distance <= before.distance) ? after.offset : before.offset;+ return true;+}++/// If \b this data-type is an array, or has an arrayed component, return \b true.+/// \param off is the out-of-bounds offset+/// \return \b true if an array is present+bool Datatype::testForArraySlack(int8 off)++{+ if (metatype == TYPE_ARRAY)+ return true;+ Nearest comp;+ if (off < 0) {+ return nearestArrayedComponentForward(off, comp);+ }+ return nearestArrayedComponentBackward(off, comp);+}+/// Called only if the \b typedefImm field is non-null. Encode the data-type to the/// stream as a simple \<typedef> element including only the names and ids of \b this and/// the data-type it typedefs.@@ -566,6 +619,8 @@ int4 Datatype::calcAlignSize(int4 sz,int4 align)return sz;}+/// \brief Is this data-type suitable as input to a CPUI_PTRSUB op+////// A CPUI_PTRSUB must act on a pointer data-type where the given offset addresses a component./// Perform this check./// \param off is the given offset@@ -578,6 +633,17 @@ bool Datatype::isPtrsubMatching(int8 off,int8 extra,int8 multiplier) constreturn false;}+/// A companion to isPtrsubMatching().+/// \param off is the given byte offset into \b this+/// \param extra is a sub-offset into the component reached by the main offset+/// \param multiplier is the size of any index multiplier to reach into the component+/// \return \b true if the offset is considered valid+bool Datatype::isOffsetValid(int8 off,int8 extra,int8 multiplier) const++{+ return false; // By default assume no sub-components+}+/// Some data-types are ephemeral, and, in the final decompiler output, get replaced with a formal version/// that is a stripped down version of the original. This method returns this stripped down version, if it/// exists, or null otherwise. A non-null return should correspond with hasStripped returning \b true.@@ -1144,23 +1210,6 @@ void TypePointer::encode(Encoder &encoder) constencoder.closeElement(ELEM_TYPE);}-/// If the given data-type is an array, or has an arrayed component, return \b true.-/// \param dt is the given data-type to check-/// \param off is the out-of-bounds offset-/// \return \b true is an array is present-bool TypePointer::testForArraySlack(Datatype *dt,int8 off)--{- int8 newoff;- int8 elSize;- if (dt->getMetatype() == TYPE_ARRAY)- return true;- if (off < 0) {- return (dt->nearestArrayedComponentForward(off, 128, &newoff, &elSize) >= 0);- }- return (dt->nearestArrayedComponentBackward(off, 128, &newoff, &elSize) >= 0);-}-/// Parse a \<type> element with a child describing the data-type being pointed to/// \param decoder is the stream decoder/// \param typegrp is the factory owning \b this data-type@@ -1280,67 +1329,10 @@ TypePointer *TypePointer::downChain(int8 &off,TypePointer *&par,int8 &parOff,boobool TypePointer::isPtrsubMatching(int8 off,int8 extra,int8 multiplier) const{- type_metatype meta = ptrto->getMetatype();- if (meta==TYPE_SPACEBASE) {- int8 newoff = AddrSpace::addressToByteInt(off,wordsize);- Datatype *subType = ptrto->getSubType(newoff,&newoff);- if (subType == (Datatype *)0 || newoff != 0)- return false;- extra = AddrSpace::addressToByteInt(extra,wordsize);- if (subType->getMetatype() == TYPE_CODE) {- // When the pointer targets inside a function, consider PTRSUB to be suitable when- // the extra is non-negative, as subType->getSize() cannot be used (it is always 1).- if (extra < 0)- return false;- }- else {- if (extra < 0 || extra >= subType->getSize()) {- if (!testForArraySlack(subType, extra))- return false;- }- }- }- else if (meta == TYPE_ARRAY) {- if (off != 0)- return false;- multiplier = AddrSpace::addressToByteInt(multiplier,wordsize);- if (multiplier >= ptrto->getAlignSize())- return false;- }- else if (meta == TYPE_STRUCT) {- int4 typesize = ptrto->getSize();- multiplier = AddrSpace::addressToByteInt(multiplier,wordsize);- if (multiplier >= ptrto->getAlignSize())- return false;- int8 newoff = AddrSpace::addressToByteInt(off,wordsize);- extra = AddrSpace::addressToByteInt(extra, wordsize);- Datatype *subType = ptrto->getSubType(newoff,&newoff);- if (subType != (Datatype *)0) {- if (newoff != 0)- return false;- if (extra < 0 || extra >= subType->getSize()) {- if (!testForArraySlack(subType, extra))- return false;- }- }- else {- extra += newoff;- if ((extra < 0 || extra >= typesize)&&(typesize!=0))- return false;- }- }- else if (meta == TYPE_UNION) {- // A PTRSUB reaching here cannot be used for a union field resolution- // These are created by ActionSetCasts::resolveUnion- return false; // So we always return false- }- else if (meta == TYPE_CODE) {- if (extra < 0)- return false;- }- else- return false; // Not a pointer to a structured data-type- return true;+ off = AddrSpace::addressToByteInt(off,wordsize);+ extra = AddrSpace::addressToByteInt(extra, wordsize);+ multiplier = AddrSpace::addressToByteInt(multiplier,wordsize);+ return ptrto->isOffsetValid(off, extra, multiplier);}Datatype *TypePointer::resolveInFlow(PcodeOp *op,int4 slot)@@ -1424,24 +1416,27 @@ Datatype *TypeArray::getSubType(int8 off,int8 *newoff) constreturn arrayof;}-int8 TypeArray::nearestArrayedComponentForward(int8 off,int8 max,int8 *newoff,int8 *elSize) const+bool TypeArray::nearestArrayedComponentForward(int8 off,Nearest &res) const{- if (off > 0) return -1; // Skip if we are in the middle of array- *newoff = off;- *elSize = arrayof->getAlignSize();- return -off;+ if (off > 0) return false; // Skip if we are in the middle of array+ res.offset = off;+ res.elSize = arrayof->getAlignSize();+ res.distance = -off;+ return true;}-int8 TypeArray::nearestArrayedComponentBackward(int8 off,int8 max,int8 *newoff,int8 *elSize) const+bool TypeArray::nearestArrayedComponentBackward(int8 off,Nearest &res) const{- if (off < 0) return -1; // Skip if we are before array- *newoff = off;- *elSize = arrayof->getAlignSize();- if (off <= size)- return (size - off);- return (off - size);+ if (off < 0) return false; // Skip if we are before array+ res.offset = off;+ res.elSize = arrayof->getAlignSize();+ if (off < size)+ res.distance = 0; // In the array, is distance 0+ else+ res.distance = (off - size);+ return true;}int4 TypeArray::getHoleSize(int4 off) const@@ -1499,6 +1494,16 @@ Datatype *TypeArray::resolveInFlow(PcodeOp *op,int4 slot)return compFill.getDatatype();}+bool TypeArray::isOffsetValid(int8 off,int8 extra,int8 multiplier) const++{+ if (off != 0)+ return false;+ if (multiplier >= getAlignSize())+ return false;+ return true;+}+Datatype* TypeArray::findResolve(const PcodeOp *op,int4 slot){@@ -1952,7 +1957,7 @@ int4 TypeStruct::getHoleSize(int4 off) constreturn getSize() - off; // Distance to end of structure}-int8 TypeStruct::nearestArrayedComponentBackward(int8 off,int8 max,int8 *newoff,int8 *elSize) const+bool TypeStruct::nearestArrayedComponentBackward(int8 off,Nearest &res) const{int4 firstIndex = getLowerBoundField(off);@@ -1961,22 +1966,18 @@ int8 TypeStruct::nearestArrayedComponentBackward(int8 off,int8 max,int8 *newoff,const TypeField &subfield( field[i] );int8 diff = off - subfield.offset;Datatype *subtype = subfield.type;- int8 suboff;int8 remain = (i == firstIndex) ? diff : subtype->getSize();- if (diff - remain > max) break;- int8 distance = subtype->nearestArrayedComponentBackward(remain, max, &suboff, elSize);- if (distance >= 0) {- distance = (diff - remain) + distance;- if (distance > max) break;- *newoff = diff;- return distance;+ if (subtype->nearestArrayedComponentBackward(remain, res)) {+ res.distance = (diff - remain) + res.distance;+ res.offset = diff;+ return true;}i -= 1;}- return -1;+ return false;}-int8 TypeStruct::nearestArrayedComponentForward(int8 off,int8 max,int8 *newoff,int8 *elSize) const+bool TypeStruct::nearestArrayedComponentForward(int8 off,Nearest &res) const{int4 i = getLowerBoundField(off);@@ -1990,21 +1991,16 @@ int8 TypeStruct::nearestArrayedComponentForward(int8 off,int8 max,int8 *newoff,iwhile(i<field.size()) {const TypeField &subfield( field[i] );int8 diff = subfield.offset - off; // The first struct field examined may have a negative diff- if (diff + remain > max) break;Datatype *subtype = subfield.type;- int8 suboff;- int8 distance = subtype->nearestArrayedComponentForward(remain, max, &suboff, elSize);- if (distance >= 0) {- distance = diff + remain + distance;- if (distance > max)- break;- *newoff = -diff;- return distance;+ if (subtype->nearestArrayedComponentForward(remain, res)) {+ res.distance = diff + remain + res.distance;+ res.offset = -diff;+ return true;}i += 1;remain = 0;}- return -1;+ return false;}int4 TypeStruct::compare(const Datatype &op,int4 level) const@@ -2122,6 +2118,29 @@ void TypeStruct::encode(Encoder &encoder) constencoder.closeElement(ELEM_TYPE);}+bool TypeStruct::isOffsetValid(int8 off,int8 extra,int8 multiplier) const++{+ if (multiplier >= getAlignSize())+ return false;+ int8 newoff;+ Datatype *subType = getSubType(off,&newoff);+ if (subType != (Datatype *)0) {+ if (newoff != 0)+ return false;+ if (extra < 0 || extra >= subType->getSize()) {+ if (!subType->testForArraySlack(extra))+ return false;+ }+ }+ else {+ extra += newoff;+ if ((extra < 0 || extra >= size)&&(size != 0))+ return false;+ }+ return true;+}+/// \brief Decode a single field, check for errors, and accumulate size and alignment////// Make sure the field fits, doesn't overlap other fields, and has a sensible name and data-type.@@ -2394,7 +2413,9 @@ void TypeStruct::assignContiguousBitfields(vector<TypeBitField> &bitlist,int4 &p/// \param newSize passes back the calculated size of the structure/// \param newAlign passes back the calculated alignment/// \param flags passes back any additional flags that should be set on the structure-void TypeStruct::assignFieldOffsets(vector<TypeField> &list,vector<TypeBitField> &bitlist,int4 &newSize,int4 &newAlign,uint4 &flags)+/// \param st is the structure to be populated+void TypeStruct::assignFieldOffsets(vector<TypeField> &list,vector<TypeBitField> &bitlist,int4 &newSize,int4 &newAlign,+ uint4 &flags,const TypeStruct *st){int4 nextBitPos = -1;@@ -2415,7 +2436,7 @@ void TypeStruct::assignFieldOffsets(vector<TypeField> &list,vector<TypeBitField>}TypeField &curField(list[pos]);if (curField.type->getMetatype() == TYPE_VOID)- throw LowlevelError("Illegal field data-type: void");+ throw LowlevelError("Illegal field void in structure: "+st->getName());if (curField.offset != -1) continue;int4 cursize = curField.type->getAlignSize();int4 align = curField.type->getAlignment();@@ -2434,7 +2455,7 @@ void TypeStruct::assignFieldOffsets(vector<TypeField> &list,vector<TypeBitField>assignContiguousBitfields(bitlist, curBitInd, offset, newAlign); // Bitfields after any other fields}if (!bitlist.empty() && curBitInd != bitlist.size())- throw LowlevelError("Malformed bitfield description");+ throw LowlevelError("Malformed bitfield description in structure: "+st->getName());if (!bitlist.empty())flags |= Datatype::has_bitfields;newSize = calcAlignSize(offset, newAlign);@@ -2658,6 +2679,26 @@ const TypeField *TypeUnion::findTruncation(int8 offset,int4 sz,const PcodeOp *opreturn (const TypeField *)0;}+bool TypeUnion::nearestArrayedComponentForward(int8 off,Nearest &res) const++{+ for(int4 i=0;i<field.size();++i) {+ if (field[i].type->nearestArrayedComponentForward(off, res))+ return true;+ }+ return false;+}++bool TypeUnion::nearestArrayedComponentBackward(int8 off,Nearest &res) const++{+ for(int4 i=0;i<field.size();++i) {+ if (field[i].type->nearestArrayedComponentBackward(off, res))+ return true;+ }+ return false;+}+int4 TypeUnion::findCompatibleResolve(Datatype *ct) const{@@ -2680,13 +2721,15 @@ int4 TypeUnion::findCompatibleResolve(Datatype *ct) constreturn -1;}-void TypeUnion::assignFieldOffsets(vector<TypeField> &list,int4 &newSize,int4 &newAlign,TypeUnion *tu)+void TypeUnion::assignFieldOffsets(vector<TypeField> &list,int4 &newSize,int4 &newAlign,uint4 &flags,+ const TypeUnion *tu){vector<TypeField>::iterator iter;newSize = 0;newAlign = 1;+ flags = 0;for(iter=list.begin();iter!=list.end();++iter) {Datatype *ct = (*iter).type;// Do some sanity checks on the field@@ -3395,6 +3438,12 @@ void TypeCode::encode(Encoder &encoder) constencoder.closeElement(ELEM_TYPE);}+bool TypeCode::isOffsetValid(int8 off,int8 extra,int8 multiplier) const++{+ return (extra >= 0); // Valid for any non-negative offset+}+/// \param decoder is the stream decodervoid TypeCode::decodeStub(Decoder &decoder)@@ -3431,13 +3480,10 @@ void TypeCode::decodePrototype(Decoder &decoder,bool isConstructor,bool isDestruScope *TypeSpacebase::getMap(void) const{- Scope *res = glb->symboltab->getGlobalScope();- if (!localframe.isInvalid()) { // If this spacebase is for a localframe- Funcdata *fd = res->queryFunction(localframe);- if (fd != (Funcdata *)0)- res = fd->getScopeLocal();- }- return res;+ Scope *scope = glb->symboltab->resolveScope(scopeId);+ if (scope == (Scope *)0)+ throw LowlevelError("Trying to get scope from unattached Typespacebase");+ return scope;}Datatype *TypeSpacebase::getSubType(int8 off,int8 *newoff) const@@ -3457,6 +3503,8 @@ Datatype *TypeSpacebase::getSubType(int8 off,int8 *newoff) constsmallest = scope->queryContainer(addr,1,nullPoint);if (smallest == (MapEntry *)0) {+ if (!scope->inScope(addr, 1, nullPoint))+ return (Datatype *)0;*newoff = 0;return glb->types->getBase(1,TYPE_UNKNOWN);}@@ -3464,7 +3512,7 @@ Datatype *TypeSpacebase::getSubType(int8 off,int8 *newoff) constreturn smallest->getSymbol()->getType();}-int8 TypeSpacebase::nearestArrayedComponentForward(int8 off,int8 max,int8 *newoff,int8 *elSize) const+bool TypeSpacebase::nearestArrayedComponentForward(int8 off,Nearest &res) const{Scope *scope = getMap();@@ -3474,57 +3522,88 @@ int8 TypeSpacebase::nearestArrayedComponentForward(int8 off,int8 max,int8 *newofAddress nullPoint;uintb fullEncoding;Address addr = glb->resolveConstant(spaceid, addrOff, -1, nullPoint, fullEncoding);++ // Look for Symbol (with an array component) at initial addressMapEntry *smallest = scope->queryContainer(addr,1,nullPoint);- Address nextAddr;Datatype *symbolType;- if (smallest == (MapEntry *)0 || smallest->getOffset() != 0)- nextAddr = addr + 32;- else {+ if (smallest != (MapEntry *)0 && smallest->getOffset() == 0) {symbolType = smallest->getSymbol()->getType();int8 structOff = addr.getOffset() - smallest->getAddr().getOffset();- int8 dummyOff;- int8 distance = symbolType->nearestArrayedComponentForward(structOff, max, &dummyOff, elSize);- if (distance >= 0) {- if (distance > max)- return -1;- *newoff = structOff;- return distance;+ // Look for arrayed component+ if (symbolType->nearestArrayedComponentForward(structOff, res)) {+ res.offset = structOff;+ return true;}- int8 sz = AddrSpace::byteToAddressInt(smallest->getSize(), spaceid->getWordSize());- nextAddr = smallest->getAddr() + sz;}- if (nextAddr < addr)- return -1; // Don't let the address wrap- smallest = scope->queryContainer(nextAddr,1,nullPoint);- if (smallest == (MapEntry *)0 || smallest->getOffset() != 0)- return -1;- symbolType = smallest->getSymbol()->getType();- *newoff = addr.getOffset() - smallest->getAddr().getOffset();- int8 dummyOff;- int8 distance = symbolType->nearestArrayedComponentForward(0, max, &dummyOff, elSize);- if (distance >= 0) {- distance = distance - *newoff;- if (distance > max)- return -1;- return distance;- }- return -1;++ // Look at Symbols in sequence after the initial address+ Address nextAddr = addr;+ do {+ smallest = scope->findSymbolAfter(nextAddr, nullPoint);+ if (smallest == (MapEntry *)0 || smallest->getOffset() != 0)+ return false;+ nextAddr = smallest->getAddr();+ symbolType = smallest->getSymbol()->getType();+ int8 structOff = addr.getOffset() - nextAddr.getOffset(); // Negative: addr is before start of Symbol+ if (symbolType->nearestArrayedComponentForward(0, res)) {+ res.distance = res.distance - structOff;+ res.offset = structOff;+ if (res.distance > MAX_ARRAY_SLACK_FORWARD)+ return false;+ // If the distance is bigger than the whole data-type, this reference will be treated as an array access+ if (res.distance <= symbolType->getSize() || symbolType->getMetatype() == TYPE_ARRAY)+ return true;+ }+ } while(nextAddr.getOffset() - addr.getOffset() < MAX_ARRAY_SLACK_FORWARD);+ return false;}-int8 TypeSpacebase::nearestArrayedComponentBackward(int8 off,int8 max,int8 *newoff,int8 *elSize) const+bool TypeSpacebase::nearestArrayedComponentBackward(int8 off,Nearest &res) const{- Datatype *subType = getSubType(off, newoff);- if (subType == (Datatype *)0)- return -1;- int8 dummyOff;- int8 distance = subType->nearestArrayedComponentBackward(*newoff,max,&dummyOff,elSize);- if (distance >= 0) {- if (distance > max)- return -1;- return distance;+ Scope *scope = getMap();+ uintb addrOff = AddrSpace::byteToAddress(off, spaceid->getWordSize()); // Convert from byte offset to address unit+ // It should always be the case that the given offset represents a full encoding of the+ // pointer, so the point of context is unused and the size is given as -1+ Address nullPoint;+ uintb fullEncoding;+ Address addr = glb->resolveConstant(spaceid, addrOff, -1, nullPoint, fullEncoding);++ int4 max = MAX_ARRAY_SLACK_BACKWARD;+ // Look for Symbol (with an array component) at the initial address+ MapEntry *smallest = scope->queryContainer(addr,1,nullPoint);+ Datatype *symbolType;+ if (smallest != (MapEntry *)0 && smallest->getOffset() == 0) {+ symbolType = smallest->getSymbol()->getType();+ int8 structOff = addr.getOffset() - smallest->getAddr().getOffset();+ if (symbolType->nearestArrayedComponentBackward(structOff, res)) {+ res.offset = structOff;+ return true;+ }}- return -1;+ else+ max = MAX_ARRAY_SLACK_FORWARD; // Search farther if there is no symbol at initial offset++ // Look at Symbols in sequence before the initial address+ Address nextAddr = addr;+ do {+ smallest = scope->findSymbolBefore(nextAddr, nullPoint);+ if (smallest == (MapEntry *)0 || smallest->getOffset() != 0)+ return false;+ symbolType = smallest->getSymbol()->getType();+ nextAddr = smallest->getAddr();+ int8 structOff = addr.getOffset() - nextAddr.getOffset();+ if (symbolType->nearestArrayedComponentBackward(symbolType->getSize(), res)) {+ res.distance = res.distance + structOff - symbolType->getSize();+ res.offset = structOff;+ if (res.distance > max)+ return false;+ // If the distance is bigger than the whole data-type, this reference will be treated as an array access+ if (res.distance <= symbolType->getSize() || symbolType->getMetatype() == TYPE_ARRAY)+ return true;+ }+ } while(addr.getOffset() - nextAddr.getOffset() < max);+ return false;}int4 TypeSpacebase::compare(const Datatype &op,int4 level) const@@ -3540,11 +3619,32 @@ int4 TypeSpacebase::compareDependency(const Datatype &op) constif (res != 0) return res;TypeSpacebase *tsb = (TypeSpacebase *) &op;if (spaceid != tsb->spaceid) return (spaceid < tsb->spaceid) ? -1:1;- if (localframe.isInvalid()) return 0; // Global space base- if (localframe != tsb->localframe) return (localframe < tsb->localframe) ? -1:1;+ if (scopeId != tsb->scopeId) return (scopeId < tsb->scopeId) ? -1:1;return 0;}+bool TypeSpacebase::isOffsetValid(int8 off,int8 extra,int8 multiplier) const++{+ int8 newoff;+ Datatype *subType = getSubType(off,&newoff);+ if (subType == (Datatype *)0 || newoff != 0)+ return false;+ if (subType->getMetatype() == TYPE_CODE) {+ // When the pointer targets inside a function, consider PTRSUB to be suitable when+ // the extra is non-negative, as subType->getSize() cannot be used (it is always 1).+ if (extra < 0)+ return false;+ }+ else {+ if (extra < 0 || extra >= subType->getSize()) {+ if (!subType->testForArraySlack(extra))+ return false;+ }+ }+ return true;+}+/// Return the Address being referred to by a specific offset relative/// to a pointer with \b this Datatype/// \param off is the offset relative to the pointer@@ -3556,7 +3656,7 @@ Address TypeSpacebase::getAddress(uintb off,int4 sz,const Address &point) const{uintb fullEncoding;// Currently a constant off of a global spacebase must be a full pointer encoding- if (localframe.isInvalid())+ if (scopeId == 0)sz = -1; // Set size to -1 to guarantee that full encoding recovery isn't launchedreturn glb->resolveConstant(spaceid,off,sz,point,fullEncoding);}@@ -3571,6 +3671,10 @@ void TypeSpacebase::encode(Encoder &encoder) constencoder.openElement(ELEM_TYPE);encodeBasic(metatype,-1,encoder);encoder.writeSpace(ATTRIB_SPACE, spaceid);+ Address localframe;+ Scope *scope = getMap();+ if (!scope->isGlobal())+ localframe = scope->getFunction()->getAddress();localframe.encode(encoder);encoder.closeElement(ELEM_TYPE);}@@ -3584,7 +3688,14 @@ void TypeSpacebase::decode(Decoder &decoder,TypeFactory &typegrp)// uint4 elemId = decoder.openElement();decodeBasic(decoder);spaceid = decoder.readSpace(ATTRIB_SPACE);- localframe = Address::decode(decoder);+ Address localframe = Address::decode(decoder);+ Scope *res = glb->symboltab->getGlobalScope();+ if (!localframe.isInvalid()) {+ Funcdata *fd = res->queryFunction(localframe);+ if (fd != (Funcdata *)0)+ res = fd->getScopeLocal();+ }+ scopeId = res->getId();// decoder.closeElement(elemId);}@@ -3998,7 +4109,8 @@ void TypeFactory::setFields(const vector<TypeField> &fd,const vector<TypeBitFieltree.erase(ot);ot->setFields(fd,bit,newSize,newAlign);ot->flags &= ~(uint4)Datatype::type_incomplete;- ot->flags |= (flags & (Datatype::opaque_string | Datatype::variable_length | Datatype::type_incomplete | Datatype::has_bitfields));+ ot->flags |= (flags & (Datatype::opaque_string | Datatype::variable_length | Datatype::type_incomplete |+ Datatype::has_bitfields));tree.insert(ot);recalcPointerSubmeta(ot, SUB_PTR);recalcPointerSubmeta(ot, SUB_PTR_STRUCT);@@ -4488,13 +4600,13 @@ TypePartialEnum *TypeFactory::getTypePartialEnum(TypeEnum *contain,int4 off,int4}/// Creates the special TypeSpacebase with an associated address space and scope-/// \param id is the address space-/// \param addr specifies the function scope, or isInvalid() for global scope+/// \param spc is the address space+/// \param scope is the id of the Scope/// \return the TypeSpacebase object-TypeSpacebase *TypeFactory::getTypeSpacebase(AddrSpace *id,const Address &addr)+TypeSpacebase *TypeFactory::getTypeSpacebase(AddrSpace *spc,uint8 scope){- TypeSpacebase tsb(id,addr,glb);+ TypeSpacebase tsb(spc,scope,glb);return (TypeSpacebase *) findAdd(tsb);}@@ -4649,7 +4761,7 @@ void TypeFactory::assignRawFields(TypeStruct *ct,vector<TypeField> &fd,vector<Tyint4 newSize;int4 newAlign;uint4 flags;- TypeStruct::assignFieldOffsets(fd,bit,newSize,newAlign,flags);+ TypeStruct::assignFieldOffsets(fd,bit,newSize,newAlign,flags,ct);glb->types->setFields(fd,bit,ct,newSize,newAlign,flags);}@@ -4663,8 +4775,9 @@ void TypeFactory::assignRawFields(TypeUnion *ct,vector<TypeField> &fd){int4 newSize;int4 newAlign;- TypeUnion::assignFieldOffsets(fd,newSize,newAlign,ct);- glb->types->setFields(fd,ct,newSize,newAlign,0);+ uint4 flags;+ TypeUnion::assignFieldOffsets(fd,newSize,newAlign,flags,ct);+ glb->types->setFields(fd,ct,newSize,newAlign,flags);}/// The indicated Datatype object is removed from this container.diff --git a/Ghidra/Features/Decompiler/src/decompile/cpp/type.hh b/Ghidra/Features/Decompiler/src/decompile/cpp/type.hhindex cc0951c206..7a9bc07eba 100644--- a/Ghidra/Features/Decompiler/src/decompile/cpp/type.hh+++ b/Ghidra/Features/Decompiler/src/decompile/cpp/type.hh@@ -154,6 +154,7 @@ extern type_class string2typeclass(const string &classstring);extern type_class metatype2typeclass(type_metatype meta);class Architecture; // Forward declarations+class Datatype;class PcodeOp;class Scope;class TypeStruct;@@ -165,6 +166,14 @@ struct DatatypeCompare;////// Used for symbols, function prototypes, type propagation etc.class Datatype {+public:+ /// \brief Response to a sub-component query+ class Nearest {+ public:+ int8 distance; ///< Distance in bytes of the sub-component to the query point+ int8 offset; ///< Offset from query point to sub-component start+ int4 elSize; ///< Element size responsive to query+ };protected:static sub_metatype base2sub[18];/// Boolean properties of datatypes@@ -207,7 +216,6 @@ protected:virtual Datatype *clone(void) const=0; ///< Clone the data-typestatic uint8 hashName(const string &nm); ///< Produce a data-type id by hashing the type namestatic uint8 hashSize(uint8 id,int4 size); ///< Reversibly hash size into id-protected:static int4 calcAlignSize(int4 sz,int4 align); ///< Calculate aligned size, given size and alignment of data-typepublic:/// \brief Construct the base data-type copying low-level properties of another@@ -248,8 +256,8 @@ public:virtual void printRaw(ostream &s) const; ///< Print a description of the type to streamvirtual const TypeField *findTruncation(int8 off,int4 sz,const PcodeOp *op,int4 slot,int8 &newoff) const;virtual Datatype *getSubType(int8 off,int8 *newoff) const; ///< Recover component data-type one-level down- virtual int8 nearestArrayedComponentForward(int8 off,int8 max,int8 *newoff,int8 *elSize) const;- virtual int8 nearestArrayedComponentBackward(int8 off,int8 max,int8 *newoff,int8 *elSize) const;+ virtual bool nearestArrayedComponentForward(int8 off,Nearest &res) const;+ virtual bool nearestArrayedComponentBackward(int8 off,Nearest &res) const;/// \brief Get number of bytes at the given offset that are padding///@@ -285,7 +293,8 @@ public:virtual int4 compare(const Datatype &op,int4 level) const; ///< Order types for propagationvirtual int4 compareDependency(const Datatype &op) const; ///< Compare for storage in tree structurevirtual void encode(Encoder &encoder) const; ///< Encode the data-type to a stream- virtual bool isPtrsubMatching(int8 off,int8 extra,int8 multiplier) const; ///< Is this data-type suitable as input to a CPUI_PTRSUB op+ virtual bool isPtrsubMatching(int8 off,int8 extra,int8 multiplier) const;+ virtual bool isOffsetValid(int8 off,int8 extra,int8 multiplier) const; ///< Is a given offset into \b this valid, given sub-offset infovirtual Datatype *getStripped(void) const; ///< Get a stripped version of \b this for formal use in formal declarationsvirtual Datatype *resolveInFlow(PcodeOp *op,int4 slot); ///< Tailor data-type propagation based on Varnode usevirtual Datatype* findResolve(const PcodeOp *op,int4 slot); ///< Find a previously resolved sub-type@@ -301,6 +310,9 @@ public:void encodeRef(Encoder &encoder) const; ///< Encode a reference of \b this to a streambool isPieceStructured(void) const; ///< Does \b this data-type consist of separate pieces?bool isPrimitiveWhole(void) const; ///< Is \b this made up of a single primitive+ bool nearestArrayedComponent(int8 off,uint4 arrayHint,int8 *newoff) const;+ bool testForArraySlack(int8 off); ///< Test if an \e out-of-bounds offset makes sense as array slack+static uint4 encodeIntegerFormat(const string &val);static string decodeIntegerFormat(uint4 val);};@@ -448,10 +460,9 @@ class TypePointer : public Datatype {protected:friend class TypeFactory;Datatype *ptrto; ///< Type being pointed to- AddrSpace *spaceid; ///< If non-null, the address space \b this is intented to point into+ AddrSpace *spaceid; ///< If non-null, the address space \b this is intended to point intoTypePointer *truncate; ///< Truncated form of the pointer (if not null)uint4 wordsize; ///< What size unit does the pointer address- static bool testForArraySlack(Datatype *dt,int8 off); ///< Test if an \e out-of-bounds offset makes sense as array slackvoid decode(Decoder &decoder,TypeFactory &typegrp); ///< Restore \b this pointer data-type from a streamvoid calcSubmeta(void); ///< Calculate specific submeta for \b this pointervoid calcTruncate(TypeFactory &typegrp); // Assign a truncated pointer subcomponent if necessary@@ -505,8 +516,8 @@ public:Datatype *getSubEntry(int4 off,int4 sz,int4 *newoff,int4 *el) const; ///< Figure out what a byte range overlapsvirtual void printRaw(ostream &s) const;virtual Datatype *getSubType(int8 off,int8 *newoff) const;- virtual int8 nearestArrayedComponentForward(int8 off,int8 max,int8 *newoff,int8 *elSize) const;- virtual int8 nearestArrayedComponentBackward(int8 off,int8 max,int8 *newoff,int8 *elSize) const;+ virtual bool nearestArrayedComponentForward(int8 off,Nearest &res) const;+ virtual bool nearestArrayedComponentBackward(int8 off,Nearest &res) const;virtual int4 getHoleSize(int4 off) const;virtual int4 numDepend(void) const { return 1; }virtual Datatype *getDepend(int4 index) const { return arrayof; }@@ -515,6 +526,7 @@ public:virtual int4 compareDependency(const Datatype &op) const; // For tree structurevirtual Datatype *clone(void) const { return new TypeArray(*this); }virtual void encode(Encoder &encoder) const;+ virtual bool isOffsetValid(int8 off,int8 extra,int8 multiplier) const;virtual Datatype *resolveInFlow(PcodeOp *op,int4 slot);virtual Datatype* findResolve(const PcodeOp *op,int4 slot);virtual int4 findCompatibleResolve(Datatype *ct) const;@@ -592,8 +604,8 @@ public:bool hasBitFieldsInRange(int4 offset,int4 sz) const; ///< Return \b true if \b this structure has 1 or more bitfields in the given byte rangevirtual const TypeField *findTruncation(int8 off,int4 sz,const PcodeOp *op,int4 slot,int8 &newoff) const;virtual Datatype *getSubType(int8 off,int8 *newoff) const;- virtual int8 nearestArrayedComponentForward(int8 off,int8 max,int8 *newoff,int8 *elSize) const;- virtual int8 nearestArrayedComponentBackward(int8 off,int8 max,int8 *newoff,int8 *elSize) const;+ virtual bool nearestArrayedComponentForward(int8 off,Nearest &res) const;+ virtual bool nearestArrayedComponentBackward(int8 off,Nearest &res) const;virtual int4 getHoleSize(int4 off) const;virtual int4 numDepend(void) const { return field.size(); }virtual Datatype *getDepend(int4 index) const { return field[index].type; }@@ -601,10 +613,12 @@ public:virtual int4 compareDependency(const Datatype &op) const; // For tree structurevirtual Datatype *clone(void) const { return new TypeStruct(*this); }virtual void encode(Encoder &encoder) const;+ virtual bool isOffsetValid(int8 off,int8 extra,int8 multiplier) const;virtual Datatype *resolveInFlow(PcodeOp *op,int4 slot);virtual Datatype* findResolve(const PcodeOp *op,int4 slot);virtual int4 findCompatibleResolve(Datatype *ct) const;- static void assignFieldOffsets(vector<TypeField> &list,vector<TypeBitField> &bitlist,int4 &newSize,int4 &newAlign,uint4 &flags);+ static void assignFieldOffsets(vector<TypeField> &list,vector<TypeBitField> &bitlist,int4 &newSize,int4 &newAlign,+ uint4 &flags,const TypeStruct *st);static int4 scoreSingleComponent(Datatype *parent,PcodeOp *op,int4 slot); ///< Determine best type fit for given PcodeOp use};@@ -624,6 +638,8 @@ public:const TypeField *getField(int4 i) const { return &field[i]; } ///< Get the i-th field of the unionvirtual const TypeField *findTruncation(int8 offset,int4 sz,const PcodeOp *op,int4 slot,int8 &newoff) const;// virtual Datatype *getSubType(int8 off,int8 *newoff) const;+ virtual bool nearestArrayedComponentForward(int8 off,Nearest &res) const;+ virtual bool nearestArrayedComponentBackward(int8 off,Nearest &res) const;virtual int4 numDepend(void) const { return field.size(); }virtual Datatype *getDepend(int4 index) const { return field[index].type; }virtual int4 compare(const Datatype &op,int4 level) const; // For tree structure@@ -634,7 +650,8 @@ public:virtual Datatype* findResolve(const PcodeOp *op,int4 slot);virtual int4 findCompatibleResolve(Datatype *ct) const;virtual const TypeField *resolveTruncation(int8 offset,PcodeOp *op,int4 slot,int8 &newoff);- static void assignFieldOffsets(vector<TypeField> &list,int4 &newSize,int4 &newAlign,TypeUnion *tu); ///< Assign field offsets+ static void assignFieldOffsets(vector<TypeField> &list,int4 &newSize,int4 &newAlign,uint4 &flags,+ const TypeUnion *tu); ///< Assign field offsets};/// \brief A data-type thats holds part of a TypeEnum and possible additional padding@@ -787,6 +804,7 @@ public:virtual int4 compareDependency(const Datatype &op) const;virtual Datatype *clone(void) const { return new TypeCode(*this); }virtual void encode(Encoder &encoder) const;+ virtual bool isOffsetValid(int8 off,int8 extra,int8 multiplier) const;};/// \brief Special Datatype object used to describe pointers that index into the symbol table@@ -795,28 +813,31 @@ public:/// This facilitates type propagation from local symbols into the stack space and/// from global symbols into the RAM space.class TypeSpacebase : public Datatype {+ static constexpr int4 MAX_ARRAY_SLACK_FORWARD = 128; ///< Maximum bytes to search forward for an array+ static constexpr int4 MAX_ARRAY_SLACK_BACKWARD = 8; ///< Maximum bytes to search backward for an arrayfriend class TypeFactory;AddrSpace *spaceid; ///< The address space we are treating as a structure- Address localframe; ///< Address of function whose symbol table is indexed (or INVALID for "global")+ uint8 scopeId; ///< Id of the Scope \b this data-type is associated withArchitecture *glb; ///< Architecture for accessing symbol tablevoid decode(Decoder &decoder,TypeFactory &typegrp); ///< Restore \b this spacebase data-type from a streampublic:/// Construct from another TypeSpacebaseTypeSpacebase(const TypeSpacebase &op) : Datatype(op) {- spaceid = op.spaceid; localframe=op.localframe; glb=op.glb;+ spaceid = op.spaceid; scopeId = op.scopeId; glb=op.glb;}/// Constructor for use with decode- TypeSpacebase(Architecture *g) : Datatype(0,1,TYPE_SPACEBASE) { spaceid = (AddrSpace *)0; glb = g; }+ TypeSpacebase(Architecture *g) : Datatype(0,1,TYPE_SPACEBASE) { spaceid = (AddrSpace *)0; glb = g; scopeId = 0; }/// Construct given an address space, scope, and architecture- TypeSpacebase(AddrSpace *id,const Address &frame,Architecture *g)- : Datatype(0,1,TYPE_SPACEBASE), localframe(frame) { spaceid = id; glb = g; }+ TypeSpacebase(AddrSpace *id,uint8 scope,Architecture *g)+ : Datatype(0,1,TYPE_SPACEBASE) { spaceid = id; glb = g; scopeId = scope; }Scope *getMap(void) const; ///< Get the symbol table indexed by \b thisAddress getAddress(uintb off,int4 sz,const Address &point) const; ///< Construct an Address given an offsetvirtual Datatype *getSubType(int8 off,int8 *newoff) const;- virtual int8 nearestArrayedComponentForward(int8 off,int8 max,int8 *newoff,int8 *elSize) const;- virtual int8 nearestArrayedComponentBackward(int8 off,int8 max,int8 *newoff,int8 *elSize) const;+ virtual bool nearestArrayedComponentForward(int8 off,Nearest &res) const;+ virtual bool nearestArrayedComponentBackward(int8 off,Nearest &res) const;virtual int4 compare(const Datatype &op,int4 level) const;virtual int4 compareDependency(const Datatype &op) const; // For tree structure+ virtual bool isOffsetValid(int8 off,int8 extra,int8 multiplier) const;virtual Datatype *clone(void) const { return new TypeSpacebase(*this); }virtual void encode(Encoder &encoder) const;};@@ -905,7 +926,7 @@ public:TypePartialUnion *getTypePartialUnion(TypeUnion *contain,int4 off,int4 sz); ///< Create a partial unionTypeEnum *getTypeEnum(const string &n); ///< Create an (empty) enumerationTypePartialEnum *getTypePartialEnum(TypeEnum *contain,int4 off,int4 sz); ///< Create a partial enumeration- TypeSpacebase *getTypeSpacebase(AddrSpace *id,const Address &addr); ///< Create a "spacebase" type+ TypeSpacebase *getTypeSpacebase(AddrSpace *spc,uint8 scope); ///< Create a "spacebase" typeTypeCode *getTypeCode(const PrototypePieces &proto); ///< Create a "function" datatypeDatatype *getTypedef(Datatype *ct,const string &name,uint8 id,uint4 format); ///< Create a new \e typedef data-typeTypePointerRel *getTypePointerRel(TypePointer *parentPtr,Datatype *ptrTo,int4 off); ///< Get pointer offset relative to a containerdiff --git a/Ghidra/Features/Decompiler/src/decompile/cpp/varmap.cc b/Ghidra/Features/Decompiler/src/decompile/cpp/varmap.ccindex 6d51a72cd2..4fe7abd530 100644--- a/Ghidra/Features/Decompiler/src/decompile/cpp/varmap.cc+++ b/Ghidra/Features/Decompiler/src/decompile/cpp/varmap.cc@@ -68,6 +68,7 @@ bool RangeHint::reconcile(const RangeHint *b) constb = a; // Make sure b is smallesta = tmp;}+ if (b->isTypeLock()) return false;int8 mod = (b->sstart - a->sstart) % a->type->getAlignSize();if (mod < 0)mod += a->type->getAlignSize();@@ -86,7 +87,6 @@ bool RangeHint::reconcile(const RangeHint *b) constif (b->rangeType == RangeType::open && b->isConstAbsorbable(a))return true;- if (b->isTypeLock()) return false;type_metatype meta = a->type->getMetatype();if (meta != TYPE_STRUCT && meta != TYPE_UNION) {if (meta != TYPE_ARRAY || ((TypeArray *)(a->type))->getBase()->getMetatype() != TYPE_UNKNOWN)@@ -97,6 +97,8 @@ bool RangeHint::reconcile(const RangeHint *b) constif (meta == TYPE_UNKNOWN || meta == TYPE_INT || meta == TYPE_UINT) {return true;}+ if (meta == TYPE_ARRAY && ((TypeArray *)(b->type))->getBase()->getMetatype() == TYPE_UNKNOWN)+ return true;return false;}@@ -170,6 +172,10 @@ bool RangeHint::preferred(const RangeHint *b,bool reconcile) constbool RangeHint::attemptJoin(RangeHint *b){+ if (b->isBackfill()) {+ if (attemptBackfill(b))+ return true;+ }if (rangeType != open) return false;if (b->rangeType == endpoint) return false; // Don't merge with bounding rangeif (isConstAbsorbable(b)) {@@ -210,6 +216,56 @@ bool RangeHint::attemptJoin(RangeHint *b)return true;}+/// Move in increments of the data-type aligned size.+/// \param point is the offset to backfill to+void RangeHint::backfillToPoint(intb point)++{+ intb diff = sstart - point;+ intb num = diff / type->getAlignSize();+ intb amount = num * type->getAlignSize();+ sstart -= amount;+ start -= amount;+}++/// \param b is the hint to backfill+/// \return \b true if we treat \b as having been absorbed into \b this+bool RangeHint::attemptBackfill(RangeHint *b)++{+ intb rightedge = sstart + size;+ if (b->sstart < rightedge)+ return true;+ if (rangeType != open) {+ b->backfillToPoint(rightedge); // If not open, backfill all the way to right edge+ return false;+ }+ if (isBackfill())+ return true; // Throw out second backfill if there are two in a row+ b->backfillToPoint((b->sstart - rightedge)/2); // Backfill half way into open space+ return true;+}++/// The start edge of \b this hint is moved backwards by element sizes (up to \b maxElements).+/// If there is no start that lies inside the range, no change is made.+/// \param range is the given range to fill+/// \param maxElements is the maximum number of array elements to fill+void RangeHint::backfillOpen(const Range &range,int4 maxElements)++{+ if (start < range.getFirst()) return;+ uintb diff = start - range.getFirst();+ uintb num = diff / type->getAlignSize();+ if (num > maxElements)+ num = maxElements;+ uintb amount = num * type->getAlignSize();+ uintb tmpStart = start - amount;+ if (!range.contains(Address(range.getSpace(),tmpStart)))+ return;+ start = tmpStart;+ sstart -= amount;+}+/// Absorb details of the other RangeHint into \b this, except for the data-type. Inherit an \e open range/// type and any indexing information. The data-type for \b this is assumed to be compatible and preferred/// over the other data-type and is not changed.@@ -262,6 +318,8 @@ bool RangeHint::merge(RangeHint *b,AddrSpace *space,TypeFactory *typeFactory)bool didReconcile;int4 resType; // 0=this, 1=b, 2=confuse+ if (b->rangeType == endpoint)+ throw LowlevelError("RangeHint overlaps endpoint");if (contain(b)) { // Does one range contain the otherdidReconcile = reconcile(b); // Can the data-type layout be reconciledif (!didReconcile && start != b->start)@@ -347,6 +405,7 @@ ScopeLocal::ScopeLocal(uint8 id,AddrSpace *spc,Funcdata *fd,Architecture *g) : SrangeLocked = false;stackGrowsNegative = true;overlapProblems = false;+ openParamRefs = false;restrictScope(fd);}@@ -392,13 +451,28 @@ void ScopeLocal::annotateRawStackPtr(void)if (spVn == (Varnode *)0) return;list<PcodeOp *>::const_iterator iter;vector<PcodeOp *> refOps;+ bool sawRaw = false;for(iter=spVn->beginDescend();iter!=spVn->endDescend();++iter) {PcodeOp *op = *iter;if (op->getEvalType() == PcodeOp::special && !op->isCall()) continue;OpCode opc = op->code();- if (opc == CPUI_INT_ADD || opc == CPUI_PTRSUB || opc == CPUI_PTRADD)+ if (opc == CPUI_PTRSUB) {+ if (op->getIn(1)->getOffset() == 0)+ sawRaw = true;+ continue;+ }+ if (opc == CPUI_INT_ADD || opc == CPUI_PTRADD)continue;refOps.push_back(op);+ sawRaw = true;+ }+ if (sawRaw) {+ // Make sure a symbol exists+ Address zeroaddr(space,0);+ if (queryContainer(zeroaddr, 1, Address()) == (MapEntry *)0) {+ Datatype *ct = fd->getArch()->types->getBase(1,TYPE_UNKNOWN);+ addSymbol("",ct,zeroaddr,Address());+ }}for(int4 i=0;i<refOps.size();++i) {PcodeOp *op = refOps[i];@@ -862,11 +936,12 @@ uintb AliasChecker::gatherOffset(Varnode *vn)/// \param rn is the subset of addresses within the address space to analyze/// \param pm is subset of ranges within the address space considered to be parameters/// \param dt is the default data-type-MapState::MapState(AddrSpace *spc,const RangeList &rn,- const RangeList &pm,Datatype *dt) : range(rn)+MapState::MapState(AddrSpace *spc,const RangeList &rn,const RangeList &pm,Datatype *dt)+ : range(rn), paramRange(pm){spaceid = spc;defaultType = dt;+ paramRangeHit = false;set<Range>::const_iterator pmiter;for(pmiter=pm.begin();pmiter!=pm.end();++pmiter) {AddrSpace *pmSpc = (*pmiter).getSpace();@@ -887,6 +962,53 @@ MapState::~MapState(void)delete *riter;}+/// If the initial offset of the hint is in range, truncate the data-type so it fits. Otherwise,+/// assuming the hint is out of bounds due to array slack, try to shift it into the nearest legal range.+/// If the hint is shifted backwards, it is converted into a \b backfill range.+/// The hint is shifted by a multiple of the data-type aligned size.+/// \param st is the starting offset of the range+/// \param ct is the data-type spanning the range+/// \param fl is additional boolean properties of the range+/// \return \b true if the hint was successfully adjusted to be in range+bool MapState::adjustOutOfRange(uintb &st,Datatype *&ct,uint4 &fl)++{+ if (paramRange.inRange(Address(spaceid,st),ct->getSize())) {+ paramRangeHit = true;+ return false;+ }+ if (defaultType->getSize() < ct->getSize() && range.inRange(Address(spaceid,st),defaultType->getSize())) {+ // Range starts valid but crosses over out of bounds+ ct = defaultType; // Convert to unknown array extending to boundary+ return true;+ }+ if (st == 0)+ return false; // Let annotateRawStackPtr handle this offset+ // Assume this is an array reference with a constant offset folded in+ // Try to shift the reference into the valid range+ const Range *near = range.getNearestRange(spaceid, st);+ if (near == (const Range *)0)+ return false;+ if (near->getLast() < st) {+ uint8 num = (st - near->getLast() - 1) / ct->getAlignSize();+ st -= ct->getAlignSize() * (num + 1);+ if (!near->contains(Address(spaceid,st + ct->getSize() -1)))+ st -= ct->getAlignSize();+ if (!near->contains(Address(spaceid,st)))+ return false;+ fl |= RangeHint::backfill;+ }+ else {+ uint8 num = (near->getFirst() - st + 1) / ct->getAlignSize();+ st += ct->getAlignSize() * (num + 1);+ if (!near->contains(Address(spaceid,st)))+ return false;+ if (!near->contains(Address(spaceid,st + ct->getSize() -1)))+ return false;+ }+ return true;+}+/// A specific range of bytes is described for the hint, given a starting offset and other information./// The size of range can be fixed or open-ended. A putative data-type can be provided./// \param st is the starting offset of the range@@ -899,18 +1021,21 @@ void MapState::addRange(uintb st,Datatype *ct,uint4 fl,RangeHint::RangeType rt,i{if ((ct == (Datatype *)0)||(ct->getSize()==0)) // Must have a real typect = defaultType;- int4 sz = ct->getSize();- if (!range.inRange(Address(spaceid,st),sz))- return;+ if (!range.inRange(Address(spaceid,st),ct->getSize())) {+ if (rt != RangeHint::open)+ return;+ if (!adjustOutOfRange(st, ct, fl))+ return;+ }intb sst = (intb)AddrSpace::byteToAddress(st,spaceid->getWordSize());sst = sign_extend(sst,spaceid->getAddrSize()*8-1);sst = (intb)AddrSpace::addressToByte(sst,spaceid->getWordSize());- RangeHint *newRange = new RangeHint(st,sz,sst,ct,fl,rt,hi);+ RangeHint *newRange = new RangeHint(st,ct->getSize(),sst,ct,fl,rt,hi);maplist.push_back(newRange);#ifdef OPACTION_DEBUGif (debugon) {ostringstream s;- s << "Add Range: " << hex << st << ":" << dec << sz;+ s << "Add Range: " << hex << st << ":" << dec << ct->getSize();s << " ";ct->printRaw(s);s << endl;@@ -1080,6 +1205,12 @@ bool MapState::initialize(void)stable_sort(maplist.begin(),maplist.end(),RangeHint::compareRanges);reconcileDatatypes();iter = maplist.begin();+ RangeHint *first = *iter;+ if (first->isBackfill()) { // If there is an initial backfill into open space+ const Range *sub = range.getRange(spaceid,first->start);+ if (sub != (const Range *)0)+ first->backfillOpen(*sub,127); // go ahead and fill it now+ }return true;}@@ -1269,11 +1400,9 @@ void ScopeLocal::restructureVarnode(bool aliasyes)state.gatherVarnodes(*fd); // Gather stack type information from varnodesstate.gatherOpen(*fd);state.gatherSymbols(maptable[space->getIndex()]);+ openParamRefs = state.hasParamRangeHit();overlapProblems = restructure(state);- // At some point, processing mapped input symbols may be folded- // into the above gather/restructure process, but for now- // we just define fake symbols so that mark_unaliased will workclearUnlockedCategory(Symbol::function_parameter);clearCategory(Symbol::fake_input);fakeInputSymbols();@@ -1313,8 +1442,11 @@ bool ScopeLocal::restructure(MapState &state)}else {if (!cur.attemptJoin(next)) {- if (cur.rangeType == RangeHint::open)+ if (cur.rangeType == RangeHint::open) {cur.size = next->sstart-cur.sstart;+ if (cur.size < 0)+ cur.size = 0x7fffffff; // Maximum size for a data-type+ }if (adjustFit(cur))createEntry(cur);cur = *next;@@ -1391,7 +1523,7 @@ void ScopeLocal::markUnaliased(const vector<uintb> &alias)/// This assigns a Symbol to any input Varnode stored in our address space, which could be/// a parameter but isn't in the formal prototype of the function (these should already be in-/// the scope marked as category '0').+/// the scope marked as category 'function_parameter').void ScopeLocal::fakeInputSymbols(void){diff --git a/Ghidra/Features/Decompiler/src/decompile/cpp/varmap.hh b/Ghidra/Features/Decompiler/src/decompile/cpp/varmap.hhindex 5143b24b18..29cf5b61bc 100644--- a/Ghidra/Features/Decompiler/src/decompile/cpp/varmap.hh+++ b/Ghidra/Features/Decompiler/src/decompile/cpp/varmap.hh@@ -4,9 +4,9 @@* Licensed under the Apache License, Version 2.0 (the "License");* you may not use this file except in compliance with the License.* You may obtain a copy of the License at- *+ ** http://www.apache.org/licenses/LICENSE-2.0- *+ ** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.@@ -100,7 +100,8 @@ public:/// \brief Boolean properties for the rangeenum {typelock = 1, ///< Data-type for the range is locked- copy_constant = 2 ///< Only a constant is COPYed into the range+ copy_constant = 2, ///< Only a constant is COPYed into the range+ backfill = 4 ///< Reference is at end of the array, try to backfill};private:uintb start; ///< Starting offset of \b this range of bytes@@ -110,16 +111,20 @@ private:uint4 flags; ///< Additional boolean properties of this rangeRangeType rangeType; ///< The type of rangeint4 highind; ///< Minimum upper bound on the array index (if \b this is \e open)+ void backfillToPoint(intb point); ///< Move \b start backward as close as possible to pointpublic:RangeHint(void) {} ///< Uninitialized constructorRangeHint(uintb st,int4 sz,intb sst,Datatype *ct,uint4 fl,RangeType rt,int4 hi) {start=st; size=sz; sstart=sst; type=ct; flags=fl; rangeType = rt; highind=hi; } ///< Initialized constructorbool isTypeLock(void) const { return ((flags & typelock)!=0); } ///< Is the data-type for \b this range locked+ bool isBackfill(void) const { return ((flags & backfill)!=0); } ///< Does \b this hint want to back fill its data-typebool isConstAbsorbable(const RangeHint *b) const; ///< Can another range by absorbed into \b this as a constantbool reconcile(const RangeHint *b) const;bool contain(const RangeHint *b) const;bool preferred(const RangeHint *b,bool reconcile) const;bool attemptJoin(RangeHint *b); ///< Try to concatenate another RangeHint onto \b this+ bool attemptBackfill(RangeHint *b); ///< Backfill another hint into space after \b this+ void backfillOpen(const Range &range,int4 maxElements); ///< Backfill \b this into given range up to a maximumvoid absorb(RangeHint *b); ///< Absorb the other RangeHint into \b thisbool merge(RangeHint *b,AddrSpace *space,TypeFactory *typeFactory); ///< Try to form the union of \b this with another RangeHintint4 compare(const RangeHint &op2) const; ///< Order \b this with another RangeHint@@ -174,11 +179,14 @@ public:class MapState {AddrSpace *spaceid; ///< The address space being analyzedRangeList range; ///< The subset of ranges, within the whole address space to analyze+ RangeList paramRange; ///< Part of address space dedicated to parametersvector<RangeHint *> maplist; ///< The list of collected RangeHintsvector<RangeHint *>::iterator iter; ///< The current iterator into the RangeHintsDatatype *defaultType; ///< The default data-type to use for RangeHintsAliasChecker checker; ///< A collection of pointer Varnodes into our address space+ bool paramRangeHit; ///< \b true if we see open reference to stack region reserved for parametersvoid addGuard(const LoadGuard &guard,OpCode opc,TypeFactory *typeFactory); ///< Add LoadGuard record as a hint to the collection+ bool adjustOutOfRange(uintb &st,Datatype *&ct,uint4 &fl); ///< Try to adjust a hint that is out of rangevoid addRange(uintb st,Datatype *ct,uint4 fl,RangeHint::RangeType rt,int4 hi); ///< Add a hint to the collectionvoid addFixedType(uintb start,Datatype *ct,uint4 flags,TypeFactory *types); ///< Add a fixed reference to a specific data-typevoid reconcileDatatypes(void); ///< Decide on data-type for RangeHints at the same address@@ -193,6 +201,7 @@ public:MapState(AddrSpace *spc,const RangeList &rn,const RangeList &pm,Datatype *dt); ///< Constructor~MapState(void); ///< Destructorbool initialize(void); ///< Initialize the hint collection for iteration+ bool hasParamRangeHit(void) const { return paramRangeHit; } ///< Return \b true if reference into parameter stack region has been seenvoid sortAlias(void) { checker.sortAlias(); } ///< Sort the alias starting offsetsconst vector<uintb> &getAlias(void) { return checker.getAlias(); } ///< Get the list of alias starting offsetsvoid gatherSymbols(const EntryMap *rangemap); ///< Add Symbol information as hints to the collection@@ -219,6 +228,7 @@ class ScopeLocal : public ScopeInternal {bool stackGrowsNegative; ///< Marked \b true if the stack is considered to \e grow towards smaller offsetsbool rangeLocked; ///< True if the subset of addresses \e mapped to \b this scope has been lockedbool overlapProblems; ///< True if the last \b restructure had overlapping variable problems+ bool openParamRefs; ///< True if we have seen references into the stack region reserved for parametersbool adjustFit(RangeHint &a) const; ///< Make the given RangeHint fit in the current Symbol mapvoid createEntry(const RangeHint &a); ///< Create a Symbol entry corresponding to the given (fitted) RangeHintbool restructure(MapState &state); ///< Merge hints into a formal Symbol layout of the address space@@ -245,6 +255,8 @@ public:bool isUnmappedUnaliased(Varnode *vn) const; ///< Check if a given unmapped Varnode should be treated as unaliased.+ bool hasOpenParamRefs(void) const { return openParamRefs; } ///< Return \b true if we have seen refs into parameter region+void markNotMapped(AddrSpace *spc,uintb first,int4 sz,bool param); ///< Mark a specific address range is not mapped// Routines that are specific to one address spacediff --git a/Ghidra/Features/Decompiler/src/decompile/datatests/stackcorner.xml b/Ghidra/Features/Decompiler/src/decompile/datatests/stackcorner.xmlnew file mode 100644index 0000000000..dbeeee8126--- /dev/null+++ b/Ghidra/Features/Decompiler/src/decompile/datatests/stackcorner.xml@@ -0,0 +1,56 @@+<decompilertest>+ <!--+ arraybottom is a function with an array at the bottom with a hidden negative index.+ paramnodirect has a stack parameter accessed only via pointer+ positivestack accesses array in the parameter region of the stack+ arrayslack has an array index with a negative adjustment+ -->+<binaryimage arch="x86:LE:64:default:gcc">+<bytechunk space="ram" offset="0x100000" readonly="true">+534883ec444889fbc704241400000048+8d3c2466e8e90f488d7c240466e8e80f+c7449c4464000000488d7c2404e8ce0f+00004883c4445bc35301f701d701cf44+01c7428d1c0f488d7c2410e8b00f0000+89d85bc34883ec08488d7c2410e89e0f+00004883c408c3534883c4804889fb48+89e7e8910f0000c7449cf82c01000048+89e7e8790f00004883ec805bc3+</bytechunk>+<symbol space="ram" offset="0x100000" name="arraybottom"/>+<symbol space="ram" offset="0x100038" name="paramnodirect"/>+<symbol space="ram" offset="0x100054" name="positivestack"/>+<symbol space="ram" offset="0x100067" name="arrayslack"/>+</binaryimage>+<script>+ <com>map fun r0x101000 read</com>+ <com>map fun r0x101008 write</com>+ <com>parse line extern void read(int4 *ptr);</com>+ <com>parse line extern void write(int4 *ptr);</com>+ <com>lo fu arraybottom</com>+ <com>dec</com>+ <com>print C</com>+ <com>lo fu paramnodirect</com>+ <com>dec</com>+ <com>print C</com>+ <com>lo fu positivestack</com>+ <com>dec</com>+ <com>print C</com>+ <com>lo fu arrayslack</com>+ <com>dec</com>+ <com>print C</com>+ <com>quit</com>+</script>+<stringmatch name="Stack corner #1" min="1" max="1">int4 aiStack_48 \[16\];</stringmatch>+<stringmatch name="Stack corner #2" min="1" max="1">iStack_4c = 0x14;</stringmatch>+<stringmatch name="Stack corner #3" min="1" max="1">aiStack_48\[param_1 \+ 0x10\] = 100;</stringmatch>+<stringmatch name="Stack corner #4" min="1" max="1">int4 paramnodirect\(int4 param_1,int4 param_2,int4 param_3,int4 param_4,int4 param_5,int4 param_6,+ int4 param_7\)</stringmatch>+<stringmatch name="Stack corner #5" min="1" max="1">read\(&param_7\);</stringmatch>+<stringmatch name="Stack corner #6" min="1" max="1">return param_. \+ param_. \+ param_. \+ param_. \+ param_. \+ param_.;</stringmatch>+<stringmatch name="Stack corner #7" min="1" max="1">int4 iStack0+8;</stringmatch>+<stringmatch name="Stack corner #8" min="1" max="1">read\(&iStack0+8\);</stringmatch>+<stringmatch name="Stack corner #9" min="1" max="1">int4 aiStack_88 \[32\];</stringmatch>+<stringmatch name="Stack corner #10" min="1" max="1">write\(aiStack_88\);</stringmatch>+<stringmatch name="Stack corner #11" min="1" max="1">aiStack_88\[param_1 \+ -2\] = 300;</stringmatch>+</decompilertest>