Ghidra is a software reverse engineering (SRE) framework
GP-7010 Add support for CALLOTHER -> CALL overrides
caheckmanda5c0f2f385e
diff --git a/Ghidra/Features/Decompiler/certification.manifest b/Ghidra/Features/Decompiler/certification.manifestindex ab4d90c4ba..45c2b37745 100644--- a/Ghidra/Features/Decompiler/certification.manifest+++ b/Ghidra/Features/Decompiler/certification.manifest@@ -65,6 +65,7 @@ src/decompile/datatests/noforloop_globcall.xml||GHIDRA||||END|src/decompile/datatests/noforloop_iterused.xml||GHIDRA||||END|src/decompile/datatests/offsetarray.xml||GHIDRA||||END|src/decompile/datatests/orcompare.xml||GHIDRA||||END|+src/decompile/datatests/overridedest.xml||GHIDRA||||END|src/decompile/datatests/packstructaccess.xml||GHIDRA||||END|src/decompile/datatests/partialmerge.xml||GHIDRA||||END|src/decompile/datatests/partialsplit.xml||GHIDRA||||END|diff --git a/Ghidra/Features/Decompiler/src/decompile/cpp/architecture.cc b/Ghidra/Features/Decompiler/src/decompile/cpp/architecture.ccindex 085bf15e5a..6ddf1d140a 100644--- a/Ghidra/Features/Decompiler/src/decompile/cpp/architecture.cc+++ b/Ghidra/Features/Decompiler/src/decompile/cpp/architecture.cc@@ -455,14 +455,27 @@ void Architecture::decodeFlowOverride(Decoder &decoder)uint4 elemId = decoder.openElement(ELEM_FLOWOVERRIDELIST);for(;;) {uint4 subId = decoder.openElement();- if (subId != ELEM_FLOW) break;- string flowType = decoder.readString(ATTRIB_TYPE);- Address funcaddr = Address::decode(decoder);- Address overaddr = Address::decode(decoder);- Funcdata *fd = symboltab->getGlobalScope()->queryFunction(funcaddr);- if (fd != (Funcdata *)0)- fd->getOverride().insertFlowOverride(overaddr,Override::stringToType(flowType));- decoder.closeElement(subId);+ if (subId == ELEM_FLOW) {+ string flowType = decoder.readString(ATTRIB_TYPE);+ Address funcaddr = Address::decode(decoder);+ Address overaddr = Address::decode(decoder);+ Funcdata *fd = symboltab->getGlobalScope()->queryFunction(funcaddr);+ if (fd != (Funcdata *)0)+ fd->getOverride().insertFlowOverride(overaddr,flowType);+ decoder.closeElement(subId);+ }+ else if (subId == ELEM_CALLDEST) {+ string flowType = decoder.readString(ATTRIB_TYPE);+ Address funcaddr = Address::decode(decoder);+ Address overaddr = Address::decode(decoder);+ Address destaddr = Address::decode(decoder);+ Funcdata *fd = symboltab->getGlobalScope()->queryFunction(funcaddr);+ if (fd != (Funcdata *)0)+ fd->getOverride().insertDestinationOverride(overaddr, destaddr, flowType);+ decoder.closeElement(subId);+ }+ else+ break;}decoder.closeElement(elemId);}diff --git a/Ghidra/Features/Decompiler/src/decompile/cpp/coreaction.cc b/Ghidra/Features/Decompiler/src/decompile/cpp/coreaction.ccindex 8e2af7ad46..ed1728bee5 100644--- a/Ghidra/Features/Decompiler/src/decompile/cpp/coreaction.cc+++ b/Ghidra/Features/Decompiler/src/decompile/cpp/coreaction.cc@@ -565,9 +565,12 @@ bool ActionLaneDivide::processVarnode(Funcdata &data,Varnode *vn,const LanedRegicollectLaneSizes(vn,lanedRegister,checkLanes);else {int4 defaultSize = data.getArch()->types->getSizeOfPointer(); // Default lane size- if (defaultSize != 4)- defaultSize = 8;- checkLanes.addLaneSize(defaultSize);+ if (defaultSize == 4 && lanedRegister.allowedLane(4))+ checkLanes.addLaneSize(4);+ else if (lanedRegister.allowedLane(8))+ checkLanes.addLaneSize(8);+ else if (lanedRegister.allowedLane(4))+ checkLanes.addLaneSize(4);}LanedRegister::const_iterator enditer = checkLanes.end();for(LanedRegister::const_iterator iter=checkLanes.begin();iter!=enditer;++iter) {diff --git a/Ghidra/Features/Decompiler/src/decompile/cpp/database.cc b/Ghidra/Features/Decompiler/src/decompile/cpp/database.ccindex c5473871b1..0125d99de2 100644--- a/Ghidra/Features/Decompiler/src/decompile/cpp/database.cc+++ b/Ghidra/Features/Decompiler/src/decompile/cpp/database.cc@@ -567,7 +567,7 @@ void FunctionSymbol::encode(Encoder &encoder) const{if (fd != (Funcdata *)0)- fd->encode(encoder,symbolId,false); // Save the function itself+ fd->encode(encoder,symbolId,false,true); // Save the function itselfelse {encoder.openElement(ELEM_FUNCTIONSHELL);encoder.writeString(ATTRIB_NAME, name);diff --git a/Ghidra/Features/Decompiler/src/decompile/cpp/flow.cc b/Ghidra/Features/Decompiler/src/decompile/cpp/flow.ccindex a9ec3af9e7..337b6c871e 100644--- a/Ghidra/Features/Decompiler/src/decompile/cpp/flow.cc+++ b/Ghidra/Features/Decompiler/src/decompile/cpp/flow.cc@@ -39,7 +39,7 @@ FlowInfo::FlowInfo(Funcdata &d,PcodeOpBank &o,BlockGraph &b,vector<FuncCallSpecsinsn_count = 0;insn_max = ~((uint4)0);baddata_count = 0;- flowoverride_present = data.getOverride().hasFlowOverride();+ pcode_override_present = data.getOverride().hasPCodeOverride();}/// Prepare a new flow cloned from an existing flow.@@ -74,7 +74,7 @@ FlowInfo::FlowInfo(Funcdata &d,PcodeOpBank &o,BlockGraph &b,vector<FuncCallSpecsinsn_count = op2->insn_count;insn_max = op2->insn_max;baddata_count = op2->baddata_count;- flowoverride_present = data.getOverride().hasFlowOverride();+ pcode_override_present = data.getOverride().hasPCodeOverride();}void FlowInfo::clearProperties(void)@@ -390,7 +390,7 @@ bool FlowInfo::processInstruction(const Address &curaddr,bool &startbasic)// JumpTable *jt;list<PcodeOp *>::const_iterator oiter;int4 step;- uint4 flowoverride;+ const Override::Record *pCodeOverride;if (insn_count >= insn_max) {if ((flags & error_toomanyinstructions)!=0)@@ -414,10 +414,10 @@ bool FlowInfo::processInstruction(const Address &curaddr,bool &startbasic)oiter = obank.endDead();--oiter;}- if (flowoverride_present)- flowoverride = data.getOverride().getFlowOverride(curaddr);+ if (pcode_override_present)+ pCodeOverride = data.getOverride().getPCodeOverride(curaddr);else- flowoverride = Override::NONE;+ pCodeOverride = (const Override::Record *)0;try {step = glb->translate->oneInstruction(emitter,curaddr); // Generate ops for instruction@@ -474,8 +474,8 @@ bool FlowInfo::processInstruction(const Address &curaddr,bool &startbasic)if (oiter != obank.endDead()) {stat.seqnum = (*oiter)->getSeqNum();data.opMarkStartInstruction(*oiter); // Mark the first op in the instruction- if (flowoverride != Override::NONE)- data.overrideFlow(curaddr,flowoverride);+ if (pCodeOverride != (const Override::Record *)0)+ pCodeOverride->performOverride(curaddr,data);xrefControlFlow(oiter,startbasic,isfallthru,(FuncCallSpecs *)0);}diff --git a/Ghidra/Features/Decompiler/src/decompile/cpp/flow.hh b/Ghidra/Features/Decompiler/src/decompile/cpp/flow.hhindex 572abd8c57..0a4ce08247 100644--- a/Ghidra/Features/Decompiler/src/decompile/cpp/flow.hh+++ b/Ghidra/Features/Decompiler/src/decompile/cpp/flow.hh@@ -98,7 +98,7 @@ private:Address eaddr; ///< End of range in which we are allowed to flowAddress minaddr; ///< Start of actual function rangeAddress maxaddr; ///< End of actual function range- bool flowoverride_present; ///< Does the function have registered flow override instructions+ bool pcode_override_present; ///< Does the function have registered p-code override instructionsuint4 flags; ///< Boolean options for flow followinguint4 baddata_count; ///< Number of instructions that could not be disassembledFuncdata *inline_head; ///< First function in the in-lining chaindiff --git a/Ghidra/Features/Decompiler/src/decompile/cpp/fspec.cc b/Ghidra/Features/Decompiler/src/decompile/cpp/fspec.ccindex d87eb2f923..cafdd93eab 100644--- a/Ghidra/Features/Decompiler/src/decompile/cpp/fspec.cc+++ b/Ghidra/Features/Decompiler/src/decompile/cpp/fspec.cc@@ -5451,7 +5451,7 @@ void FuncCallSpecs::deindirect(Funcdata &data,Funcdata *newfd)data.opSetInput(op,vn,0);data.opSetOpcode(op,CPUI_CALL);- data.getOverride().insertIndirectOverride(op->getAddr(),entryaddress);+ data.getOverride().insertDeindirect(op->getAddr(),entryaddress);// Try our best to merge existing prototype// with the one we have just been handeddiff --git a/Ghidra/Features/Decompiler/src/decompile/cpp/funcdata.cc b/Ghidra/Features/Decompiler/src/decompile/cpp/funcdata.ccindex 6571bfe9b5..6cfe150561 100644--- a/Ghidra/Features/Decompiler/src/decompile/cpp/funcdata.cc+++ b/Ghidra/Features/Decompiler/src/decompile/cpp/funcdata.cc@@ -730,8 +730,9 @@ void Funcdata::encodeTree(Encoder &encoder) const/// tree is also emitted./// \param encoder is the stream encoder/// \param id is the unique id associated with the function symbol-/// \param savetree is \b true if the p-code tree should be emitted-void Funcdata::encode(Encoder &encoder,uint8 id,bool savetree) const+/// \param saveTree is \b true if the p-code tree should be emitted+/// \param saveOverrides is \b true if information about overrides should be emitted+void Funcdata::encode(Encoder &encoder,uint8 id,bool saveTree,bool saveOverrides) const{encoder.openElement(ELEM_FUNCTION);@@ -747,13 +748,14 @@ void Funcdata::encode(Encoder &encoder,uint8 id,bool savetree) constlocalmap->encodeRecursive(encoder,false); // Save scope and all subscopes}- if (savetree) {+ if (saveTree) {encodeTree(encoder);encodeHigh(encoder);}encodeJumpTable(encoder);funcp.encode(encoder); // Must be saved after database- localoverride.encode(encoder,glb);+ if (saveOverrides)+ localoverride.encode(encoder,glb);encoder.closeElement(ELEM_FUNCTION);}diff --git a/Ghidra/Features/Decompiler/src/decompile/cpp/funcdata.hh b/Ghidra/Features/Decompiler/src/decompile/cpp/funcdata.hhindex 6558ee8d59..f417560951 100644--- a/Ghidra/Features/Decompiler/src/decompile/cpp/funcdata.hh+++ b/Ghidra/Features/Decompiler/src/decompile/cpp/funcdata.hh@@ -134,8 +134,6 @@ class Funcdata {static bool descendantsOutside(Varnode *vn);static void encodeVarnode(Encoder &encoder,VarnodeLocSet::const_iterator iter,VarnodeLocSet::const_iterator enditer);static bool checkIndirectUse(Varnode *vn);- static PcodeOp *findPrimaryBranch(PcodeOpTree::const_iterator iter,PcodeOpTree::const_iterator enditer,- bool findbranch,bool findcall,bool findreturn);public:Funcdata(const string &nm,const string &disp,Scope *conf,const Address &addr,FunctionSymbol *sym,int4 sz=0); ///< Constructor~Funcdata(void); ///< Destructor@@ -197,14 +195,13 @@ public:void followFlow(const Address &baddr,const Address &eadddr);void truncatedFlow(const Funcdata *fd,const FlowInfo *flow);int4 inlineFlow(Funcdata *inlinefd,FlowInfo &flow,PcodeOp *callop);- void overrideFlow(const Address &addr,uint4 type);void doLiveInject(InjectPayload *payload,const Address &addr,BlockBasic *bl,list<PcodeOp *>::iterator pos);void printRaw(ostream &s) const; ///< Print raw p-code op descriptions to a streamvoid printVarnodeTree(ostream &s) const; ///< Print a description of all Varnodes to a streamvoid printBlockTree(ostream &s) const; ///< Print a description of control-flow structuring to a streamvoid printLocalRange(ostream &s) const; ///< Print description of memory ranges associated with local scopes- void encode(Encoder &encoder,uint8 id,bool savetree) const; ///< Encode a description of \b this function to stream+ void encode(Encoder &encoder,uint8 id,bool saveTree,bool saveOverrides) const; ///< Encode a description of \b this function to streamuint8 decode(Decoder &decoder); ///< Restore the state of \b this function from a streamvoid encodeJumpTable(Encoder &encoder) const; ///< Encode a description of jump-tables to streamvoid decodeJumpTable(Decoder &decoder); ///< Decode jump-tables from a stream@@ -536,6 +533,8 @@ public:/// \brief End of all (alive) PcodeOp objects attached to a specific AddressPcodeOpTree::const_iterator endOp(const Address &addr) const { return obank.end(addr); }+ PcodeOp *findPrimaryBranch(const Address &addr,bool findBranch,bool findCall,bool findCallother,bool findReturn);+bool moveRespectingCover(PcodeOp *op,PcodeOp *lastOp); ///< Move given op past \e lastOp respecting covers if possibleconst ResolvedUnion *getUnionField(const Datatype *unresType,const PcodeOp *op,int4 slot) const;diff --git a/Ghidra/Features/Decompiler/src/decompile/cpp/funcdata_op.cc b/Ghidra/Features/Decompiler/src/decompile/cpp/funcdata_op.ccindex b8bb92d492..bf79e64352 100644--- a/Ghidra/Features/Decompiler/src/decompile/cpp/funcdata_op.cc+++ b/Ghidra/Features/Decompiler/src/decompile/cpp/funcdata_op.cc@@ -917,109 +917,40 @@ int4 Funcdata::inlineFlow(Funcdata *inlinefd,FlowInfo &flow,PcodeOp *callop)/// \brief Find the primary branch operation for an instruction///-/// For machine instructions that branch, this finds the \e primary PcodeOp that performs-/// the branch. The instruction is provided as a list of p-code ops, and the caller can-/// specify whether they expect to see a \e branch, \e call, or \e return operation.-/// \param iter is the start of the operations for the instruction-/// \param enditer is the end of the operations for the instruction-/// \param findbranch is \b true if the caller expects to see a BRANCH, CBRANCH, or BRANCHIND-/// \param findcall is \b true if the caller expects to see CALL or CALLIND-/// \param findreturn is \b true if the caller expects to see RETURN+/// For instructions that branch, this finds the \e primary PcodeOp that performs the branch.+/// The caller can specify whether they expect to see a \e branch, \e call, \e callother, or \e return operation.+/// \param addr is the address of the instruction+/// \param findBranch is \b true if the caller expects to see a BRANCH, CBRANCH, or BRANCHIND+/// \param findCall is \b true if the caller expects to see CALL or CALLIND+/// \param findCallother is \b true if the caller expects to see CALLOTHER+/// \param findReturn is \b true if the caller expects to see RETURN/// \return the first branching PcodeOp that matches the criteria or NULL-PcodeOp *Funcdata::findPrimaryBranch(PcodeOpTree::const_iterator iter,PcodeOpTree::const_iterator enditer,- bool findbranch,bool findcall,bool findreturn)+PcodeOp *Funcdata::findPrimaryBranch(const Address &addr,bool findBranch,bool findCall,bool findCallother,bool findReturn){+ PcodeOpTree::const_iterator iter = beginOp(addr);+ PcodeOpTree::const_iterator enditer = endOp(addr);while(iter != enditer) {PcodeOp *op = (*iter).second;- switch(op->code()) {- case CPUI_BRANCH:- case CPUI_CBRANCH:- if (findbranch) {+ if (op->isCallOrBranch() || op->isFlowBreak()) {+ OpCode opc = op->code();+ if (findBranch && (opc == CPUI_BRANCH || opc == CPUI_CBRANCH)) {if (!op->getIn(0)->isConstant()) // Make sure this is not an internal branchreturn op;}- break;- case CPUI_BRANCHIND:- if (findbranch)+ if (findBranch && opc == CPUI_BRANCHIND)return op;- break;- case CPUI_CALL:- case CPUI_CALLIND:- if (findcall)+ if (findCall && (opc == CPUI_CALL || opc == CPUI_CALLIND))return op;- break;- case CPUI_RETURN:- if (findreturn)+ if (findReturn && opc == CPUI_RETURN)+ return op;+ if (findCallother && opc == CPUI_CALLOTHER)return op;- break;- default:- break;}++iter;}return (PcodeOp *)0;}-/// \brief Override the control-flow p-code for a particular instruction-///-/// P-code in \b this function is modified to change the control-flow of-/// the instruction at the given address, based on the Override type.-/// \param addr is the given address of the instruction to modify-/// \param type is the Override type-void Funcdata::overrideFlow(const Address &addr,uint4 type)--{- PcodeOpTree::const_iterator iter = beginOp(addr);- PcodeOpTree::const_iterator enditer = endOp(addr);-- PcodeOp *op = (PcodeOp *)0;- if (type == Override::BRANCH)- op = findPrimaryBranch(iter,enditer,false,true,true);- else if (type == Override::CALL)- op = findPrimaryBranch(iter,enditer,true,false,true);- else if (type == Override::CALL_RETURN)- op = findPrimaryBranch(iter,enditer,true,true,true);- else if (type == Override::RETURN)- op = findPrimaryBranch(iter,enditer,true,true,false);-- if ((op == (PcodeOp *)0)||(!op->isDead()))- throw LowlevelError("Could not apply flowoverride");-- OpCode opc = op->code();- if (type == Override::BRANCH) {- if (opc == CPUI_CALL)- opSetOpcode(op,CPUI_BRANCH);- else if (opc == CPUI_CALLIND)- opSetOpcode(op,CPUI_BRANCHIND);- else if (opc == CPUI_RETURN)- opSetOpcode(op,CPUI_BRANCHIND);- }- else if ((type == Override::CALL)||(type == Override::CALL_RETURN)) {- if (opc == CPUI_BRANCH)- opSetOpcode(op,CPUI_CALL);- else if (opc == CPUI_BRANCHIND)- opSetOpcode(op,CPUI_CALLIND);- else if (opc == CPUI_CBRANCH)- throw LowlevelError("Do not currently support CBRANCH overrides");- else if (opc == CPUI_RETURN)- opSetOpcode(op,CPUI_CALLIND);- if (type == Override::CALL_RETURN) { // Insert a new return op after call- PcodeOp *newReturn = newOp(1,addr);- opSetOpcode(newReturn,CPUI_RETURN);- opSetInput(newReturn,newConstant(1,0),0);- opDeadInsertAfter(newReturn,op);- }- }- else if (type == Override::RETURN) {- if ((opc == CPUI_BRANCH)||(opc == CPUI_CBRANCH)||(opc == CPUI_CALL))- throw LowlevelError("Do not currently support complex overrides");- else if (opc == CPUI_BRANCHIND)- opSetOpcode(op,CPUI_RETURN);- else if (opc == CPUI_CALLIND)- opSetOpcode(op,CPUI_RETURN);- }-}-/// Do in-place replacement of/// - `c <= x` with `c-1 < x` OR/// - `x <= c` with `x < c+1`diff --git a/Ghidra/Features/Decompiler/src/decompile/cpp/ghidra_process.cc b/Ghidra/Features/Decompiler/src/decompile/cpp/ghidra_process.ccindex 8ac5921aca..aab4fcfed9 100644--- a/Ghidra/Features/Decompiler/src/decompile/cpp/ghidra_process.cc+++ b/Ghidra/Features/Decompiler/src/decompile/cpp/ghidra_process.cc@@ -317,7 +317,7 @@ void DecompileAt::rawAction(void)ParamIDAnalysis pidanalysis( fd, false );pidanalysis.encode( encoder, true );}- fd->encode(encoder,0,ghidra->getSendSyntaxTree());+ fd->encode(encoder,0,ghidra->getSendSyntaxTree(),false);if (ghidra->getSendCCode()&&(ghidra->allacts.getCurrentName() == "decompile"))ghidra->print->docFunction(fd);diff --git a/Ghidra/Features/Decompiler/src/decompile/cpp/ifacedecomp.cc b/Ghidra/Features/Decompiler/src/decompile/cpp/ifacedecomp.ccindex fad4bdee65..385d74c8f1 100644--- a/Ghidra/Features/Decompiler/src/decompile/cpp/ifacedecomp.cc+++ b/Ghidra/Features/Decompiler/src/decompile/cpp/ifacedecomp.cc@@ -72,6 +72,7 @@ void IfaceDecompCapability::registerCommands(IfaceStatus *status)status->registerCom(new IfcProtooverride(),"override","prototype");status->registerCom(new IfcJumpOverride(),"override","jumptable");status->registerCom(new IfcFlowOverride(),"override","flow");+ status->registerCom(new IfcDestinationOverride(),"override","destination");status->registerCom(new IfcDeadcodedelay(),"deadcode","delay");status->registerCom(new IfcGlobalAdd(),"global","add");status->registerCom(new IfcGlobalRemove(),"global","remove");@@ -1933,7 +1934,6 @@ void IfcFlowOverride::execute(istream &s){int4 discard;- uint4 type;string token;if (dcp->fd == (Funcdata *)0)@@ -1944,12 +1944,37 @@ void IfcFlowOverride::execute(istream &s)s >> token;if (token.size() == 0)throw IfaceParseError("Missing override type");- type = Override::stringToType(token);- if (type == Override::NONE)- throw IfaceParseError("Bad override type");- dcp->fd->getOverride().insertFlowOverride(addr,type);- *status->optr << "Successfully added override" << endl;+ dcp->fd->getOverride().insertFlowOverride(addr,token);+ *status->optr << "Successfully added flow override" << endl;+}++/// \class IfcDestinationOverride+/// \brief Create an override changing a call destination: `override destination <address> <type> <destaddress>`+///+/// The override modifies a branching op-code at \<address\> to have particular destination address,+/// depending on the \<type\>.+/// - callind_call converts a CALLIND to CALL (with the destination address)+/// - callother_call converts a CALLOTHER to a CALL+/// - callother_branch converts a CALLOTHER to a BRANCH+/// - call_call converts a CALL to have the specified destination address+void IfcDestinationOverride::execute(istream &s)++{+ int4 discard;+ string token;++ if (dcp->fd == (Funcdata *)0)+ throw IfaceExecutionError("No function selected");++ s >> ws;+ Address addr( parse_machaddr(s,discard,*dcp->conf->types));+ s >> token >> ws;+ if (token.size() == 0)+ throw IfaceParseError("Missing override type");+ Address dest( parse_machaddr(s,discard,*dcp->conf->types));+ dcp->fd->getOverride().insertDestinationOverride(addr, dest, token);+ *status->optr << "Successfully added destination override" << endl;}/// \class IfcDeadcodedelaydiff --git a/Ghidra/Features/Decompiler/src/decompile/cpp/ifacedecomp.hh b/Ghidra/Features/Decompiler/src/decompile/cpp/ifacedecomp.hhindex 5958f67c88..60fc62ada4 100644--- a/Ghidra/Features/Decompiler/src/decompile/cpp/ifacedecomp.hh+++ b/Ghidra/Features/Decompiler/src/decompile/cpp/ifacedecomp.hh@@ -405,6 +405,11 @@ public:virtual void execute(istream &s);};+class IfcDestinationOverride : public IfaceDecompCommand {+public:+ virtual void execute(istream &s);+};+class IfcDeadcodedelay : public IfaceDecompCommand {public:virtual void execute(istream &s);diff --git a/Ghidra/Features/Decompiler/src/decompile/cpp/override.cc b/Ghidra/Features/Decompiler/src/decompile/cpp/override.ccindex 0c2b57342f..0560e9300a 100644--- a/Ghidra/Features/Decompiler/src/decompile/cpp/override.cc+++ b/Ghidra/Features/Decompiler/src/decompile/cpp/override.cc@@ -21,7 +21,7 @@ namespace ghidra {ElementId ELEM_DEADCODEDELAY = ElementId("deadcodedelay",218);ElementId ELEM_FLOW = ElementId("flow",219);ElementId ELEM_FORCEGOTO = ElementId("forcegoto",220);-ElementId ELEM_INDIRECTOVERRIDE = ElementId("indirectoverride",221);+ElementId ELEM_CALLDEST = ElementId("calldest",221);ElementId ELEM_MULTISTAGEJUMP = ElementId("multistagejump",222);ElementId ELEM_OVERRIDE = ElementId("override",223);ElementId ELEM_PROTOOVERRIDE = ElementId("protooverride",224);@@ -29,17 +29,19 @@ ElementId ELEM_PROTOOVERRIDE = ElementId("protooverride",224);void Override::clear(void){- map<Address,FuncProto *>::iterator iter;+ for(map<Address,FuncProto *>::iterator iter=protoover.begin();iter!=protoover.end();++iter)+ delete (*iter).second;- for(iter=protoover.begin();iter!=protoover.end();++iter)+ for(map<Address,Record *>::iterator iter=pcodeover.begin();iter!=pcodeover.end();++iter)delete (*iter).second;+ protoover.clear();+ pcodeover.clear();forcegoto.clear();deadcodedelay.clear();- indirectover.clear();+ deindirect.clear();protoover.clear();multistagejump.clear();- flowoverride.clear();}/// \brief Generate \e warning message related to a dead code delay@@ -104,12 +106,12 @@ bool Override::hasDeadcodeDelay(AddrSpace *spc) const////// The command consists of the address of the indirect call instruction and/// the target address of the direct address-/// \param callpoint is the address of the indirect call-/// \param directcall is the target address of the direct call-void Override::insertIndirectOverride(const Address &callpoint,const Address &directcall)+/// \param callPoint is the address of the indirect call+/// \param directAddr is the target address of the direct call+void Override::insertDeindirect(const Address &callPoint,const Address &directAddr){- indirectover[callpoint] = directcall;+ deindirect[callPoint] = directAddr;}/// \brief Override the assumed function prototype at a specific call site@@ -145,10 +147,23 @@ void Override::insertMultistageJump(const Address &addr)/// Change the interpretation of a BRANCH, CALL, or RETURN/// \param addr is the address of the branch instruction/// \param type is the type of flow that should be forced-void Override::insertFlowOverride(const Address &addr,uint4 type)+void Override::insertFlowOverride(const Address &addr,const string &type)++{+ Record *rec = Record::allocateFlow(type);+ pcodeover[addr] = rec;+}++/// \brief Change a CALL, CALLIND, or CALLOTHER instruction into a CALL with the specified destination address+///+/// \param addr is the address of the instruction+/// \param dest is the new destination address+/// \param type is the type of override to force+void Override::insertDestinationOverride(const Address &addr,const Address &dest,const string &type){- flowoverride[addr] = type;+ Record *rec = Record::allocateCallDest(type,dest);+ pcodeover[addr] = rec;}/// \brief Look for and apply a function prototype override@@ -177,9 +192,9 @@ void Override::applyPrototype(Funcdata &data,FuncCallSpecs &fspecs) constvoid Override::applyIndirect(Funcdata &data,FuncCallSpecs &fspecs) const{- if (!indirectover.empty()) {- map<Address,Address>::const_iterator iter = indirectover.find(fspecs.getOp()->getAddr());- if (iter != indirectover.end())+ if (!deindirect.empty()) {+ map<Address,Address>::const_iterator iter = deindirect.find(fspecs.getOp()->getAddr());+ if (iter != deindirect.end())fspecs.setAddress( (*iter).second );}}@@ -229,14 +244,14 @@ void Override::applyDeadCodeDelay(Funcdata &data) const/// \brief Return the particular flow override at a given address////// \param addr is the address of a branch instruction-/// \return the override type-uint4 Override::getFlowOverride(const Address &addr) const+/// \return the override record or null if there is no override+const Override::Record *Override::getPCodeOverride(const Address &addr) const{- map<Address,uint4>::const_iterator iter;- iter = flowoverride.find(addr);- if (iter == flowoverride.end())- return Override::NONE;+ map<Address,Record *>::const_iterator iter;+ iter = pcodeover.find(addr);+ if (iter == pcodeover.end())+ return (Record *)0;return (*iter).second;}@@ -248,9 +263,7 @@ uint4 Override::getFlowOverride(const Address &addr) constvoid Override::printRaw(ostream &s,Architecture *glb) const{- map<Address,Address>::const_iterator iter;-- for(iter=forcegoto.begin();iter!=forcegoto.end();++iter)+ for(map<Address,Address>::const_iterator iter=forcegoto.begin();iter!=forcegoto.end();++iter)s << "force goto at " << (*iter).first << " jumping to " << (*iter).second << endl;for(int4 i=0;i<deadcodedelay.size();++i) {@@ -259,12 +272,13 @@ void Override::printRaw(ostream &s,Architecture *glb) consts << "dead code delay on " << spc->getName() << " set to " << dec << deadcodedelay[i] << endl;}- for(iter=indirectover.begin();iter!=indirectover.end();++iter)+ for(map<Address,Address>::const_iterator iter=deindirect.begin();iter!=deindirect.end();++iter)s << "override indirect at " << (*iter).first << " to call directly to " << (*iter).second << endl;- map<Address,FuncProto *>::const_iterator fiter;+ for(map<Address,Record *>::const_iterator iter=pcodeover.begin();iter!=pcodeover.end();++iter)+ (*iter).second->printRaw(s, (*iter).first);- for(fiter=protoover.begin();fiter!=protoover.end();++fiter) {+ for(map<Address,FuncProto *>::const_iterator fiter=protoover.begin();fiter!=protoover.end();++fiter) {s << "override prototype at " << (*fiter).first << " to ";(*fiter).second->printRaw("func",s);s << endl;@@ -294,14 +308,12 @@ void Override::generateOverrideMessages(vector<string> &messagelist,Architecturevoid Override::encode(Encoder &encoder,Architecture *glb) const{- if (forcegoto.empty() && deadcodedelay.empty() && indirectover.empty() && protoover.empty() &&- multistagejump.empty() && flowoverride.empty())+ if (forcegoto.empty() && deadcodedelay.empty() && deindirect.empty() && protoover.empty() &&+ multistagejump.empty() && pcodeover.empty())return;encoder.openElement(ELEM_OVERRIDE);- map<Address,Address>::const_iterator iter;-- for(iter=forcegoto.begin();iter!=forcegoto.end();++iter) {+ for(map<Address,Address>::const_iterator iter=forcegoto.begin();iter!=forcegoto.end();++iter) {encoder.openElement(ELEM_FORCEGOTO);(*iter).first.encode(encoder);(*iter).second.encode(encoder);@@ -317,16 +329,7 @@ void Override::encode(Encoder &encoder,Architecture *glb) constencoder.closeElement(ELEM_DEADCODEDELAY);}- for(iter=indirectover.begin();iter!=indirectover.end();++iter) {- encoder.openElement(ELEM_INDIRECTOVERRIDE);- (*iter).first.encode(encoder);- (*iter).second.encode(encoder);- encoder.closeElement(ELEM_INDIRECTOVERRIDE);- }-- map<Address,FuncProto *>::const_iterator fiter;-- for(fiter=protoover.begin();fiter!=protoover.end();++fiter) {+ for(map<Address,FuncProto *>::const_iterator fiter=protoover.begin();fiter!=protoover.end();++fiter) {encoder.openElement(ELEM_PROTOOVERRIDE);(*fiter).first.encode(encoder);(*fiter).second->encode(encoder);@@ -339,13 +342,9 @@ void Override::encode(Encoder &encoder,Architecture *glb) constencoder.closeElement(ELEM_MULTISTAGEJUMP);}- map<Address,uint4>::const_iterator titer;- for(titer=flowoverride.begin();titer!=flowoverride.end();++titer) {- encoder.openElement(ELEM_FLOW);- encoder.writeString(ATTRIB_TYPE, typeToString( (*titer).second ));- (*titer).first.encode(encoder);- encoder.closeElement(ELEM_FLOW);- }+ for(map<Address,Record *>::const_iterator titer=pcodeover.begin();titer!=pcodeover.end();++titer)+ (*titer).second->encode(encoder, (*titer).first);+encoder.closeElement(ELEM_OVERRIDE);}@@ -360,12 +359,7 @@ void Override::decode(Decoder &decoder,Architecture *glb)for(;;) {uint4 subId = decoder.openElement();if (subId == 0) break;- if (subId == ELEM_INDIRECTOVERRIDE) {- Address callpoint = Address::decode(decoder);- Address directcall = Address::decode(decoder);- insertIndirectOverride(callpoint,directcall);- }- else if (subId == ELEM_PROTOOVERRIDE) {+ if (subId == ELEM_PROTOOVERRIDE) {Address callpoint = Address::decode(decoder);unique_ptr<FuncProto> fp(new FuncProto());fp->setInternal(glb->defaultfp,glb->types->getTypeVoid());@@ -389,47 +383,278 @@ void Override::decode(Decoder &decoder,Architecture *glb)insertMultistageJump(callpoint);}else if (subId == ELEM_FLOW) {- uint4 type = stringToType(decoder.readString(ATTRIB_TYPE));+ string type = decoder.readString(ATTRIB_TYPE);Address addr = Address::decode(decoder);- if ((type == Override::NONE)||(addr.isInvalid()))- throw LowlevelError("Bad flowoverride tag");- insertFlowOverride(addr,type);+ if (addr.isInvalid())+ throw LowlevelError("Bad flow override address");+ pcodeover[addr] = Record::allocateFlow(type);+ }+ else if (subId == ELEM_CALLDEST) {+ string type = decoder.readString(ATTRIB_TYPE);+ Address addr = Address::decode(decoder);+ Address dest = Address::decode(decoder);+ if (addr.isInvalid() || dest.isInvalid())+ throw LowlevelError("Bad destination override address");+ pcodeover[addr] = Record::allocateCallDest(type,dest);}decoder.closeElement(subId);}decoder.closeElement(elemId);}-/// \param tp is the override type-/// \return the corresponding name string-string Override::typeToString(uint4 tp)+/// Flow records take no additional parameters to construct+/// \param name is the particular flow override name+/// \return a newly allocated flow override record+Override::Record *Override::Record::allocateFlow(const string &name)++{+ if (name == Branch::NAME)+ return new Branch();+ else if (name == Call::NAME)+ return new Call();+ else if (name == CallReturn::NAME)+ return new CallReturn();+ else if (name == Return::NAME)+ return new Return();+ throw LowlevelError("Unknown flow override name: "+name);+}++/// \param name is the particular call destination override name+/// \param dest is the new destination address+/// \return a newly allocated destination override record+Override::Record *Override::Record::allocateCallDest(const string &name,const Address &dest)++{+ if (name == CallotherCall::NAME)+ return new CallotherCall(dest);+ else if (name == CallotherBranch::NAME)+ return new CallotherBranch(dest);+ else if (name == CallCall::NAME)+ return new CallCall(dest);+ throw LowlevelError("Unknown call destination override name: "+name);+}++const string Override::Branch::NAME = "branch";++void Override::Branch::performOverride(const Address &addr,Funcdata &data) const++{+ PcodeOp *op = data.findPrimaryBranch(addr,false,true,false,true);++ if (op == (PcodeOp *)0 || !op->isDead())+ throw LowlevelError("Could not apply BRANCH override");+ OpCode opc = op->code();+ if (opc == CPUI_CALL)+ data.opSetOpcode(op,CPUI_BRANCH);+ else if (opc == CPUI_CALLIND)+ data.opSetOpcode(op,CPUI_BRANCHIND);+ else if (opc == CPUI_RETURN)+ data.opSetOpcode(op,CPUI_BRANCHIND);+}++void Override::Branch::encode(Encoder &encoder,const Address &addr) const++{+ encoder.openElement(ELEM_FLOW);+ encoder.writeString(ATTRIB_TYPE, NAME);+ addr.encode(encoder);+ encoder.closeElement(ELEM_FLOW);+}++void Override::Branch::printRaw(ostream &s,const Address &addr) const++{+ s << "override CALL, CALLIND, or RETURN at " << addr << " to a BRANCH" << endl;+}++const string Override::Call::NAME = "call";++void Override::Call::performOverride(const Address &addr,Funcdata &data) const++{+ PcodeOp *op = data.findPrimaryBranch(addr,true,false,false,true);++ if (op == (PcodeOp *)0 || !op->isDead())+ throw LowlevelError("Could not apply CALL override");+ OpCode opc = op->code();+ if (opc == CPUI_BRANCH)+ data.opSetOpcode(op,CPUI_CALL);+ else if (opc == CPUI_BRANCHIND)+ data.opSetOpcode(op,CPUI_CALLIND);+ else if (opc == CPUI_CBRANCH)+ throw LowlevelError("Do not currently support CBRANCH overrides");+ else if (opc == CPUI_RETURN)+ data.opSetOpcode(op,CPUI_CALLIND);+}++void Override::Call::encode(Encoder &encoder,const Address &addr) const++{+ encoder.openElement(ELEM_FLOW);+ encoder.writeString(ATTRIB_TYPE, NAME);+ addr.encode(encoder);+ encoder.closeElement(ELEM_FLOW);+}++void Override::Call::printRaw(ostream &s,const Address &addr) const++{+ s << "override BRANCH, BRANCHIND, or RETURN at " << addr << " to a CALL" << endl;+}++const string Override::CallReturn::NAME = "callreturn";++void Override::CallReturn::performOverride(const Address &addr,Funcdata &data) const++{+ PcodeOp *op = data.findPrimaryBranch(addr,true,true,false,true);++ if (op == (PcodeOp *)0 || !op->isDead())+ throw LowlevelError("Could not apply CALL_RETURN override");+ OpCode opc = op->code();+ if (opc == CPUI_BRANCH)+ data.opSetOpcode(op,CPUI_CALL);+ else if (opc == CPUI_BRANCHIND)+ data.opSetOpcode(op,CPUI_CALLIND);+ else if (opc == CPUI_CBRANCH)+ throw LowlevelError("Do not currently support CBRANCH overrides");+ else if (opc == CPUI_RETURN)+ data.opSetOpcode(op,CPUI_CALLIND);+ PcodeOp *newReturn = data.newOp(1,addr);+ data.opSetOpcode(newReturn,CPUI_RETURN);+ data.opSetInput(newReturn,data.newConstant(1,0),0);+ data.opDeadInsertAfter(newReturn,op);+}++void Override::CallReturn::encode(Encoder &encoder,const Address &addr) const++{+ encoder.openElement(ELEM_FLOW);+ encoder.writeString(ATTRIB_TYPE, NAME);+ addr.encode(encoder);+ encoder.closeElement(ELEM_FLOW);+}++void Override::CallReturn::printRaw(ostream &s,const Address &addr) const++{+ s << "override BRANCH, BRANCHIND, or RETURN at " << addr << " to a CALL followed by a RETURN" << endl;+}++const string Override::Return::NAME = "return";++void Override::Return::performOverride(const Address &addr,Funcdata &data) const++{+ PcodeOp *op = data.findPrimaryBranch(addr,true,true,false,false);+ if (op == (PcodeOp *)0 || !op->isDead())+ throw LowlevelError("Could not apply RETURN override");+ OpCode opc = op->code();+ if (opc == CPUI_BRANCH || opc == CPUI_CBRANCH || opc == CPUI_CALL)+ throw LowlevelError("Do not currently support complex overrides");+ else if (opc == CPUI_BRANCHIND)+ data.opSetOpcode(op,CPUI_RETURN);+ else if (opc == CPUI_CALLIND)+ data.opSetOpcode(op,CPUI_RETURN);+}++void Override::Return::encode(Encoder &encoder,const Address &addr) const++{+ encoder.openElement(ELEM_FLOW);+ encoder.writeString(ATTRIB_TYPE, NAME);+ addr.encode(encoder);+ encoder.closeElement(ELEM_FLOW);+}++void Override::Return::printRaw(ostream &s,const Address &addr) const++{+ s << "override BRANCHIND or CALLIND at " << addr << " to a RETURN" << endl;+}++const string Override::CallotherCall::NAME = "callother_call";++void Override::CallotherCall::performOverride(const Address &addr,Funcdata &data) const++{+ PcodeOp *op = data.findPrimaryBranch(addr,false,false,true,false);+ if (op == (PcodeOp *)0 || !op->isDead())+ throw LowlevelError("Could not apply CALLOTHER->CALL override");+ data.opSetOpcode(op,CPUI_CALL);+ data.opSetInput(op, data.newCodeRef(callAddress), 0);+}++void Override::CallotherCall::encode(Encoder &encoder,const Address &addr) const++{+ encoder.openElement(ELEM_CALLDEST);+ encoder.writeString(ATTRIB_TYPE, NAME);+ addr.encode(encoder);+ callAddress.encode(encoder);+ encoder.closeElement(ELEM_CALLDEST);+}++void Override::CallotherCall::printRaw(ostream &s,const Address &addr) const++{+ s << "override CALLOTHER at " << addr << " to CALL directly to " << callAddress << endl;+}++const string Override::CallotherBranch::NAME = "callother_branch";++void Override::CallotherBranch::performOverride(const Address &addr,Funcdata &data) const++{+ PcodeOp *op = data.findPrimaryBranch(addr,false,false,true,false);+ if (op == (PcodeOp *)0 || !op->isDead())+ throw LowlevelError("Could not apply CALLOTHER->BRANCH override");+ data.opSetOpcode(op,CPUI_BRANCH);+ data.opSetInput(op, data.newCodeRef(branchAddress), 0);+}++void Override::CallotherBranch::encode(Encoder &encoder,const Address &addr) const++{+ encoder.openElement(ELEM_CALLDEST);+ encoder.writeString(ATTRIB_TYPE, NAME);+ addr.encode(encoder);+ branchAddress.encode(encoder);+ encoder.closeElement(ELEM_CALLDEST);+}++void Override::CallotherBranch::printRaw(ostream &s,const Address &addr) const++{+ s << "override CALLOTHER at " << addr << " to BRANCH directly to " << branchAddress << endl;+}++const string Override::CallCall::NAME = "call_call";++void Override::CallCall::performOverride(const Address &addr,Funcdata &data) const++{+ PcodeOp *op = data.findPrimaryBranch(addr,false,true,false,false);+ if (op == (PcodeOp *)0 || !op->isDead())+ throw LowlevelError("Could not apply CALL destination override");+ data.opSetOpcode(op, CPUI_CALL);+ data.opSetInput(op, data.newCodeRef(callAddress), 0);+}++void Override::CallCall::encode(Encoder &encoder,const Address &addr) const{- if (tp == Override::BRANCH)- return "branch";- if (tp == Override::CALL)- return "call";- if (tp == Override::CALL_RETURN)- return "callreturn";- if (tp == Override::RETURN)- return "return";- return "none";+ encoder.openElement(ELEM_CALLDEST);+ encoder.writeString(ATTRIB_TYPE, NAME);+ addr.encode(encoder);+ callAddress.encode(encoder);+ encoder.closeElement(ELEM_CALLDEST);}-/// \param nm is the override name-/// \return the override enumeration type-uint4 Override::stringToType(const string &nm)+void Override::CallCall::printRaw(ostream &s,const Address &addr) const{- if (nm == "branch")- return Override::BRANCH;- else if (nm == "call")- return Override::CALL;- else if (nm == "callreturn")- return Override::CALL_RETURN;- else if (nm == "return")- return Override::RETURN;- return Override::NONE;+ s << "override CALL at " << addr << " to call to a new address " << callAddress << endl;}} // End namespace ghidradiff --git a/Ghidra/Features/Decompiler/src/decompile/cpp/override.hh b/Ghidra/Features/Decompiler/src/decompile/cpp/override.hhindex 693c2e62b3..edb75eec7b 100644--- a/Ghidra/Features/Decompiler/src/decompile/cpp/override.hh+++ b/Ghidra/Features/Decompiler/src/decompile/cpp/override.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.@@ -26,9 +26,9 @@ namespace ghidra {class FuncCallSpecs; // Forward declarationextern ElementId ELEM_DEADCODEDELAY; ///< Marshaling element \<deadcodedelay>-extern ElementId ELEM_FLOW; ///< Marshaling element \<flow>+extern ElementId ELEM_FLOW; ///< Marshaling element \<flow>extern ElementId ELEM_FORCEGOTO; ///< Marshaling element \<forcegoto>-extern ElementId ELEM_INDIRECTOVERRIDE; ///< Marshaling element \<indirectoverride>+extern ElementId ELEM_CALLDEST; ///< Marshaling element \<calldest>extern ElementId ELEM_MULTISTAGEJUMP; ///< Marshaling element \<multistagejump>extern ElementId ELEM_OVERRIDE; ///< Marshaling element \<override>extern ElementId ELEM_PROTOOVERRIDE; ///< Marshaling element \<protooverride>@@ -49,21 +49,111 @@ extern ElementId ELEM_PROTOOVERRIDE; ///< Marshaling element \<protooverride>/// calling the apply* or get* methods.class Override {public:- /// \brief Enumeration of possible branch overrides- enum {- NONE = 0, ///< No override- BRANCH = 1, ///< Replace primary CALL or RETURN with suitable BRANCH operation- CALL = 2, ///< Replace primary BRANCH or RETURN with suitable CALL operation- CALL_RETURN = 3, ///< Replace primary BRANCH or RETURN with suitable CALL/RETURN operation- RETURN = 4 ///< Replace primary BRANCH or CALL with a suitable RETURN operation+ /// \brief Abstract class performing an override of p-code on an instruction+ ///+ /// Instances operate directly on raw p-code emitted for a single instruction,+ /// prior to incorporation in the syntax tree.+ class Record {+ public:+ virtual ~Record(void) {} ///< Destructor++ /// \brief Perform p-code modifications for the instruction at the given address+ ///+ /// \param addr is the given address of the instruction+ /// \param data is the function+ virtual void performOverride(const Address &addr,Funcdata &data) const=0;++ /// \brief Encode \b this record to stream+ ///+ /// \param encoder is the stream+ /// \param addr is the address of the instruction the override applies to+ virtual void encode(Encoder &encoder,const Address &addr) const=0;++ /// \brief Print a description of the override as a console message+ ///+ /// \param s is the stream to write to+ /// \param addr is the address \b this override applies to+ virtual void printRaw(ostream &s,const Address &addr) const=0;++ static Record *allocateFlow(const string &name); ///< Return a corresponding flow override record+ static Record *allocateCallDest(const string &name,const Address &dest); ///< Return a corresponding call destination override+ };++ /// \brief Override a CALL, CALLIND, or RETURN to become a BRANCH or BRANCHIND+ class Branch : public Record {+ public:+ virtual void performOverride(const Address &addr,Funcdata &data) const;+ virtual void encode(Encoder &encoder,const Address &addr) const;+ virtual void printRaw(ostream &s,const Address &addr) const;+ static const string NAME;+ };++ /// \brief Override a BRANCH, BRANCHIND, or RETURN to become a CALL or CALLIND operation+ class Call : public Record {+ public:+ virtual void performOverride(const Address &addr,Funcdata &data) const;+ virtual void encode(Encoder &encoder,const Address &addr) const;+ virtual void printRaw(ostream &s,const Address &addr) const;+ static const string NAME;+ };++ /// \brief Override a BRANCH, BRANCHIND, or RETURN to become a CALL or CALLIND, followed by a RETURN+ class CallReturn : public Record {+ public:+ virtual void performOverride(const Address &addr,Funcdata &data) const;+ virtual void encode(Encoder &encoder,const Address &addr) const;+ virtual void printRaw(ostream &s,const Address &addr) const;+ static const string NAME;+ };++ /// \brief Override a BRANCHIND or CALLIND to become a RETURN+ class Return : public Record {+ public:+ virtual void performOverride(const Address &addr,Funcdata &data) const;+ virtual void encode(Encoder &encoder,const Address &addr) const;+ virtual void printRaw(ostream &s,const Address &addr) const;+ static const string NAME;+ };++ /// \brief Convert a CALLOTHER to a direct CALL+ class CallotherCall : public Record {+ Address callAddress; ///< Address of direct CALL+ public:+ CallotherCall(const Address &dest) : callAddress(dest) {}+ virtual void performOverride(const Address &addr,Funcdata &data) const;+ virtual void encode(Encoder &encoder,const Address &addr) const;+ virtual void printRaw(ostream &s,const Address &addr) const;+ static const string NAME;+ };++ /// \brief Convert a CALLOTHER to a BRANCH+ class CallotherBranch : public Record {+ Address branchAddress; ///< Destination of BRANCH+ public:+ CallotherBranch(const Address &dest) : branchAddress(dest) {}+ virtual void performOverride(const Address &addr,Funcdata &data) const;+ virtual void encode(Encoder &encoder,const Address &addr) const;+ virtual void printRaw(ostream &s,const Address &addr) const;+ static const string NAME;+ };++ /// \brief Convert CALL or CALLIND into a CALL with a new destination address+ class CallCall : public Record {+ Address callAddress; ///< Address of (new) CALL+ public:+ CallCall(const Address &dest) : callAddress(dest) {}+ virtual void performOverride(const Address &addr,Funcdata &data) const;+ virtual void encode(Encoder &encoder,const Address &addr) const;+ virtual void printRaw(ostream &s,const Address &addr) const;+ static const string NAME;};private:+ map<Address,Record *> pcodeover; ///< Raw p-code overrides for instructionsmap<Address,Address> forcegoto; ///< Force goto on jump at \b targetpc to \b destpcvector<int4> deadcodedelay; ///< Delay count indexed by address space- map<Address,Address> indirectover; ///< Override indirect at \b call-point into direct to \b addr+ map<Address,Address> deindirect; ///< Convert CALLIND into CALL with recovered direct \b addrmap<Address,FuncProto *> protoover; ///< Override prototype at \b call-pointvector<Address> multistagejump; ///< Addresses of indirect jumps that need multistage recovery- map<Address,uint4> flowoverride; ///< Override the CALL <-> BRANCHvoid clear(void); ///< Clear the entire set of overridesstatic string generateDeadcodeDelayMessage(int4 index,Architecture *glb);public:@@ -71,24 +161,23 @@ public:void insertForceGoto(const Address &targetpc,const Address &destpc);void insertDeadcodeDelay(AddrSpace *spc,int4 delay);bool hasDeadcodeDelay(AddrSpace *spc) const;- void insertIndirectOverride(const Address &callpoint,const Address &directcall);+ void insertDeindirect(const Address &callPoint,const Address &directAddr);void insertProtoOverride(const Address &callpoint,FuncProto *p);void insertMultistageJump(const Address &addr);- void insertFlowOverride(const Address &addr,uint4 type);+ void insertFlowOverride(const Address &addr,const string &type);+ void insertDestinationOverride(const Address &addr,const Address &dest,const string &type);void applyPrototype(Funcdata &data,FuncCallSpecs &fspecs) const;void applyIndirect(Funcdata &data,FuncCallSpecs &fspecs) const;bool queryMultistageJumptable(const Address &addr) const;void applyDeadCodeDelay(Funcdata &data) const;void applyForceGoto(Funcdata &data) const;- bool hasFlowOverride(void) const { return (!flowoverride.empty()); } ///< Are there any flow overrides- uint4 getFlowOverride(const Address &addr) const;+ bool hasPCodeOverride(void) const { return (!pcodeover.empty()); } ///< Are there any flow overrides+ const Record *getPCodeOverride(const Address &addr) const;void printRaw(ostream &s,Architecture *glb) const;void generateOverrideMessages(vector<string> &messagelist,Architecture *glb) const;void encode(Encoder &encoder,Architecture *glb) const;void decode(Decoder &decoder,Architecture *glb);- static string typeToString(uint4 tp); ///< Convert a flow override type to a string- static uint4 stringToType(const string &nm); ///< Convert a string to a flow override type};} // End namespace ghidradiff --git a/Ghidra/Features/Decompiler/src/decompile/cpp/transform.cc b/Ghidra/Features/Decompiler/src/decompile/cpp/transform.ccindex 538d47bc12..692e3061b1 100644--- a/Ghidra/Features/Decompiler/src/decompile/cpp/transform.cc+++ b/Ghidra/Features/Decompiler/src/decompile/cpp/transform.cc@@ -320,7 +320,7 @@ void LanedRegister::LanedIterator::normalize(void)s.unsetf(ios::dec | ios::hex | ios::oct);int4 sz = -1;s >> sz;- if (sz < 0 || sz > 16)+ if (sz <= 0 || sz >= wholeSize || sz > 16)throw LowlevelError("Bad lane size: " + value);addLaneSize(sz);}diff --git a/Ghidra/Features/Decompiler/src/decompile/datatests/overridedest.xml b/Ghidra/Features/Decompiler/src/decompile/datatests/overridedest.xmlnew file mode 100644index 0000000000..0bbd144202--- /dev/null+++ b/Ghidra/Features/Decompiler/src/decompile/datatests/overridedest.xml@@ -0,0 +1,31 @@+<decompilertest>+ <!--+ Examples of overriding destination addresses+ -->+<binaryimage arch="x86:LE:64:default:gcc">+<bytechunk space="ram" offset="0x100647" readonly="true">+ 4883ec08ffd766e8e9+ff0f050f054883c408c3+</bytechunk>+<symbol space="ram" offset="0x10063a" name="badcall"/>+<symbol space="ram" offset="0x10063d" name="mycallinddest"/>+<symbol space="ram" offset="0x100640" name="mysyscalldest"/>+<symbol space="ram" offset="0x100643" name="mynewcalldest"/>+</binaryimage>+<script>+ <com>map fun r0x100647 overridedest</com>+ <com>override dest r0x10064b call_call r0x10063d</com>+ <com>override dest r0x10064d call_call r0x100643</com>+ <com>override dest r0x100651 callother_call r0x100640</com>+ <com>override dest r0x100653 callother_branch r0x100651</com>+ <com>lo fu overridedest</com>+ <com>dec</com>+ <com>print C</com>+ <com>quit</com>+</script>+<stringmatch name="Override destination #1" min="1" max="1">mycallinddest\(\);</stringmatch>+<stringmatch name="Override destination #2" min="1" max="1">mysyscalldest\(\);</stringmatch>+<stringmatch name="Override destination #3" min="1" max="1">mynewcalldest\(\);</stringmatch>+<stringmatch name="Override destination #4" min="1" max="1">\} while\( true \);</stringmatch>+<stringmatch name="Override destination #5" min="0" max="0">badcall</stringmatch>+</decompilertest>diff --git a/Ghidra/Features/Decompiler/src/main/java/ghidra/app/decompiler/DecompileCallback.java b/Ghidra/Features/Decompiler/src/main/java/ghidra/app/decompiler/DecompileCallback.javaindex 547ddfe1c4..0d6ccdf3b5 100644--- a/Ghidra/Features/Decompiler/src/main/java/ghidra/app/decompiler/DecompileCallback.java+++ b/Ghidra/Features/Decompiler/src/main/java/ghidra/app/decompiler/DecompileCallback.java@@ -223,10 +223,7 @@ public class DecompileCallback {}if (debug != null) {debug.getPcode(addr, instr);- FlowOverride fo = instr.getFlowOverride();- if (fo != FlowOverride.NONE) {- debug.addFlowOverride(addr, fo);- }+ debug.handleOverrides(addr, instr);}instr.getPrototype()diff --git a/Ghidra/Features/Decompiler/src/main/java/ghidra/app/decompiler/DecompileDebug.java b/Ghidra/Features/Decompiler/src/main/java/ghidra/app/decompiler/DecompileDebug.javaindex 956755994c..93bd14f568 100644--- a/Ghidra/Features/Decompiler/src/main/java/ghidra/app/decompiler/DecompileDebug.java+++ b/Ghidra/Features/Decompiler/src/main/java/ghidra/app/decompiler/DecompileDebug.java@@ -37,6 +37,7 @@ import ghidra.program.model.mem.MemoryAccessException;import ghidra.program.model.mem.MemoryBlock;import ghidra.program.model.pcode.*;import ghidra.program.model.symbol.Namespace;+import ghidra.program.model.symbol.RefType;import ghidra.util.Msg;import ghidra.util.xml.SpecXmlUtils;@@ -779,6 +780,37 @@ public class DecompileDebug {flowoverride.add(encoder.toString());}+ public void addDestinationOverride(Address addr, Address destAddr, String type)+ throws IOException {+ XmlEncode encoder = new XmlEncode();+ encoder.openElement(ELEM_CALLDEST);+ encoder.writeString(ATTRIB_TYPE, type);+ AddressXML.encode(encoder, func.getEntryPoint());+ AddressXML.encode(encoder, addr);+ AddressXML.encode(encoder, destAddr);+ encoder.closeElement(ELEM_CALLDEST);+ flowoverride.add(encoder.toString());+ }++ public void handleOverrides(Address addr, Instruction instr) throws IOException {+ InstructionPcodeOverride over = new InstructionPcodeOverride(instr);+ FlowOverride flowOverride = over.getFlowOverride();+ if (flowOverride != FlowOverride.NONE)+ addFlowOverride(addr, flowOverride);+ Address destAddr = over.getOverridingReference(RefType.CALL_OVERRIDE_UNCONDITIONAL);+ if (destAddr != null) {+ addDestinationOverride(addr, destAddr, "call_call");+ }+ destAddr = over.getOverridingReference(RefType.CALLOTHER_OVERRIDE_CALL);+ if (destAddr != null) {+ addDestinationOverride(addr, destAddr, "callother_call");+ }+ destAddr = over.getOverridingReference(RefType.CALLOTHER_OVERRIDE_JUMP);+ if (destAddr != null) {+ addDestinationOverride(addr, destAddr, "callother_branch");+ }+ }+public void addInject(Address addr, String name, int injectType, String payload)throws IOException {XmlEncode encoder = new XmlEncode();diff --git a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/pcode/ElementId.java b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/pcode/ElementId.javaindex b308889907..cd6b429893 100644--- a/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/pcode/ElementId.java+++ b/Ghidra/Framework/SoftwareModeling/src/main/java/ghidra/program/model/pcode/ElementId.java@@ -331,9 +331,9 @@ public record ElementId(String name, int id) {// overridepublic static final ElementId ELEM_DEADCODEDELAY = new ElementId("deadcodedelay", 218);public static final ElementId ELEM_FLOW = new ElementId("flow", 219);- public static final ElementId ELEM_FORCEGOTO = new ElementId("forcegoto", 220);- public static final ElementId ELEM_INDIRECTOVERRIDE = new ElementId("indirectoverride", 221);- public static final ElementId ELEM_MULTISTAGEJUMP = new ElementId("multistagejump", 222);+// public static final ElementId ELEM_FORCEGOTO = new ElementId("forcegoto", 220);+ public static final ElementId ELEM_CALLDEST = new ElementId("calldest", 221);+// public static final ElementId ELEM_MULTISTAGEJUMP = new ElementId("multistagejump", 222);public static final ElementId ELEM_OVERRIDE = new ElementId("override", 223);public static final ElementId ELEM_PROTOOVERRIDE = new ElementId("protooverride", 224);