Ghidra is a software reverse engineering (SRE) framework
GP-6757 unique_ptr protections
caheckmandc38904b1627
diff --git a/Ghidra/Features/Decompiler/src/decompile/cpp/architecture.cc b/Ghidra/Features/Decompiler/src/decompile/cpp/architecture.ccindex e71bf7ad44..8efa97962e 100644--- a/Ghidra/Features/Decompiler/src/decompile/cpp/architecture.cc+++ b/Ghidra/Features/Decompiler/src/decompile/cpp/architecture.cc@@ -624,8 +624,9 @@ void Architecture::postSpecFile(void)void Architecture::restoreFromSpec(DocumentStorage &store){- Translate *newtrans = buildTranslator(store); // Once language is described we can build translator- newtrans->initialize(store);+ unique_ptr<Translate> utrans(buildTranslator(store)); // Once language is described we can build translator+ utrans->initialize(store);+ Translate *newtrans = utrans.release();translate = newtrans;modifySpaces(newtrans); // Give architecture chance to modify spaces, before copyingcopySpaces(newtrans);@@ -741,23 +742,21 @@ void Architecture::decodeDynamicRule(Decoder &decoder)ProtoModel *Architecture::decodeProto(Decoder &decoder){- ProtoModel *res;+ unique_ptr<ProtoModel> umodel;uint4 elemId = decoder.peekElement();if (elemId == ELEM_PROTOTYPE)- res = new ProtoModel(this);+ umodel.reset(new ProtoModel(this));else if (elemId == ELEM_RESOLVEPROTOTYPE)- res = new ProtoModelMerged(this);+ umodel.reset(new ProtoModelMerged(this));elsethrow LowlevelError("Expecting <prototype> or <resolveprototype> tag");- res->decode(decoder);+ umodel->decode(decoder);- ProtoModel *other = getModel(res->getName());- if (other != (ProtoModel *)0) {- string errMsg = "Duplicate ProtoModel name: " + res->getName();- delete res;- throw LowlevelError(errMsg);- }+ ProtoModel *other = getModel(umodel->getName());+ if (other != (ProtoModel *)0)+ throw LowlevelError("Duplicate ProtoModel name: " + umodel->getName());+ ProtoModel *res = umodel.release();protoModels[res->getName()] = res;return res;}diff --git a/Ghidra/Features/Decompiler/src/decompile/cpp/bfd_arch.cc b/Ghidra/Features/Decompiler/src/decompile/cpp/bfd_arch.ccindex a3f111f173..5a028a8864 100644--- a/Ghidra/Features/Decompiler/src/decompile/cpp/bfd_arch.cc+++ b/Ghidra/Features/Decompiler/src/decompile/cpp/bfd_arch.cc@@ -5,9 +5,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.@@ -67,19 +67,19 @@ bool BfdArchitectureCapability::isXmlMatch(Document *doc) constvoid BfdArchitecture::buildLoader(DocumentStorage &store){- LoadImageBfd *ldr;+ unique_ptr<LoadImageBfd> ldr;collectSpecFiles(*errorstream);if (getTarget().find("binary")==0)- ldr = new LoadImageBfd(getFilename(),"binary");+ ldr.reset(new LoadImageBfd(getFilename(),"binary"));else if (getTarget().find("default")==0)- ldr = new LoadImageBfd(getFilename(),"default");+ ldr.reset(new LoadImageBfd(getFilename(),"default"));else- ldr = new LoadImageBfd(getFilename(),getTarget());+ ldr.reset(new LoadImageBfd(getFilename(),getTarget()));ldr->open();if (adjustvma!=0)ldr->adjustVma(adjustvma);- loader = ldr;+ loader = ldr.release();}void BfdArchitecture::resolveArchitecture(void)diff --git a/Ghidra/Features/Decompiler/src/decompile/cpp/block.cc b/Ghidra/Features/Decompiler/src/decompile/cpp/block.ccindex bf7103d916..615057605d 100644--- a/Ghidra/Features/Decompiler/src/decompile/cpp/block.cc+++ b/Ghidra/Features/Decompiler/src/decompile/cpp/block.cc@@ -1402,7 +1402,7 @@ void BlockGraph::decodeBody(Decoder &decoder){BlockMap newresolver;- vector<FlowBlock *> tmplist;+ vector<unique_ptr<FlowBlock> > tmplist;for(;;) {uint4 subId = decoder.peekElement();@@ -1411,15 +1411,14 @@ void BlockGraph::decodeBody(Decoder &decoder)int4 newindex = decoder.readSignedInteger(ATTRIB_INDEX);FlowBlock *bl = newresolver.createBlock(decoder.readString(ATTRIB_TYPE));bl->index = newindex; // Need to set index here for sort- tmplist.push_back(bl);+ tmplist.push_back(unique_ptr<FlowBlock>(bl));decoder.closeElement(subId);}newresolver.sortList();for(int4 i=0;i<tmplist.size();++i) {- FlowBlock *bl = tmplist[i];- bl->decode(decoder,newresolver);- addBlock(bl);+ tmplist[i]->decode(decoder,newresolver);+ addBlock(tmplist[i].release());}}@@ -1905,12 +1904,13 @@ BlockSwitch *BlockGraph::newBlockSwitch(const vector<FlowBlock *> &cs,bool hasEx{FlowBlock *rootbl = cs[0];- BlockSwitch *ret = new BlockSwitch(rootbl);+ unique_ptr<BlockSwitch> uret( new BlockSwitch(rootbl) );const FlowBlock *leafbl = rootbl->getExitLeaf();if ((leafbl == (const FlowBlock *)0)||(leafbl->getType() != FlowBlock::t_copy))throw LowlevelError("Could not get switch leaf");- ret->grabCaseBasic(leafbl->subBlock(0),cs); // Must be called before the identifyInternal- identifyInternal(ret,cs);+ uret->grabCaseBasic(leafbl->subBlock(0),cs); // Must be called before the identifyInternal+ identifyInternal(uret.get(),cs);+ BlockSwitch *ret = uret.release();addBlock(ret);if (hasExit)ret->forceOutputNum(1); // If there is an exit, there should be exactly 1 out edgediff --git a/Ghidra/Features/Decompiler/src/decompile/cpp/consolemain.cc b/Ghidra/Features/Decompiler/src/decompile/cpp/consolemain.ccindex d31e287580..87c13b8184 100644--- a/Ghidra/Features/Decompiler/src/decompile/cpp/consolemain.cc+++ b/Ghidra/Features/Decompiler/src/decompile/cpp/consolemain.cc@@ -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.@@ -206,43 +206,38 @@ int main(int argc,char **argv)startDecompilerLibrary(ghidraroot.c_str(), extrapaths);}- IfaceStatus *status;+ int4 retval = 2;try {- status = new IfaceTerm("[decomp]> ",cin,cout); // Set up interface- } catch(IfaceError &err) {- cerr << "Interface error during setup: " << err.explain << endl;- exit(1);- }- IfaceCapability::registerAllCommands(status); // Register commands for decompiler and all modules-- // Extra commands specific to the console application- status->registerCom(new IfcLoadFile(),"load","file");- status->registerCom(new IfcAddpath(),"addpath");- status->registerCom(new IfcSave(),"save");- status->registerCom(new IfcRestore(),"restore");-- if (initscript != (const char *)0) {- try {- status->pushScript(initscript,"init> ");- } catch(IfaceParseError &err) {- *status->optr << err.explain << endl;- status->done = true;+ unique_ptr<IfaceStatus> status(new IfaceTerm("[decomp]> ",cin,cout)); // Set up interface+ IfaceCapability::registerAllCommands(status.get()); // Register commands for decompiler and all modules++ // Extra commands specific to the console application+ status->registerCom(new IfcLoadFile(),"load","file");+ status->registerCom(new IfcAddpath(),"addpath");+ status->registerCom(new IfcSave(),"save");+ status->registerCom(new IfcRestore(),"restore");++ if (initscript != (const char *)0) {+ try {+ status->pushScript(initscript,"init> ");+ } catch(IfaceParseError &err) {+ *status->optr << err.explain << endl;+ status->done = true;+ }}- }- if (!status->done)- mainloop(status);- int4 retval = status->isInError() ? 1 : 0;+ if (!status->done)+ mainloop(status.get());+ retval = status->isInError() ? 1 : 0;#ifdef CPUI_STATISTICS- IfaceDecompData *decompdata = (IfaceDecompData *)status->getData("decompile");- decompdata->conf->stats->printResults(cout);+ IfaceDecompData *decompdata = (IfaceDecompData *)status->getData("decompile");+ decompdata->conf->stats->printResults(cout);#endif- try {- delete status;} catch(IfaceError &err) {- cerr << err.explain << endl;+ cerr << "Interface error: " << err.explain << endl;+ retval = 2;}shutdownDecompilerLibrary();diff --git a/Ghidra/Features/Decompiler/src/decompile/cpp/database.cc b/Ghidra/Features/Decompiler/src/decompile/cpp/database.ccindex c6529baea5..b8907a6ef3 100644--- a/Ghidra/Features/Decompiler/src/decompile/cpp/database.cc+++ b/Ghidra/Features/Decompiler/src/decompile/cpp/database.cc@@ -1585,7 +1585,7 @@ Symbol *Scope::addMapSym(Decoder &decoder)throw LowlevelError("Unknown symbol type");try { // Protect against duplicate scope errorssym->decode(decoder);- } catch(RecovError &err) {+ } catch(...) {delete sym;throw;}@@ -2946,28 +2946,24 @@ Database::~Database(void)void Database::attachScope(Scope *newscope,Scope *parent){+ unique_ptr<Scope> uscope(newscope);if (parent == (Scope *)0) {if (globalscope != (Scope *)0)throw LowlevelError("Multiple global scopes");- if (newscope->name.size() != 0)+ if (uscope->name.size() != 0)throw LowlevelError("Global scope does not have empty name");- globalscope = newscope;+ globalscope = uscope.release();idmap[globalscope->uniqueId] = globalscope;return;}- if (newscope->name.size()==0)+ if (uscope->name.size()==0)throw LowlevelError("Non-global scope has empty name");- pair<uint8,Scope *> value(newscope->uniqueId,newscope);+ pair<uint8,Scope *> value(uscope->uniqueId,uscope.get());pair<ScopeMap::iterator,bool> res;res = idmap.insert(value);- if (res.second==false) {- ostringstream s;- s << "Duplicate scope id: ";- s << newscope->getFullName();- delete newscope;- throw RecovError(s.str());- }- parent->attachScope(newscope);+ if (res.second==false)+ throw RecovError("Duplicate scope id: " + uscope->getFullName());+ parent->attachScope(uscope.release());}/// Give \b this database the chance to inform existing scopes of any change to the@@ -3375,17 +3371,18 @@ void Database::decode(Decoder &decoder)void Database::decodeScope(Decoder &decoder,Scope *newScope){+ unique_ptr<Scope> uscope(newScope);uint4 elemId = decoder.openElement();if (elemId == ELEM_SCOPE) {Scope *parentScope = parseParentTag(decoder);- attachScope(newScope,parentScope);+ attachScope(uscope.release(),parentScope);newScope->decode(decoder);}else {- newScope->decodeWrappingAttributes(decoder);+ uscope->decodeWrappingAttributes(decoder);uint4 subId = decoder.openElement(ELEM_SCOPE);Scope *parentScope = parseParentTag(decoder);- attachScope(newScope,parentScope);+ attachScope(uscope.release(),parentScope);newScope->decode(decoder);decoder.closeElement(subId);}diff --git a/Ghidra/Features/Decompiler/src/decompile/cpp/error.hh b/Ghidra/Features/Decompiler/src/decompile/cpp/error.hhindex f61227fef0..d294a993a3 100644--- a/Ghidra/Features/Decompiler/src/decompile/cpp/error.hh+++ b/Ghidra/Features/Decompiler/src/decompile/cpp/error.hh@@ -33,6 +33,7 @@#include <algorithm>#include <cstring>#include <cctype>+#include <memory>namespace ghidra {@@ -65,6 +66,7 @@ using std::max;using std::to_string;using std::piecewise_construct;using std::forward_as_tuple;+using std::unique_ptr;/// \brief The lowest level error generated by the decompilerdiff --git a/Ghidra/Features/Decompiler/src/decompile/cpp/flow.cc b/Ghidra/Features/Decompiler/src/decompile/cpp/flow.ccindex b16f794910..0add3cc173 100644--- a/Ghidra/Features/Decompiler/src/decompile/cpp/flow.cc+++ b/Ghidra/Features/Decompiler/src/decompile/cpp/flow.cc@@ -682,8 +682,8 @@ bool FlowInfo::setupCallSpecs(PcodeOp *op,FuncCallSpecs *fc){FuncCallSpecs *res;res = new FuncCallSpecs(op);- data.opSetInput(op,data.newVarnodeCallSpecs(res),0);qlst.push_back(res);+ data.opSetInput(op,data.newVarnodeCallSpecs(res),0);data.getOverride().applyPrototype(data,*res);queryCall(*res);diff --git a/Ghidra/Features/Decompiler/src/decompile/cpp/funcdata.cc b/Ghidra/Features/Decompiler/src/decompile/cpp/funcdata.ccindex f004922e9c..72809aefac 100644--- a/Ghidra/Features/Decompiler/src/decompile/cpp/funcdata.cc+++ b/Ghidra/Features/Decompiler/src/decompile/cpp/funcdata.cc@@ -615,9 +615,9 @@ void Funcdata::decodeJumpTable(Decoder &decoder){uint4 elemId = decoder.openElement(ELEM_JUMPTABLELIST);while(decoder.peekElement() != 0) {- JumpTable *jt = new JumpTable();+ unique_ptr<JumpTable> jt(new JumpTable());jt->decode(decoder);- jumpvec.push_back(jt);+ jumpvec.push_back(jt.release());}decoder.closeElement(elemId);}diff --git a/Ghidra/Features/Decompiler/src/decompile/cpp/ifacedecomp.cc b/Ghidra/Features/Decompiler/src/decompile/cpp/ifacedecomp.ccindex 04bc55619c..e62ab6ab08 100644--- a/Ghidra/Features/Decompiler/src/decompile/cpp/ifacedecomp.cc+++ b/Ghidra/Features/Decompiler/src/decompile/cpp/ifacedecomp.cc@@ -1856,12 +1856,12 @@ void IfcProtooverride::execute(istream &s)PrototypePieces pieces;parse_protopieces(pieces,s,dcp->conf); // Parse the prototype from stream- FuncProto *newproto = new FuncProto();+ unique_ptr<FuncProto> newproto(new FuncProto());// Make proto whose storage is internal, not backed by a real scopenewproto->setInternal(pieces.model,dcp->conf->types->getTypeVoid());newproto->setPieces(pieces);- dcp->fd->getOverride().insertProtoOverride(callpoint,newproto);+ dcp->fd->getOverride().insertProtoOverride(callpoint,newproto.release());dcp->fd->clear(); // Clear any analysis (this leaves overrides intact)}diff --git a/Ghidra/Features/Decompiler/src/decompile/cpp/ifaceterm.cc b/Ghidra/Features/Decompiler/src/decompile/cpp/ifaceterm.ccindex 20ca9f663a..3d84ebbf2d 100644--- a/Ghidra/Features/Decompiler/src/decompile/cpp/ifaceterm.cc+++ b/Ghidra/Features/Decompiler/src/decompile/cpp/ifaceterm.cc@@ -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.@@ -249,7 +249,7 @@ void IfaceTerm::pushScript(istream *iptr,const string &newprompt){inputstack.push_back(sptr);sptr = iptr;- IfaceStatus::pushScript(iptr,newprompt);+ IfaceStatus::pushScript((istream *)0,newprompt);}void IfaceTerm::popScript(void)diff --git a/Ghidra/Features/Decompiler/src/decompile/cpp/interface.cc b/Ghidra/Features/Decompiler/src/decompile/cpp/interface.ccindex 85f5f91df3..ab23a13cb7 100644--- a/Ghidra/Features/Decompiler/src/decompile/cpp/interface.cc+++ b/Ghidra/Features/Decompiler/src/decompile/cpp/interface.cc@@ -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.@@ -145,8 +145,10 @@ void IfaceStatus::pushScript(const string &filename,const string &newprompt){ifstream *s = new ifstream(filename.c_str());- if (!*s)+ if (!*s) {+ delete s;throw IfaceParseError("Unable to open script file: "+filename);+ }pushScript(s,newprompt);}@@ -159,6 +161,10 @@ void IfaceStatus::pushScript(const string &filename,const string &newprompt)void IfaceStatus::pushScript(istream *iptr,const string &newprompt){+ if (iptr != (istream *)0) {+ delete iptr;+ throw IfaceExecutionError("Unable to read script from stream on this interface");+ }promptstack.push_back(prompt);uint4 flags = 0;if (errorisdone)diff --git a/Ghidra/Features/Decompiler/src/decompile/cpp/jumptable.cc b/Ghidra/Features/Decompiler/src/decompile/cpp/jumptable.ccindex 936bd5b8aa..42b10f0e99 100644--- a/Ghidra/Features/Decompiler/src/decompile/cpp/jumptable.cc+++ b/Ghidra/Features/Decompiler/src/decompile/cpp/jumptable.cc@@ -2482,11 +2482,11 @@ void JumpTable::setOverride(const vector<Address> &addrtable,const Address &naddif (jmodel != (JumpModel *)0)delete jmodel;- JumpBasicOverride *override;- jmodel = override = new JumpBasicOverride(this);- override->setAddresses(addrtable);- override->setNorm(naddr,h);- override->setStartingValue(sv);+ JumpBasicOverride *jumpOverride;+ jmodel = jumpOverride = new JumpBasicOverride(this);+ jumpOverride->setAddresses(addrtable);+ jumpOverride->setNorm(naddr,h);+ jumpOverride->setStartingValue(sv);}/// \brief Get the index of the i-th address table entry that corresponds to the given basic-blockdiff --git a/Ghidra/Features/Decompiler/src/decompile/cpp/loadimage.cc b/Ghidra/Features/Decompiler/src/decompile/cpp/loadimage.ccindex 87bcb5de89..558229946c 100644--- a/Ghidra/Features/Decompiler/src/decompile/cpp/loadimage.cc+++ b/Ghidra/Features/Decompiler/src/decompile/cpp/loadimage.cc@@ -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.@@ -30,8 +30,6 @@ uint1 *LoadImage::load(int4 size,const Address &addr){uint1 *buf = new uint1[ size ];- if (buf == (uint1 *)0)- throw LowlevelError("Out of memory");loadFill(buf,size,addr);return buf;}@@ -62,6 +60,7 @@ void RawLoadImage::open(void)thefile = new ifstream(filename.c_str());if (!(*thefile)) {string errmsg = "Unable to open raw image file: "+filename;+ delete thefile;throw LowlevelError(errmsg);}thefile->seekg(0,ios::end);diff --git a/Ghidra/Features/Decompiler/src/decompile/cpp/modelrules.cc b/Ghidra/Features/Decompiler/src/decompile/cpp/modelrules.ccindex 2335bc012d..3f4bb8ef35 100644--- a/Ghidra/Features/Decompiler/src/decompile/cpp/modelrules.cc+++ b/Ghidra/Features/Decompiler/src/decompile/cpp/modelrules.cc@@ -252,23 +252,23 @@ PrimitiveExtractor::PrimitiveExtractor(Datatype *dt,bool unionIllegal,int offsetDatatypeFilter *DatatypeFilter::decodeFilter(Decoder &decoder){- DatatypeFilter *filter;+ unique_ptr<DatatypeFilter> filter;uint4 elemId = decoder.openElement(ELEM_DATATYPE);string nm = decoder.readString(ATTRIB_NAME);if (nm == "any") {- filter = new SizeRestrictedFilter();+ filter.reset(new SizeRestrictedFilter());}else if (nm == "homogeneous-float-aggregate") {- filter = new HomogeneousAggregate(TYPE_FLOAT,4,0,0);+ filter.reset(new HomogeneousAggregate(TYPE_FLOAT,4,0,0));}else {// If no other name matches, assume this is a metatypetype_metatype meta = string2metatype(nm);- filter = new MetaTypeFilter(meta);+ filter.reset(new MetaTypeFilter(meta));}filter->decode(decoder);decoder.closeElement(elemId);- return filter;+ return filter.release();}/// Parse the given string as a comma or space separated list of decimal integers,@@ -451,18 +451,18 @@ void HomogeneousAggregate::decode(Decoder &decoder)QualifierFilter *QualifierFilter::decodeFilter(Decoder &decoder){- QualifierFilter *filter;+ unique_ptr<QualifierFilter> filter;uint4 elemId = decoder.peekElement();if (elemId == ELEM_VARARGS)- filter = new VarargsFilter();+ filter.reset(new VarargsFilter());else if (elemId == ELEM_POSITION)- filter = new PositionMatchFilter(-1);+ filter.reset(new PositionMatchFilter(-1));else if (elemId == ELEM_DATATYPE_AT)- filter = new DatatypeMatchFilter();+ filter.reset(new DatatypeMatchFilter());elsereturn (QualifierFilter *)0;filter->decode(decoder);- return filter;+ return filter.release();}/// The AndFilter assumes ownership of all the filters in the array and the original vector is cleared@@ -592,32 +592,32 @@ bool AssignAction::fillinOutputMap(ParamActive *active) constAssignAction *AssignAction::decodeAction(Decoder &decoder,const ParamListStandard *res){- AssignAction *action;+ unique_ptr<AssignAction> action;uint4 elemId = decoder.peekElement();if (elemId == ELEM_GOTO_STACK)- action = new GotoStack(res,0);+ action.reset(new GotoStack(res,0));else if (elemId == ELEM_JOIN) {- action = new MultiSlotAssign(res);+ action.reset(new MultiSlotAssign(res));}else if (elemId == ELEM_CONSUME) {- action = new ConsumeAs(TYPECLASS_GENERAL,res);+ action.reset(new ConsumeAs(TYPECLASS_GENERAL,res));}else if (elemId == ELEM_CONVERT_TO_PTR) {- action = new ConvertToPointer(res);+ action.reset(new ConvertToPointer(res));}else if (elemId == ELEM_HIDDEN_RETURN) {- action = new HiddenReturnAssign(res,hiddenret_specialreg);+ action.reset(new HiddenReturnAssign(res,hiddenret_specialreg));}else if (elemId == ELEM_JOIN_PER_PRIMITIVE) {- action = new MultiMemberAssign(TYPECLASS_GENERAL,false,res->isBigEndian(),res);+ action.reset(new MultiMemberAssign(TYPECLASS_GENERAL,false,res->isBigEndian(),res));}else if (elemId == ELEM_JOIN_DUAL_CLASS) {- action = new MultiSlotDualAssign(res);+ action.reset(new MultiSlotDualAssign(res));}elsethrow DecoderError("Expecting model rule action");action->decode(decoder);- return action;+ return action.release();}/// \brief Read the next model rule precondition element from the stream@@ -629,18 +629,18 @@ AssignAction *AssignAction::decodeAction(Decoder &decoder,const ParamListStandar/// \return the new precondition, or null if no more preconditions are in the streamAssignAction *AssignAction::decodePrecondition(Decoder &decoder,const ParamListStandard *res){- AssignAction *action;+ unique_ptr<AssignAction> action;uint4 elemId = decoder.peekElement();if (elemId == ELEM_CONSUME_EXTRA) {- action = new ConsumeExtra(res);+ action.reset(new ConsumeExtra(res));}else {return (AssignAction *)0;}action->decode(decoder);- return action;+ return action.release();}/// \brief Read the next model rule sideeffect element from the stream@@ -653,22 +653,22 @@ AssignAction *AssignAction::decodePrecondition(Decoder &decoder,const ParamListSAssignAction *AssignAction::decodeSideeffect(Decoder &decoder,const ParamListStandard *res){- AssignAction *action;+ unique_ptr<AssignAction> action;uint4 elemId = decoder.peekElement();if (elemId == ELEM_CONSUME_EXTRA) {- action = new ConsumeExtra(res);+ action.reset(new ConsumeExtra(res));}else if (elemId == ELEM_EXTRA_STACK) {- action = new ExtraStack(res);+ action.reset(new ExtraStack(res));}else if (elemId == ELEM_CONSUME_REMAINING) {- action = new ConsumeRemaining(res);+ action.reset(new ConsumeRemaining(res));}elsethrow DecoderError("Expecting model rule sideeffect");action->decode(decoder);- return action;+ return action.release();}/// \brief Truncate a tiling by a given number of bytes@@ -1695,9 +1695,9 @@ void ModelRule::decode(Decoder &decoder,const ParamListStandard *res)qualifier = new AndFilter(qualifiers);}for (;;) {- AssignAction *precond = AssignAction::decodePrecondition(decoder, res);- if (precond == (AssignAction *)0)- break;+ AssignAction *precond = AssignAction::decodePrecondition(decoder, res);+ if (precond == (AssignAction *)0)+ break;preconditions.push_back(precond);}assign = AssignAction::decodeAction(decoder, res);diff --git a/Ghidra/Features/Decompiler/src/decompile/cpp/override.cc b/Ghidra/Features/Decompiler/src/decompile/cpp/override.ccindex f6fd0f5524..0c2b57342f 100644--- a/Ghidra/Features/Decompiler/src/decompile/cpp/override.cc+++ b/Ghidra/Features/Decompiler/src/decompile/cpp/override.cc@@ -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.@@ -367,10 +367,10 @@ void Override::decode(Decoder &decoder,Architecture *glb)}else if (subId == ELEM_PROTOOVERRIDE) {Address callpoint = Address::decode(decoder);- FuncProto *fp = new FuncProto();+ unique_ptr<FuncProto> fp(new FuncProto());fp->setInternal(glb->defaultfp,glb->types->getTypeVoid());fp->decode(decoder,glb);- insertProtoOverride(callpoint,fp);+ insertProtoOverride(callpoint,fp.release());}else if (subId == ELEM_FORCEGOTO) {Address targetpc = Address::decode(decoder);diff --git a/Ghidra/Features/Decompiler/src/decompile/cpp/raw_arch.cc b/Ghidra/Features/Decompiler/src/decompile/cpp/raw_arch.ccindex 9e4169cc18..48dcc8b1b4 100644--- a/Ghidra/Features/Decompiler/src/decompile/cpp/raw_arch.cc+++ b/Ghidra/Features/Decompiler/src/decompile/cpp/raw_arch.cc@@ -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.@@ -55,14 +55,12 @@ bool RawBinaryArchitectureCapability::isXmlMatch(Document *doc) constvoid RawBinaryArchitecture::buildLoader(DocumentStorage &store){- RawLoadImage *ldr;-collectSpecFiles(*errorstream);- ldr = new RawLoadImage(getFilename());+ unique_ptr<RawLoadImage> ldr(new RawLoadImage(getFilename()));ldr->open();if (adjustvma != 0)ldr->adjustVma(adjustvma);- loader = ldr;+ loader = ldr.release();}void RawBinaryArchitecture::resolveArchitecture(void)diff --git a/Ghidra/Features/Decompiler/src/decompile/cpp/semantics.cc b/Ghidra/Features/Decompiler/src/decompile/cpp/semantics.ccindex 18e2ff8ba1..7b06da8e0b 100644--- a/Ghidra/Features/Decompiler/src/decompile/cpp/semantics.cc+++ b/Ghidra/Features/Decompiler/src/decompile/cpp/semantics.cc@@ -721,8 +721,8 @@ void OpTpl::decode(Decoder &decoder)}while(decoder.peekElement() != 0) {VarnodeTpl *vn = new VarnodeTpl();- vn->decode(decoder);input.push_back(vn);+ vn->decode(decoder);}decoder.closeElement(el);}@@ -915,8 +915,8 @@ int4 ConstructTpl::decode(Decoder &decoder)}while(decoder.peekElement() != 0) {OpTpl *op = new OpTpl();- op->decode(decoder);vec.push_back(op);+ op->decode(decoder);}decoder.closeElement(el);return sectionid;diff --git a/Ghidra/Features/Decompiler/src/decompile/cpp/sleigh.cc b/Ghidra/Features/Decompiler/src/decompile/cpp/sleigh.ccindex 320416f746..0c56b2e162 100644--- a/Ghidra/Features/Decompiler/src/decompile/cpp/sleigh.cc+++ b/Ghidra/Features/Decompiler/src/decompile/cpp/sleigh.cc@@ -453,8 +453,8 @@ void DisassemblyCache::initialize(int4 min,int4 hashsize)hashtable = new ParserContext *[hashsize];for(int4 i=0;i<minimumreuse;++i) {ParserContext *pos = new ParserContext(contextcache,translate);- pos->initialize(75,20,constspace);list[i] = pos;+ pos->initialize(75,20,constspace);}ParserContext *pos = list[0];for(int4 i=0;i<hashsize;++i)diff --git a/Ghidra/Features/Decompiler/src/decompile/cpp/slghpatexpress.cc b/Ghidra/Features/Decompiler/src/decompile/cpp/slghpatexpress.ccindex 9410978595..03bc815c9a 100644--- a/Ghidra/Features/Decompiler/src/decompile/cpp/slghpatexpress.cc+++ b/Ghidra/Features/Decompiler/src/decompile/cpp/slghpatexpress.cc@@ -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.@@ -504,8 +504,12 @@ PatternExpression *PatternExpression::decodeExpression(Decoder &decoder,Translatres = new NotExpression();elsereturn (PatternExpression *)0;-- res->decode(decoder,trans);+ try {+ res->decode(decoder,trans);+ } catch(...) {+ delete res;+ throw;+ }return res;}diff --git a/Ghidra/Features/Decompiler/src/decompile/cpp/slghpattern.cc b/Ghidra/Features/Decompiler/src/decompile/cpp/slghpattern.ccindex fc993930b4..b74e204efd 100644--- a/Ghidra/Features/Decompiler/src/decompile/cpp/slghpattern.cc+++ b/Ghidra/Features/Decompiler/src/decompile/cpp/slghpattern.cc@@ -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.@@ -149,8 +149,9 @@ DisjointPattern *DisjointPattern::decodeDisjoint(Decoder &decoder)res = new ContextPattern();elseres = new CombinePattern();- res->decode(decoder);- return res;+ unique_ptr<DisjointPattern> upattern(res);+ upattern->decode(decoder);+ return upattern.release();}void PatternBlock::normalize(void)diff --git a/Ghidra/Features/Decompiler/src/decompile/cpp/slghsymbol.cc b/Ghidra/Features/Decompiler/src/decompile/cpp/slghsymbol.ccindex e62c4708b2..f77a4a0aa3 100644--- a/Ghidra/Features/Decompiler/src/decompile/cpp/slghsymbol.cc+++ b/Ghidra/Features/Decompiler/src/decompile/cpp/slghsymbol.cc@@ -232,7 +232,9 @@ void SymbolTable::decodeSymbolHeader(Decoder &decoder)sym = new SubtableSymbol();elsethrow SleighError("Bad symbol xml");- sym->decodeHeader(decoder); // Restore basic elements of symbol+ unique_ptr<SleighSymbol> usym(sym);+ usym->decodeHeader(decoder); // Restore basic elements of symbol+ usym.release();symbollist[sym->id] = sym; // Put the basic symbol in the tabletable[sym->scopeid]->addSymbol(sym); // to allow recursion}@@ -1631,28 +1633,28 @@ void Constructor::decode(Decoder &decoder,SleighBase *trans)}else if (subel == sla::ELEM_CONTEXT_OP) {ContextOp *c_op = new ContextOp();- c_op->decode(decoder,trans);context.push_back(c_op);+ c_op->decode(decoder,trans);}else if (subel == sla::ELEM_COMMIT) {ContextCommit *c_op = new ContextCommit();- c_op->decode(decoder,trans);context.push_back(c_op);+ c_op->decode(decoder,trans);}else {- ConstructTpl *cur = new ConstructTpl();+ unique_ptr<ConstructTpl> cur(new ConstructTpl());int4 sectionid = cur->decode(decoder);if (sectionid < 0) {if (templ != (ConstructTpl *)0)throw LowlevelError("Duplicate main section");- templ = cur;+ templ = cur.release();}else {while(namedtempl.size() <= sectionid)namedtempl.push_back((ConstructTpl *)0);if (namedtempl[sectionid] != (ConstructTpl *)0)throw LowlevelError("Duplicate named section");- namedtempl[sectionid] = cur;+ namedtempl[sectionid] = cur.release();}}subel = decoder.peekElement();@@ -2341,8 +2343,8 @@ void DecisionNode::decode(Decoder &decoder,DecisionNode *par,SubtableSymbol *sub}else if (subel == sla::ELEM_DECISION) {DecisionNode *subnode = new DecisionNode();- subnode->decode(decoder,this,sub);children.push_back(subnode);+ subnode->decode(decoder,this,sub);}subel = decoder.peekElement();}diff --git a/Ghidra/Features/Decompiler/src/decompile/cpp/translate.cc b/Ghidra/Features/Decompiler/src/decompile/cpp/translate.ccindex 98060c2b96..3e23891a17 100644--- a/Ghidra/Features/Decompiler/src/decompile/cpp/translate.cc+++ b/Ghidra/Features/Decompiler/src/decompile/cpp/translate.cc@@ -258,20 +258,20 @@ AddrSpace *AddrSpaceManager::decodeSpace(Decoder &decoder,const Translate *trans{uint4 elemId = decoder.peekElement();- AddrSpace *res;+ unique_ptr<AddrSpace> res;if (elemId == ELEM_SPACE_BASE)- res = new SpacebaseSpace(this,trans);+ res.reset(new SpacebaseSpace(this,trans));else if (elemId == ELEM_SPACE_UNIQUE)- res = new UniqueSpace(this,trans);+ res.reset(new UniqueSpace(this,trans));else if (elemId == ELEM_SPACE_OTHER)- res = new OtherSpace(this,trans);+ res.reset(new OtherSpace(this,trans));else if (elemId == ELEM_SPACE_OVERLAY)- res = new OverlaySpace(this,trans);+ res.reset(new OverlaySpace(this,trans));else- res = new AddrSpace(this,trans,IPTR_PROCESSOR);+ res.reset(new AddrSpace(this,trans,IPTR_PROCESSOR));res->decode(decoder);- return res;+ return res.release();}/// This routine initializes (almost) all the address spaces used@@ -352,49 +352,49 @@ void AddrSpaceManager::setReverseJustified(AddrSpace *spc)void AddrSpaceManager::insertSpace(AddrSpace *spc){- bool nameTypeMismatch = false;- bool duplicateName = false;- bool duplicateId = false;+ unique_ptr<AddrSpace> uspc;+ if (spc->refcount == 0)+ uspc.reset(spc); // Take ownership if this is the first referenceswitch(spc->getType()) {case IPTR_CONSTANT:if (spc->getName() != ConstantSpace::NAME)- nameTypeMismatch = true;+ throw LowlevelError("Space " + spc->getName() + " was initialized with wrong type");if (spc->index != ConstantSpace::INDEX)throw LowlevelError("const space must be assigned index 0");constantspace = spc;break;case IPTR_INTERNAL:if (spc->getName() != UniqueSpace::NAME)- nameTypeMismatch = true;+ throw LowlevelError("Space " + spc->getName() + " was initialized with wrong type");if (uniqspace != (AddrSpace *)0)- duplicateName = true;+ throw LowlevelError("Space " + spc->getName() + " was initialized more than once");uniqspace = spc;break;case IPTR_FSPEC:if (spc->getName() != "fspec")- nameTypeMismatch = true;+ throw LowlevelError("Space " + spc->getName() + " was initialized with wrong type");if (fspecspace != (AddrSpace *)0)- duplicateName = true;+ throw LowlevelError("Space " + spc->getName() + " was initialized more than once");fspecspace = spc;break;case IPTR_JOIN:if (spc->getName() != JoinSpace::NAME)- nameTypeMismatch = true;+ throw LowlevelError("Space " + spc->getName() + " was initialized with wrong type");if (joinspace != (AddrSpace *)0)- duplicateName = true;+ throw LowlevelError("Space " + spc->getName() + " was initialized more than once");joinspace = spc;break;case IPTR_IOP:if (spc->getName() != "iop")- nameTypeMismatch = true;+ throw LowlevelError("Space " + spc->getName() + " was initialized with wrong type");if (iopspace != (AddrSpace *)0)- duplicateName = true;+ throw LowlevelError("Space " + spc->getName() + " was initialized more than once");iopspace = spc;break;case IPTR_SPACEBASE:if (spc->getName() == "stack") {if (stackspace != (AddrSpace *)0)- duplicateName = true;+ throw LowlevelError("Space " + spc->getName() + " was initialized more than once");stackspace = spc;}// fallthru@@ -412,26 +412,14 @@ void AddrSpaceManager::insertSpace(AddrSpace *spc)if (baselist.size() <= spc->index)baselist.resize(spc->index+1, (AddrSpace *)0);- duplicateId = baselist[spc->index] != (AddrSpace *)0;+ if (baselist[spc->index] != (AddrSpace *)0)+ throw LowlevelError("Space " + spc->getName() + " was assigned id duplicating: "+baselist[spc->index]->getName());- if (!nameTypeMismatch && !duplicateName && !duplicateId) {- duplicateName = !name2Space.insert(pair<string,AddrSpace *>(spc->getName(),spc)).second;- }+ if (!name2Space.insert(pair<string,AddrSpace *>(spc->getName(),spc)).second)+ throw LowlevelError("Space " + spc->getName() + " was initialized more than once");- if (nameTypeMismatch || duplicateName || duplicateId) {- string errMsg = "Space " + spc->getName();- if (nameTypeMismatch)- errMsg = errMsg + " was initialized with wrong type";- if (duplicateName)- errMsg = errMsg + " was initialized more than once";- if (duplicateId)- errMsg = errMsg + " was assigned as id duplicating: "+baselist[spc->index]->getName();- if (spc->refcount == 0)- delete spc;- spc = (AddrSpace *)0;- throw LowlevelError(errMsg);- }baselist[spc->index] = spc;+ uspc.release();spc->refcount += 1;assignShortcut(spc);}diff --git a/Ghidra/Features/Decompiler/src/decompile/cpp/userop.cc b/Ghidra/Features/Decompiler/src/decompile/cpp/userop.ccindex 9fe8b78d03..5837b2c976 100644--- a/Ghidra/Features/Decompiler/src/decompile/cpp/userop.cc+++ b/Ghidra/Features/Decompiler/src/decompile/cpp/userop.cc@@ -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.@@ -490,6 +490,7 @@ UserPcodeOp *UserOpManage::registerBuiltin(uint4 i)void UserOpManage::registerOp(UserPcodeOp *op){+ unique_ptr<UserPcodeOp> uop(op); // Take ownershipint4 ind = op->getIndex();if (ind < 0) throw LowlevelError("UserOp not assigned an index");@@ -509,7 +510,7 @@ void UserOpManage::registerOp(UserPcodeOp *op)// We assume this registration customizes an existing useropdelete useroplist[ind]; // Delete the old spec}- useroplist[ind] = op; // Index crossref+ useroplist[ind] = uop.release(); // Index crossrefuseropmap[op->getName()] = op; // Name crossrefSegmentOp *s_op = dynamic_cast<SegmentOp *>(op);@@ -533,15 +534,9 @@ void UserOpManage::registerOp(UserPcodeOp *op)void UserOpManage::decodeSegmentOp(Decoder &decoder,Architecture *glb){- SegmentOp *s_op;- s_op = new SegmentOp("",glb,useroplist.size());- try {- s_op->decode(decoder);- registerOp(s_op);- } catch(LowlevelError &err) {- delete s_op;- throw err;- }+ unique_ptr<UserPcodeOp> s_op(new SegmentOp("",glb,useroplist.size()));+ s_op->decode(decoder);+ registerOp(s_op.release());}/// Create either a VolatileReadOp or VolatileWriteOp description object based on@@ -589,14 +584,9 @@ void UserOpManage::decodeVolatile(Decoder &decoder,Architecture *glb)void UserOpManage::decodeCallOtherFixup(Decoder &decoder,Architecture *glb){- InjectedUserOp *op = new InjectedUserOp("",glb,0,0);- try {- op->decode(decoder);- registerOp(op);- } catch(LowlevelError &err) {- delete op;- throw err;- }+ unique_ptr<UserPcodeOp> op(new InjectedUserOp("",glb,0,0));+ op->decode(decoder);+ registerOp(op.release());}/// Create a JumpAssistOp description object based on the element@@ -606,14 +596,9 @@ void UserOpManage::decodeCallOtherFixup(Decoder &decoder,Architecture *glb)void UserOpManage::decodeJumpAssist(Decoder &decoder,Architecture *glb){- JumpAssistOp *op = new JumpAssistOp(glb);- try {- op->decode(decoder);- registerOp(op);- } catch(LowlevelError &err) {- delete op;- throw err;- }+ unique_ptr<UserPcodeOp> op(new JumpAssistOp(glb));+ op->decode(decoder);+ registerOp(op.release());}/// \brief Manually install an InjectedUserOp given just names of the user defined op and the p-code snippet@@ -637,12 +622,7 @@ void UserOpManage::manualCallOtherFixup(const string &useropname,const string &oint4 injectid = glb->pcodeinjectlib->manualCallOtherFixup(useropname,outname,inname,snippet);InjectedUserOp *op = new InjectedUserOp(useropname,glb,userop->getIndex(),injectid);- try {- registerOp(op);- } catch(LowlevelError &err) {- delete op;- throw err;- }+ registerOp(op);}} // End namespace ghidra