From df491a637256c7c100f7b9e15f19bbe4519336f2 Mon Sep 17 00:00:00 2001 From: Jason Hiser <jdhiser@gmail.com> Date: Fri, 25 Jan 2019 14:54:01 -0500 Subject: [PATCH] ir builder works with IRDB-api Former-commit-id: 9a8878428887649e77956c9ff3b59fc037327db7 --- SConstruct | 5 +- dump_insns/SConscript | 5 +- dump_insns/dump_insns.cpp | 33 +- dump_map/SConscript | 5 +- dump_map/dump_map.cpp | 66 +- ir_builders/SConscript | 10 +- ir_builders/calc_conflicts.cpp | 4 +- ir_builders/check_thunks.cpp | 222 ++-- ir_builders/check_thunks.hpp | 6 +- ir_builders/clone.cpp | 26 +- ir_builders/fill_in_cfg.cpp | 240 +++-- ir_builders/fill_in_cfg.hpp | 36 +- ir_builders/fill_in_indtargs.cpp | 1105 ++++++++++---------- ir_builders/fill_in_indtargs.hpp | 50 +- ir_builders/find_strings.cpp | 2 +- ir_builders/fix_calls.cpp | 355 ++++--- ir_builders/read_ehframe.cpp | 38 +- ir_builders/split_eh_frame.cpp | 265 ++--- ir_builders/split_eh_frame.hpp | 32 +- libElfDep/include/libElfDep.hpp | 23 +- libElfDep/src/SConscript | 1 + libElfDep/src/elfdep.cpp | 140 +-- libIRDB/include/cfg/BasicBlock.hpp | 10 +- libIRDB/include/cfg/CFG.hpp | 14 +- libIRDB/include/cfg/callgraph.hpp | 26 +- libIRDB/include/core/IRDB_Objects.hpp | 38 +- libIRDB/include/core/address.hpp | 25 +- libIRDB/include/core/archdesc.hpp | 21 +- libIRDB/include/core/baseobj.hpp | 34 +- libIRDB/include/core/basetypes.hpp | 38 +- libIRDB/include/core/dbinterface.hpp | 20 +- libIRDB/include/core/decode.hpp | 33 +- libIRDB/include/core/decode_base.hpp | 27 +- libIRDB/include/core/decode_csarm.hpp | 27 +- libIRDB/include/core/decode_csx86.hpp | 27 +- libIRDB/include/core/decode_dispatch.hpp | 18 +- libIRDB/include/core/doip.hpp | 14 +- libIRDB/include/core/eh.hpp | 83 +- libIRDB/include/core/file.hpp | 32 +- libIRDB/include/core/fileir.hpp | 180 ++-- libIRDB/include/core/function.hpp | 42 +- libIRDB/include/core/icfs.hpp | 38 +- libIRDB/include/core/instruction.hpp | 71 +- libIRDB/include/core/operand_base.hpp | 7 +- libIRDB/include/core/operand_csarm.hpp | 10 +- libIRDB/include/core/operand_csx86.hpp | 12 +- libIRDB/include/core/operand_dispatch.hpp | 8 +- libIRDB/include/core/pqxxdb.hpp | 23 +- libIRDB/include/core/reloc.hpp | 30 +- libIRDB/include/core/scoop.hpp | 67 +- libIRDB/include/core/transform_step.h | 11 +- libIRDB/include/core/type.hpp | 104 +- libIRDB/include/core/variantid.hpp | 37 +- libIRDB/include/libIRDB-cfg.hpp | 2 + libIRDB/include/libIRDB-core.hpp | 11 +- libIRDB/include/syscall/syscall.hpp | 25 +- libIRDB/include/util/IBT_Provenance.hpp | 8 +- libIRDB/include/util/Provenance.hpp | 2 +- libIRDB/include/util/insn_preds.hpp | 14 +- libIRDB/include/util/params.hpp | 10 +- libIRDB/include/utils.hpp | 5 +- libIRDB/src/cfg/BasicBlock.cpp | 49 +- libIRDB/src/cfg/CFG.cpp | 46 +- libIRDB/src/cfg/SConscript | 1 + libIRDB/src/cfg/callgraph.cpp | 70 +- libIRDB/src/cfg/domgraph.cpp | 8 +- libIRDB/src/core/IRDB_Objects.cpp | 73 +- libIRDB/src/core/SConscript | 5 +- libIRDB/src/core/address.cpp | 8 +- libIRDB/src/core/baseobj.cpp | 9 +- libIRDB/src/core/dbinterface.cpp | 16 +- libIRDB/src/core/decode_base.cpp | 34 +- libIRDB/src/core/decode_csarm.cpp | 23 +- libIRDB/src/core/decode_csx86.cpp | 45 +- libIRDB/src/core/decode_dispatch.cpp | 13 +- libIRDB/src/core/eh.cpp | 26 +- libIRDB/src/core/file.cpp | 4 +- libIRDB/src/core/fileir.cpp | 1139 ++++++++++++--------- libIRDB/src/core/function.cpp | 47 +- libIRDB/src/core/generate_spri.cpp | 196 ++-- libIRDB/src/core/icfs.cpp | 26 +- libIRDB/src/core/instruction.cpp | 95 +- libIRDB/src/core/operand_csarm.cpp | 5 +- libIRDB/src/core/operand_csx86.cpp | 6 +- libIRDB/src/core/pqxxdb.cpp | 19 +- libIRDB/src/core/reloc.cpp | 8 +- libIRDB/src/core/scoop.cpp | 18 +- libIRDB/src/core/type.cpp | 59 +- libIRDB/src/core/variantid.cpp | 212 ++-- libIRDB/src/syscall/Makefile.in | 29 - libIRDB/src/syscall/SConscript | 1 + libIRDB/src/syscall/syscall.cpp | 24 +- libIRDB/src/util/IBT_Provenance.cpp | 17 +- libIRDB/src/util/SConscript | 1 + libIRDB/src/util/insn_preds.cpp | 30 +- libIRDB/src/util/params.cpp | 117 +-- libtransform/include/Rewrite_Utility.hpp | 8 +- libtransform/include/transform.hpp | 30 +- libtransform/src/Rewrite_Utility.cpp | 201 ++-- libtransform/src/SConscript | 1 + libtransform/src/integertransform32.cpp | 394 +++---- libtransform/src/integertransform64.cpp | 270 ++--- libtransform/src/pointercheck64.cpp | 8 +- libtransform/src/transform.cpp | 246 ++--- meds2pdb/SConscript | 2 +- meds2pdb/aspri.h | 2 +- meds2pdb/constant_hash.cpp | 4 +- meds2pdb/constant_hash.h | 6 +- meds2pdb/elfreader.cpp | 25 +- meds2pdb/elfreader.h | 24 +- meds2pdb/framerestore_hash.cpp | 8 +- meds2pdb/framerestore_hash.h | 8 +- meds2pdb/function_descriptor.cpp | 9 +- meds2pdb/function_descriptor.h | 18 +- meds2pdb/instruction_descriptor.cpp | 4 +- meds2pdb/instruction_descriptor.h | 10 +- meds2pdb/instrument.h | 6 +- meds2pdb/meds2pdb.cpp | 31 +- meds2pdb/meds_all.h | 4 +- meds2pdb/null_transform.cpp | 6 +- meds2pdb/read_annot_file.cpp | 4 +- meds2pdb/rewriter.cpp | 37 +- meds2pdb/rewriter.h | 12 +- meds2pdb/stackref_hash.cpp | 4 +- meds2pdb/stackref_hash.h | 6 +- thanos/SConscript | 7 +- thanos/thanos.cpp | 18 +- tools/SConscript | 8 +- tools/selective_cfi/SConscript | 1 + tools/selective_cfi/color_map.cpp | 23 +- tools/selective_cfi/color_map.hpp | 22 +- tools/selective_cfi/scfi_driver.cpp | 38 +- tools/selective_cfi/scfi_instr.cpp | 438 ++++---- tools/selective_cfi/scfi_instr.hpp | 65 +- 134 files changed, 4203 insertions(+), 4157 deletions(-) delete mode 100644 libIRDB/src/syscall/Makefile.in diff --git a/SConstruct b/SConstruct index d678c73e2..1fe720b55 100644 --- a/SConstruct +++ b/SConstruct @@ -15,8 +15,7 @@ env.Replace(LINKFLAGS="-fPIC -fmax-errors=2 -Wall -Werror -fmax-errors=2 ") # parse arguments env.Replace(SECURITY_TRANSFORMS_HOME=os.environ['SECURITY_TRANSFORMS_HOME']) -if 'PEDI_HOME' in os.environ: - env.Replace(PEDI_HOME=os.environ['PEDI_HOME']) +env.Replace(IRDB_SDK=os.environ['IRDB_SDK']) #env.Replace(SMPSA_HOME=os.environ['SMPSA_HOME']) env.Replace(do_64bit_build=ARGUMENTS.get("do_64bit_build",None)) env.Replace(debug=ARGUMENTS.get("debug",0)) @@ -24,6 +23,8 @@ env.Replace(build_appfw=ARGUMENTS.get("build_appfw", 0)) env.Replace(build_tools=ARGUMENTS.get("build_tools", 1)) env.Replace(build_stars=ARGUMENTS.get("build_stars", 1)) env.Replace(build_cgc=ARGUMENTS.get("build_cgc", 0)) +if 'PEDI_HOME' in os.environ: + env.Replace(PEDI_HOME=os.environ['PEDI_HOME']) env.Append(LINKFLAGS=" -Wl,-unresolved-symbols=ignore-in-shared-libs ") diff --git a/dump_insns/SConscript b/dump_insns/SConscript index c8e05de6c..61ea7c0bf 100644 --- a/dump_insns/SConscript +++ b/dump_insns/SConscript @@ -7,10 +7,7 @@ myenv=env.Clone() myenv.Replace(SECURITY_TRANSFORMS_HOME=os.environ['SECURITY_TRANSFORMS_HOME']) cpppath=''' - $SECURITY_TRANSFORMS_HOME/include - $SECURITY_TRANSFORMS_HOME/libIRDB/include - $SECURITY_TRANSFORMS_HOME/libMEDSannotation/include - $SECURITY_TRANSFORMS_HOME/tools/transforms + $IRDB_SDK/include ''' diff --git a/dump_insns/dump_insns.cpp b/dump_insns/dump_insns.cpp index 704b56136..a51b71f07 100644 --- a/dump_insns/dump_insns.cpp +++ b/dump_insns/dump_insns.cpp @@ -20,14 +20,14 @@ #include <stdlib.h> #include <fstream> -#include <libIRDB-core.hpp> +#include <irdb-core> #include <libgen.h> #include <iomanip> #include <algorithm> using namespace std; -using namespace libIRDB; +using namespace IRDB_SDK; void usage(char* name) { @@ -48,39 +48,40 @@ int main(int argc, char **argv) string programName(argv[0]); int variantID = atoi(argv[1]); - VariantID_t *pidp=NULL; /* setup the interface to the sql server */ - pqxxDB_t pqxx_interface; - BaseObj_t::SetInterface(&pqxx_interface); + auto pqxx_interface=pqxxDB_t::factory(); + BaseObj_t::setInterface(pqxx_interface.get()); - pidp=new VariantID_t(variantID); - assert(pidp->IsRegistered()==true); + auto pidp=VariantID_t::factory(variantID); + assert(pidp->isRegistered()==true); bool one_success = false; - for(set<File_t*>::iterator it=pidp->GetFiles().begin(); - it!=pidp->GetFiles().end(); + for(set<File_t*>::iterator it=pidp->getFiles().begin(); + it!=pidp->getFiles().end(); ++it) { File_t* this_file = *it; try { - FileIR_t *firp = new FileIR_t(*pidp, this_file); + auto firp = FileIR_t::factory(pidp.get(), this_file); assert(firp && pidp); - for(auto insn : firp->GetInstructions()) + for(auto insn : firp->getInstructions()) { assert(insn); - const auto d=DecodedInstruction_t(insn); + const auto p_d=DecodedInstruction_t::factory(insn); + const auto &d=*p_d; const auto &operands=d.getOperands(); cout<<" "<<d.getDisassembly()<<endl; int op_count=0; - for(auto op : operands) + for(const auto p_op : operands) { + const auto &op=*p_op; auto readWriteString= string(); if(op.isRead()) readWriteString += "READ "; if(op.isWritten()) readWriteString += "WRITE "; @@ -104,11 +105,11 @@ int main(int argc, char **argv) } catch (DatabaseError_t pnide) { - cerr << programName << ": Unexpected database error: " << pnide << "file url: " << this_file->GetURL() << endl; + cerr << programName << ": Unexpected database error: " << pnide << "file url: " << this_file->getURL() << endl; } catch (...) { - cerr << programName << ": Unexpected error file url: " << this_file->GetURL() << endl; + cerr << programName << ": Unexpected error file url: " << this_file->getURL() << endl; } } // end file iterator @@ -116,7 +117,7 @@ int main(int argc, char **argv) if (one_success) { cout<<"Commiting changes...\n"; - pqxx_interface.Commit(); + pqxx_interface->commit(); } return 0; diff --git a/dump_map/SConscript b/dump_map/SConscript index 7fd50e3ef..c3962b85d 100644 --- a/dump_map/SConscript +++ b/dump_map/SConscript @@ -7,10 +7,7 @@ myenv=env.Clone() myenv.Replace(SECURITY_TRANSFORMS_HOME=os.environ['SECURITY_TRANSFORMS_HOME']) cpppath=''' - $SECURITY_TRANSFORMS_HOME/include - $SECURITY_TRANSFORMS_HOME/libIRDB/include - $SECURITY_TRANSFORMS_HOME/libMEDSannotation/include - $SECURITY_TRANSFORMS_HOME/tools/transforms + $IRDB_SDK/include ''' diff --git a/dump_map/dump_map.cpp b/dump_map/dump_map.cpp index 9fe268d22..e9d996a85 100644 --- a/dump_map/dump_map.cpp +++ b/dump_map/dump_map.cpp @@ -20,14 +20,14 @@ #include <stdlib.h> #include <fstream> -#include <libIRDB-core.hpp> +#include <irdb-core> #include <libgen.h> #include <iomanip> #include <algorithm> using namespace std; -using namespace libIRDB; +using namespace IRDB_SDK; void usage(char* name) { @@ -37,16 +37,16 @@ void usage(char* name) void dump_icfs(Instruction_t* insn) { - if(insn->GetIBTargets()==NULL) + if(insn->getIBTargets()==NULL) return; - cout<<"\tComplete: "<<boolalpha<<insn->GetIBTargets()->IsComplete()<<endl; - cout<<"\tModComplete: "<<boolalpha<<insn->GetIBTargets()->IsModuleComplete()<<endl; + cout<<"\tComplete: "<<boolalpha<<insn->getIBTargets()->isComplete()<<endl; + cout<<"\tModComplete: "<<boolalpha<<insn->getIBTargets()->isModuleComplete()<<endl; cout<<"\tTargets: "<<endl; - for_each(insn->GetIBTargets()->begin(), insn->GetIBTargets()->end(), [&](const Instruction_t* targ) + for_each(insn->getIBTargets()->begin(), insn->getIBTargets()->end(), [&](const Instruction_t* targ) { - const auto d=DecodedInstruction_t(targ); - cout<<"\t"<<targ->GetBaseID()<<":"<<d.getDisassembly()<<endl; + const auto d=DecodedInstruction_t::factory(targ); + cout<<"\t"<<targ->getBaseID()<<":"<<d->getDisassembly()<<endl; }); } @@ -58,37 +58,35 @@ int main(int argc, char **argv) exit(1); } - auto dump_icfs_flag=(db_id_t)BaseObj_t::NOT_IN_DATABASE; + auto dump_icfs_flag=(DatabaseID_t)BaseObj_t::NOT_IN_DATABASE; auto dump_icfs_str=getenv("DUMP_ICFS"); if(dump_icfs_str) - dump_icfs_flag=(db_id_t)strtoull(dump_icfs_str,NULL,0); + dump_icfs_flag=(DatabaseID_t)strtoull(dump_icfs_str,NULL,0); string programName(argv[0]); int variantID = atoi(argv[1]); - VariantID_t *pidp=NULL; - /* setup the interface to the sql server */ - pqxxDB_t pqxx_interface; - BaseObj_t::SetInterface(&pqxx_interface); + auto pqxx_interface=pqxxDB_t::factory(); + BaseObj_t::setInterface(pqxx_interface.get()); - pidp=new VariantID_t(variantID); - assert(pidp->IsRegistered()==true); + auto pidp=VariantID_t::factory(variantID); + assert(pidp->isRegistered()==true); bool one_success = false; - for(set<File_t*>::iterator it=pidp->GetFiles().begin(); - it!=pidp->GetFiles().end(); + for(set<File_t*>::iterator it=pidp->getFiles().begin(); + it!=pidp->getFiles().end(); ++it) { File_t* this_file = *it; try { - FileIR_t *firp = new FileIR_t(*pidp, this_file); + auto firp = FileIR_t::factory(pidp.get(), this_file); - cout<<"file: "<<this_file->GetURL()<<endl; + cout<<"file: "<<this_file->getURL()<<endl; cout<<setw(9)<<"ID"<<" " <<setw(10)<<"Addr."<<" " <<setw(10)<<"IBTA"<<" " @@ -99,29 +97,29 @@ int main(int argc, char **argv) assert(firp && pidp); - for(InstructionSet_t::iterator it=firp->GetInstructions().begin(); it!=firp->GetInstructions().end(); ++it) + for(auto it=firp->getInstructions().begin(); it!=firp->getInstructions().end(); ++it) { Instruction_t* insn=*it; assert(insn); - cout<<hex<<setw(9)<<insn->GetBaseID()<<" "<<hex<<setw(10)<<insn->GetAddress()->GetVirtualOffset(); + cout<<hex<<setw(9)<<insn->getBaseID()<<" "<<hex<<setw(10)<<insn->getAddress()->getVirtualOffset(); cout<<" "<<hex<<setw(10)<< - (insn->GetIndirectBranchTargetAddress() ? - insn->GetIndirectBranchTargetAddress()->GetVirtualOffset() : + (insn->getIndirectBranchTargetAddress() ? + insn->getIndirectBranchTargetAddress()->getVirtualOffset() : 0 ) <<" "; - cout<<hex<<setw(9)<<(insn->GetFallthrough() ? insn->GetFallthrough()->GetBaseID() : -1) << " "; - cout<<hex<<setw(9)<<(insn->GetTarget() ? insn->GetTarget()->GetBaseID() : -1) << " "; - if(insn->GetFunction() && insn->GetFunction()->GetEntryPoint()) - cout<<hex<<setw(9)<<insn->GetFunction()->GetEntryPoint()->GetBaseID(); + cout<<hex<<setw(9)<<(insn->getFallthrough() ? insn->getFallthrough()->getBaseID() : -1) << " "; + cout<<hex<<setw(9)<<(insn->getTarget() ? insn->getTarget()->getBaseID() : -1) << " "; + if(insn->getFunction() && insn->getFunction()->getEntryPoint()) + cout<<hex<<setw(9)<<insn->getFunction()->getEntryPoint()->getBaseID(); else cout<<setw(9)<<"NoFunc"; - const auto d=DecodedInstruction_t(insn); - cout<<" "<<d.getDisassembly()<<"("<<insn->GetComment()<<")"<<endl; + const auto d=DecodedInstruction_t::factory(insn); + cout<<" "<<d->getDisassembly()<<"("<<insn->getComment()<<")"<<endl; - if(dump_icfs_flag == insn->GetBaseID()) + if(dump_icfs_flag == insn->getBaseID()) dump_icfs(insn); } @@ -130,11 +128,11 @@ int main(int argc, char **argv) } catch (DatabaseError_t pnide) { - cerr << programName << ": Unexpected database error: " << pnide << "file url: " << this_file->GetURL() << endl; + cerr << programName << ": Unexpected database error: " << pnide << "file url: " << this_file->getURL() << endl; } catch (...) { - cerr << programName << ": Unexpected error file url: " << this_file->GetURL() << endl; + cerr << programName << ": Unexpected error file url: " << this_file->getURL() << endl; } } // end file iterator @@ -142,7 +140,7 @@ int main(int argc, char **argv) if (one_success) { cout<<"Commiting changes...\n"; - pqxx_interface.Commit(); + pqxx_interface->commit(); } return 0; diff --git a/ir_builders/SConscript b/ir_builders/SConscript index 170d80f84..5777a8135 100644 --- a/ir_builders/SConscript +++ b/ir_builders/SConscript @@ -11,7 +11,7 @@ installed=[] if 'build_tools' not in myenv or myenv['build_tools'] is None or int(myenv['build_tools']) == 1: cpppath=''' - $SECURITY_TRANSFORMS_HOME/include + $IRDB_SDK/include $SECURITY_TRANSFORMS_HOME/libIRDB/include $SECURITY_TRANSFORMS_HOME/libMEDSannotation/include $SECURITY_TRANSFORMS_HOME/libEXEIO/include @@ -56,10 +56,10 @@ if 'build_tools' not in myenv or myenv['build_tools'] is None or int(myenv['buil # ilr goes to $sectrans/plugins_install - pgm=myenv.Program(target="ilr.exe", source=Split("ilr.cpp"), LIBPATH=LIBPATH, LIBS=LIBS) - install=myenv.Install("$SECURITY_TRANSFORMS_HOME/plugins_install/", pgm) - Default(install) - installed=installed+install + # pgm=myenv.Program(target="ilr.exe", source=Split("ilr.cpp"), LIBPATH=LIBPATH, LIBS=LIBS) + # install=myenv.Install("$SECURITY_TRANSFORMS_HOME/plugins_install/", pgm) + # Default(install) + # installed=installed+install Return('installed') diff --git a/ir_builders/calc_conflicts.cpp b/ir_builders/calc_conflicts.cpp index c26b02d1b..15dd95ead 100644 --- a/ir_builders/calc_conflicts.cpp +++ b/ir_builders/calc_conflicts.cpp @@ -43,7 +43,7 @@ int bad_fallthrough_count=0; using namespace libIRDB; using namespace std; -set< pair<db_id_t,int> > missed_instructions; +set< pair<DatabaseID_t,int> > missed_instructions; int failed_target_count=0; pqxxDB_t pqxx_interface; @@ -65,7 +65,7 @@ void count_conflicts (FileIR_t* virp) { Instruction_t *insn=*it; - virtual_offset_t vo=insn->GetAddress()->GetVirtualOffset(); + VirtualOffset_t vo=insn->GetAddress()->GetVirtualOffset(); for(int i=0;i<insn->GetDataBits().length();i++) conflict_map[(vo+i)]++; diff --git a/ir_builders/check_thunks.cpp b/ir_builders/check_thunks.cpp index 22c22b63f..dd3052250 100644 --- a/ir_builders/check_thunks.cpp +++ b/ir_builders/check_thunks.cpp @@ -23,7 +23,7 @@ -#include <libIRDB-core.hpp> +#include <irdb-core> #include <libIRDB-cfg.hpp> #include <utils.hpp> #include <iostream> @@ -36,7 +36,7 @@ #include "fill_in_indtargs.hpp" -using namespace libIRDB; +using namespace IRDB_SDK; using namespace std; #define HIWORD(a) ((a)&0xFFFF0000) @@ -45,35 +45,19 @@ using namespace std; /* * check_for_thunk_offsets - check non-function thunks for extra offsets */ -void check_for_thunk_offsets(FileIR_t* firp, virtual_offset_t thunk_base) +void check_for_thunk_offsets(FileIR_t* firp, VirtualOffset_t thunk_base) { - - - for( - set<Instruction_t*>::iterator it=firp->GetInstructions().begin(); - it!=firp->GetInstructions().end(); - ++it - ) + for(auto insn : firp->getInstructions()) { - // if it has a targ and fallthrough (quick test) it might be a call - Instruction_t* insn=*it; - //DISASM d; - //Disassemble(insn,d); - const auto d=DecodedInstruction_t(insn); - - //if(string(d.Instruction.Mnemonic)==string("add ")) - if(d.getMnemonic()=="add") + const auto d=DecodedInstruction_t::factory(insn); + if(d->getMnemonic()=="add") { // check that arg2 is a constant - // if(HIWORD(d.Argument2.ArgType)!=CONSTANT_TYPE+ABSOLUTE_) - if(!d.getOperand(1).isConstant()) + if(!d->getOperand(1)->isConstant()) continue; - // string add_offset=string(d.Argument2.ArgMnemonic); - //const auto add_offset=d.getOperand(1).getString(); - - virtual_offset_t addoff=d.getOperand(1).getConstant(); //strtol(add_offset.c_str(),NULL,16); + auto addoff=d->getOperand(1)->getConstant(); /* bounds check gently */ if(0<addoff && addoff<100) @@ -82,18 +66,15 @@ void check_for_thunk_offsets(FileIR_t* firp, virtual_offset_t thunk_base) possible_target(thunk_base+addoff, 0, ibt_provenance_t::ibtp_text); } // else if(string(d.Instruction.Mnemonic)==string("lea ")) - if(d.getMnemonic()=="lea") + if(d->getMnemonic()=="lea") { - // assert (d.Argument2.ArgType==MEMORY_TYPE); - assert (d.getOperand(1).isMemory()); + assert (d->getOperand(1)->isMemory()); /* no indexing please! */ - // if(d.Argument2.Memory.IndexRegister!=0) - if(d.getOperand(1).hasIndexRegister()) + if(d->getOperand(1)->hasIndexRegister()) continue; - // virtual_offset_t leaoff=d.Argument2.Memory.Displacement; - virtual_offset_t leaoff=d.getOperand(1).getMemoryDisplacement(); + auto leaoff=d->getOperand(1)->getMemoryDisplacement(); /* bounds check gently */ if(0<leaoff && leaoff<100) @@ -110,12 +91,10 @@ void check_for_thunk_offsets(FileIR_t* firp, virtual_offset_t thunk_base) void check_for_thunk_offsets(FileIR_t* firp, Instruction_t *thunk_insn, string reg, uint64_t offset) { - virtual_offset_t thunk_base=thunk_insn->GetFallthrough()->GetAddress()->GetVirtualOffset()+offset; - //virtual_offset_t thunk_call_addr=thunk_insn->GetAddress()->GetVirtualOffset(); - //virtual_offset_t thunk_call_offset=strtol(offset.c_str(),NULL,16); + auto thunk_base=thunk_insn->getFallthrough()->getAddress()->getVirtualOffset()+offset; /* don't check inserted thunk addresses */ - if(thunk_insn->GetAddress()->GetVirtualOffset()==0) + if(thunk_insn->getAddress()->getVirtualOffset()==0) return; check_for_thunk_offsets(firp,thunk_base); @@ -133,39 +112,25 @@ void check_func_for_thunk_offsets(Function_t *func, Instruction_t* thunk_insn, - virtual_offset_t thunk_base=thunk_insn->GetFallthrough()->GetAddress()->GetVirtualOffset()+offset; - //virtual_offset_t thunk_call_addr=thunk_insn->GetAddress()->GetVirtualOffset(); - //virtual_offset_t thunk_call_offset=strtol(offset.c_str(),NULL,16); + auto thunk_base=thunk_insn->getFallthrough()->getAddress()->getVirtualOffset()+offset; /* don't check inserted thunk addresses */ - if(thunk_insn->GetAddress()->GetVirtualOffset()==0) + if(thunk_insn->getAddress()->getVirtualOffset()==0) return; - for( - set<Instruction_t*>::iterator it=func->GetInstructions().begin(); - it!=func->GetInstructions().end(); - ++it - ) + for(auto insn : func->getInstructions()) { // if it has a targ and fallthrough (quick test) it might be a call - Instruction_t* insn=*it; - // DISASM d; - // Disassemble(insn,d); - const auto d=DecodedInstruction_t(insn); + const auto d=DecodedInstruction_t::factory(insn); - // if(string(d.Instruction.Mnemonic)==string("add ")) - if(d.getMnemonic()=="add") + if(d->getMnemonic()=="add") { // check that arg2 is a constant - // if(HIWORD(d.Argument2.ArgType)!=CONSTANT_TYPE+ABSOLUTE_) - if(!d.getOperand(1).isConstant()) + if(!d->getOperand(1)->isConstant()) continue; - // string add_offset=string(d.Argument2.ArgMnemonic); - // const auto add_offset=d.getOperand(1).getString(); - - virtual_offset_t addoff=d.getOperand(1).getConstant(); //strtol(add_offset.c_str(),NULL,16); + auto addoff=d->getOperand(1)->getConstant(); /* bounds check gently */ if(0<addoff && addoff<100) @@ -176,19 +141,15 @@ void check_func_for_thunk_offsets(Function_t *func, Instruction_t* thunk_insn, // <<" addoff: " << addoff << " total: "<< (thunk_base+addoff)<<endl; possible_target(thunk_base+addoff, 0, ibt_provenance_t::ibtp_text); } - // else if(string(d.Instruction.Mnemonic)==string("lea ")) - else if(d.getMnemonic()=="lea") + else if(d->getMnemonic()=="lea") { - // assert (d.Argument2.ArgType==MEMORY_TYPE); - assert (d.getOperand(1).isMemory()); + assert (d->getOperand(1)->isMemory()); /* no indexing please! */ - // if(d.Argument2.Memory.IndexRegister!=0) - if(!d.getOperand(1).hasIndexRegister()) + if(!d->getOperand(1)->hasIndexRegister()) continue; - // virtual_offset_t leaoff=d.Argument2.Memory.Displacement; - virtual_offset_t leaoff=d.getOperand(1).getMemoryDisplacement(); + VirtualOffset_t leaoff=d->getOperand(1)->getMemoryDisplacement(); /* bounds check gently */ if(0<leaoff && leaoff<100) @@ -210,20 +171,15 @@ void check_func_for_thunk_offsets(Function_t *func, Instruction_t* thunk_insn, */ bool is_thunk_load(Instruction_t* insn, string ®) { - //DISASM d; - //Disassemble(insn,d); - const auto d=DecodedInstruction_t(insn); + const auto d=DecodedInstruction_t::factory(insn); - //if(string(d.Instruction.Mnemonic)!=string("mov ")) - if(d.getMnemonic()!="mov") + if(d->getMnemonic()!="mov") return false; - //if(d.Argument2.ArgType!=MEMORY_TYPE || string(d.Argument2.ArgMnemonic)!=string("esp")) - if(!d.getOperand(1).isMemory() || d.getOperand(1).getString()!="esp") + if(!d->getOperand(1)->isMemory() || d->getOperand(1)->getString()!="esp") return false; - // reg=string(d.Argument1.ArgMnemonic); - reg=d.getOperand(0).getString(); + reg=d->getOperand(0)->getString(); return true; } @@ -232,15 +188,8 @@ bool is_thunk_load(Instruction_t* insn, string ®) */ bool is_ret(Instruction_t* insn) { - //DISASM d; - //Disassemble(insn,d); - const auto d=DecodedInstruction_t(insn); - return d.isReturn(); - -// if(d.Instruction.BranchType!=RetType) -// return false; -// -// return true; + const auto d=DecodedInstruction_t::factory(insn); + return d->isReturn(); } /* @@ -248,14 +197,12 @@ bool is_ret(Instruction_t* insn) */ bool is_pop(Instruction_t* insn, string ®) { - //DISASM d; - //Disassemble(insn,d); - const auto d=DecodedInstruction_t(insn); + const auto d=DecodedInstruction_t::factory(insn); - if(d.getMnemonic()!="pop") + if(d->getMnemonic()!="pop") return false; - reg=d.getOperand(0).getString(); + reg=d->getOperand(0)->getString(); return true; } @@ -267,29 +214,26 @@ bool is_pop(Instruction_t* insn, string ®) /* note: reg is output paramater */ bool is_thunk_call(Instruction_t* insn, string ®) { - //DISASM d; - //Disassemble(insn,d); - const auto d=DecodedInstruction_t(insn); + const auto d=DecodedInstruction_t::factory(insn); /* not a call */ - //if(d.Instruction.BranchType!=CallType) - if(!d.isCall()) + if(!d->isCall()) return false; /* no target in IRDB */ - if(insn->GetTarget()==NULL) + if(insn->getTarget()==NULL) return false; /* Target not the right type of load */ - if(!is_thunk_load(insn->GetTarget(),reg)) + if(!is_thunk_load(insn->getTarget(),reg)) return false; /* target has no FT? */ - if(!insn->GetTarget()->GetFallthrough()) + if(!insn->getTarget()->getFallthrough()) return false; /* target's FT is a return insn */ - if(!is_ret(insn->GetTarget()->GetFallthrough())) + if(!is_ret(insn->getTarget()->getFallthrough())) return false; return true; @@ -297,27 +241,24 @@ bool is_thunk_call(Instruction_t* insn, string ®) bool is_thunk_call_type2(Instruction_t* insn, string ®, Instruction_t** newinsn) { - //DISASM d; - //Disassemble(insn,d); - const auto d=DecodedInstruction_t(insn); + const auto d=DecodedInstruction_t::factory(insn); /* not a call */ - //if(d.Instruction.BranchType!=CallType) - if(!d.isCall()) + if(!d->isCall()) return false; /* no target in IRDB */ - if(insn->GetTarget()==NULL) + if(insn->getTarget()==NULL) return false; - if(insn->GetTarget() != insn->GetFallthrough()) + if(insn->getTarget() != insn->getFallthrough()) return false; /* target's FT is a return insn */ - if(!is_pop(insn->GetTarget(), reg)) + if(!is_pop(insn->getTarget(), reg)) return false; - *newinsn=insn->GetTarget()->GetFallthrough(); + *newinsn=insn->getTarget()->getFallthrough(); return true; } @@ -328,29 +269,23 @@ bool is_thunk_call_type2(Instruction_t* insn, string ®, Instruction_t** newin /* note: offset is an output parameter */ bool is_thunk_add(Instruction_t *insn, string reg, uint64_t &offset) { - //DISASM d; - //Disassemble(insn,d); - const auto d=DecodedInstruction_t(insn); + const auto d=DecodedInstruction_t::factory(insn); // make sure it's an add instruction - //if(string(d.Instruction.Mnemonic)!=string("add ")) - if(d.getMnemonic()!="add") + if(d->getMnemonic()!="add") return false; // check that it's an add of the proper reg - if(d.getOperand(0).getString()!=reg) + if(d->getOperand(0)->getString()!=reg) return false; // check that arg2 is a constant - //if(HIWORD(d.Argument2.ArgType)!=CONSTANT_TYPE+ABSOLUTE_) - if(!d.getOperand(1).isConstant()) + if(!d->getOperand(1)->isConstant()) return false; - // offset=string(d.Argument2.ArgMnemonic); - //offset=d.getOperand(1).getString(); - offset=d.getOperand(1).getConstant(); + offset=d->getOperand(1)->getConstant(); - virtual_offset_t intoff=d.getOperand(1).getConstant(); // strtol(offset.c_str(),NULL,16); + auto intoff=d->getOperand(1)->getConstant(); /* bounds check gently */ if(0<intoff && intoff<100) @@ -365,23 +300,18 @@ bool is_thunk_add(Instruction_t *insn, string reg, uint64_t &offset) void check_func_for_thunk_calls(Function_t* func) { // for each insn in the func - for( - set<Instruction_t*>::iterator it=func->GetInstructions().begin(); - it!=func->GetInstructions().end(); - ++it - ) + for(auto insn : func->getInstructions()) { // if it has a targ and fallthrough (quick test) it might be a call - Instruction_t* insn=*it; /* check if we might be calling a thunk */ - if(insn->GetFallthrough() && insn->GetTarget()) + if(insn->getFallthrough() && insn->getTarget()) { // check for a call, followed by an add of reg (note the output params of reg and offset) string reg; uint64_t offset=0; if(is_thunk_call(insn,reg) && - is_thunk_add(insn->GetFallthrough(),reg,offset)) + is_thunk_add(insn->getFallthrough(),reg,offset)) { check_func_for_thunk_offsets(func,insn,reg,offset); } @@ -394,29 +324,24 @@ void check_func_for_thunk_calls(Function_t* func) void check_non_funcs_for_thunks(FileIR_t *firp) { // for each insn in the func - for( - set<Instruction_t*>::iterator it=firp->GetInstructions().begin(); - it!=firp->GetInstructions().end(); - ++it - ) + for(auto insn : firp->getInstructions()) { // if it has a targ and fallthrough (quick test) it might be a call - Instruction_t* insn=*it; /* these instructions/thunks are checked with the functions */ /* check if we might be calling a thunk */ - if(insn->GetFallthrough() && insn->GetTarget()) + if(insn->getFallthrough() && insn->getTarget()) { // check for a call, followed by an add of reg (note the output params of reg and offset) string reg; uint64_t offset=0; if(is_thunk_call(insn,reg) && - is_thunk_add(insn->GetFallthrough(),reg,offset)) + is_thunk_add(insn->getFallthrough(),reg,offset)) { cout<<"Found non-function thunk at "<< - insn->GetAddress()->GetVirtualOffset()<<endl; + insn->getAddress()->getVirtualOffset()<<endl; check_for_thunk_offsets(firp,insn,reg,offset); } } @@ -439,47 +364,38 @@ void check_non_funcs_for_thunks(FileIR_t *firp) * If L1+k1+k2 is found, and points at a code address (outside this function?), mark it as an indirect branch target. * */ -void check_for_thunks(FileIR_t* firp, const std::set<virtual_offset_t>& thunk_bases) +void check_for_thunks(FileIR_t* firp, const std::set<VirtualOffset_t>& thunk_bases) { /* thunk bases is the module start's found for this firp */ cout<<"Starting check for thunks"<<endl; - for(set<virtual_offset_t>::iterator it=thunk_bases.begin(); it!=thunk_bases.end(); ++it) - { - virtual_offset_t offset=*it; + for(auto offset : thunk_bases) check_for_thunk_offsets(firp,offset); - } } -void find_all_module_starts(FileIR_t* firp, set<virtual_offset_t> &thunk_bases) +void find_all_module_starts(FileIR_t* firp, set<VirtualOffset_t> &thunk_bases) { thunk_bases.clear(); cout<<"Finding thunk bases"<<endl; // for each insn in the func - for( - set<Instruction_t*>::iterator it=firp->GetInstructions().begin(); - it!=firp->GetInstructions().end(); - ++it - ) + for(auto insn : firp->getInstructions()) { // if it has a targ and fallthrough (quick test) it might be a call - Instruction_t* insn=*it; - /* check if we might be calling a thunk */ - if(insn->GetFallthrough() && insn->GetTarget()) + if(insn->getFallthrough() && insn->getTarget()) { // check for a call, followed by an add of reg (note the output params of reg and offset) string reg; uint64_t offset=0; if(is_thunk_call(insn,reg) && - is_thunk_add(insn->GetFallthrough(),reg,offset)) + is_thunk_add(insn->getFallthrough(),reg,offset)) { - virtual_offset_t thunk_base=insn->GetFallthrough()->GetAddress()->GetVirtualOffset()+ offset; + auto thunk_base=insn->getFallthrough()->getAddress()->getVirtualOffset()+ offset; if(thunk_bases.find(thunk_base)==thunk_bases.end()) - cout<<"Found new thunk at "<<insn->GetAddress()->GetVirtualOffset()<<" with base: "<<hex<<thunk_base<<endl; + cout<<"Found new thunk at "<<insn->getAddress()->getVirtualOffset()<<" with base: "<<hex<<thunk_base<<endl; thunk_bases.insert(thunk_base); } Instruction_t* newinsn=NULL; @@ -487,9 +403,9 @@ void find_all_module_starts(FileIR_t* firp, set<virtual_offset_t> &thunk_bases) { if(newinsn && is_thunk_add(newinsn,reg,offset)) { - virtual_offset_t thunk_base=insn->GetFallthrough()->GetAddress()->GetVirtualOffset()+ offset; + VirtualOffset_t thunk_base=insn->getFallthrough()->getAddress()->getVirtualOffset()+ offset; if(thunk_bases.find(thunk_base)==thunk_bases.end()) - cout<<"Found new thunk at "<<insn->GetAddress()->GetVirtualOffset()<<" with base: "<<hex<<thunk_base<<endl; + cout<<"Found new thunk at "<<insn->getAddress()->getVirtualOffset()<<" with base: "<<hex<<thunk_base<<endl; thunk_bases.insert(thunk_base); } } diff --git a/ir_builders/check_thunks.hpp b/ir_builders/check_thunks.hpp index ed7ce8d80..27b77593f 100644 --- a/ir_builders/check_thunks.hpp +++ b/ir_builders/check_thunks.hpp @@ -23,10 +23,10 @@ #define check_thunks_hpp #include <set> -#include "libIRDB-core.hpp" +#include <irdb-core> -void find_all_module_starts(libIRDB::FileIR_t* firp, std::set<libIRDB::virtual_offset_t>& thunk_bases); -void check_for_thunks(libIRDB::FileIR_t* firp, const std::set<libIRDB::virtual_offset_t>& thunk_bases); +void find_all_module_starts(IRDB_SDK::FileIR_t* firp, std::set<IRDB_SDK::VirtualOffset_t>& thunk_bases); +void check_for_thunks(IRDB_SDK::FileIR_t* firp, const std::set<IRDB_SDK::VirtualOffset_t>& thunk_bases); #endif diff --git a/ir_builders/clone.cpp b/ir_builders/clone.cpp index 73c2525d7..d5211b723 100644 --- a/ir_builders/clone.cpp +++ b/ir_builders/clone.cpp @@ -20,13 +20,13 @@ -#include <libIRDB-core.hpp> +#include <irdb-core> #include <iostream> #include <fstream> #include <stdlib.h> -using namespace libIRDB; +using namespace IRDB_SDK; using namespace std; int main(int argc, char* argv[]) @@ -40,28 +40,24 @@ int main(int argc, char* argv[]) /* setup the interface to the sql server */ - pqxxDB_t pqxx_interface; - BaseObj_t::SetInterface(&pqxx_interface); + auto pqxx_interface=pqxxDB_t::factory(); + BaseObj_t::setInterface(pqxx_interface.get()); - VariantID_t *pidp=NULL; - VariantID_t *newpidp=NULL; try { - pidp=new VariantID_t(atoi(argv[1])); + auto pidp=VariantID_t::factory(atoi(argv[1])); + assert(pidp->isRegistered()==true); - assert(pidp->IsRegistered()==true); - - newpidp=pidp->Clone(); - - assert(newpidp->IsRegistered()==true); + auto newpidp=pidp->clone(); + assert(newpidp->isRegistered()==true); cout<<"Cloned Variant is: "<<*newpidp << endl; // commit the changes to the db if all went well - pqxx_interface.Commit(); + pqxx_interface->commit(); - db_id_t newpid_id=newpidp->GetBaseID(); + auto newpid_id=newpidp->getBaseID(); ofstream f; f.open(argv[2]); if(!f.is_open()) @@ -80,8 +76,6 @@ int main(int argc, char* argv[]) } - delete newpidp; - delete pidp; return 0; } diff --git a/ir_builders/fill_in_cfg.cpp b/ir_builders/fill_in_cfg.cpp index 62b62510c..aa921235f 100644 --- a/ir_builders/fill_in_cfg.cpp +++ b/ir_builders/fill_in_cfg.cpp @@ -28,13 +28,13 @@ #include "elfio/elfio.hpp" #include "split_eh_frame.hpp" -using namespace libIRDB; using namespace std; using namespace EXEIO; +using namespace IRDB_SDK; void PopulateCFG::populate_instruction_map ( - map< pair<db_id_t,virtual_offset_t>, Instruction_t*> &insnMap, + map< pair<DatabaseID_t,VirtualOffset_t>, Instruction_t*> &insnMap, FileIR_t *firp ) { @@ -43,12 +43,12 @@ void PopulateCFG::populate_instruction_map /* for each instruction in the IR */ - for(auto insn : firp->GetInstructions()) + for(auto insn : firp->getInstructions()) { - auto fileID=insn->GetAddress()->GetFileID(); - auto vo=insn->GetAddress()->GetVirtualOffset(); + auto fileID=insn->getAddress()->getFileID(); + auto vo=insn->getAddress()->getVirtualOffset(); - auto p=pair<db_id_t,virtual_offset_t>(fileID,vo); + auto p=pair<DatabaseID_t,VirtualOffset_t>(fileID,vo); assert(insnMap[p]==NULL); insnMap[p]=insn; @@ -58,14 +58,14 @@ void PopulateCFG::populate_instruction_map void PopulateCFG::set_fallthrough ( - map< pair<db_id_t,virtual_offset_t>, Instruction_t*> &insnMap, + map< pair<DatabaseID_t,VirtualOffset_t>, Instruction_t*> &insnMap, DecodedInstruction_t *disasm, Instruction_t *insn, FileIR_t *firp ) { assert(disasm); assert(insn); - if(insn->GetFallthrough()) + if(insn->getFallthrough()) return; // check for branches with targets @@ -80,10 +80,10 @@ void PopulateCFG::set_fallthrough /* get the address of the next instrution */ - auto virtual_offset=insn->GetAddress()->GetVirtualOffset() + insn->GetDataBits().size(); + auto virtual_offset=insn->getAddress()->getVirtualOffset() + insn->getDataBits().size(); /* create a pair of offset/file */ - auto p=pair<db_id_t,virtual_offset_t>(insn->GetAddress()->GetFileID(),virtual_offset); + auto p=pair<DatabaseID_t,VirtualOffset_t>(insn->getAddress()->getFileID(),virtual_offset); /* lookup the target insn from the map */ auto fallthrough_insn=insnMap[p]; @@ -91,7 +91,7 @@ void PopulateCFG::set_fallthrough /* sanity, note we may see odd control transfers to 0x0 */ if(fallthrough_insn==NULL && virtual_offset!=0) { - cout<<"Cannot set fallthrough for "<<std::hex<<insn->GetAddress()->GetVirtualOffset(); + cout<<"Cannot set fallthrough for "<<std::hex<<insn->getAddress()->getVirtualOffset(); cout<< " : "<<insn->getDisassembly()<<endl; bad_fallthrough_count++; } @@ -100,16 +100,16 @@ void PopulateCFG::set_fallthrough if(fallthrough_insn!=0) { fallthroughs_set++; - insn->SetFallthrough(fallthrough_insn); + insn->setFallthrough(fallthrough_insn); } else - missed_instructions.insert(pair<db_id_t,virtual_offset_t>(insn->GetAddress()->GetFileID(),virtual_offset)); + missed_instructions.insert(pair<DatabaseID_t,VirtualOffset_t>(insn->getAddress()->getFileID(),virtual_offset)); } void PopulateCFG::set_target ( - map< pair<db_id_t,virtual_offset_t>, Instruction_t*> &insnMap, + map< pair<DatabaseID_t,VirtualOffset_t>, Instruction_t*> &insnMap, DecodedInstruction_t *disasm, Instruction_t *insn, FileIR_t *firp ) { @@ -117,7 +117,7 @@ void PopulateCFG::set_target assert(insn); assert(disasm); - if(insn->GetTarget()) + if(insn->getTarget()) return; const auto &operands = disasm->getOperands(); @@ -127,10 +127,10 @@ void PopulateCFG::set_target if( disasm->isBranch() && // it is a branch !disasm->isReturn() && // and not a return - operand.isConstant() // and has a constant argument + operand->isConstant() // and has a constant argument ) { - // cout<<"Found direct jump with addr=" << insn->GetAddress()->GetVirtualOffset() << + // cout<<"Found direct jump with addr=" << insn->getAddress()->getVirtualOffset() << // " disasm="<<disasm->CompleteInstr<<" ArgMnemonic="<< // disasm->Argument1.ArgMnemonic<<"."<<endl; @@ -138,7 +138,7 @@ void PopulateCFG::set_target auto virtual_offset=disasm->getAddress(); /* create a pair of offset/file */ - auto p=pair<db_id_t,virtual_offset_t>(insn->GetAddress()->GetFileID(),virtual_offset); + auto p=pair<DatabaseID_t,VirtualOffset_t>(insn->getAddress()->getFileID(),virtual_offset); /* lookup the target insn from the map */ auto target_insn=insnMap[p]; @@ -147,27 +147,27 @@ void PopulateCFG::set_target if(target_insn==NULL) { unsigned char first_byte=0; - if(insn->GetFallthrough()) - first_byte=(insn->GetFallthrough()->GetDataBits().c_str())[0]; - virtual_offset_t jump_dist=virtual_offset-(insn->GetAddress()->GetVirtualOffset()+(insn->GetDataBits()).size()); + if(insn->getFallthrough()) + first_byte=(insn->getFallthrough()->getDataBits().c_str())[0]; + VirtualOffset_t jump_dist=virtual_offset-(insn->getAddress()->getVirtualOffset()+(insn->getDataBits()).size()); if( // jump 1 byte forward jump_dist == 1 && // and we calculated the fallthrough - insn->GetFallthrough()!=NULL && + insn->getFallthrough()!=NULL && // and the fallthrough starts with a lock prefix first_byte==0xf0 ) { odd_target_count++; - target_insn=insn->GetFallthrough(); + target_insn=insn->getFallthrough(); } else { if(virtual_offset!=0) - cout<<"Cannot set target (target="<< std::hex << virtual_offset << ") for "<<std::hex<<insn->GetAddress()->GetVirtualOffset()<<"."<<endl; + cout<<"Cannot set target (target="<< std::hex << virtual_offset << ") for "<<std::hex<<insn->getAddress()->getVirtualOffset()<<"."<<endl; bad_target_count++; } } @@ -176,19 +176,19 @@ void PopulateCFG::set_target if(target_insn!=0) { targets_set++; - insn->SetTarget(target_insn); + insn->setTarget(target_insn); } else - missed_instructions.insert( pair<db_id_t,virtual_offset_t>(insn->GetAddress()->GetFileID(),virtual_offset)); + missed_instructions.insert( pair<DatabaseID_t,VirtualOffset_t>(insn->getAddress()->getFileID(),virtual_offset)); } } } -File_t* PopulateCFG::find_file(FileIR_t* firp, db_id_t fileid) +File_t* PopulateCFG::find_file(FileIR_t* firp, DatabaseID_t fileid) { - assert(firp->GetFile()->GetBaseID()==fileid); - return firp->GetFile(); + assert(firp->getFile()->getBaseID()==fileid); + return firp->getFile(); } @@ -225,18 +225,19 @@ void PopulateCFG::add_new_instructions(FileIR_t *firp) if( !elfiop->sections[secndx]->isExecutable()) continue; - virtual_offset_t first=elfiop->sections[secndx]->get_address(); - virtual_offset_t second=elfiop->sections[secndx]->get_address()+elfiop->sections[secndx]->get_size(); + VirtualOffset_t first=elfiop->sections[secndx]->get_address(); + VirtualOffset_t second=elfiop->sections[secndx]->get_address()+elfiop->sections[secndx]->get_size(); /* is the missed instruction in this section */ if(first<=missed_address && missed_address<second) { const char* data=elfiop->sections[secndx]->get_data(); // second=data? - virtual_offset_t offset_into_section=missed_address-elfiop->sections[secndx]->get_address(); + VirtualOffset_t offset_into_section=missed_address-elfiop->sections[secndx]->get_address(); /* disassemble the instruction */ - DecodedInstruction_t disasm(missed_address, (void*)&data[offset_into_section], elfiop->sections[secndx]->get_size()-offset_into_section ); + auto disasm_p=DecodedInstruction_t::factory(missed_address, (void*)&data[offset_into_section], elfiop->sections[secndx]->get_size()-offset_into_section ); + auto &disasm=*disasm_p; @@ -266,26 +267,34 @@ void PopulateCFG::add_new_instructions(FileIR_t *firp) newinsnbits[i]=data[offset_into_section+i]; /* create a new address */ + /* auto newaddr=new AddressID_t(); assert(newaddr); - newaddr->SetVirtualOffset(missed_address); - newaddr->SetFileID(missed_fileid); + newaddr->setVirtualOffset(missed_address); + newaddr->setFileID(missed_fileid); + firp->getAddresses().insert(newaddr); + */ + auto newaddr=firp->addNewAddress(missed_fileid,missed_address); /* create a new instruction */ + /* auto newinsn=new Instruction_t(); assert(newinsn); - newinsn->SetAddress(newaddr); - newinsn->SetDataBits(newinsnbits); - newinsn->SetComment(disasm.getDisassembly()+string(" from fill_in_cfg ")); - newinsn->SetAddress(newaddr); + newinsn->setAddress(newaddr); + newinsn->setDataBits(newinsnbits); + newinsn->setComment(disasm.getDisassembly()+string(" from fill_in_cfg ")); + firp->getInstructions().insert(newinsn); + newinsn->setAddress(newaddr); + */ + auto newinsn=firp->addNewInstruction(newaddr, nullptr, newinsnbits, disasm.getDisassembly()+string(" from fill_in_cfg "), nullptr); + (void)newinsn;// just add to IR + /* fallthrough/target/is indirect will be set later */ /* insert into the IR */ - firp->GetInstructions().insert(newinsn); - firp->GetAddresses().insert(newaddr); - cout<<"Found new instruction, "<<newinsn->GetComment()<<", at "<<std::hex<<newinsn->GetAddress()->GetVirtualOffset()<<" in file "<<"<no name yet>"<<"."<<endl; + cout<<"Found new instruction, "<<newinsn->getComment()<<", at "<<std::hex<<newinsn->getAddress()->getVirtualOffset()<<" in file "<<"<no name yet>"<<"."<<endl; found_instructions++; } @@ -312,22 +321,22 @@ void PopulateCFG::fill_in_cfg(FileIR_t *firp) failed_target_count=0; missed_instructions.clear(); - map< pair<db_id_t,virtual_offset_t>, Instruction_t*> insnMap; + map< pair<DatabaseID_t,VirtualOffset_t>, Instruction_t*> insnMap; populate_instruction_map(insnMap, firp); - cout << "Found "<<firp->GetInstructions().size()<<" instructions." <<endl; + cout << "Found "<<firp->getInstructions().size()<<" instructions." <<endl; /* for each instruction, disassemble it and set the target/fallthrough */ - for(auto insn : firp->GetInstructions()) + for(auto insn : firp->getInstructions()) { - DecodedInstruction_t disasm(insn); + auto disasm=DecodedInstruction_t::factory(insn); - const auto instr_len = disasm.length(); + const auto instr_len = disasm->length(); - assert(instr_len==insn->GetDataBits().size()); + assert(instr_len==insn->getDataBits().size()); - set_fallthrough(insnMap, &disasm, insn, firp); - set_target(insnMap, &disasm, insn, firp); + set_fallthrough(insnMap, disasm.get(), insn, firp); + set_target(insnMap, disasm.get(), insn, firp); } if(bad_target_count>0) @@ -347,20 +356,20 @@ void PopulateCFG::fill_in_cfg(FileIR_t *firp) for(auto p : missed_instructions) { /* get the address we've missed */ - virtual_offset_t missed_address=p.second; + VirtualOffset_t missed_address=p.second; cout << missed_address << ", "; } cout<<dec<<endl; /* set the base IDs for all instructions */ - firp->SetBaseIDS(); + firp->setBaseIDS(); /* for each instruction, set the original address id to be that of the address id, as fill_in_cfg is * designed to work on only original programs. */ - for(auto insn : firp->GetInstructions()) - insn->SetOriginalAddressID(insn->GetAddress()->GetBaseID()); + for(auto insn : firp->getInstructions()) + insn->setOriginalAddressID(insn->getAddress()->getBaseID()); } @@ -373,8 +382,8 @@ bool PopulateCFG::is_in_relro_segment(const int secndx) int segnum = real_elfiop->segments.size(); - virtual_offset_t sec_start=(virtual_offset_t)(elfiop->sections[secndx]->get_address()); - virtual_offset_t sec_end=(virtual_offset_t)(elfiop->sections[secndx]->get_address() + elfiop->sections[secndx]->get_size() - 1 ); + VirtualOffset_t sec_start=(VirtualOffset_t)(elfiop->sections[secndx]->get_address()); + VirtualOffset_t sec_end=(VirtualOffset_t)(elfiop->sections[secndx]->get_address() + elfiop->sections[secndx]->get_size() - 1 ); /* look through each section */ for (int segndx=1; segndx<segnum; segndx++) @@ -386,8 +395,8 @@ bool PopulateCFG::is_in_relro_segment(const int secndx) if(type==PT_GNU_RELRO) { - virtual_offset_t seg_start=(virtual_offset_t)(real_elfiop->segments[segndx]->get_virtual_address()); - virtual_offset_t seg_end=(virtual_offset_t)(real_elfiop->segments[segndx]->get_virtual_address() + real_elfiop->segments[segndx]->get_memory_size() - 1 ); + VirtualOffset_t seg_start=(VirtualOffset_t)(real_elfiop->segments[segndx]->get_virtual_address()); + VirtualOffset_t seg_end=(VirtualOffset_t)(real_elfiop->segments[segndx]->get_virtual_address() + real_elfiop->segments[segndx]->get_memory_size() - 1 ); // check if start lies within if(seg_start <= sec_start && sec_start <= seg_end) @@ -409,7 +418,7 @@ bool PopulateCFG::is_in_relro_segment(const int secndx) void PopulateCFG::fill_in_scoops(FileIR_t *firp) { - auto max_base_id=firp->GetMaxBaseID(); + auto max_base_id=firp->getMaxBaseID(); auto secnum = elfiop->sections.size(); auto secndx=0; @@ -439,18 +448,25 @@ void PopulateCFG::fill_in_scoops(FileIR_t *firp) string name=elfiop->sections[secndx]->get_name(); /* start address */ + /* auto startaddr=new AddressID_t(); assert(startaddr); - startaddr->SetVirtualOffset( elfiop->sections[secndx]->get_address()); - startaddr->SetFileID(firp->GetFile()->GetBaseID()); - firp->GetAddresses().insert(startaddr); + startaddr->setVirtualOffset( elfiop->sections[secndx]->get_address()); + startaddr->setFileID(firp->getFile()->getBaseID()); + firp->getAddresses().insert(startaddr); + */ + auto startaddr=firp->addNewAddress(firp->getFile()->getBaseID(), elfiop->sections[secndx]->get_address()); /* end */ + /* auto endaddr=new AddressID_t(); assert(endaddr); - endaddr->SetVirtualOffset( elfiop->sections[secndx]->get_address() + elfiop->sections[secndx]->get_size()-1); - endaddr->SetFileID(firp->GetFile()->GetBaseID()); - firp->GetAddresses().insert(endaddr); + endaddr->setVirtualOffset( elfiop->sections[secndx]->get_address() + elfiop->sections[secndx]->get_size()-1); + endaddr->setFileID(firp->getFile()->getBaseID()); + firp->getAddresses().insert(endaddr); + */ + auto endaddr=firp->addNewAddress(firp->getFile()->getBaseID(), elfiop->sections[secndx]->get_address() + elfiop->sections[secndx]->get_size()-1); + string the_contents; the_contents.resize(elfiop->sections[secndx]->get_size()); @@ -467,14 +483,18 @@ void PopulateCFG::fill_in_scoops(FileIR_t *firp) ( elfiop->sections[secndx]->isExecutable() << 0 ) ; bool is_relro=is_in_relro_segment(secndx); - DataScoop_t *newscoop=new DataScoop_t(max_base_id++, name, startaddr, endaddr, NULL, permissions, is_relro, the_contents); scoops_detected++; + /* + DataScoop_t *newscoop=new DataScoop_t(max_base_id++, name, startaddr, endaddr, NULL, permissions, is_relro, the_contents); assert(newscoop); - firp->GetDataScoops().insert(newscoop); + firp->getDataScoops().insert(newscoop); + */ + auto newscoop=firp->addNewDataScoop( name, startaddr, endaddr, NULL, permissions, is_relro, the_contents, max_base_id++ ); + (void)newscoop; // just give it to the IR cout<<"Allocated new scoop for section "<<name - <<"("<<hex<<startaddr->GetVirtualOffset()<<"-" - <<hex<<endaddr->GetVirtualOffset()<<")" + <<"("<<hex<<startaddr->getVirtualOffset()<<"-" + <<hex<<endaddr->getVirtualOffset()<<")" <<" perms="<<permissions<<" relro="<<boolalpha<<is_relro<<endl; } @@ -484,25 +504,25 @@ void PopulateCFG::fill_in_scoops(FileIR_t *firp) void PopulateCFG::detect_scoops_in_code(FileIR_t *firp) { // data for this function - auto already_scoopified=set<virtual_offset_t>(); + auto already_scoopified=set<VirtualOffset_t>(); // only valid for arm64 - if(firp->GetArchitecture()->getMachineType() != admtAarch64) return; + if(firp->getArchitecture()->getMachineType() != admtAarch64) return; // check each insn for an ldr with a pcrel operand. - for(auto insn : firp->GetInstructions()) + for(auto insn : firp->getInstructions()) { // look for ldr's with a pcrel operand - const auto d=DecodedInstruction_t(insn); - if(d.getMnemonic()!="ldr") continue; // only valid on arm. - const auto op0=d.getOperand(0); - const auto op1=d.getOperand(1); - if( !op1.isPcrel()) continue; + const auto d=DecodedInstruction_t::factory(insn); + if(d->getMnemonic()!="ldr") continue; // only valid on arm. + const auto op0=d->getOperand(0); + const auto op1=d->getOperand(1); + if( !op1->isPcrel()) continue; // sanity check that it's a memory operation, and extract fields - assert(op1.isMemory()); - const auto referenced_address=op1.getMemoryDisplacement(); - const auto op0_str=op0.getString(); + assert(op1->isMemory()); + const auto referenced_address=op1->getMemoryDisplacement(); + const auto op0_str=op0->getString(); const auto referenced_size= // could use API call? op0_str[0]=='w' ? 4 : op0_str[0]=='x' ? 8 : @@ -531,25 +551,33 @@ void PopulateCFG::detect_scoops_in_code(FileIR_t *firp) const auto sec_data=sec->get_data(); const auto sec_start=sec->get_address(); const auto the_contents=string(&sec_data[referenced_address-sec_start],referenced_size); - const auto fileid=firp->GetFile()->GetBaseID(); + const auto fileid=firp->getFile()->getBaseID(); + /* auto start_addr=new AddressID_t(BaseObj_t::NOT_IN_DATABASE,fileid,referenced_address); assert(start_addr); - firp->GetAddresses().insert(start_addr); + firp->getAddresses().insert(start_addr); auto end_addr=new AddressID_t(BaseObj_t::NOT_IN_DATABASE,fileid,referenced_address+referenced_size-1); assert(end_addr); - firp->GetAddresses().insert(end_addr); + firp->getAddresses().insert(end_addr); + */ + auto start_addr=firp->addNewAddress(fileid,referenced_address); + auto end_addr =firp->addNewAddress(fileid,referenced_address+referenced_size-1); const auto name="data_in_text_"+to_string(referenced_address); const auto permissions=0x4; /* R-- */ const auto is_relro=false; + /* auto newscoop=new DataScoop_t(BaseObj_t::NOT_IN_DATABASE, name, start_addr, end_addr, NULL, permissions, is_relro, the_contents); - firp->GetDataScoops().insert(newscoop); + firp->getDataScoops().insert(newscoop); + */ + auto newscoop=firp->addNewDataScoop(name, start_addr, end_addr, NULL, permissions, is_relro, the_contents); + (void)newscoop; - cout<< "Allocated data in text segment "<<name<<"=("<<start_addr->GetVirtualOffset()<<"-" - << end_addr->GetVirtualOffset()<<")"<<endl; + cout<< "Allocated data in text segment "<<name<<"=("<<start_addr->getVirtualOffset()<<"-" + << end_addr->getVirtualOffset()<<")"<<endl; } } @@ -563,14 +591,14 @@ void PopulateCFG::fill_in_landing_pads(FileIR_t *firp) map<Function_t*,set<Instruction_t*> > insns_to_add_to_funcs; - // for_each(firp->GetInstructions().begin(), firp->GetInstructions().end(), [&](Instruction_t* t) - for(const auto t : firp->GetInstructions()) + // for_each(firp->getInstructions().begin(), firp->getInstructions().end(), [&](Instruction_t* t) + for(const auto t : firp->getInstructions()) { - if(t->GetFunction()==NULL) + if(t->getFunction()==NULL) continue; auto lp=eh_frame_rep_ptr->find_lp(t); - if(lp && lp->GetFunction()==NULL) - insns_to_add_to_funcs[t->GetFunction()].insert(lp); + if(lp && lp->getFunction()==NULL) + insns_to_add_to_funcs[t->getFunction()].insert(lp); }; @@ -588,25 +616,25 @@ void PopulateCFG::fill_in_landing_pads(FileIR_t *firp) insns.erase(it); assert(insn); - if(insn->GetFunction()!=NULL) + if(insn->getFunction()!=NULL) continue; auto lp=eh_frame_rep_ptr->find_lp(insn); - if(lp && lp->GetFunction()==NULL) + if(lp && lp->getFunction()==NULL) insns.insert(lp); - insn->SetFunction(func); - cout<<" Adding "<<insn->GetBaseID()<<":"<<insn->getDisassembly()<<"@"<<hex<<insn->GetAddress()->GetVirtualOffset()<<dec<<endl; + insn->setFunction(func); + cout<<" Adding "<<insn->getBaseID()<<":"<<insn->getDisassembly()<<"@"<<hex<<insn->getAddress()->getVirtualOffset()<<dec<<endl; insn_count++; - auto target=insn->GetTarget(); - auto fallthru=insn->GetFallthrough(); + auto target=insn->getTarget(); + auto fallthru=insn->getFallthrough(); if(target) insns.insert(target); if(fallthru) insns.insert(fallthru); } - cout<<"Found LP outside of function "<<func->GetName()<<" added "<<insn_count<<" instructions"<<endl; + cout<<"Found LP outside of function "<<func->getName()<<" added "<<insn_count<<" instructions"<<endl; }; } @@ -644,20 +672,20 @@ int PopulateCFG::executeStep(IRDBObjects_t *const irdb_objects) { const auto pqxx_interface = irdb_objects->getDBInterface(); // now set the DB interface for THIS PLUGIN LIBRARY -- VERY IMPORTANT - BaseObj_t::SetInterface(pqxx_interface); + BaseObj_t::setInterface(pqxx_interface); const auto variant = irdb_objects->addVariant(variant_id); - for(File_t* file : variant->GetFiles()) + for(File_t* file : variant->getFiles()) { - const auto firp = irdb_objects->addFileIR(variant_id, file->GetBaseID()); + const auto firp = irdb_objects->addFileIR(variant_id, file->getBaseID()); assert(firp); - cout<<"Filling in cfg for "<<firp->GetFile()->GetURL()<<endl; + cout<<"Filling in cfg for "<<firp->getFile()->getURL()<<endl; /* get the OID of the file */ - const int elfoid=firp->GetFile()->GetELFOID(); + const int elfoid=firp->getFile()->getELFOID(); pqxx::largeobject lo(elfoid); - lo.to_file(pqxx_interface->GetTransaction(),"readeh_tmp_file.exe"); + lo.to_file(pqxx_interface->getTransaction(),"readeh_tmp_file.exe"); elfiop.reset(new exeio()); elfiop->load(string("readeh_tmp_file.exe")); @@ -699,8 +727,8 @@ int PopulateCFG::executeStep(IRDBObjects_t *const irdb_objects) extern "C" -shared_ptr<Transform_SDK::TransformStep_t> GetTransformStep(void) +shared_ptr<TransformStep_t> getTransformStep(void) { - const shared_ptr<Transform_SDK::TransformStep_t> the_step(new PopulateCFG()); + const shared_ptr<TransformStep_t> the_step(new PopulateCFG()); return the_step; } diff --git a/ir_builders/fill_in_cfg.hpp b/ir_builders/fill_in_cfg.hpp index 42c72625a..93c36e48b 100644 --- a/ir_builders/fill_in_cfg.hpp +++ b/ir_builders/fill_in_cfg.hpp @@ -1,15 +1,15 @@ #ifndef fill_in_cfg_hpp #define fill_in_cfg_hpp -#include <libIRDB-core.hpp> +#include <irdb-core> #include <stdlib.h> #include <map> #include <exeio.h> -class PopulateCFG : public libIRDB::Transform_SDK::TransformStep_t +class PopulateCFG : public IRDB_SDK::TransformStep_t { public: - PopulateCFG(libIRDB::db_id_t p_variant_id = 0, + PopulateCFG(IRDB_SDK::DatabaseID_t p_variant_id = 0, bool p_fix_landing_pads = true ) : @@ -39,37 +39,37 @@ class PopulateCFG : public libIRDB::Transform_SDK::TransformStep_t return std::string("fill_in_cfg"); } int parseArgs(const std::vector<std::string> step_args) override; - int executeStep(libIRDB::IRDBObjects_t *const) override; + int executeStep(IRDB_SDK::IRDBObjects_t *const) override; private: // methods // main workers - void fill_in_cfg(libIRDB::FileIR_t *); - void fill_in_scoops(libIRDB::FileIR_t *); - void detect_scoops_in_code(libIRDB::FileIR_t *firp); - void fill_in_landing_pads(libIRDB::FileIR_t *); + void fill_in_cfg(IRDB_SDK::FileIR_t *); + void fill_in_scoops(IRDB_SDK::FileIR_t *); + void detect_scoops_in_code(IRDB_SDK::FileIR_t *firp); + void fill_in_landing_pads(IRDB_SDK::FileIR_t *); // helpers void populate_instruction_map ( - std::map< std::pair<libIRDB::db_id_t,libIRDB::virtual_offset_t>, libIRDB::Instruction_t*>&, - libIRDB::FileIR_t * + std::map< std::pair<IRDB_SDK::DatabaseID_t,IRDB_SDK::VirtualOffset_t>, IRDB_SDK::Instruction_t*>&, + IRDB_SDK::FileIR_t * ); void set_fallthrough ( - std::map< std::pair<libIRDB::db_id_t,libIRDB::virtual_offset_t>, libIRDB::Instruction_t*>&, - libIRDB::DecodedInstruction_t *, libIRDB::Instruction_t *, libIRDB::FileIR_t * + std::map< std::pair<IRDB_SDK::DatabaseID_t,IRDB_SDK::VirtualOffset_t>, IRDB_SDK::Instruction_t*>&, + IRDB_SDK::DecodedInstruction_t *, IRDB_SDK::Instruction_t *, IRDB_SDK::FileIR_t * ); void set_target ( - std::map< std::pair<libIRDB::db_id_t,libIRDB::virtual_offset_t>, libIRDB::Instruction_t*>&, - libIRDB::DecodedInstruction_t *, libIRDB::Instruction_t *, libIRDB::FileIR_t * + std::map< std::pair<IRDB_SDK::DatabaseID_t,IRDB_SDK::VirtualOffset_t>, IRDB_SDK::Instruction_t*>&, + IRDB_SDK::DecodedInstruction_t *, IRDB_SDK::Instruction_t *, IRDB_SDK::FileIR_t * ); - libIRDB::File_t* find_file(libIRDB::FileIR_t *, libIRDB::db_id_t); - void add_new_instructions(libIRDB::FileIR_t *); + IRDB_SDK::File_t* find_file(IRDB_SDK::FileIR_t *, IRDB_SDK::DatabaseID_t); + void add_new_instructions(IRDB_SDK::FileIR_t *); bool is_in_relro_segment(const int); private: //data @@ -85,11 +85,11 @@ class PopulateCFG : public libIRDB::Transform_SDK::TransformStep_t size_t scoops_detected=0; // non-optional - libIRDB::db_id_t variant_id; + IRDB_SDK::DatabaseID_t variant_id; bool fix_landing_pads; std::unique_ptr<EXEIO::exeio> elfiop; - std::set< std::pair<libIRDB::db_id_t,libIRDB::virtual_offset_t> > missed_instructions; + std::set< std::pair<IRDB_SDK::DatabaseID_t,IRDB_SDK::VirtualOffset_t> > missed_instructions; }; #endif diff --git a/ir_builders/fill_in_indtargs.cpp b/ir_builders/fill_in_indtargs.cpp index ca367f1ac..d38a32241 100644 --- a/ir_builders/fill_in_indtargs.cpp +++ b/ir_builders/fill_in_indtargs.cpp @@ -19,7 +19,7 @@ * */ -#include <libIRDB-core.hpp> +#include <irdb-core> #include <libIRDB-util.hpp> #include <iostream> #include <fstream> @@ -43,7 +43,7 @@ #include "fill_in_indtargs.hpp" #include "libMEDSAnnotation.h" -using namespace libIRDB; +using namespace IRDB_SDK; using namespace std; using namespace EXEIO; using namespace MEDS_Annotation; @@ -52,23 +52,22 @@ using namespace MEDS_Annotation; /* * defines */ -#define arch_ptr_bytes() (firp->GetArchitectureBitWidth()/8) #define ALLOF(a) begin(a),end(a) extern void read_ehframe(FileIR_t* firp, EXEIO::exeio* ); -class PopulateIndTargs_t : public libIRDB::Transform_SDK::TransformStep_t +class PopulateIndTargs_t : public TransformStep_t { // record all full addresses and page-addresses found per function (or null for no function -using PerFuncAddrSet_t=set<virtual_offset_t>; +using PerFuncAddrSet_t=set<VirtualOffset_t>; map<Function_t*,PerFuncAddrSet_t> all_adrp_results; map<Function_t*,PerFuncAddrSet_t> all_add_adrp_results; // record all full addresses and page-addresses found that are spilled to the stack -using SpillPoint_t = pair<Function_t*, virtual_offset_t>; +using SpillPoint_t = pair<Function_t*, VirtualOffset_t>; map<SpillPoint_t,PerFuncAddrSet_t> spilled_add_adrp_results; map<SpillPoint_t,PerFuncAddrSet_t> spilled_adrps; @@ -87,13 +86,13 @@ public: // the bounds of the executable sections in the pgm. -set< pair <virtual_offset_t,virtual_offset_t> > bounds; +set< pair <VirtualOffset_t,VirtualOffset_t> > bounds; // the set of (possible) targets we've found. -map<virtual_offset_t,ibt_provenance_t> targets; +map<VirtualOffset_t,ibt_provenance_t> targets; // the set of ranges represented by the eh_frame section, could be empty for non-elf files. -set< pair< virtual_offset_t, virtual_offset_t> > ranges; +set< pair< VirtualOffset_t, VirtualOffset_t> > ranges; // a way to map an instruction to its set of (direct) predecessors. map< Instruction_t* , InstructionSet_t > preds; @@ -102,16 +101,16 @@ map< Instruction_t* , InstructionSet_t > preds; map< Instruction_t*, fii_icfs > jmptables; // a map of virtual offset -> instruction for quick access. -map<virtual_offset_t,Instruction_t*> lookupInstructionMap; +map<VirtualOffset_t,Instruction_t*> lookupInstructionMap; // the set of things that are partially unpinned already. set<Instruction_t*> already_unpinned; long total_unpins=0; -void range(virtual_offset_t start, virtual_offset_t end) +void range(VirtualOffset_t start, VirtualOffset_t end) { - pair<virtual_offset_t,virtual_offset_t> foo(start,end); + pair<VirtualOffset_t,VirtualOffset_t> foo(start,end); ranges.insert(foo); } @@ -119,7 +118,7 @@ void range(virtual_offset_t start, virtual_offset_t end) /* * is_in_range - determine if an address is referenced by the eh_frame section */ -bool is_in_range(virtual_offset_t p) +bool is_in_range(VirtualOffset_t p) { for(auto bound : ranges) { @@ -139,7 +138,7 @@ void process_ranges(FileIR_t* firp) } -bool possible_target(virtual_offset_t p, virtual_offset_t from_addr, ibt_provenance_t prov) +bool possible_target(VirtualOffset_t p, VirtualOffset_t from_addr, ibt_provenance_t prov) { if(is_possible_target(p,from_addr)) { @@ -156,7 +155,7 @@ bool possible_target(virtual_offset_t p, virtual_offset_t from_addr, ibt_provena return false; } -bool is_possible_target(virtual_offset_t p, virtual_offset_t addr) +bool is_possible_target(VirtualOffset_t p, VirtualOffset_t addr) { for(auto bound : bounds) { @@ -171,7 +170,7 @@ bool is_possible_target(virtual_offset_t p, virtual_offset_t addr) } -EXEIO::section* find_section(virtual_offset_t addr, EXEIO::exeio *elfiop) +EXEIO::section* find_section(VirtualOffset_t addr, EXEIO::exeio *elfiop) { for ( int i = 0; i < elfiop->sections.size(); ++i ) { @@ -189,23 +188,23 @@ EXEIO::section* find_section(virtual_offset_t addr, EXEIO::exeio *elfiop) void handle_argument( const DecodedInstruction_t& decoded_insn, - const DecodedOperand_t *arg, + const DecodedOperand_t &arg, Instruction_t* insn, ibt_provenance_t::provtype_t pt = ibt_provenance_t::ibtp_text ) { - if(arg->isMemory() && decoded_insn.getMnemonic()=="lea") + if(arg.isMemory() && decoded_insn.getMnemonic()=="lea") { - if(arg->isPcrel()) + if(arg.isPcrel()) { assert(insn); - assert(insn->GetAddress()); - possible_target(arg->getMemoryDisplacement() + insn->GetAddress()->GetVirtualOffset() + - insn->GetDataBits().length(), insn->GetAddress()->GetVirtualOffset(), pt); + assert(insn->getAddress()); + possible_target(arg.getMemoryDisplacement() + insn->getAddress()->getVirtualOffset() + + insn->getDataBits().length(), insn->getAddress()->getVirtualOffset(), pt); } else { - possible_target(arg->getMemoryDisplacement(), insn->GetAddress()->GetVirtualOffset(), pt); + possible_target(arg.getMemoryDisplacement(), insn->getAddress()->getVirtualOffset(), pt); } } } @@ -214,14 +213,14 @@ void handle_argument( void lookupInstruction_init(FileIR_t *firp) { lookupInstructionMap.clear(); - for(auto insn : firp->GetInstructions()) + for(auto insn : firp->getInstructions()) { - const auto addr=insn->GetAddress()->GetVirtualOffset(); + const auto addr=insn->getAddress()->getVirtualOffset(); lookupInstructionMap[addr]=insn; } } -Instruction_t *lookupInstruction(FileIR_t *firp, virtual_offset_t virtual_offset) +Instruction_t *lookupInstruction(FileIR_t *firp, VirtualOffset_t virtual_offset) { if(lookupInstructionMap.find(virtual_offset)!=lookupInstructionMap.end()) return lookupInstructionMap[virtual_offset]; @@ -230,9 +229,9 @@ Instruction_t *lookupInstruction(FileIR_t *firp, virtual_offset_t virtual_offset void mark_targets(FileIR_t *firp) { - for(auto insn : firp->GetInstructions()) + for(auto insn : firp->getInstructions()) { - auto addr=insn->GetAddress()->GetVirtualOffset(); + auto addr=insn->getAddress()->getVirtualOffset(); /* lookup in the list of targets */ if(targets.find(addr)!=targets.end()) @@ -253,12 +252,14 @@ void mark_targets(FileIR_t *firp) { if(getenv("IB_VERBOSE")!=nullptr) cout<<"Setting pin at "<<hex<<addr<<endl; + /* AddressID_t* newaddr = new AddressID_t; - newaddr->SetFileID(insn->GetAddress()->GetFileID()); - newaddr->SetVirtualOffset(insn->GetAddress()->GetVirtualOffset()); - - insn->SetIndirectBranchTargetAddress(newaddr); - firp->GetAddresses().insert(newaddr); + newaddr->SetFileID(insn->getAddress()->getFileID()); + newaddr->setVirtualOffset(insn->getAddress()->getVirtualOffset()); + firp->getAddresses().insert(newaddr); + */ + auto newaddr=firp->addNewAddress(insn->getAddress()->getFileID(), insn->getAddress()->getVirtualOffset()); + insn->setIndirectBranchTargetAddress(newaddr); } } } @@ -267,22 +268,21 @@ void mark_targets(FileIR_t *firp) bool CallToPrintfFollows(FileIR_t *firp, Instruction_t* insn, const string& arg_str) { - for(Instruction_t* ptr=insn->GetFallthrough(); ptr!=nullptr; ptr=ptr->GetFallthrough()) + for(auto ptr=insn->getFallthrough(); ptr!=nullptr; ptr=ptr->getFallthrough()) { - DecodedInstruction_t d(ptr); - // Disassemble(ptr,d); - if(d.getMnemonic() == string("call")) + auto d=DecodedInstruction_t ::factory(ptr); + if(d->getMnemonic() == string("call")) { // check we have a target - if(ptr->GetTarget()==nullptr) + if(ptr->getTarget()==nullptr) return false; // check the target has a function - if(ptr->GetTarget()->GetFunction()==nullptr) + if(ptr->getTarget()->getFunction()==nullptr) return false; // check if we're calling printf. - if(ptr->GetTarget()->GetFunction()->GetName().find("printf")==string::npos) + if(ptr->getTarget()->getFunction()->getName().find("printf")==string::npos) return false; // found it @@ -290,7 +290,7 @@ bool CallToPrintfFollows(FileIR_t *firp, Instruction_t* insn, const string& arg_ } // found reference to argstring, assume it's a write and exit - if(d.getDisassembly()/*string(d.CompleteInstr)*/.find(arg_str)!= string::npos) + if(d->getDisassembly().find(arg_str)!= string::npos) return false; } @@ -301,50 +301,50 @@ bool texttoprintf(FileIR_t *firp,Instruction_t* insn) { string dst=""; // note that dst is an output parameter of IsParameterWrite and an input parameter to CallFollows - if(IsParameterWrite(firp,insn, dst) && CallToPrintfFollows(firp,insn,dst)) + if(libIRDB::IsParameterWrite(firp,insn, dst) && CallToPrintfFollows(firp,insn,dst)) { return true; } return false; } -void get_instruction_targets(FileIR_t *firp, EXEIO::exeio* elfiop, const set<virtual_offset_t>& thunk_bases) +void get_instruction_targets(FileIR_t *firp, EXEIO::exeio* elfiop, const set<VirtualOffset_t>& thunk_bases) { - for(auto insn : firp->GetInstructions()) + for(auto insn : firp->getInstructions()) { - DecodedInstruction_t disasm(insn); - virtual_offset_t instr_len = disasm.length(); // Disassemble(insn,disasm); + auto disasm=DecodedInstruction_t::factory(insn); + VirtualOffset_t instr_len = disasm->length(); // Disassemble(insn,disasm); - assert(instr_len==insn->GetDataBits().size()); + assert(instr_len==insn->getDataBits().size()); - const auto mt=firp->GetArchitecture()->getMachineType(); + const auto mt=firp->getArchitecture()->getMachineType(); if(mt==admtX86_64 || mt==admtI386) { // work for both 32- and 64-bit. - check_for_PIC_switch_table32_type2(firp, insn,disasm, elfiop, thunk_bases); - check_for_PIC_switch_table32_type3(firp, insn,disasm, elfiop, thunk_bases); + check_for_PIC_switch_table32_type2(firp, insn, *disasm, elfiop, thunk_bases); + check_for_PIC_switch_table32_type3(firp, insn, *disasm, elfiop, thunk_bases); - if (firp->GetArchitectureBitWidth()==32) - check_for_PIC_switch_table32(firp, insn,disasm, elfiop, thunk_bases); - else if (firp->GetArchitectureBitWidth()==64) - check_for_PIC_switch_table64(firp, insn,disasm, elfiop); + if (firp->getArchitectureBitWidth()==32) + check_for_PIC_switch_table32(firp, insn, *disasm, elfiop, thunk_bases); + else if (firp->getArchitectureBitWidth()==64) + check_for_PIC_switch_table64(firp, insn, *disasm, elfiop); else assert(0); - check_for_nonPIC_switch_table(firp, insn,disasm, elfiop); - check_for_nonPIC_switch_table_pattern2(firp, insn,disasm, elfiop); + check_for_nonPIC_switch_table(firp, insn, *disasm, elfiop); + check_for_nonPIC_switch_table_pattern2(firp, insn, *disasm, elfiop); } else if(mt==admtAarch64) { - check_for_arm_switch_type1(firp,insn, disasm, elfiop); + check_for_arm_switch_type1(firp,insn, *disasm, elfiop); } else throw invalid_argument("Cannot determine machine type"); /* other branches can't indicate an indirect branch target */ - if(disasm.isBranch()) // disasm.Instruction.BranchType) + if(disasm->isBranch()) // disasm.Instruction.BranchType) continue; ibt_provenance_t::provtype_t prov=0; @@ -354,22 +354,22 @@ void get_instruction_targets(FileIR_t *firp, EXEIO::exeio* elfiop, const set<vir } else { - cout<<"TextToPrintf analysis of '"<<disasm.getDisassembly()<<"' successful at " <<hex<<insn->GetAddress()->GetVirtualOffset()<<endl; + cout<<"TextToPrintf analysis of '"<<disasm->getDisassembly()<<"' successful at " <<hex<<insn->getAddress()->getVirtualOffset()<<endl; prov=ibt_provenance_t::ibtp_texttoprintf; } /* otherwise, any immediate is a possible branch target */ - for(const auto& op: disasm.getOperands()) + for(const auto& op: disasm->getOperands()) { - if(op.isConstant()) - possible_target(op.getConstant(), 0, prov); + if(op->isConstant()) + possible_target(op->getConstant(), 0, prov); } for(auto i=0;i<4;i++) { - if(disasm.hasOperand(i)) + if(disasm->hasOperand(i)) { - const auto op=disasm.getOperand(i); - handle_argument(disasm, &op, insn, prov); + const auto op=disasm->getOperand(i); + handle_argument(*disasm, *op, insn, prov); } } } @@ -386,10 +386,10 @@ void get_executable_bounds(FileIR_t *firp, const section* shdr) if( !shdr->isExecutable() ) return; - virtual_offset_t first=shdr->get_address(); - virtual_offset_t second=shdr->get_address()+shdr->get_size(); + VirtualOffset_t first=shdr->get_address(); + VirtualOffset_t second=shdr->get_address()+shdr->get_size(); - bounds.insert(pair<virtual_offset_t,virtual_offset_t>(first,second)); + bounds.insert(pair<VirtualOffset_t,VirtualOffset_t>(first,second)); } @@ -416,7 +416,7 @@ void infer_targets(FileIR_t *firp, section* shdr) const char* data=shdr->get_data() ; // C(char*)malloc(shdr->sh_size); assert(arch_ptr_bytes()==4 || arch_ptr_bytes()==8); - for(int i=0;i+arch_ptr_bytes()<=shdr->get_size();i++) + for(auto i=0u;i+arch_ptr_bytes()<=(size_t)shdr->get_size();i++) { // even on 64-bit, pointers might be stored as 32-bit, as a // elf object has the 32-bit limitations. @@ -425,7 +425,7 @@ void infer_targets(FileIR_t *firp, section* shdr) if(arch_ptr_bytes()==4) p=*(int*)&data[i]; else - p=*(virtual_offset_t*)&data[i]; // 64 or 32-bit depending on sizeof uintptr_t, may need porting for cross platform analysis. + p=*(VirtualOffset_t*)&data[i]; // 64 or 32-bit depending on sizeof uintptr_t, may need porting for cross platform analysis. @@ -456,30 +456,30 @@ void infer_targets(FileIR_t *firp, section* shdr) void handle_scoop_scanning(FileIR_t* firp) { // check for addresses in scoops in the text section. - for(auto scoop : firp->GetDataScoops()) + for(auto scoop : firp->getDataScoops()) { // test if scoop was added by fill_in_cfg -- make this test better. - if(scoop->GetName().find("data_in_text_")==string::npos) continue; + if(scoop->getName().find("data_in_text_")==string::npos) continue; // at the moment, FIC only creates 4-, 8-, and 16- bytes scoops // change this code if FIC chagnes. - if(scoop->GetSize() == 4 ) + if(scoop->getSize() == 4 ) { // may be a 4-byter, which can't hold an address. continue; } - if(scoop->GetSize() == 8 ) + if(scoop->getSize() == 8 ) { // check to see if the scoop has an IBTA - const auto addr=*(uint64_t*)(scoop->GetContents().c_str()); - possible_target(addr, scoop->GetStart()->GetVirtualOffset(), ibt_provenance_t::ibtp_unknown); + const auto addr=*(uint64_t*)(scoop->getContents().c_str()); + possible_target(addr, scoop->getStart()->getVirtualOffset(), ibt_provenance_t::ibtp_unknown); } else { // we may see 16 indicating that a ldr q-word happened. // this isn't likely an IBT, so we skip scanning it. - assert(scoop->GetSize() == 16 ); + assert(scoop->getSize() == 16 ); } } } @@ -511,12 +511,12 @@ set<Instruction_t*> find_in_function(string needle, Function_t *haystack) assert(0 == regcomp(&preg, needle.c_str(), REG_EXTENDED)); - for (auto candidate : haystack->GetInstructions()) + for (auto candidate : haystack->getInstructions()) { - auto disasm=DecodedInstruction_t(candidate); + auto disasm=DecodedInstruction_t::factory(candidate); // check it's the requested type - if(regexec(&preg, disasm.getDisassembly().c_str(), 0, nullptr, 0) == 0) + if(regexec(&preg, disasm->getDisassembly().c_str(), 0, nullptr, 0) == 0) { found_instructions.insert(candidate); } @@ -584,17 +584,17 @@ bool backup_until(const string &insn_type_regex_str, // get I7's disassembly - const auto disasm=DecodedInstruction_t(prev); + const auto disasm=DecodedInstruction_t::factory(prev); // check it's the requested type - if(regexec(&preg, disasm.getDisassembly().c_str(), 0, nullptr, 0) == 0) + if(regexec(&preg, disasm->getDisassembly().c_str(), 0, nullptr, 0) == 0) return true; if(stop_if_set!="") { - for(const auto operand : disasm.getOperands()) + for(const auto operand : disasm->getOperands()) { - if(operand.isWritten() && regexec(&stop_expression, operand.getString().c_str(), 0, nullptr, 0) == 0) + if(operand->isWritten() && regexec(&stop_expression, operand->getString().c_str(), 0, nullptr, 0) == 0) return false; } } @@ -609,15 +609,15 @@ bool backup_until(const string &insn_type_regex_str, for(const auto pred : mypreds) { prev=pred;// mark that we are here, in case we return true here. - const auto disasm=DecodedInstruction_t(pred); + const auto disasm=DecodedInstruction_t::factory(pred); // check it's the requested type - if(regexec(&preg, disasm.getDisassembly().c_str(), 0, nullptr, 0) == 0) + if(regexec(&preg, disasm->getDisassembly().c_str(), 0, nullptr, 0) == 0) return true; if(stop_if_set!="") { - for(const auto operand : disasm.getOperands()) + for(const auto operand : disasm->getOperands()) { - if(operand.isWritten() && regexec(&stop_expression, operand.getString().c_str(), 0, nullptr, 0) == 0) + if(operand->isWritten() && regexec(&stop_expression, operand->getString().c_str(), 0, nullptr, 0) == 0) return false; } } @@ -688,7 +688,7 @@ notes: if(d10.getMnemonic() != "br") return; // grab the reg - const auto i10_reg=d10.getOperand(0).getString(); + const auto i10_reg=d10.getOperand(0)->getString(); // try to find I9 auto i9=(Instruction_t*)nullptr; @@ -704,9 +704,10 @@ notes: // Extract the I9 fields. assert(i9); - const auto d9 = DecodedInstruction_t(i9); - const auto offset_reg = d9.getOperand(1).getString(); - const auto table_entry_reg = d9.getOperand(2).getString(); + const auto d9p = DecodedInstruction_t::factory(i9); + const auto &d9 = *d9p; + const auto offset_reg = d9.getOperand(1)->getString(); + const auto table_entry_reg = d9.getOperand(2)->getString(); // try to find I8 @@ -721,8 +722,9 @@ notes: // extract the I8 fields assert(i8); - const auto d8 = DecodedInstruction_t(i8); - const auto jump_base_addr = d8.getOperand(1).getConstant(); + const auto d8p = DecodedInstruction_t::factory(i8); + const auto &d8 = *d8p; + const auto jump_base_addr = d8.getOperand(1)->getConstant(); // try to find I7 auto i7=(Instruction_t*)nullptr; @@ -736,8 +738,9 @@ notes: // extract the I7 fields assert(i7); - const auto d7 = DecodedInstruction_t(i7); - const auto memory_op_string = d7.getOperand(1).getString(); + const auto d7p = DecodedInstruction_t::factory(i7); + const auto &d7 = *d7p; + const auto memory_op_string = d7.getOperand(1)->getString(); const auto plus_pos = memory_op_string.find(" +"); const auto table_base_reg = memory_op_string.substr(0,plus_pos); const auto table_index_reg = memory_op_string.substr(plus_pos+3); @@ -768,9 +771,10 @@ notes: // extract the I6 fields assert(i6); - const auto d6 = DecodedInstruction_t(i6); - const auto table_page_reg = d6.getOperand(1).getString(); - const auto table_page_offset = d6.getOperand(2).getConstant(); + const auto d6p = DecodedInstruction_t::factory(i6); + const auto &d6 = *d6p; + const auto table_page_reg = d6.getOperand(1)->getString(); + const auto table_page_offset = d6.getOperand(2)->getConstant(); // try to find I5 auto i5=(Instruction_t*)nullptr; @@ -785,14 +789,15 @@ notes: { // extract i5 fields assert(i5); - const auto d5 = DecodedInstruction_t(i5); - const auto table_page = d5.getOperand(1).getConstant(); + const auto d5p = DecodedInstruction_t::factory(i5); + const auto &d5 = *d5p; + const auto table_page = d5.getOperand(1)->getConstant(); const auto table_addr=table_page+table_page_offset; all_table_bases= PerFuncAddrSet_t({table_addr}); } else { - for(auto adrp_value : all_adrp_results[i10->GetFunction()]) + for(auto adrp_value : all_adrp_results[i10->getFunction()]) { all_table_bases.insert(adrp_value+table_page_offset); } @@ -810,25 +815,26 @@ notes: )) { assert(i6); - const auto d6 = DecodedInstruction_t(i6); + const auto d6p = DecodedInstruction_t::factory(i6); + const auto &d6 = *d6p; // found reload of table address from spill location! // reloads write to the stack with a constant offset. const auto reload_op1=d6.getOperand(1); - assert(reload_op1.isMemory()); - const auto reload_op1_string=reload_op1.getString(); + assert(reload_op1->isMemory()); + const auto reload_op1_string=reload_op1->getString(); // needs to have a base reg, which is either sp or x29 - const auto hasbr = (reload_op1.hasBaseRegister()) ; + const auto hasbr = (reload_op1->hasBaseRegister()) ; const auto okbr = (reload_op1_string.substr(0,2)=="sp" || reload_op1_string.substr(0,3)=="x29" ) ; - const auto hasdisp = (reload_op1.hasMemoryDisplacement()) ; - const auto hasir = (reload_op1.hasIndexRegister()) ; + const auto hasdisp = (reload_op1->hasMemoryDisplacement()) ; + const auto hasir = (reload_op1->hasIndexRegister()) ; const auto ok = hasbr && okbr && hasdisp && !hasir; if(ok) { // extract fields - const auto reload_disp=reload_op1.getMemoryDisplacement(); - const auto reload_loc=SpillPoint_t({i10->GetFunction(),reload_disp}); + const auto reload_disp=reload_op1->getMemoryDisplacement(); + const auto reload_loc=SpillPoint_t({i10->getFunction(),reload_disp}); const auto &spills=spilled_add_adrp_results[reload_loc]; if(spills.size()>0) { @@ -849,15 +855,16 @@ notes: )) { assert(i6); - const auto d6 = DecodedInstruction_t(i6); + const auto d6p = DecodedInstruction_t::factory(i6); + const auto &d6 = *d6p; const auto reload_op1 = d6.getOperand(1); - const auto reload_op1_str = reload_op1.getString(); + const auto reload_op1_str = reload_op1->getString(); const auto is_dreg = reload_op1_str[0]=='d'; if(is_dreg) { - const auto reload_loc = DregSpillPoint_t({i6->GetFunction(), reload_op1_str}); + const auto reload_loc = DregSpillPoint_t({i6->getFunction(), reload_op1_str}); const auto spills = spilled_to_dreg[reload_loc]; if(spills.size()>0) { @@ -906,11 +913,11 @@ notes: { if(i1!=new_i1) /* sanity check that we got to the same place */ break; - const auto d1 = DecodedInstruction_t(i1); - const auto d1op1 = d1.getOperand(1); - if(d1op1.isConstant()) + const auto d1 = DecodedInstruction_t::factory(i1); + const auto d1op1 = d1->getOperand(1); + if(d1op1->isConstant()) { - my_bound=d1op1.getConstant(); + my_bound=d1op1->getConstant(); } break; @@ -923,11 +930,11 @@ notes: )) { // track backwards on reg 2 if we find a mov <reg1>, <reg2> - const auto d1 = DecodedInstruction_t(new_i1); - const auto new_d1op1 = d1.getOperand(1); - if(new_d1op1.isRegister()) + const auto d1 = DecodedInstruction_t::factory(new_i1); + const auto new_d1op1 = d1->getOperand(1); + if(new_d1op1->isRegister()) { - next_reg=new_d1op1.getString(); + next_reg=new_d1op1->getString(); continue; } else @@ -957,13 +964,13 @@ notes: // calculate any possible targets for this switch. // consider each jump table - auto my_targets=set<virtual_offset_t>(); + auto my_targets=set<VirtualOffset_t>(); auto valid_table_count=0u; for(auto cur_table_addr : all_table_bases) { // try to find switch table jumps - const auto i10_func=i10->GetFunction(); + const auto i10_func=i10->getFunction(); // find the section with the jump table const auto table_section=find_section(cur_table_addr,elfiop); @@ -997,7 +1004,7 @@ notes: if(do_verbose) { // log that we've found a table, etc. - cout << "Found ARM type1 at 0x"<<hex<<i10->GetAddress()->GetVirtualOffset() + cout << "Found ARM type1 at 0x"<<hex<<i10->getAddress()->getVirtualOffset() << " with my_bound = 0x"<<hex<<my_bound << ", table_entry_size = "<<dec<<table_entry_size << ", jump_base_addr = 0x"<<hex<<jump_base_addr @@ -1011,7 +1018,8 @@ notes: // look at each table entry auto target_count=0U; - auto this_table_targets=vector<tuple<virtual_offset_t, virtual_offset_t, ibt_provenance_t> >(); + using OffOffProvTuple_t = tuple<VirtualOffset_t, VirtualOffset_t, ibt_provenance_t> ; + auto this_table_targets=vector<OffOffProvTuple_t>(); for ( ; getEntryPtr(target_count)+table_entry_size < table_section_end_ptr ; target_count++ ) { const auto entry_ptr = getEntryPtr(target_count); @@ -1036,7 +1044,7 @@ notes: cout<<" -- no target insn!"<<endl; break; } - const auto ibtarget_func=ibtarget->GetFunction(); + const auto ibtarget_func=ibtarget->getFunction(); if( i10_func == nullptr ) { // finding switch in non-function is OK. @@ -1062,7 +1070,7 @@ notes: cout<<" -- not valid target!"<<endl; break; } - if(firp->FindScoop(candidate_ibta)!=nullptr) + if(firp->findScoop(candidate_ibta)!=nullptr) { if(do_verbose) cout<<" -- not valid target due to data-in-text detection!"<<endl; @@ -1106,7 +1114,7 @@ notes: /* * check_for_PIC_switch_table32 - look for switch tables in PIC code for 32-bit code. */ -void check_for_PIC_switch_table32(FileIR_t *firp, Instruction_t* insn, DecodedInstruction_t disasm, EXEIO::exeio* elfiop, const set<virtual_offset_t> &thunk_bases) +void check_for_PIC_switch_table32(FileIR_t *firp, Instruction_t* insn, const DecodedInstruction_t& disasm, EXEIO::exeio* elfiop, const set<VirtualOffset_t> &thunk_bases) { ibt_provenance_t prov=ibt_provenance_t::ibtp_switchtable_type1; @@ -1143,15 +1151,15 @@ I7: 08069391 <_gedit_app_ready+0x91> ret return; // return if it's a jump to a constant address, these are common - if(disasm.getOperand(0).isConstant() ) + if(disasm.getOperand(0)->isConstant() ) return; // return if it's a jump to a memory address - if(disasm.getOperand(0).isMemory() ) + if(disasm.getOperand(0)->isMemory() ) return; - assert(disasm.getOperand(0).isRegister()); - const auto I5_reg=disasm.getOperand(0).getString(); + assert(disasm.getOperand(0)->isRegister()); + const auto I5_reg=disasm.getOperand(0)->getString(); auto jmp_reg=string(); auto add_reg=string(); @@ -1163,20 +1171,22 @@ I7: 08069391 <_gedit_app_ready+0x91> ret auto mov_insn=static_cast<Instruction_t*>(nullptr); if(!backup_until(string()+"mov "+I5_reg, mov_insn, I5, I5_reg)) return; - const auto mov_insn_disasm=DecodedInstruction_t(mov_insn); - if(!mov_insn_disasm.getOperand(1).isRegister()) + const auto p_mov_insn_disasm=DecodedInstruction_t::factory(mov_insn); + const auto &mov_insn_disasm=*p_mov_insn_disasm; + if(!mov_insn_disasm.getOperand(1)->isRegister()) return; - const auto mov_reg=mov_insn_disasm.getOperand(1).getString(); + const auto mov_reg=mov_insn_disasm.getOperand(1)->getString(); if(!backup_until(string()+"add "+mov_reg, I4, mov_insn, mov_reg)) return; jmp_reg=mov_reg; } else { - const auto d4=DecodedInstruction_t(I4); + const auto p_d4=DecodedInstruction_t::factory(I4); + const auto &d4=*p_d4; if(d4.getMnemonic()=="lea") { - const auto base_reg=d4.getOperand(1).getBaseRegister(); + const auto base_reg=d4.getOperand(1)->getBaseRegister(); switch(base_reg) { case 0/*REG0*/: jmp_reg="eax"; break; @@ -1191,7 +1201,7 @@ I7: 08069391 <_gedit_app_ready+0x91> ret // no base register; return; } - const auto index_reg=d4.getOperand(1).getBaseRegister(); + const auto index_reg=d4.getOperand(1)->getBaseRegister(); switch(index_reg) { case 0/*REG0*/: add_reg="eax"; break; @@ -1210,9 +1220,9 @@ I7: 08069391 <_gedit_app_ready+0x91> ret else { jmp_reg=I5_reg; - if(!d4.getOperand(1).isRegister()) + if(!d4.getOperand(1)->isRegister()) return; - add_reg=d4.getOperand(1).getString(); + add_reg=d4.getOperand(1)->getString(); } } @@ -1234,27 +1244,28 @@ I7: 08069391 <_gedit_app_ready+0x91> ret { //DISASM dcmp; //Disassemble(Icmp,dcmp); - DecodedInstruction_t dcmp(Icmp); - table_size = dcmp.getImmediate(); //Instruction.Immediat; + auto dcmp=DecodedInstruction_t::factory(Icmp); + table_size = dcmp->getImmediate(); //Instruction.Immediat; if(table_size<=0) table_size=std::numeric_limits<int>::max(); } // grab the offset out of the lea. - const auto d2=DecodedInstruction_t(I3); + const auto p_d2=DecodedInstruction_t::factory(I3); + const auto &d2=*p_d2; // get the offset from the thunk auto table_offset=d2.getAddress(); if(table_offset==0) return; - cout<<hex<<"Found switch dispatch at "<<I3->GetAddress()->GetVirtualOffset() + cout<<hex<<"Found switch dispatch at "<<I3->getAddress()->getVirtualOffset() << " with table_offset="<<table_offset <<" and table_size="<<table_size<<endl; /* iterate over all thunk_bases/module_starts */ for(auto thunk_base : thunk_bases) { - virtual_offset_t table_base=thunk_base+table_offset; + VirtualOffset_t table_base=thunk_base+table_offset; // find the section with the data table EXEIO::section *pSec=find_section(table_base,elfiop); @@ -1267,7 +1278,7 @@ I7: 08069391 <_gedit_app_ready+0x91> ret continue; // get the base offset into the section - virtual_offset_t offset=table_base-pSec->get_address(); + VirtualOffset_t offset=table_base-pSec->get_address(); int i; for(i=0;i<3;i++) { @@ -1294,7 +1305,7 @@ I7: 08069391 <_gedit_app_ready+0x91> ret break; const int32_t *table_entry_ptr=(const int32_t*)&(secdata[offset+i*4]); - virtual_offset_t table_entry=*table_entry_ptr; + VirtualOffset_t table_entry=*table_entry_ptr; if(getenv("IB_VERBOSE")!=0) cout<<"Found switch table (thunk-relative) entry["<<dec<<i<<"], "<<hex<<thunk_base+table_entry<<endl; @@ -1312,11 +1323,11 @@ I7: 08069391 <_gedit_app_ready+0x91> ret // valid switch table? may or may not have default: in the switch // table size = 8, #entries: 9 b/c of default cout << "pic32 (base pattern): table size: " << table_size << " ibtargets.size: " << ibtargets.size() << endl; - jmptables[I5].AddTargets(ibtargets); + jmptables[I5].addTargets(ibtargets); if (table_size == ibtargets.size() || table_size == (ibtargets.size()-1)) { cout << "pic32 (base pattern): valid switch table detected ibtp_switchtable_type1" << endl; - jmptables[I5].SetAnalysisStatus(ICFS_Analysis_Complete); + jmptables[I5].setAnalysisStatus(iasAnalysisComplete); } } @@ -1332,7 +1343,7 @@ I7: 08069391 <_gedit_app_ready+0x91> ret -void check_for_PIC_switch_table32_type2(FileIR_t *firp, Instruction_t* insn, DecodedInstruction_t disasm, EXEIO::exeio* elfiop, const set<virtual_offset_t> &thunk_bases) +void check_for_PIC_switch_table32_type2(FileIR_t *firp, Instruction_t* insn, const DecodedInstruction_t& disasm, EXEIO::exeio* elfiop, const set<VirtualOffset_t> &thunk_bases) { ibt_provenance_t prov=ibt_provenance_t::ibtp_switchtable_type2; auto ibtargets = InstructionSet_t(); @@ -1354,12 +1365,12 @@ I5: 0x809900e <text_handler+51>: jmp ecx return; // return if it's a jump to a constant address, these are common - if(disasm.getOperand(0).isConstant() /*disasm.Argument1.ArgType&CONSTANT_TYPE*/) + if(disasm.getOperand(0)->isConstant() /*disasm.Argument1.ArgType&CONSTANT_TYPE*/) return; // return if it's a jump to a memory address //if(disasm.Argument1.ArgType&MEMORY_TYPE) - if(disasm.getOperand(0).isMemory()) + if(disasm.getOperand(0)->isMemory()) return; // has to be a jump to a register now @@ -1368,8 +1379,8 @@ I5: 0x809900e <text_handler+51>: jmp ecx if(!backup_until("add", I4, I5)) return; - const auto d4=DecodedInstruction_t(I4); - if(!d4.hasOperand(1) || !d4.getOperand(1).isMemory()) + const auto d4=DecodedInstruction_t::factory(I4); + if(!d4->hasOperand(1) || !d4->getOperand(1)->isMemory()) return; // found that sometimes I3 is set a different way, @@ -1378,17 +1389,12 @@ I5: 0x809900e <text_handler+51>: jmp ecx // if(!backup_until("lea", I3, I4)) // return; - // grab the offset out of the lea. - //DISASM d2; - //Disassemble(I3,d2); - //DecodedInstruction_t d2(I3); - // get the offset from the thunk - virtual_offset_t table_offset=d4.getOperand(1).getMemoryDisplacement(); //d2.getAddress(); // d2.Instruction.AddrValue; + VirtualOffset_t table_offset=d4->getOperand(1)->getMemoryDisplacement(); if(table_offset==0) return; -cout<<hex<<"Found (type2) switch dispatch at "<<I5->GetAddress()->GetVirtualOffset()<< " with table_offset="<<table_offset<<endl; + cout<<hex<<"Found (type2) switch dispatch at "<<I5->getAddress()->getVirtualOffset()<< " with table_offset="<<table_offset<<endl; /* iterate over all thunk_bases/module_starts */ for(auto thunk_base : thunk_bases ) @@ -1406,7 +1412,7 @@ cout<<hex<<"Found (type2) switch dispatch at "<<I5->GetAddress()->GetVirtualOffs continue; // get the base offset into the section - virtual_offset_t offset=table_base-pSec->get_address(); + VirtualOffset_t offset=table_base-pSec->get_address(); int i; for(i=0;i<3;i++) { @@ -1414,7 +1420,7 @@ cout<<hex<<"Found (type2) switch dispatch at "<<I5->GetAddress()->GetVirtualOffs break; const int32_t *table_entry_ptr=(const int32_t*)&(secdata[offset+i*4]); - virtual_offset_t table_entry=*table_entry_ptr; + VirtualOffset_t table_entry=*table_entry_ptr; // cout<<"Checking target base:" << std::hex << table_base+table_entry << ", " << table_base+i*4<<endl; if(!is_possible_target(table_base+table_entry,table_base+i*4) && !is_possible_target(thunk_base+table_entry,table_base+i*4)) @@ -1432,7 +1438,7 @@ cout<<hex<<"Found (type2) switch dispatch at "<<I5->GetAddress()->GetVirtualOffs break; const int32_t *table_entry_ptr=(const int32_t*)&(secdata[offset+i*4]); - virtual_offset_t table_entry=*table_entry_ptr; + VirtualOffset_t table_entry=*table_entry_ptr; if(getenv("IB_VERBOSE")!=0) cout<<"Found switch table (thunk-relative) entry["<<dec<<i<<"], "<<hex<<table_base+table_entry<<" or "<<thunk_base+table_entry<<endl; @@ -1457,7 +1463,7 @@ cout<<hex<<"Found (type2) switch dispatch at "<<I5->GetAddress()->GetVirtualOffs // now, try next thunk base } - jmptables[I5].AddTargets(ibtargets); + jmptables[I5].addTargets(ibtargets); } @@ -1468,9 +1474,9 @@ cout<<hex<<"Found (type2) switch dispatch at "<<I5->GetAddress()->GetVirtualOffs * * nb: also works for 64-bit. */ -void check_for_PIC_switch_table32_type3(FileIR_t* firp, Instruction_t* insn, DecodedInstruction_t disasm, EXEIO::exeio* elfiop, const set<virtual_offset_t> &thunk_bases) +void check_for_PIC_switch_table32_type3(FileIR_t* firp, Instruction_t* insn, const DecodedInstruction_t& disasm, EXEIO::exeio* elfiop, const set<VirtualOffset_t> &thunk_bases) { - uint32_t ptrsize=firp->GetArchitectureBitWidth()/8; + uint32_t ptrsize=firp->getArchitectureBitWidth()/8; ibt_provenance_t prov=ibt_provenance_t::ibtp_switchtable_type3; Instruction_t* I5=insn; @@ -1479,20 +1485,20 @@ void check_for_PIC_switch_table32_type3(FileIR_t* firp, Instruction_t* insn, Dec return; // return if it's not a jump to a memory address - if(!(disasm.getOperand(0).isMemory())) + if(!(disasm.getOperand(0)->isMemory())) return; /* return if there's no displacement */ - if(disasm.getOperand(0).getMemoryDisplacement()==0) + if(disasm.getOperand(0)->getMemoryDisplacement()==0) return; - if(!disasm.getOperand(0).hasIndexRegister() || disasm.getOperand(0).getScaleValue()!=ptrsize) + if(!disasm.getOperand(0)->hasIndexRegister() || disasm.getOperand(0)->getScaleValue()!=ptrsize) return; // grab the table base out of the jmp. - virtual_offset_t table_base=disasm.getOperand(0).getMemoryDisplacement();//disasm.Argument1.Memory.Displacement; - if(disasm.getOperand(0).isPcrel()) - table_base+=insn->GetDataBits().size()+insn->GetAddress()->GetVirtualOffset(); + VirtualOffset_t table_base=disasm.getOperand(0)->getMemoryDisplacement(); + if(disasm.getOperand(0)->isPcrel()) + table_base+=insn->getDataBits().size()+insn->getAddress()->getVirtualOffset(); if(table_base==0) return; @@ -1507,8 +1513,8 @@ void check_for_PIC_switch_table32_type3(FileIR_t* firp, Instruction_t* insn, Dec if(backup_until("cmp ", cmp_insn, insn)) { assert(cmp_insn); - const auto cmp_decode=DecodedInstruction_t(cmp_insn); - table_max=cmp_decode.getImmediate(); + const auto cmp_decode=DecodedInstruction_t::factory(cmp_insn); + table_max=cmp_decode->getImmediate(); } @@ -1518,12 +1524,12 @@ void check_for_PIC_switch_table32_type3(FileIR_t* firp, Instruction_t* insn, Dec return; // get the base offset into the section - virtual_offset_t offset=table_base-pSec->get_address(); + VirtualOffset_t offset=table_base-pSec->get_address(); // check to see if stars already marked this complete. // if so, just figure out the table size - if(jmptables[insn].GetAnalysisStatus()==ICFS_Analysis_Complete) + if(jmptables[insn].getAnalysisStatus()==iasAnalysisComplete) { // we already know it's a type3, we can just record the type and table base. jmptables[insn].AddSwitchType(prov); @@ -1539,14 +1545,14 @@ void check_for_PIC_switch_table32_type3(FileIR_t* firp, Instruction_t* insn, Dec const void *table_entry_ptr=(const int*)&(secdata[offset+i*ptrsize]); - virtual_offset_t table_entry=0; + VirtualOffset_t table_entry=0; switch(ptrsize) { case 4: - table_entry=(virtual_offset_t)*(int*)table_entry_ptr; + table_entry=(VirtualOffset_t)*(int*)table_entry_ptr; break; case 8: - table_entry=(virtual_offset_t)*(int**)table_entry_ptr; + table_entry=(VirtualOffset_t)*(int**)table_entry_ptr; break; default: assert(0); @@ -1560,7 +1566,7 @@ void check_for_PIC_switch_table32_type3(FileIR_t* firp, Instruction_t* insn, Dec jmptables[insn].SetTableSize(i); if(getenv("IB_VERBOSE")) { - cout<<"Found type3 at "<<hex<<insn->GetAddress()->GetVirtualOffset() + cout<<"Found type3 at "<<hex<<insn->getAddress()->getVirtualOffset() <<" already complete, setting base to "<<hex<<table_base<<" and size to "<<dec<<i<<endl; } return; @@ -1575,14 +1581,14 @@ void check_for_PIC_switch_table32_type3(FileIR_t* firp, Instruction_t* insn, Dec const void *table_entry_ptr=(const int*)&(secdata[offset+i*ptrsize]); - virtual_offset_t table_entry=0; + VirtualOffset_t table_entry=0; switch(ptrsize) { case 4: - table_entry=(virtual_offset_t)*(int*)table_entry_ptr; + table_entry=(VirtualOffset_t)*(int*)table_entry_ptr; break; case 8: - table_entry=(virtual_offset_t)*(int**)table_entry_ptr; + table_entry=(VirtualOffset_t)*(int**)table_entry_ptr; break; default: assert(0); @@ -1593,7 +1599,7 @@ void check_for_PIC_switch_table32_type3(FileIR_t* firp, Instruction_t* insn, Dec /* if there's no base register and no index reg, */ /* then this jmp can't have more than one valid table entry */ - if( !disasm.getOperand(0).hasBaseRegister() && !disasm.getOperand(0).hasIndexRegister()) + if( !disasm.getOperand(0)->hasBaseRegister() && !disasm.getOperand(0)->hasIndexRegister()) { /* but the table can have 1 valid entry. */ if(pSec->get_name()==".got.plt") @@ -1602,10 +1608,10 @@ void check_for_PIC_switch_table32_type3(FileIR_t* firp, Instruction_t* insn, Dec if(ibtarget) { jmptables[I5].insert(ibtarget); - jmptables[I5].SetAnalysisStatus(ICFS_Analysis_Module_Complete); + jmptables[I5].setAnalysisStatus(iasAnalysisModuleComplete); possible_target(table_entry,table_base+0*ptrsize, ibt_provenance_t::ibtp_gotplt); if(getenv("IB_VERBOSE")!=0) - cout<<hex<<"Found plt dispatch ("<<disasm.getDisassembly()<<"') at "<<I5->GetAddress()->GetVirtualOffset()<< endl; + cout<<hex<<"Found plt dispatch ("<<disasm.getDisassembly()<<"') at "<<I5->getAddress()->getVirtualOffset()<< endl; return; } } @@ -1615,7 +1621,7 @@ void check_for_PIC_switch_table32_type3(FileIR_t* firp, Instruction_t* insn, Dec possible_target(table_entry,table_base+0*ptrsize, ibt_provenance_t::ibtp_rodata); if(getenv("IB_VERBOSE")!=0) cout<<hex<<"Found constant-memory dispatch from non- .got.plt location ("<<disasm.getDisassembly()<<"') at " - <<I5->GetAddress()->GetVirtualOffset()<< endl; + <<I5->getAddress()->getVirtualOffset()<< endl; return; } if(!is_possible_target(table_entry,table_base+i*ptrsize)) @@ -1623,7 +1629,7 @@ void check_for_PIC_switch_table32_type3(FileIR_t* firp, Instruction_t* insn, Dec if(getenv("IB_VERBOSE")!=0) { cout<<hex<<"Found (type3) candidate for switch dispatch for '"<<disasm.getDisassembly()<<"' at " - <<I5->GetAddress()->GetVirtualOffset()<< " with table_base="<<table_base<<endl; + <<I5->getAddress()->getVirtualOffset()<< " with table_base="<<table_base<<endl; cout<<"Found table_entry "<<hex<<table_entry<<" is not valid\n"<<endl; } return; @@ -1631,7 +1637,7 @@ void check_for_PIC_switch_table32_type3(FileIR_t* firp, Instruction_t* insn, Dec } - cout<<hex<<"Definitely found (type3) switch dispatch at "<<I5->GetAddress()->GetVirtualOffset()<< " with table_base="<<table_base<<endl; + cout<<hex<<"Definitely found (type3) switch dispatch at "<<I5->getAddress()->getVirtualOffset()<< " with table_base="<<table_base<<endl; /* did we finish the loop or break out? */ if(i==3) @@ -1647,24 +1653,24 @@ void check_for_PIC_switch_table32_type3(FileIR_t* firp, Instruction_t* insn, Dec { if(getenv("IB_VERBOSE")!=0) { - cout<<hex<<"Switch dispatch at "<<I5->GetAddress()->GetVirtualOffset()<< " with table_base=" + cout<<hex<<"Switch dispatch at "<<I5->getAddress()->getVirtualOffset()<< " with table_base=" <<table_base<<" is complete!"<<endl; } - jmptables[insn].SetAnalysisStatus(ICFS_Analysis_Complete); + jmptables[insn].setAnalysisStatus(iasAnalysisComplete); } if((int)(offset+i*ptrsize+ptrsize) > (int)pSec->get_size() || i > table_max) return; const void *table_entry_ptr=(const int*)&(secdata[offset+i*ptrsize]); - virtual_offset_t table_entry=0; + VirtualOffset_t table_entry=0; switch(ptrsize) { case 4: - table_entry=(virtual_offset_t)*(int*)table_entry_ptr; + table_entry=(VirtualOffset_t)*(int*)table_entry_ptr; break; case 8: - table_entry=(virtual_offset_t)*(int**)table_entry_ptr; + table_entry=(VirtualOffset_t)*(int**)table_entry_ptr; break; default: assert(0); @@ -1694,7 +1700,7 @@ void check_for_PIC_switch_table32_type3(FileIR_t* firp, Instruction_t* insn, Dec * if so, see if we can trace back a few instructions to find a * the start of the table. */ -void check_for_PIC_switch_table64(FileIR_t* firp, Instruction_t* insn, DecodedInstruction_t disasm, EXEIO::exeio* elfiop) +void check_for_PIC_switch_table64(FileIR_t* firp, Instruction_t* insn, const DecodedInstruction_t& p_disasm, EXEIO::exeio* elfiop) { ibt_provenance_t prov=ibt_provenance_t::ibtp_switchtable_type4; /* here's the pattern we're looking for */ @@ -1767,14 +1773,14 @@ Note: Here the operands of the add are reversed, so lookup code was not finding Instruction_t* I5=nullptr; Instruction_t* I1=nullptr; // check if I8 is a jump - if(strstr(disasm.getMnemonic().c_str()/*Instruction.Mnemonic*/, "jmp")==nullptr) + if(strstr(p_disasm.getMnemonic().c_str(), "jmp")==nullptr) return; // return if it's a jump to a constant address, these are common - if(disasm.getOperand(0).isConstant()) //disasm.Argument1.ArgType&CONSTANT_TYPE) + if(p_disasm.getOperand(0)->isConstant()) return; // return if it's a jump to a memory address - if(disasm.getOperand(0).isMemory()) // Argument1.ArgType&MEMORY_TYPE) + if(p_disasm.getOperand(0)->isMemory()) return; // has to be a jump to a register now @@ -1787,30 +1793,29 @@ Note: Here the operands of the add are reversed, so lookup code was not finding * Backup and find the instruction that's an add or lea before I8. */ table_index_str = "(add "; - table_index_str += disasm.getOperand(0).getString(); //Argument1.ArgMnemonic; + table_index_str += p_disasm.getOperand(0)->getString(); table_index_str += "|lea "; - table_index_str += disasm.getOperand(0).getString(); //Argument1.ArgMnemonic; + table_index_str += p_disasm.getOperand(0)->getString(); table_index_str += ")"; - const auto cmp_str = string("cmp ") + disasm.getOperand(0).getString(); //Argument1.ArgMnemonic; + const auto cmp_str = string("cmp ") + p_disasm.getOperand(0)->getString(); // this was completely broken because argument2 had a null mnemonic, which we found out because getOperand(1) threw an exception. // i suspect it's attempting to find a compare of operand1 on the RHS of a compare, but i need better regex foo to get that. // for now, repeat what was working. - const auto cmp_str2 = string("cmp "); // + disasm.getOperand(1).getString(); //Argument2.ArgMnemonic; + const auto cmp_str2 = string("cmp "); if(!backup_until(table_index_str.c_str(), I7, I8)) return; - // Disassemble(I7,disasm); - disasm=DecodedInstruction_t(I7); + const auto d7=DecodedInstruction_t::factory(I7); // Check if lea instruction is being used as add (scale=1, disp=0) - if(strstr(disasm.getMnemonic().c_str() /* Instruction.Mnemonic*/, "lea")) + if(strstr(d7->getMnemonic().c_str(), "lea")) { - if(!(disasm.getOperand(1).isMemory() /*disasm.Argument2.ArgType&MEMORY_TYPE)*/)) + if(!(d7->getOperand(1)->isMemory() )) return; - if(!(disasm.getOperand(1).getScaleValue() /* .Argument2.Memory.Scale */ == 1 && disasm.getOperand(1).getMemoryDisplacement() /*Argument2.Memory.Displacement*/ == 0)) + if(!(d7->getOperand(1)->getScaleValue() == 1 && d7->getOperand(1)->getMemoryDisplacement() == 0)) return; } // backup and find the instruction that's an movsxd before I7 @@ -1823,9 +1828,8 @@ Note: Here the operands of the add are reversed, so lookup code was not finding string lea_string="lea "; - // Disassemble(I6,disasm); - disasm=DecodedInstruction_t(I6); - if( disasm.getOperand(1).isMemory() /* (disasm.Argument2.ArgType&MEMORY_TYPE) == MEMORY_TYPE*/) + const auto d6=DecodedInstruction_t::factory(I6); + if( d6->getOperand(1)->isMemory() ) { // try to be smarter for memory types. @@ -1835,9 +1839,9 @@ Note: Here the operands of the add are reversed, so lookup code was not finding * for the base of the jump table. */ string base_reg=""; - if(!disasm.getOperand(1).hasBaseRegister() /*Argument2.Memory.BaseRegister*/) + if(!d6->getOperand(1)->hasBaseRegister() ) return; - switch(disasm.getOperand(1).getBaseRegister() /*Argument2.Memory.BaseRegister*/) + switch(d6->getOperand(1)->getBaseRegister() ) { case 0/*REG0*/: base_reg="rax"; break; case 1/*REG1*/: base_reg="rcx"; break; @@ -1876,14 +1880,13 @@ Note: Here the operands of the add are reversed, so lookup code was not finding * Convert to return set */ - set<Instruction_t*>::const_iterator found_leas_it; - set<Instruction_t*> found_leas; + auto found_leas=InstructionSet_t(); - if (I6->GetFunction()) + if (I6->getFunction()) { cout << "Using find_in_function method." << endl; - found_leas=find_in_function(lea_string,I6->GetFunction()); + found_leas=find_in_function(lea_string,I6->getFunction()); } else { @@ -1904,66 +1907,58 @@ Note: Here the operands of the add are reversed, so lookup code was not finding /* * Check each one that is returned. */ - found_leas_it = found_leas.begin(); + auto found_leas_it = found_leas.begin(); for (; found_leas_it != found_leas.end(); found_leas_it++) { - Instruction_t *I5_cur = *found_leas_it; - //Disassemble(I5_cur,disasm); - disasm=DecodedInstruction_t(I5_cur); + auto I5_cur = *found_leas_it; + auto d5p=DecodedInstruction_t::factory(I5_cur); + auto &d5=*d5p; - if(!(disasm.getOperand(1).isMemory() /*Argument2.ArgType&MEMORY_TYPE*/)) - //return; + if(!(d5.getOperand(1)->isMemory() )) continue; - if(!(disasm.getOperand(1).isPcrel() /*Argument2.ArgType&RELATIVE_*/)) - //return; + if(!(d5.getOperand(1)->isPcrel() )) continue; // note that we'd normally have to add the displacement to the // instruction address (and include the instruction's size, etc. // but, fix_calls has already removed this oddity so we can relocate // the instruction. - virtual_offset_t D1=strtol(disasm.getOperand(1).getString().c_str()/*Argument2.ArgMnemonic*/, nullptr, 0); - D1+=I5_cur->GetAddress()->GetVirtualOffset(); + VirtualOffset_t D1=strtol(d5.getOperand(1)->getString().c_str(), nullptr, 0); + D1+=I5_cur->getAddress()->getVirtualOffset(); // find the section with the data table - EXEIO::section *pSec=find_section(D1,elfiop); + auto pSec=find_section(D1,elfiop); // sanity check there's a section if(!pSec) - //return; continue; const char* secdata=pSec->get_data(); // if the section has no data, abort if(!secdata) - //return; continue; auto table_size = 0U; if(backup_until(cmp_str.c_str(), I1, I8)) { - //DISASM d1; - //Disassemble(I1,d1); - DecodedInstruction_t d1(I1); - table_size = d1.getImmediate(); // Instruction.Immediat; + auto d1=DecodedInstruction_t::factory(I1); + table_size = d1->getImmediate(); // Instruction.Immediat; if (table_size <= 4) { - cout<<"pic64: found I1 ('"<<d1.getDisassembly()/*CompleteInstr*/<<"'), but could not find size of switch table"<<endl; + cout<<"pic64: found I1 ('"<<d1->getDisassembly()<<"'), but could not find size of switch table"<<endl; // set table_size to be very large, so we can still do pinning appropriately table_size=std::numeric_limits<int>::max(); } } else if(backup_until(cmp_str2.c_str(), I1, I8)) { - //DISASM d1; - //Disassemble(I1,d1); - DecodedInstruction_t d1(I1); - table_size = d1.getImmediate()/*Instruction.Immediat*/; + auto d1=DecodedInstruction_t::factory(I1); + table_size = d1->getImmediate()/*Instruction.Immediat*/; if (table_size <= 4) { // set table_size to be very large, so we can still do pinning appropriately - cout<<"pic64: found I1 ('"<<d1.getDisassembly()/*CompleteInstr*/<<"'), but could not find size of switch table"<<endl; + cout<<"pic64: found I1 ('"<<d1->getDisassembly()<<"'), but could not find size of switch table"<<endl; table_size=std::numeric_limits<int>::max(); } } @@ -1976,8 +1971,8 @@ Note: Here the operands of the add are reversed, so lookup code was not finding table_size=std::numeric_limits<int>::max(); } - set<Instruction_t *> ibtargets; - virtual_offset_t offset=D1-pSec->get_address(); + auto ibtargets=InstructionSet_t(); + auto offset=D1-pSec->get_address(); auto entry=0U; auto found_table_error = false; do @@ -1990,7 +1985,7 @@ Note: Here the operands of the add are reversed, so lookup code was not finding } const int *table_entry_ptr=(const int*)&(secdata[offset]); - virtual_offset_t table_entry=*table_entry_ptr; + VirtualOffset_t table_entry=*table_entry_ptr; if(!possible_target(D1+table_entry, 0/* from addr unknown */,prov)) { @@ -2000,13 +1995,13 @@ Note: Here the operands of the add are reversed, so lookup code was not finding if(getenv("IB_VERBOSE")) { - cout<<"Found possible table entry, at: "<< std::hex << I8->GetAddress()->GetVirtualOffset() - << " insn: " << disasm.getDisassembly()/*CompleteInstr*/<< " d1: " + cout<<"Found possible table entry, at: "<< std::hex << I8->getAddress()->getVirtualOffset() + << " insn: " << d5.getDisassembly()<< " d1: " << D1 << " table_entry:" << table_entry << " target: "<< D1+table_entry << std::dec << endl; } - Instruction_t *ibtarget = lookupInstruction(firp, D1+table_entry); + auto ibtarget = lookupInstruction(firp, D1+table_entry); if (ibtarget && ibtargets.size() <= table_size) { if(getenv("IB_VERBOSE")) @@ -2030,18 +2025,18 @@ Note: Here the operands of the add are reversed, so lookup code was not finding // table size = 8, #entries: 9 b/c of default cout << "pic64: detected table size (max_int means no found): 0x"<< hex << table_size << " #entries: 0x" << entry << " ibtargets.size: " << ibtargets.size() << endl; - jmptables[I8].AddTargets(ibtargets); + jmptables[I8].addTargets(ibtargets); // note that there may be an off-by-one error here as table size depends on whether instruction I2 is a jb or jbe. if (!found_table_error) { - cout << "pic64: valid switch table for "<<hex<<I8->GetAddress()->GetVirtualOffset() + cout << "pic64: valid switch table for "<<hex<<I8->getAddress()->getVirtualOffset() <<"detected ibtp_switchtable_type4" << endl; - jmptables[I8].SetAnalysisStatus(ICFS_Analysis_Complete); + jmptables[I8].setAnalysisStatus(iasAnalysisComplete); } else { cout << "pic64: INVALID switch table detected for, " - <<hex<<I8->GetAddress()->GetVirtualOffset()<<"type=ibtp_switchtable_type4" << endl; + <<hex<<I8->getAddress()->getVirtualOffset()<<"type=ibtp_switchtable_type4" << endl; } } } @@ -2059,7 +2054,7 @@ Note: Here the operands of the add are reversed, so lookup code was not finding nb: handles both 32 and 64 bit */ -void check_for_nonPIC_switch_table_pattern2(FileIR_t* firp, Instruction_t* insn, DecodedInstruction_t disasm, EXEIO::exeio* elfiop) +void check_for_nonPIC_switch_table_pattern2(FileIR_t* firp, Instruction_t* insn, const DecodedInstruction_t& p_disasm, EXEIO::exeio* elfiop) { ibt_provenance_t prov=ibt_provenance_t::ibtp_switchtable_type5; Instruction_t *I1 = nullptr; @@ -2068,27 +2063,23 @@ void check_for_nonPIC_switch_table_pattern2(FileIR_t* firp, Instruction_t* insn, assert(IJ); // check if IJ is a jump - //if(strstr(disasm.Instruction.Mnemonic, "jmp")==nullptr) - if(strstr(disasm.getMnemonic().c_str(), "jmp")==nullptr) + if(strstr(p_disasm.getMnemonic().c_str(), "jmp")==nullptr) return; // look for a memory type - //if(!(disasm.Argument1.ArgType&MEMORY_TYPE)) - if(!(disasm.getOperand(0).isMemory())) + if(!(p_disasm.getOperand(0)->isMemory())) return; // make sure there's a scaling factor - //if (disasm.Argument1.Memory.Scale < 4) - //if (disasm.getOperand(0).getScaleValue() < 4) assumes scale is meaningful here? - if (!disasm.getOperand(0).hasIndexRegister() || disasm.getOperand(0).getScaleValue() < 4) + if (!p_disasm.getOperand(0)->hasIndexRegister() || p_disasm.getOperand(0)->getScaleValue() < 4) return; // extract start of jmp table - virtual_offset_t table_offset = disasm.getAddress(); // disasm.Instruction.AddrValue; + VirtualOffset_t table_offset = p_disasm.getAddress(); // disasm.Instruction.AddrValue; if(table_offset==0) return; - cout<<hex<<"(nonPIC-pattern2): Found switch dispatch at 0x"<<hex<<IJ->GetAddress()->GetVirtualOffset()<< " with table_offset="<<hex<<table_offset<<dec<<endl; + cout<<hex<<"(nonPIC-pattern2): Found switch dispatch at 0x"<<hex<<IJ->getAddress()->getVirtualOffset()<< " with table_offset="<<hex<<table_offset<<dec<<endl; if(!backup_until("cmp", I1, IJ)) { @@ -2098,17 +2089,16 @@ void check_for_nonPIC_switch_table_pattern2(FileIR_t* firp, Instruction_t* insn, // extract size off the comparison // make sure not off by one - //DISASM d1; - //Disassemble(I1,d1); - DecodedInstruction_t d1(I1); - virtual_offset_t table_size = d1.getImmediate()/*d1.Instruction.Immediat*/; + auto d1p=DecodedInstruction_t::factory(I1); + auto &d1=*d1p; + VirtualOffset_t table_size = d1.getImmediate()/*d1.Instruction.Immediat*/; if (table_size <= 0) return; cout<<"(nonPIC-pattern2): size of jmp table: "<< table_size << endl; // find the section with the data table - EXEIO::section *pSec=find_section(table_offset,elfiop); + auto pSec=find_section(table_offset,elfiop); if(!pSec) { return; @@ -2120,10 +2110,10 @@ void check_for_nonPIC_switch_table_pattern2(FileIR_t* firp, Instruction_t* insn, return; // get the base offset into the section - virtual_offset_t offset=table_offset-pSec->get_address(); + auto offset=table_offset-pSec->get_address(); auto i=0U; - set<Instruction_t*> ibtargets; + InstructionSet_t ibtargets; for(i=0;i<table_size;++i) { if((int)(offset+i*arch_ptr_bytes()+sizeof(int)) > (int)pSec->get_size()) @@ -2132,8 +2122,8 @@ void check_for_nonPIC_switch_table_pattern2(FileIR_t* firp, Instruction_t* insn, return; } - const virtual_offset_t *table_entry_ptr=(const virtual_offset_t*)&(secdata[offset+i*arch_ptr_bytes()]); - virtual_offset_t table_entry=*table_entry_ptr; + const VirtualOffset_t *table_entry_ptr=(const VirtualOffset_t*)&(secdata[offset+i*arch_ptr_bytes()]); + VirtualOffset_t table_entry=*table_entry_ptr; possible_target(table_entry,0,prov); Instruction_t *ibtarget = lookupInstruction(firp, table_entry); @@ -2150,8 +2140,8 @@ void check_for_nonPIC_switch_table_pattern2(FileIR_t* firp, Instruction_t* insn, cout << "(non-PIC) valid switch table found - ibtp_switchtable_type5" << endl; - jmptables[IJ].AddTargets(ibtargets); - jmptables[IJ].SetAnalysisStatus(ICFS_Analysis_Complete); + jmptables[IJ].addTargets(ibtargets); + jmptables[IJ].setAnalysisStatus(iasAnalysisComplete); } /* @@ -2167,26 +2157,25 @@ void check_for_nonPIC_switch_table_pattern2(FileIR_t* firp, Instruction_t* insn, nb: handles both 32 and 64 bit */ -void check_for_nonPIC_switch_table(FileIR_t* firp, Instruction_t* insn, DecodedInstruction_t disasm, EXEIO::exeio* elfiop) +void check_for_nonPIC_switch_table(FileIR_t* firp, Instruction_t* insn, const DecodedInstruction_t& p_disasm, EXEIO::exeio* elfiop) { ibt_provenance_t prov=ibt_provenance_t::ibtp_switchtable_type6; Instruction_t *I1 = nullptr; - //Instruction_t *I2 = nullptr; Instruction_t *I4 = nullptr; Instruction_t *IJ = insn; if (!IJ) return; // check if IJ is a jump - if(strstr(disasm.getMnemonic().c_str()/*disasm.Instruction.Mnemonic*/, "jmp")==nullptr) + if(strstr(p_disasm.getMnemonic().c_str()/*disasm.Instruction.Mnemonic*/, "jmp")==nullptr) return; // return if it's a jump to a constant address, these are common - if(disasm.getOperand(0).isConstant() /*disasm.Argument1.ArgType&CONSTANT_TYPE*/) + if(p_disasm.getOperand(0)->isConstant() /*disasm.Argument1.ArgType&CONSTANT_TYPE*/) return; // return if it's a jump to a memory address - if(disasm.getOperand(0).isMemory() /*disasm.Argument1.ArgType&MEMORY_TYPE*/) + if(p_disasm.getOperand(0)->isMemory() /*disasm.Argument1.ArgType&MEMORY_TYPE*/) return; // has to be a jump to a register now @@ -2198,18 +2187,19 @@ void check_for_nonPIC_switch_table(FileIR_t* firp, Instruction_t* insn, DecodedI // extract start of jmp table // DISASM d4; // Disassemble(I4,d4); - DecodedInstruction_t d4(I4); + auto d4p=DecodedInstruction_t::factory(I4); + auto &d4=*d4p; // make sure there's a scaling factor - if (d4.getOperand(1).isMemory() && d4.getOperand(1).getScaleValue() /*d4.Argument2.Memory.Scale*/ < 4) + if (d4.getOperand(1)->isMemory() && d4.getOperand(1)->getScaleValue() < 4) return; - virtual_offset_t table_offset=d4.getAddress(); // d4.Instruction.AddrValue; + VirtualOffset_t table_offset=d4.getAddress(); if(table_offset==0) return; if(getenv("IB_VERBOSE")) - cout<<hex<<"(nonPIC): Found switch dispatch at 0x"<<hex<<I4->GetAddress()->GetVirtualOffset()<< " with table_offset="<<hex<<table_offset<<dec<<endl; + cout<<hex<<"(nonPIC): Found switch dispatch at 0x"<<hex<<I4->getAddress()->getVirtualOffset()<< " with table_offset="<<hex<<table_offset<<dec<<endl; if(!backup_until("cmp", I1, I4)) { @@ -2219,17 +2209,16 @@ void check_for_nonPIC_switch_table(FileIR_t* firp, Instruction_t* insn, DecodedI // extract size off the comparison // make sure not off by one - //DISASM d1; - //Disassemble(I1,d1); - DecodedInstruction_t d1(I1); - virtual_offset_t table_size = d1.getImmediate(); // d1.Instruction.Immediat; + auto d1p=DecodedInstruction_t::factory(I1); + auto &d1=*d1p; + auto table_size = d1.getImmediate(); // d1.Instruction.Immediat; if (table_size <= 0) return; if(getenv("IB_VERBOSE")) cout<<"(nonPIC): size of jmp table: "<< table_size << endl; // find the section with the data table - EXEIO::section *pSec=find_section(table_offset,elfiop); + auto pSec=find_section(table_offset,elfiop); if(!pSec) { cout<<hex<<"(nonPIC): could not find jump table in section"<<endl; @@ -2242,13 +2231,13 @@ void check_for_nonPIC_switch_table(FileIR_t* firp, Instruction_t* insn, DecodedI return; // get the base offset into the section - virtual_offset_t offset=table_offset-pSec->get_address(); + auto offset=table_offset-pSec->get_address(); auto i=0U; if(getenv("IB_VERBOSE")) - cout << hex << "offset: " << offset << " arch bit width: " << dec << firp->GetArchitectureBitWidth() << endl; + cout << hex << "offset: " << offset << " arch bit width: " << dec << firp->getArchitectureBitWidth() << endl; - set<Instruction_t*> ibtargets; + InstructionSet_t ibtargets; for(i=0;i<table_size;++i) { if((int)(offset+i*arch_ptr_bytes()+sizeof(int)) > (int)pSec->get_size()) @@ -2257,22 +2246,22 @@ void check_for_nonPIC_switch_table(FileIR_t* firp, Instruction_t* insn, DecodedI return; } - virtual_offset_t table_entry=0; - if (firp->GetArchitectureBitWidth()==32) + VirtualOffset_t table_entry=0; + if (firp->getArchitectureBitWidth()==32) { const int *table_entry_ptr=(const int*)&(secdata[offset+i*arch_ptr_bytes()]); table_entry=*table_entry_ptr; } - else if (firp->GetArchitectureBitWidth()==64) + else if (firp->getArchitectureBitWidth()==64) { - const virtual_offset_t *table_entry_ptr=(const virtual_offset_t*)&(secdata[offset+i*arch_ptr_bytes()]); + const VirtualOffset_t *table_entry_ptr=(const VirtualOffset_t*)&(secdata[offset+i*arch_ptr_bytes()]); table_entry=*table_entry_ptr; } else assert(0 && "Unknown arch size."); possible_target(table_entry, 0 /* from addr unknown */, prov); - Instruction_t *ibtarget = lookupInstruction(firp, table_entry); + auto ibtarget = lookupInstruction(firp, table_entry); if (!ibtarget) { if(getenv("IB_VERBOSE")) cout << "0x" << hex << table_entry << " is not an instruction, invalid switch table" << endl; @@ -2285,24 +2274,19 @@ void check_for_nonPIC_switch_table(FileIR_t* firp, Instruction_t* insn, DecodedI } cout << "(non-PIC) valid switch table found - prov=ibt_provenance_t::ibtp_switchtable_type6" << endl; - jmptables[IJ].AddTargets(ibtargets); - jmptables[IJ].SetAnalysisStatus(ICFS_Analysis_Complete); + jmptables[IJ].addTargets(ibtargets); + jmptables[IJ].setAnalysisStatus(iasAnalysisComplete); } void calc_preds(FileIR_t* firp) { preds.clear(); - for( - set<Instruction_t*>::const_iterator it=firp->GetInstructions().begin(); - it!=firp->GetInstructions().end(); - ++it - ) + for(auto insn : firp->getInstructions()) { - Instruction_t* insn=*it; - if(insn->GetTarget()) - preds[insn->GetTarget()].insert(insn); - if(insn->GetFallthrough()) - preds[insn->GetFallthrough()].insert(insn); + if(insn->getTarget()) + preds[insn->getTarget()].insert(insn); + if(insn->getFallthrough()) + preds[insn->getFallthrough()].insert(insn); } } @@ -2312,11 +2296,11 @@ void handle_takes_address_annot(FileIR_t* firp,Instruction_t* insn, MEDS_TakesAd if(p_takes_address_annotation->isCode()) { const auto refd_addr=referenced_addr; - possible_target(refd_addr,insn->GetAddress()->GetVirtualOffset(), ibt_provenance_t::ibtp_text); + possible_target(refd_addr,insn->getAddress()->getVirtualOffset(), ibt_provenance_t::ibtp_text); } else { - all_add_adrp_results[insn->GetFunction()].insert(referenced_addr); + all_add_adrp_results[insn->getFunction()].insert(referenced_addr); } } @@ -2324,7 +2308,7 @@ void handle_ib_annot(FileIR_t* firp,Instruction_t* insn, MEDS_IBAnnotation* p_ib { if(p_ib_annotation->IsComplete()) { - jmptables[insn].SetAnalysisStatus(ICFS_Analysis_Complete); + jmptables[insn].setAnalysisStatus(iasAnalysisComplete); } } void handle_ibt_annot(FileIR_t* firp,Instruction_t* insn, MEDS_IBTAnnotation* p_ibt_annotation) @@ -2341,21 +2325,21 @@ void handle_ibt_annot(FileIR_t* firp,Instruction_t* insn, MEDS_IBTAnnotation* p_ /* meds annotations * typedef enum { SWITCH, RET, DATA, UNREACHABLE, ADDRESSED, UNKNOWN } ibt_reason_code_t; */ - //cout<<"at handl_ibt with addr="<<hex<<insn->GetAddress()->GetVirtualOffset()<<" code="<<p_ibt_annotation->GetReason()<<endl; + //cout<<"at handl_ibt with addr="<<hex<<insn->getAddress()->getVirtualOffset()<<" code="<<p_ibt_annotation->GetReason()<<endl; switch(p_ibt_annotation->GetReason()) { case MEDS_IBTAnnotation::SWITCH: case MEDS_IBTAnnotation::INDIRCALL: { - possible_target((EXEIO::virtual_offset_t)p_ibt_annotation->getVirtualOffset().getOffset(), + possible_target((VirtualOffset_t)p_ibt_annotation->getVirtualOffset().getOffset(), 0,ibt_provenance_t::ibtp_stars_switch); - libIRDB::virtual_offset_t addr=(libIRDB::virtual_offset_t)p_ibt_annotation->GetXrefAddr(); - Instruction_t* fromib=lookupInstruction(firp, addr); - Instruction_t* ibt=lookupInstruction(firp, p_ibt_annotation->getVirtualOffset().getOffset()); + auto addr=(VirtualOffset_t)p_ibt_annotation->GetXrefAddr(); + auto fromib=lookupInstruction(firp, addr); + auto ibt=lookupInstruction(firp, p_ibt_annotation->getVirtualOffset().getOffset()); if(fromib && ibt) { if(getenv("IB_VERBOSE")!=nullptr) - cout<<hex<<"Adding call/switch icfs: "<<fromib->GetAddress()->GetVirtualOffset()<<"->"<<ibt->GetAddress()->GetVirtualOffset()<<endl; + cout<<hex<<"Adding call/switch icfs: "<<fromib->getAddress()->getVirtualOffset()<<"->"<<ibt->getAddress()->getVirtualOffset()<<endl; jmptables[fromib].insert(ibt); } else @@ -2367,18 +2351,18 @@ void handle_ibt_annot(FileIR_t* firp,Instruction_t* insn, MEDS_IBTAnnotation* p_ case MEDS_IBTAnnotation::RET: { /* we are not going to mark return points as IBTs yet. that's fix-calls job */ - // possible_target((EXEIO::virtual_offset_t)p_ibt_annotation->getVirtualOffset().getOffset(), + // possible_target((VirtualOffset_t)p_ibt_annotation->getVirtualOffset().getOffset(), // 0,ibt_provenance_t::ibtp_stars_ret); - libIRDB::virtual_offset_t fromaddr=(libIRDB::virtual_offset_t)p_ibt_annotation->GetXrefAddr(); - Instruction_t* fromib=lookupInstruction(firp, fromaddr); - libIRDB::virtual_offset_t toaddr=p_ibt_annotation->getVirtualOffset().getOffset(); - Instruction_t* ibt=lookupInstruction(firp, toaddr); + auto fromaddr=(VirtualOffset_t)p_ibt_annotation->GetXrefAddr(); + auto fromib=lookupInstruction(firp, fromaddr); + auto toaddr=p_ibt_annotation->getVirtualOffset().getOffset(); + auto ibt=lookupInstruction(firp, toaddr); if(fromib && ibt) { if(getenv("IB_VERBOSE")!=nullptr) - cout<<hex<<"Adding ret icfs: "<<fromib->GetAddress()->GetVirtualOffset()<<"->"<<ibt->GetAddress()->GetVirtualOffset()<<endl; + cout<<hex<<"Adding ret icfs: "<<fromib->getAddress()->getVirtualOffset()<<"->"<<ibt->getAddress()->getVirtualOffset()<<endl; jmptables[fromib].insert(ibt); } else @@ -2389,7 +2373,7 @@ void handle_ibt_annot(FileIR_t* firp,Instruction_t* insn, MEDS_IBTAnnotation* p_ } case MEDS_IBTAnnotation::DATA: { - possible_target((EXEIO::virtual_offset_t)p_ibt_annotation->getVirtualOffset().getOffset(), + possible_target((VirtualOffset_t)p_ibt_annotation->getVirtualOffset().getOffset(), 0,ibt_provenance_t::ibtp_stars_data); if(getenv("IB_VERBOSE")!=nullptr) cout<<hex<<"detected stars data ibt at"<<p_ibt_annotation->getVirtualOffset().getOffset()<<endl; @@ -2397,7 +2381,7 @@ void handle_ibt_annot(FileIR_t* firp,Instruction_t* insn, MEDS_IBTAnnotation* p_ } case MEDS_IBTAnnotation::UNREACHABLE: { - possible_target((EXEIO::virtual_offset_t)p_ibt_annotation->getVirtualOffset().getOffset(), + possible_target((VirtualOffset_t)p_ibt_annotation->getVirtualOffset().getOffset(), 0,ibt_provenance_t::ibtp_stars_unreachable); if(getenv("IB_VERBOSE")!=nullptr) cout<<hex<<"detected stars unreachable ibt at"<<p_ibt_annotation->getVirtualOffset().getOffset()<<endl; @@ -2405,7 +2389,7 @@ void handle_ibt_annot(FileIR_t* firp,Instruction_t* insn, MEDS_IBTAnnotation* p_ } case MEDS_IBTAnnotation::ADDRESSED: { - possible_target((EXEIO::virtual_offset_t)p_ibt_annotation->getVirtualOffset().getOffset(), + possible_target((VirtualOffset_t)p_ibt_annotation->getVirtualOffset().getOffset(), 0,ibt_provenance_t::ibtp_stars_addressed); if(getenv("IB_VERBOSE")!=nullptr) cout<<hex<<"detected stars addresssed ibt at"<<p_ibt_annotation->getVirtualOffset().getOffset()<<endl; @@ -2413,7 +2397,7 @@ void handle_ibt_annot(FileIR_t* firp,Instruction_t* insn, MEDS_IBTAnnotation* p_ } case MEDS_IBTAnnotation::UNKNOWN: { - possible_target((EXEIO::virtual_offset_t)p_ibt_annotation->getVirtualOffset().getOffset(), + possible_target((VirtualOffset_t)p_ibt_annotation->getVirtualOffset().getOffset(), 0,ibt_provenance_t::ibtp_stars_unknown); if(getenv("IB_VERBOSE")!=nullptr) cout<<hex<<"detected stars unknown ibt at"<<p_ibt_annotation->getVirtualOffset().getOffset()<<endl; @@ -2434,7 +2418,7 @@ void read_stars_xref_file(FileIR_t* firp) const auto BINARY_NAME=string("a.ncexe"); const auto SHARED_OBJECTS_DIR=string("shared_objects"); - const auto fileBasename = string(basename((char*)firp->GetFile()->GetURL().c_str())); + const auto fileBasename = string(basename((char*)firp->getFile()->getURL().c_str())); auto annotationParser=MEDS_AnnotationParser(); // need to map filename to integer annotation file produced by STARS @@ -2453,10 +2437,10 @@ void read_stars_xref_file(FileIR_t* firp) cout<<"Warning: annotation parser reports error: "<<s<<endl; } - for(auto insn : firp->GetInstructions()) + for(auto insn : firp->getInstructions()) { - const auto irdb_vo = insn->GetAddress()->GetVirtualOffset(); - const auto vo=VirtualOffset(irdb_vo); + const auto irdb_vo = insn->getAddress()->getVirtualOffset(); + const auto vo=VirtualOffset_t(irdb_vo); /* find it in the annotations */ const auto ret = annotationParser.getAnnotations().equal_range(vo); @@ -2489,18 +2473,18 @@ void process_dynsym(FileIR_t* firp) auto target=(unsigned int)0; while( fscanf(dynsymfile, "%x", &target) != -1) { - possible_target((virtual_offset_t)target,0,ibt_provenance_t::ibtp_dynsym); + possible_target((VirtualOffset_t)target,0,ibt_provenance_t::ibtp_dynsym); } } ICFS_t* setup_hellnode(FileIR_t* firp, EXEIO::exeio* elfiop, ibt_provenance_t allowed) { - auto hn=new ICFS_t(ICFS_Analysis_Module_Complete); + auto hn=firp->addNewICFS(nullptr, {}, iasAnalysisModuleComplete); - for(auto insn: firp->GetInstructions()) + for(auto insn: firp->getInstructions()) { - auto prov=targets[insn->GetAddress()->GetVirtualOffset()]; + auto prov=targets[insn->getAddress()->getVirtualOffset()]; if(prov.isEmpty()) continue; @@ -2512,7 +2496,7 @@ ICFS_t* setup_hellnode(FileIR_t* firp, EXEIO::exeio* elfiop, ibt_provenance_t al } if(hn->size() < 1000 && !elfiop->isDynamicallyLinked()) - hn->SetAnalysisStatus(ICFS_Analysis_Complete); + hn->setAnalysisStatus(iasAnalysisComplete); return hn; } @@ -2556,7 +2540,7 @@ ICFS_t* setup_call_hellnode(FileIR_t* firp, EXEIO::exeio* elfiop) * ibt_provenance_t::ibtp_switchtable_type10 */ - ICFS_t* ret=setup_hellnode(firp,elfiop,allowed); + auto ret=setup_hellnode(firp,elfiop,allowed); cout<<"# ATTRIBUTE fill_in_indtargs::call_hellnode_size="<<dec<<ret->size()<<endl; return ret; @@ -2600,7 +2584,7 @@ ICFS_t* setup_jmp_hellnode(FileIR_t* firp, EXEIO::exeio* elfiop) * ibt_provenance_t::ibtp_switchtable_type10 */ - ICFS_t* ret=setup_hellnode(firp,elfiop,allowed); + auto ret=setup_hellnode(firp,elfiop,allowed); cout<<"# ATTRIBUTE fill_in_indtargs::jmp_hellnode_size="<<dec<<ret->size()<<endl; return ret; @@ -2649,7 +2633,7 @@ ICFS_t* setup_ret_hellnode(FileIR_t* firp, EXEIO::exeio* elfiop) * ibt_provenance_t::ibtp_gotplt */ - ICFS_t* ret_hell_node=setup_hellnode(firp,elfiop,allowed); + auto ret_hell_node=setup_hellnode(firp,elfiop,allowed); cout<<"# ATTRIBUTE fill_in_indtargs::basicret_hellnode_size="<<dec<<ret_hell_node->size()<<endl; cout<<"# ATTRIBUTE fill_in_indtargs::fullret_hellnode_size="<<dec<<ret_hell_node->size()<<endl; @@ -2661,19 +2645,12 @@ void mark_return_points(FileIR_t* firp) { // add unmarked return points. fix_calls will deal with whether they need to be pinned or not later. - for( - InstructionSet_t::const_iterator it=firp->GetInstructions().begin(); - it!=firp->GetInstructions().end(); - ++it - ) + for(auto insn : firp->getInstructions()) { - Instruction_t* insn=*it; - //DISASM d; - //Disassemble(insn,d); - DecodedInstruction_t d(insn); - if(string("call")==d.getMnemonic() /*.Instruction.Mnemonic*/ && insn->GetFallthrough()) + auto d=DecodedInstruction_t::factory(insn); + if(string("call")==d->getMnemonic() && insn->getFallthrough()) { - targets[insn->GetFallthrough()->GetAddress()->GetVirtualOffset()].add(ibt_provenance_t::ibtp_ret); + targets[insn->getFallthrough()->getAddress()->getVirtualOffset()].add(ibt_provenance_t::ibtp_ret); } } } @@ -2682,25 +2659,19 @@ void mark_return_points(FileIR_t* firp) void print_icfs(FileIR_t* firp) { cout<<"Printing ICFS sets."<<endl; - for( - InstructionSet_t::const_iterator it=firp->GetInstructions().begin(); - it!=firp->GetInstructions().end(); - ++it - ) + for(auto insn : firp->getInstructions()) { - Instruction_t* insn=*it; - ICFS_t *icfs=insn->GetIBTargets(); + auto icfs=insn->getIBTargets(); // not an IB if(!icfs) continue; - cout<<hex<<insn->GetAddress()->GetVirtualOffset()<<" -> "; + cout<<hex<<insn->getAddress()->getVirtualOffset()<<" -> "; - for(ICFS_t::const_iterator icfsit=icfs->begin(); icfsit!=icfs->end(); ++icfsit) + for(auto target : *icfs) { - Instruction_t* target=*icfsit; - cout<<hex<<target->GetAddress()->GetVirtualOffset()<<" "; + cout<<hex<<target->getAddress()->getVirtualOffset()<<" "; } cout<<endl; } @@ -2728,51 +2699,44 @@ void setup_icfs(FileIR_t* firp, EXEIO::exeio* elfiop) // setup calls, jmps and ret hell nodes. - ICFS_t *call_hell = setup_call_hellnode(firp,elfiop); - firp->GetAllICFS().insert(call_hell); - - ICFS_t *jmp_hell = setup_jmp_hellnode(firp,elfiop); - firp->GetAllICFS().insert(jmp_hell); - - ICFS_t *ret_hell = setup_ret_hellnode(firp,elfiop); - firp->GetAllICFS().insert(ret_hell); - + auto call_hell = setup_call_hellnode(firp,elfiop); + auto jmp_hell = setup_jmp_hellnode(firp,elfiop); + auto ret_hell = setup_ret_hellnode(firp,elfiop); // for each instruction - for( - set<Instruction_t*>::const_iterator it=firp->GetInstructions().begin(); - it!=firp->GetInstructions().end(); - ++it - ) + for(auto insn : firp->getInstructions()) { // if we already got it complete (via stars or FII) - Instruction_t* insn=*it; - - if(insn->GetIndirectBranchTargetAddress()!=nullptr) + if(insn->getIndirectBranchTargetAddress()!=nullptr) total_ibta_set++; // warning check - ibt_provenance_t prov=targets[insn->GetAddress()->GetVirtualOffset()]; + ibt_provenance_t prov=targets[insn->getAddress()->getVirtualOffset()]; // stars calls it data, but printw arning if we didn't find it in data or as a printf addr. if(prov.isPartiallySet(stars_data) && !prov.isPartiallySet(non_stars_data)) { //ofstream fout("warning.txt", ofstream::out | ofstream::app); - cerr<<"STARS found an IBT in data that FII wasn't able to classify at "<<hex<<insn->GetAddress()->GetVirtualOffset()<<"."<<endl; + cerr<<"STARS found an IBT in data that FII wasn't able to classify at "<<hex<<insn->getAddress()->getVirtualOffset()<<"."<<endl; } // create icfs for complete jump tables. - if(jmptables[insn].IsComplete()) + if(jmptables[insn].isComplete()) { + // get the strcuture into the IRDB - ICFS_t* nn=new ICFS_t(jmptables[insn]); + /* + auto nn=new ICFS_t(jmptables[insn]); firp->GetAllICFS().insert(nn); insn->SetIBTargets(nn); + */ + auto nn=firp->addNewICFS(insn,jmptables[insn]); + if(getenv("IB_VERBOSE")!=0) { - cout<<"IB complete for "<<hex<<insn->GetAddress()->GetVirtualOffset() + cout<<"IB complete for "<<hex<<insn->getAddress()->getVirtualOffset() <<":"<<insn->getDisassembly()<<" with "<<dec<<nn->size()<<" targets."<<endl; } @@ -2781,32 +2745,28 @@ void setup_icfs(FileIR_t* firp, EXEIO::exeio* elfiop) } // disassemble the instruction, and figure out which type of hell node we need. - //DISASM d; - //Disassemble(insn,d); - DecodedInstruction_t d(insn); - if(d.isReturn()) // string("ret")==d.getMnemonic() /*Instruction.Mnemonic*/ || string("retn")==d.getMnemonic() /*d.Instruction.Mnemonic*/) + auto d=DecodedInstruction_t::factory(insn); + if(d->isReturn()) { if(getenv("IB_VERBOSE")!=0) - cout<<"using ret hell node for "<<hex<<insn->GetAddress()->GetVirtualOffset()<<endl; - insn->SetIBTargets(ret_hell); + cout<<"using ret hell node for "<<hex<<insn->getAddress()->getVirtualOffset()<<endl; + insn->setIBTargets(ret_hell); ret_hell->insert(ALLOF(jmptables[insn])); // insert any partially analyzed results from rets. } - //else if ( (string("call ")==d.Instruction.Mnemonic) && ((d.Argument1.ArgType&0xffff0000&CONSTANT_TYPE)!=CONSTANT_TYPE)) - else if ( d.isCall() /* (string("call")==d.getMnemonic()) */ && (!d.getOperand(0).isConstant())) + else if ( d->isCall() && (!d->getOperand(0)->isConstant())) { if(getenv("IB_VERBOSE")!=0) - cout<<"using call hell node for "<<hex<<insn->GetAddress()->GetVirtualOffset()<<endl; + cout<<"using call hell node for "<<hex<<insn->getAddress()->getVirtualOffset()<<endl; // indirect call - insn->SetIBTargets(call_hell); + insn->setIBTargets(call_hell); call_hell->insert(ALLOF(jmptables[insn])); // insert any partially analyzed results from calls. } - //else if ( (string("jmp ")==d.Instruction.Mnemonic) && ((d.Argument1.ArgType&0xffff0000&CONSTANT_TYPE)!=CONSTANT_TYPE)) - else if ( d.isUnconditionalBranch() /*(string("jmp")==d.getMnemonic()) */&& (!d.getOperand(0).isConstant())) + else if ( d->isUnconditionalBranch() && (!d->getOperand(0)->isConstant())) { if(getenv("IB_VERBOSE")!=0) - cout<<"using jmp hell node for "<<hex<<insn->GetAddress()->GetVirtualOffset()<<endl; + cout<<"using jmp hell node for "<<hex<<insn->getAddress()->getVirtualOffset()<<endl; // indirect jmp - insn->SetIBTargets(jmp_hell); + insn->setIBTargets(jmp_hell); jmp_hell->insert(ALLOF(jmptables[insn])); // insert any partially analyzed results from jmps. } @@ -2824,35 +2784,35 @@ void unpin_elf_tables(FileIR_t *firp, int64_t do_unpin_opt) map<string,int> unpin_counts; map<string,int> missed_unpins; - for(auto scoop : firp->GetDataScoops()) + for(auto scoop : firp->getDataScoops()) { // 4 or 8 - const auto ptrsize=firp->GetArchitectureBitWidth()/8; - const char *scoop_contents=scoop->GetContents().c_str(); - if(scoop->GetName()==".init_array" || scoop->GetName()==".fini_array" || scoop->GetName()==".got.plt" || scoop->GetName()==".got") + const auto ptrsize=firp->getArchitectureBitWidth()/8; + const char *scoop_contents=scoop->getContents().c_str(); + if(scoop->getName()==".init_array" || scoop->getName()==".fini_array" || scoop->getName()==".got.plt" || scoop->getName()==".got") { - const auto start_offset= (scoop->GetName()==".got.plt") ? 3*ptrsize : 0u; - for(auto i=start_offset; i+ptrsize <= scoop->GetSize() ; i+=ptrsize) + const auto start_offset= (scoop->getName()==".got.plt") ? 3*ptrsize : 0u; + for(auto i=start_offset; i+ptrsize <= scoop->getSize() ; i+=ptrsize) { const auto vo= - ptrsize==4 ? (virtual_offset_t)*(uint32_t*)&scoop_contents[i] : - ptrsize==8 ? (virtual_offset_t)*(uint64_t*)&scoop_contents[i] : + ptrsize==4 ? (VirtualOffset_t)*(uint32_t*)&scoop_contents[i] : + ptrsize==8 ? (VirtualOffset_t)*(uint64_t*)&scoop_contents[i] : throw domain_error("Invalid ptr size"); auto insn=lookupInstruction(firp,vo); // OK for .got scoop to miss, some entries are empty. - if(scoop->GetName()==".got" && insn==nullptr) + if(scoop->getName()==".got" && insn==nullptr) { if(getenv("UNPIN_VERBOSE")!=0) - cout<<"Skipping "<<scoop->GetName()<<" unpin for "<<hex<<vo<<" due to no instruction at vo"<<endl; + cout<<"Skipping "<<scoop->getName()<<" unpin for "<<hex<<vo<<" due to no instruction at vo"<<endl; continue; } if(vo==0) { // some segments may be null terminated. - assert(i+ptrsize==scoop->GetSize()); + assert(i+ptrsize==scoop->getSize()); break; } @@ -2863,8 +2823,8 @@ void unpin_elf_tables(FileIR_t *firp, int64_t do_unpin_opt) if( targets[vo].areOnlyTheseSet( ibt_provenance_t::ibtp_initarray | ibt_provenance_t::ibtp_finiarray | - ibt_provenance_t::ibtp_gotplt | - ibt_provenance_t::ibtp_got | + ibt_provenance_t::ibtp_gotplt | + ibt_provenance_t::ibtp_got | ibt_provenance_t::ibtp_stars_data) ) { @@ -2895,54 +2855,60 @@ void unpin_elf_tables(FileIR_t *firp, int64_t do_unpin_opt) { // mark as unpinned already_unpinned.insert(insn); - unpin_counts[scoop->GetName()]++; + unpin_counts[scoop->getName()]++; // add reloc to IR. - Relocation_t* nr=new Relocation_t(BaseObj_t::NOT_IN_DATABASE, i, "data_to_insn_ptr", insn); + auto nr=firp->addNewRelocation(scoop, i, "data_to_insn_ptr", insn); assert(nr); - firp->GetRelocations().insert(nr); - scoop->GetRelocations().insert(nr); + /* + Relocation_t* nr=new Relocation_t(BaseObj_t::NOT_IN_DATABASE, i, "data_to_insn_ptr", insn); + firp->getRelocations().insert(nr); + scoop->getRelocations().insert(nr); + */ if(getenv("UNPIN_VERBOSE")!=0) - cout<<"Unpinning "+scoop->GetName()+" entry at offset "<<dec<<i<<endl; - if(insn->GetIndirectBranchTargetAddress()==nullptr) + cout<<"Unpinning "+scoop->getName()+" entry at offset "<<dec<<i<<endl; + if(insn->getIndirectBranchTargetAddress()==nullptr) { // add ibta to mark as unpipnned - const auto fileid=insn->GetAddress()->GetFileID(); + const auto fileid=insn->getAddress()->getFileID(); + /* auto newaddr = new AddressID_t(BaseObj_t::NOT_IN_DATABASE,fileid,0); assert(newaddr); - firp->GetAddresses().insert(newaddr); - insn->SetIndirectBranchTargetAddress(newaddr); + firp->getAddresses().insert(newaddr); + */ + auto newaddr=firp->addNewAddress(fileid,0); + insn->setIndirectBranchTargetAddress(newaddr); } else { // just mark as unpinned. - insn->GetIndirectBranchTargetAddress()->SetVirtualOffset(0); + insn->getIndirectBranchTargetAddress()->setVirtualOffset(0); } } } else { if(getenv("UNPIN_VERBOSE")!=0) - cout<<"Skipping "<<scoop->GetName()<<" unpin for "<<hex<<vo<<" due to other references at offset="<<dec<<i<<endl; - missed_unpins[scoop->GetName()]++; + cout<<"Skipping "<<scoop->getName()<<" unpin for "<<hex<<vo<<" due to other references at offset="<<dec<<i<<endl; + missed_unpins[scoop->getName()]++; } } } - else if(scoop->GetName()==".dynsym") + else if(scoop->getName()==".dynsym") { - const auto ptrsize=firp->GetArchitectureBitWidth()/8; - const auto scoop_contents=scoop->GetContents().c_str(); + const auto ptrsize=firp->getArchitectureBitWidth()/8; + const auto scoop_contents=scoop->getContents().c_str(); const auto symsize= ptrsize==8 ? sizeof(Elf64_Sym) : ptrsize==4 ? sizeof(Elf32_Sym) : throw domain_error("Cannot detect ptr size -> ELF symbol mapping"); auto table_entry_no=0U; - for(auto i=0U;i+symsize<scoop->GetSize(); i+=symsize, table_entry_no++) + for(auto i=0U;i+symsize<scoop->getSize(); i+=symsize, table_entry_no++) { int addr_offset=0; - virtual_offset_t vo=0; + VirtualOffset_t vo=0; int st_info_field=0; int shndx=0; switch(ptrsize) @@ -3002,34 +2968,41 @@ void unpin_elf_tables(FileIR_t *firp, int64_t do_unpin_opt) // when/if these asserts fail, convert to if and guard the reloc creation. - unpin_counts[scoop->GetName()]++; + unpin_counts[scoop->getName()]++; + /* auto nr=new Relocation_t(BaseObj_t::NOT_IN_DATABASE, i+addr_offset, "data_to_insn_ptr", insn); assert(nr); // add reloc to IR. - firp->GetRelocations().insert(nr); - scoop->GetRelocations().insert(nr); + firp->getRelocations().insert(nr); + scoop->getRelocations().insert(nr); + */ + auto nr=firp->addNewRelocation(scoop, i+addr_offset, "data_to_insn_ptr", insn); + (void)nr; - if(insn->GetIndirectBranchTargetAddress()==nullptr) + if(insn->getIndirectBranchTargetAddress()==nullptr) { + /* auto newaddr = new AddressID_t; assert(newaddr); - newaddr->SetFileID(insn->GetAddress()->GetFileID()); - newaddr->SetVirtualOffset(0); // unpinne + newaddr->SetFileID(insn->getAddress()->getFileID()); + newaddr->setVirtualOffset(0); // unpinne - firp->GetAddresses().insert(newaddr); - insn->SetIndirectBranchTargetAddress(newaddr); + firp->getAddresses().insert(newaddr); + */ + auto newaddr=firp->addNewAddress(insn->getAddress()->getFileID(),0); + insn->setIndirectBranchTargetAddress(newaddr); } else { - insn->GetIndirectBranchTargetAddress()->SetVirtualOffset(0); + insn->getIndirectBranchTargetAddress()->setVirtualOffset(0); } } else { if(getenv("UNPIN_VERBOSE")!=0) cout<<"Skipping .dynsm unpin for "<<hex<<vo<<" due to other references."<<dec<<i<<endl; - missed_unpins[scoop->GetName()]++; + missed_unpins[scoop->getName()]++; } } } @@ -3037,7 +3010,7 @@ void unpin_elf_tables(FileIR_t *firp, int64_t do_unpin_opt) else { if(getenv("UNPIN_VERBOSE")!=0) - cout<<"Skipping unpin of section "<<scoop->GetName()<<endl; + cout<<"Skipping unpin of section "<<scoop->getName()<<endl; } } @@ -3062,11 +3035,11 @@ void unpin_elf_tables(FileIR_t *firp, int64_t do_unpin_opt) } -DataScoop_t* find_scoop(FileIR_t *firp, const virtual_offset_t &vo) +DataScoop_t* find_scoop(FileIR_t *firp, const VirtualOffset_t &vo) { - for(auto s : firp->GetDataScoops()) + for(auto s : firp->getDataScoops()) { - if( s->GetStart()->GetVirtualOffset()<=vo && vo<s->GetEnd()->GetVirtualOffset() ) + if( s->getStart()->getVirtualOffset()<=vo && vo<s->getEnd()->getVirtualOffset() ) return s; } return nullptr; @@ -3085,7 +3058,7 @@ void unpin_type3_switchtable(FileIR_t* firp,Instruction_t* insn,DataScoop_t* sco if(getenv("UNPIN_VERBOSE")) { - cout<<"Unpinning type3 switch, dispatch is "<<hex<<insn->GetAddress()->GetVirtualOffset()<<":" + cout<<"Unpinning type3 switch, dispatch is "<<hex<<insn->getAddress()->getVirtualOffset()<<":" <<insn->getDisassembly()<<" with tabSz="<<jmptables[insn].GetTableSize()<<endl; } @@ -3101,27 +3074,27 @@ void unpin_type3_switchtable(FileIR_t* firp,Instruction_t* insn,DataScoop_t* sco ibt_provenance_t::ibtp_stars_switch ; // found as stars switch // ptr size - int ptrsize=firp->GetArchitectureBitWidth()/8; + int ptrsize=firp->getArchitectureBitWidth()/8; // offset from start of scoop - virtual_offset_t scoop_off=jmptables[insn].GetTableStart() - scoop->GetStart()->GetVirtualOffset(); + VirtualOffset_t scoop_off=jmptables[insn].GetTableStart() - scoop->getStart()->getVirtualOffset(); // scoop contents - const char *scoop_contents=scoop->GetContents().c_str(); + const char *scoop_contents=scoop->getContents().c_str(); for(int i=0; i<jmptables[insn].GetTableSize(); i++) { // grab the value out of the scoop - virtual_offset_t table_entry=0; + VirtualOffset_t table_entry=0; switch(ptrsize) { case 4: - table_entry=(virtual_offset_t)*(int*)&scoop_contents[scoop_off]; + table_entry=(VirtualOffset_t)*(int*)&scoop_contents[scoop_off]; break; case 8: - table_entry=(virtual_offset_t)*(int**)&scoop_contents[scoop_off]; + table_entry=(VirtualOffset_t)*(int**)&scoop_contents[scoop_off]; break; default: assert(0); @@ -3160,28 +3133,36 @@ void unpin_type3_switchtable(FileIR_t* firp,Instruction_t* insn,DataScoop_t* sco already_unpinned.insert(ibt); // add reloc to IR. + /* auto nr=new Relocation_t(BaseObj_t::NOT_IN_DATABASE, scoop_off, "data_to_insn_ptr", ibt); assert(nr); - firp->GetRelocations().insert(nr); - scoop->GetRelocations().insert(nr); + firp->getRelocations().insert(nr); + scoop->getRelocations().insert(nr); + */ + auto nr=firp->addNewRelocation(scoop,scoop_off, "data_to_insn_ptr", ibt); + (void)nr; + // remove rodata reference for hell nodes. targets[table_entry]=newprov; switch_targs.insert(ibt); - if(ibt->GetIndirectBranchTargetAddress()==nullptr) + if(ibt->getIndirectBranchTargetAddress()==nullptr) { + /* auto newaddr = new AddressID_t; assert(newaddr); - newaddr->SetFileID(ibt->GetAddress()->GetFileID()); - newaddr->SetVirtualOffset(0); // unpinne + newaddr->SetFileID(ibt->getAddress()->getFileID()); + newaddr->setVirtualOffset(0); // unpinne - firp->GetAddresses().insert(newaddr); - ibt->SetIndirectBranchTargetAddress(newaddr); + firp->getAddresses().insert(newaddr); + */ + auto newaddr=firp->addNewAddress(ibt->getAddress()->getFileID(),0); + ibt->setIndirectBranchTargetAddress(newaddr); } else { - ibt->GetIndirectBranchTargetAddress()->SetVirtualOffset(0); + ibt->getIndirectBranchTargetAddress()->setVirtualOffset(0); } } } @@ -3204,8 +3185,8 @@ void unpin_switches(FileIR_t *firp, int do_unpin_opt) // for each instruction for( - set<Instruction_t*>::const_iterator it=firp->GetInstructions().begin(); - it!=firp->GetInstructions().end(); + set<Instruction_t*>::const_iterator it=firp->getInstructions().begin(); + it!=firp->getInstructions().end(); ++it ) @@ -3219,10 +3200,10 @@ void unpin_switches(FileIR_t *firp, int do_unpin_opt) continue; // sanity check we have a good switch - if(insn->GetIBTargets()==nullptr) continue; + if(insn->getIBTargets()==nullptr) continue; // sanity check we have a good switch - if(insn->GetIBTargets()->GetAnalysisStatus()!=ICFS_Analysis_Complete) continue; + if(insn->getIBTargets()->getAnalysisStatus()!=iasAnalysisComplete) continue; // find the scoop, try next if we fail. DataScoop_t* scoop=find_scoop(firp,jmptables[insn].GetTableStart()); @@ -3243,13 +3224,13 @@ void print_unpins(FileIR_t *firp) if(getenv("UNPIN_VERBOSE") == nullptr) return; - for(auto scoop : firp->GetDataScoops()) + for(auto scoop : firp->getDataScoops()) { assert(scoop); - for(auto reloc : scoop->GetRelocations()) + for(auto reloc : scoop->getRelocations()) { assert(reloc); - cout<<"Found relocation in "<<scoop->GetName()<<" of type "<<reloc->GetType()<<" at offset "<<hex<<reloc->GetOffset()<<endl; + cout<<"Found relocation in "<<scoop->getName()<<" of type "<<reloc->getType()<<" at offset "<<hex<<reloc->getOffset()<<endl; } } } @@ -3262,7 +3243,7 @@ void unpin_well_analyzed_ibts(FileIR_t *firp, int64_t do_unpin_opt) print_unpins(firp); } -bool find_arm_address_gen(Instruction_t* insn, const string& reg, virtual_offset_t& address, bool& page_only) +bool find_arm_address_gen(Instruction_t* insn, const string& reg, VirtualOffset_t& address, bool& page_only) { // init output args, just in case. address=0; @@ -3276,11 +3257,11 @@ bool find_arm_address_gen(Instruction_t* insn, const string& reg, virtual_offset true)) /* try hard to find the other half, more expensive */ { assert(adrp_insn); - const auto adrp_disasm=DecodedInstruction_t(adrp_insn); - const auto page_no=adrp_disasm.getOperand(1).getConstant(); + const auto adrp_disasm=DecodedInstruction_t::factory(adrp_insn); + const auto page_no=adrp_disasm->getOperand(1)->getConstant(); - cout<<"Found spilled page_no at "<<hex<<insn->GetAddress()->GetVirtualOffset()<<" in: "<<endl; - cout<<"\t"<<adrp_disasm.getDisassembly()<<endl; + cout<<"Found spilled page_no at "<<hex<<insn->getAddress()->getVirtualOffset()<<" in: "<<endl; + cout<<"\t"<<adrp_disasm->getDisassembly()<<endl; cout<<"\t"<<insn->getDisassembly()<<endl; page_only=true; address=page_no; @@ -3295,15 +3276,15 @@ bool find_arm_address_gen(Instruction_t* insn, const string& reg, virtual_offset true)) /* try hard to find the other half, more expensive */ { assert(add_insn); - const auto add_disasm=DecodedInstruction_t(add_insn); - const auto add_op1=add_disasm.getOperand(1); - const auto add_op2=add_disasm.getOperand(2); - if(!add_op1.isRegister()) return false; - if( add_op1.getString()=="x29") return false; // skip arm SP. - if(!add_op2.isConstant()) return false; + const auto add_disasm=DecodedInstruction_t::factory(add_insn); + const auto add_op1=add_disasm->getOperand(1); + const auto add_op2=add_disasm->getOperand(2); + if(!add_op1->isRegister()) return false; + if( add_op1->getString()=="x29") return false; // skip arm SP. + if(!add_op2->isConstant()) return false; - const auto add_op1_reg=add_op1.getString(); - const auto add_op2_constant=add_op2.getConstant(); + const auto add_op1_reg=add_op1->getString(); + const auto add_op2_constant=add_op2->getConstant(); // try to find an adrp auto adrp_insn=(Instruction_t*)nullptr; @@ -3315,12 +3296,12 @@ bool find_arm_address_gen(Instruction_t* insn, const string& reg, virtual_offset return false; assert(adrp_insn); - const auto adrp_disasm=DecodedInstruction_t(adrp_insn); - const auto adrp_page=adrp_disasm.getOperand(1).getConstant(); + const auto adrp_disasm=DecodedInstruction_t::factory(adrp_insn); + const auto adrp_page=adrp_disasm->getOperand(1)->getConstant(); const auto spilled_address=adrp_page+add_op2_constant; - cout<<"Found spilled address at "<<hex<<insn->GetAddress()->GetVirtualOffset()<<" in: "<<endl; - cout<<"\t"<<adrp_disasm.getDisassembly()<<endl; - cout<<"\t"<<add_disasm.getDisassembly()<<endl; + cout<<"Found spilled address at "<<hex<<insn->getAddress()->getVirtualOffset()<<" in: "<<endl; + cout<<"\t"<<adrp_disasm->getDisassembly()<<endl; + cout<<"\t"<<add_disasm->getDisassembly()<<endl; cout<<"\t"<<insn->getDisassembly()<<endl; page_only=false; address=spilled_address; @@ -3335,7 +3316,7 @@ void find_all_arm_unks(FileIR_t* firp) { auto page_only=true; - auto address=virtual_offset_t(0); + auto address=VirtualOffset_t(0); if(find_arm_address_gen(insn,reg, address, page_only)) { if(page_only) @@ -3346,34 +3327,34 @@ void find_all_arm_unks(FileIR_t* firp) }; const auto do_verbose=getenv("IB_VERBOSE"); /* only valid for arm */ - if(firp->GetArchitecture()->getMachineType() != admtAarch64) return; + if(firp->getArchitecture()->getMachineType() != admtAarch64) return; /* find adrps */ - for(auto insn : firp->GetInstructions()) + for(auto insn : firp->getInstructions()) { - const auto d=DecodedInstruction_t(insn); - if(d.getMnemonic()!="adrp") continue; - const auto op1=d.getOperand(1); - const auto op1_constant=op1.getConstant(); - all_adrp_results[insn->GetFunction()].insert(op1_constant); + const auto d=DecodedInstruction_t::factory(insn); + if(d->getMnemonic()!="adrp") continue; + const auto op1=d->getOperand(1); + const auto op1_constant=op1->getConstant(); + all_adrp_results[insn->getFunction()].insert(op1_constant); } /* find add/adrp pairs */ - for(auto insn : firp->GetInstructions()) - { - const auto d=DecodedInstruction_t(insn); - if(d.getMnemonic()!="add") continue; - if(!d.hasOperand(1)) continue; - if(!d.hasOperand(2)) continue; - const auto op0=d.getOperand(1); - const auto op1=d.getOperand(1); - const auto op2=d.getOperand(2); - if(!op1.isRegister()) continue; - if(op1.getString()=="x29") continue; // skip arm SP. - if(!op2.isConstant()) continue; - - const auto op1_reg=op1.getString(); - const auto op2_constant=op2.getConstant(); + for(auto insn : firp->getInstructions()) + { + const auto d=DecodedInstruction_t::factory(insn); + if(d->getMnemonic()!="add") continue; + if(!d->hasOperand(1)) continue; + if(!d->hasOperand(2)) continue; + const auto op0=d->getOperand(1); + const auto op1=d->getOperand(1); + const auto op2=d->getOperand(2); + if(!op1->isRegister()) continue; + if(op1->getString()=="x29") continue; // skip arm SP. + if(!op2->isConstant()) continue; + + const auto op1_reg=op1->getString(); + const auto op2_constant=op2->getConstant(); // try to find an adrp auto adrp_insn=(Instruction_t*)nullptr; @@ -3385,25 +3366,25 @@ void find_all_arm_unks(FileIR_t* firp) continue; assert(adrp_insn); - const auto adrp_disasm=DecodedInstruction_t(adrp_insn); - const auto adrp_page=adrp_disasm.getOperand(1).getConstant(); + const auto adrp_disasm=DecodedInstruction_t::factory(adrp_insn); + const auto adrp_page=adrp_disasm->getOperand(1)->getConstant(); const auto unk_value=adrp_page+op2_constant; - all_add_adrp_results [ insn->GetFunction() ].insert(unk_value); - all_add_adrp_results [ adrp_insn->GetFunction()].insert(unk_value); - per_reg_add_adrp_results [ op0.getString() ].insert(unk_value); + all_add_adrp_results [ insn->getFunction() ].insert(unk_value); + all_add_adrp_results [ adrp_insn->getFunction()].insert(unk_value); + per_reg_add_adrp_results [ op0->getString() ].insert(unk_value); /* check for scoops at the unk address. * if found, we assume that the unk points at data. * else, we mark it as a possible code target. */ - if(firp->FindScoop(unk_value)==nullptr) + if(firp->findScoop(unk_value)==nullptr) possible_target(unk_value, 0, ibt_provenance_t::ibtp_text); /* verbose logging */ if(do_verbose) - cout << "Detected ARM unk="<<hex<<unk_value<<" for "<<d.getDisassembly() - << " and "<<adrp_disasm.getDisassembly()<<endl; + cout << "Detected ARM unk="<<hex<<unk_value<<" for "<<d->getDisassembly() + << " and "<<adrp_disasm->getDisassembly()<<endl; } /* find spilled adrp's and add/adrp pairs @@ -3420,91 +3401,91 @@ void find_all_arm_unks(FileIR_t* firp) * * we record these later, in case we find a switch dispatch that has a spilled jump table address. */ - for(auto insn : firp->GetInstructions()) + for(auto insn : firp->getInstructions()) { // look for a spill of an address - const auto d=DecodedInstruction_t(insn); + const auto d=DecodedInstruction_t::factory(insn); // spills are str instructions - if(d.getMnemonic()!="str") continue; + if(d->getMnemonic()!="str") continue; // spills of an address are writing an X register. - const auto spill_op0_reg=d.getOperand(0).getString(); + const auto spill_op0_reg=d->getOperand(0)->getString(); if(spill_op0_reg[0]!='x') continue; // spills write to the stack with a constant offset. - const auto spill_op1=d.getOperand(1); - assert(spill_op1.isMemory()); - const auto spill_op1_string=spill_op1.getString(); + const auto spill_op1=d->getOperand(1); + assert(spill_op1->isMemory()); + const auto spill_op1_string=spill_op1->getString(); // needs to have a base reg, which is either sp or x29 - if(!spill_op1.hasBaseRegister()) continue; + if(!spill_op1->hasBaseRegister()) continue; if( spill_op1_string.substr(0,2)!="sp" && spill_op1_string.substr(0,3)!="x29" ) continue; - if(!spill_op1.hasMemoryDisplacement()) continue; - if( spill_op1.hasIndexRegister()) continue; + if(!spill_op1->hasMemoryDisplacement()) continue; + if( spill_op1->hasIndexRegister()) continue; - const auto spill_disp=spill_op1.getMemoryDisplacement(); + const auto spill_disp=spill_op1->getMemoryDisplacement(); // found str <x-reg> [sp+const] - reg_to_spilled_addr(insn, spill_op0_reg, SpillPoint_t({insn->GetFunction(),spill_disp })); + reg_to_spilled_addr(insn, spill_op0_reg, SpillPoint_t({insn->getFunction(),spill_disp })); } - for(auto insn : firp->GetInstructions()) + for(auto insn : firp->getInstructions()) { // look for a spill of an address - const auto d=DecodedInstruction_t(insn); + const auto d=DecodedInstruction_t::factory(insn); // spills are str instructions - if(d.getMnemonic()!="stp") continue; + if(d->getMnemonic()!="stp") continue; // spills of an address are writing an X register. - const auto spill_op0_reg=d.getOperand(0).getString(); - const auto spill_op1_reg=d.getOperand(1).getString(); + const auto spill_op0_reg=d->getOperand(0)->getString(); + const auto spill_op1_reg=d->getOperand(1)->getString(); if(spill_op0_reg[0]!='x') continue; // spills write to the stack with a constant offset. - const auto spill_op2=d.getOperand(2); - assert(spill_op2.isMemory()); - const auto spill_op2_string=spill_op2.getString(); + const auto spill_op2=d->getOperand(2); + assert(spill_op2->isMemory()); + const auto spill_op2_string=spill_op2->getString(); // needs to have a base reg, which is either sp or x29 - if(!spill_op2.hasBaseRegister()) continue; + if(!spill_op2->hasBaseRegister()) continue; if( spill_op2_string.substr(0,2)!="sp" && spill_op2_string.substr(0,3)!="x29" ) continue; - if(!spill_op2.hasMemoryDisplacement()) continue; - if( spill_op2.hasIndexRegister()) continue; + if(!spill_op2->hasMemoryDisplacement()) continue; + if( spill_op2->hasIndexRegister()) continue; - const auto spill_disp=spill_op2.getMemoryDisplacement(); + const auto spill_disp=spill_op2->getMemoryDisplacement(); // found stp <xreg> <xreg> [sp+const] - reg_to_spilled_addr(insn, spill_op0_reg, SpillPoint_t({insn->GetFunction(),spill_disp })); - reg_to_spilled_addr(insn, spill_op1_reg, SpillPoint_t({insn->GetFunction(),spill_disp+8})); + reg_to_spilled_addr(insn, spill_op0_reg, SpillPoint_t({insn->getFunction(),spill_disp })); + reg_to_spilled_addr(insn, spill_op1_reg, SpillPoint_t({insn->getFunction(),spill_disp+8})); } // look for spilling an address into a d-register. - for(auto insn : firp->GetInstructions()) + for(auto insn : firp->getInstructions()) { // look for moves to d-regs via fmov. - const auto d = DecodedInstruction_t(insn); - if( d.getMnemonic()!="fmov" ) continue; + const auto d = DecodedInstruction_t::factory(insn); + if( d->getMnemonic()!="fmov" ) continue; // look for a spill of an address - const auto op0 = d.getOperand(0); - const auto op1 = d.getOperand(1); - const auto op0_str = op0.getString(); - const auto op1_str = op1.getString(); + const auto op0 = d->getOperand(0); + const auto op1 = d->getOperand(1); + const auto op0_str = op0->getString(); + const auto op1_str = op1->getString(); // spills to d-regs are fmov instructions with a d-reg dest and an xreg src. if( op0_str[0] !='d' ) continue; if( op1_str[0] !='x' ) continue; auto page_only=true; - auto address=virtual_offset_t(0); + auto address=VirtualOffset_t(0); if(find_arm_address_gen(insn,op1_str, address, page_only)) { - const auto spill_loc = DregSpillPoint_t({insn->GetFunction(), op0_str}); + const auto spill_loc = DregSpillPoint_t({insn->getFunction(), op0_str}); spilled_to_dreg[spill_loc].insert(address); } @@ -3520,7 +3501,7 @@ void fill_in_indtargs(FileIR_t* firp, exeio* elfiop, int64_t do_unpin_opt) { calc_preds(firp); - set<virtual_offset_t> thunk_bases; + set<VirtualOffset_t> thunk_bases; find_all_module_starts(firp,thunk_bases); // reset global vars @@ -3596,8 +3577,8 @@ void fill_in_indtargs(FileIR_t* firp, exeio* elfiop, int64_t do_unpin_opt) bool split_eh_frame_opt=true; int64_t do_unpin_opt=numeric_limits<int64_t>::max() ; -db_id_t variant_id=BaseObj_t::NOT_IN_DATABASE; -set<virtual_offset_t> forced_pins; +DatabaseID_t variant_id=BaseObj_t::NOT_IN_DATABASE; +set<VirtualOffset_t> forced_pins; int parseArgs(const vector<string> step_args) { @@ -3662,7 +3643,7 @@ int parseArgs(const vector<string> step_args) for (; argc_iter < step_args.size(); argc_iter++) { char *end_ptr; - virtual_offset_t offset = strtol(step_args[argc_iter].c_str(), &end_ptr, 0); + VirtualOffset_t offset = strtol(step_args[argc_iter].c_str(), &end_ptr, 0); if (*end_ptr == '\0') { cout << "force pinning: 0x" << std::hex << offset << endl; @@ -3684,7 +3665,7 @@ int executeStep(IRDBObjects_t *const irdb_objects) { /* setup the interface to the sql server */ const auto pqxx_interface=irdb_objects->getDBInterface(); - BaseObj_t::SetInterface(pqxx_interface); + BaseObj_t::setInterface(pqxx_interface); auto pidp = irdb_objects->addVariant(variant_id); assert(pidp); @@ -3692,28 +3673,28 @@ int executeStep(IRDBObjects_t *const irdb_objects) // pidp=new VariantID_t(atoi(argv[1])); - assert(pidp->IsRegistered()==true); + assert(pidp->isRegistered()==true); cout<<"New Variant, after reading registration, is: "<<*pidp << endl; - for(const auto &this_file : pidp->GetFiles()) + for(const auto &this_file : pidp->getFiles()) { assert(this_file); - cout<<"Analyzing file "<<this_file->GetURL()<<endl; + cout<<"Analyzing file "<<this_file->getURL()<<endl; // read the db - auto firp = irdb_objects->addFileIR(variant_id, this_file->GetBaseID()); + auto firp = irdb_objects->addFileIR(variant_id, this_file->getBaseID()); // firp=new FileIR_t(*pidp, this_file); assert(firp); - firp->SetBaseIDS(); - firp->AssembleRegistry(); + firp->setBaseIDS(); + firp->assembleRegistry(); // read the executeable file - int elfoid=firp->GetFile()->GetELFOID(); + int elfoid=firp->getFile()->getELFOID(); pqxx::largeobject lo(elfoid); - lo.to_file(pqxx_interface->GetTransaction(),"readeh_tmp_file.exe"); + lo.to_file(pqxx_interface->getTransaction(),"readeh_tmp_file.exe"); auto elfiop=unique_ptr<EXEIO::exeio>(new EXEIO::exeio); elfiop->load(string("readeh_tmp_file.exe")); @@ -3756,27 +3737,25 @@ std::string getStepName(void) const override }; -shared_ptr<Transform_SDK::TransformStep_t> curInvocation; +shared_ptr<TransformStep_t> curInvocation; -bool possible_target(virtual_offset_t p, virtual_offset_t from_addr, ibt_provenance_t prov) +bool possible_target(VirtualOffset_t p, VirtualOffset_t from_addr, ibt_provenance_t prov) { assert(curInvocation); return (dynamic_cast<PopulateIndTargs_t*>(curInvocation.get()))->possible_target(p,from_addr,prov); } -void range(virtual_offset_t start, virtual_offset_t end) +void range(VirtualOffset_t start, VirtualOffset_t end) { assert(curInvocation); return (dynamic_cast<PopulateIndTargs_t*>(curInvocation.get()))->range(start,end); } extern "C" -shared_ptr<Transform_SDK::TransformStep_t> GetTransformStep(void) +shared_ptr<TransformStep_t> getTransformStep(void) { curInvocation.reset(new PopulateIndTargs_t()); return curInvocation; - - //return shared_ptr<Transform_SDK::TransformStep_t>(new PopulateIndTargs_t()); } diff --git a/ir_builders/fill_in_indtargs.hpp b/ir_builders/fill_in_indtargs.hpp index ed5f56458..dd0500d1f 100644 --- a/ir_builders/fill_in_indtargs.hpp +++ b/ir_builders/fill_in_indtargs.hpp @@ -19,7 +19,7 @@ * */ -#include <libIRDB-core.hpp> +#include <irdb-core> #include <iostream> #include <limits> #include <stdlib.h> @@ -36,14 +36,11 @@ #include <exeio.h> #include "check_thunks.hpp" -using namespace libIRDB; -using namespace std; -using namespace EXEIO; /* * defines */ -#define arch_ptr_bytes() (firp->GetArchitectureBitWidth()/8) +#define arch_ptr_bytes() (firp->getArchitectureBitWidth()/8u) /* * global variables @@ -114,7 +111,7 @@ class ibt_provenance_t private: provtype_t value; - friend ostream& operator<<(ostream& out, const ibt_provenance_t& prov); + friend std::ostream& operator<<(std::ostream& out, const ibt_provenance_t& prov); }; @@ -169,16 +166,16 @@ static inline std::ostream& operator<<(std::ostream& out, const ibt_provenance_t * Forward prototypes */ -bool is_possible_target(virtual_offset_t p, virtual_offset_t addr); -bool possible_target(virtual_offset_t p, virtual_offset_t from_addr, ibt_provenance_t prov=ibt_provenance_t::ibtp_unknown); +bool is_possible_target(IRDB_SDK::VirtualOffset_t p, IRDB_SDK::VirtualOffset_t addr); +bool possible_target(IRDB_SDK::VirtualOffset_t p, IRDB_SDK::VirtualOffset_t from_addr, ibt_provenance_t prov=ibt_provenance_t::ibtp_unknown); -class fii_icfs : public ICFS_t +class fii_icfs : public IRDB_SDK::InstructionSet_t { public: // get/set table start - virtual_offset_t GetTableStart() {return table_start; } - void SetTableStart(virtual_offset_t s) {table_start=s; } + IRDB_SDK::VirtualOffset_t GetTableStart() {return table_start; } + void SetTableStart(IRDB_SDK::VirtualOffset_t s) {table_start=s; } // get/set switch type ibt_provenance_t GetSwitchType() { return switch_type; } @@ -187,13 +184,40 @@ class fii_icfs : public ICFS_t // get/set table size int GetTableSize() { return table_size; } void SetTableSize(int s) { table_size=s; } + + void addTargets(const IRDB_SDK::InstructionSet_t &other) + { + insert(std::begin(other), std::end(other)); + } + bool isIncomplete() const { + return getAnalysisStatus() == IRDB_SDK::iasAnalysisIncomplete; + } + + bool isComplete() const { + return getAnalysisStatus() == IRDB_SDK::iasAnalysisComplete; + } + + bool isModuleComplete() const { + return getAnalysisStatus() == IRDB_SDK::iasAnalysisModuleComplete; + } + + void setAnalysisStatus(const IRDB_SDK::ICFSAnalysisStatus_t p_status) { + m_icfs_analysis_status = p_status; + } + + IRDB_SDK::ICFSAnalysisStatus_t getAnalysisStatus() const { + return m_icfs_analysis_status; + } + + private: - virtual_offset_t table_start; + IRDB_SDK::VirtualOffset_t table_start; ibt_provenance_t switch_type; int table_size; + IRDB_SDK::ICFSAnalysisStatus_t m_icfs_analysis_status; }; -void split_eh_frame(FileIR_t* firp); +void split_eh_frame(IRDB_SDK::FileIR_t* firp); diff --git a/ir_builders/find_strings.cpp b/ir_builders/find_strings.cpp index 711f78484..a91071a64 100644 --- a/ir_builders/find_strings.cpp +++ b/ir_builders/find_strings.cpp @@ -65,7 +65,7 @@ typedef struct elf_info { ::Elf64_Addr got; #endif int secnum; - virtual_offset_t got; + VirtualOffset_t got; char const **sec_data; exeio *elfiop; } elf_info_t; diff --git a/ir_builders/fix_calls.cpp b/ir_builders/fix_calls.cpp index 92615fd53..9ef6496b4 100644 --- a/ir_builders/fix_calls.cpp +++ b/ir_builders/fix_calls.cpp @@ -19,7 +19,7 @@ */ -#include <libIRDB-core.hpp> +#include <irdb-core> #include <libIRDB-cfg.hpp> #include <utils.hpp> #include <iostream> @@ -33,9 +33,9 @@ #include "fill_in_indtargs.hpp" -using namespace libIRDB; using namespace std; using namespace EXEIO; +using namespace IRDB_SDK; // macros #define ALLOF(a) begin(a),end(a) @@ -44,7 +44,7 @@ using namespace EXEIO; // externs extern void read_ehframe(FileIR_t* firp, EXEIO::exeio* ); -class FixCalls_t : public libIRDB::Transform_SDK::TransformStep_t +class FixCalls_t : public TransformStep_t { public: @@ -52,32 +52,32 @@ public: class Range_t { public: - Range_t(virtual_offset_t p_s, virtual_offset_t p_e) : m_start(p_s), m_end(p_e) { } + Range_t(VirtualOffset_t p_s, VirtualOffset_t p_e) : m_start(p_s), m_end(p_e) { } Range_t() : m_start(0), m_end(0) { } - virtual virtual_offset_t GetStart() const { return m_start; } - virtual virtual_offset_t GetEnd() const { return m_end; } - virtual void SetStart(virtual_offset_t s) { m_start=s; } - virtual void SetEnd(virtual_offset_t e) { m_end=e; } + virtual VirtualOffset_t getStart() const { return m_start; } + virtual VirtualOffset_t getEnd() const { return m_end; } + virtual void setStart(VirtualOffset_t s) { m_start=s; } + virtual void setEnd(VirtualOffset_t e) { m_end=e; } protected: - virtual_offset_t m_start, m_end; + VirtualOffset_t m_start, m_end; }; struct Range_tCompare { bool operator() (const Range_t &first, const Range_t &second) const { - return first.GetEnd() < second.GetStart(); + return first.getEnd() < second.getStart(); } }; -using RangeSet_t = std::set<Range_t, Range_tCompare>; +using Rangeset_t = std::set<Range_t, Range_tCompare>; -RangeSet_t eh_frame_ranges; +Rangeset_t eh_frame_ranges; size_t no_target_insn=0; size_t no_fallthrough_insn=0; size_t target_not_in_function=0; @@ -95,7 +95,7 @@ size_t not_calls=0; bool opt_fix_icalls = false; bool opt_fix_safefn = true; -bool check_entry(bool &found, ControlFlowGraph_t* cfg) +bool check_entry(bool &found, libIRDB::ControlFlowGraph_t* cfg) { auto entry=cfg->GetEntry(); @@ -103,15 +103,16 @@ bool check_entry(bool &found, ControlFlowGraph_t* cfg) for(auto insn : entry->GetInstructions()) { - DecodedInstruction_t disasm(insn); + auto disasmp = DecodedInstruction_t::factory(insn); + auto &disasm = *disasmp; if(disasm.setsStackPointer()) { return false; } else { if(getenv("VERBOSE_FIX_CALLS")) { - virtual_offset_t addr = 0; - if (insn->GetAddress()) - addr = insn->GetAddress()->GetVirtualOffset(); + VirtualOffset_t addr = 0; + if (insn->getAddress()) + addr = insn->getAddress()->getVirtualOffset(); cout<<"check_entry: does not set stack pointer?"<< " address=" <<hex<<addr<<": "<<insn->getDisassembly()<<endl; } @@ -122,9 +123,9 @@ bool check_entry(bool &found, ControlFlowGraph_t* cfg) found=true; if(getenv("VERBOSE_FIX_CALLS")) { - virtual_offset_t addr = 0; - if (insn->GetAddress()) - addr = insn->GetAddress()->GetVirtualOffset(); + VirtualOffset_t addr = 0; + if (insn->getAddress()) + addr = insn->getAddress()->getVirtualOffset(); cout<<"Needs fix (check_entry): [esp]"<< " address=" <<hex<<addr<<": "<<insn->getDisassembly()<<endl; } @@ -135,20 +136,20 @@ bool check_entry(bool &found, ControlFlowGraph_t* cfg) return false; } -using ControlFlowGraphMap_t = map<Function_t*, ControlFlowGraph_t*>; +using ControlFlowGraphMap_t = map<Function_t*, libIRDB::ControlFlowGraph_t*>; ControlFlowGraphMap_t cfg_optimizer; bool call_needs_fix(Instruction_t* insn) { - for(auto reloc : insn->GetRelocations()) + for(auto reloc : insn->getRelocations()) { - if(string("safefr") == reloc->GetType()) + if(string("safefr") == reloc->getType()) return false; } - auto target=insn->GetTarget(); - auto fallthru=insn->GetFallthrough(); + auto target=insn->getTarget(); + auto fallthru=insn->getFallthrough(); string pattern; @@ -162,9 +163,9 @@ bool call_needs_fix(Instruction_t* insn) { if(getenv("VERBOSE_FIX_CALLS")) { - virtual_offset_t addr = 0; - if (insn->GetAddress()) - addr = insn->GetAddress()->GetVirtualOffset(); + VirtualOffset_t addr = 0; + if (insn->getAddress()) + addr = insn->getAddress()->getVirtualOffset(); cout<<"Needs fix: No fallthrough"<< " address=" <<hex<<addr<<": "<<insn->getDisassembly()<<endl; } @@ -172,7 +173,7 @@ bool call_needs_fix(Instruction_t* insn) return true; } - auto addr=fallthru->GetAddress()->GetVirtualOffset(); + auto addr=fallthru->getAddress()->getVirtualOffset(); auto rangeiter=eh_frame_ranges.find(Range_t(addr,addr)); if(rangeiter != eh_frame_ranges.end()) // found an eh_frame addr entry for this call { @@ -180,7 +181,7 @@ bool call_needs_fix(Instruction_t* insn) return true; } - if (!opt_fix_icalls && insn->GetIBTargets() && insn->GetIBTargets()->size() > 0) + if (!opt_fix_icalls && insn->getIBTargets() && insn->getIBTargets()->size() > 0) { /* do not fix indirect calls */ no_fix_for_ib++; @@ -191,8 +192,8 @@ bool call_needs_fix(Instruction_t* insn) if(!target) { /* call 0's aren't to real locations */ - DecodedInstruction_t disasm(insn); - if(disasm.getOperand(0).isConstant() && disasm.getAddress()==0) + auto disasm=DecodedInstruction_t::factory(insn); + if(disasm->getOperand(0)->isConstant() && disasm->getAddress()==0) { return false; } @@ -200,9 +201,9 @@ bool call_needs_fix(Instruction_t* insn) if(getenv("VERBOSE_FIX_CALLS")) { - virtual_offset_t addr = 0; - if (insn->GetAddress()) - addr = insn->GetAddress()->GetVirtualOffset(); + VirtualOffset_t addr = 0; + if (insn->getAddress()) + addr = insn->getAddress()->getVirtualOffset(); cout<<"Needs fix: No target instruction"<< " address=" <<hex<<addr<<": "<<insn->getDisassembly()<<endl; } @@ -216,16 +217,16 @@ bool call_needs_fix(Instruction_t* insn) */ - auto func=target->GetFunction(); + auto func=target->getFunction(); /* if there's no function for this instruction */ if(!func) { if(getenv("VERBOSE_FIX_CALLS")) { - virtual_offset_t addr = 0; - if (insn->GetAddress()) - addr = insn->GetAddress()->GetVirtualOffset(); + VirtualOffset_t addr = 0; + if (insn->getAddress()) + addr = insn->getAddress()->getVirtualOffset(); cout<<"Needs fix: Target not in a function"<< " address=" <<hex<<addr<<": "<<insn->getDisassembly()<<endl; } @@ -241,7 +242,7 @@ bool call_needs_fix(Instruction_t* insn) if(!is_found) /* build a cfg for this function */ - cfg_optimizer[func]=new ControlFlowGraph_t(func); + cfg_optimizer[func]=new libIRDB::ControlFlowGraph_t(func); auto cfg=cfg_optimizer[func]; @@ -268,9 +269,9 @@ bool call_needs_fix(Instruction_t* insn) { if(getenv("VERBOSE_FIX_CALLS")) { - virtual_offset_t addr = 0; - if (insn->GetAddress()) - addr = insn->GetAddress()->GetVirtualOffset(); + VirtualOffset_t addr = 0; + if (insn->getAddress()) + addr = insn->getAddress()->getVirtualOffset(); cout<<"Needs fix: (via check_entry) Thunk detected"<< " address=" <<hex<<addr<<": "<<insn->getDisassembly()<<endl; } @@ -416,15 +417,16 @@ string adjust_esp_offset(string newbits, int offset) */ void convert_to_jump(Instruction_t* insn, int offset) { - string newbits=insn->GetDataBits(); - DecodedInstruction_t d(insn); + string newbits=insn->getDataBits(); + auto dp=DecodedInstruction_t::factory(insn); + auto &d=*dp; /* this case is odd, handle it specially (and more easily to understand) */ if(strcmp(d.getDisassembly().c_str(), "call qword [rsp]")==0) { char buf[100]; sprintf(buf,"jmp qword [rsp+%d]", offset); - insn->Assemble(buf); + insn->assemble(buf); return; } @@ -487,7 +489,7 @@ void convert_to_jump(Instruction_t* insn, int offset) } /* set the instruction's bits */ - insn->SetDataBits(newbits); + insn->setDataBits(newbits); return; } @@ -497,31 +499,32 @@ void convert_to_jump(Instruction_t* insn, int offset) */ void fix_call(Instruction_t* insn, FileIR_t *firp, bool can_unpin) { - if(firp->GetArchitecture()->getMachineType()==admtAarch64) + if(firp->getArchitecture()->getMachineType()==admtAarch64) return; /* record the possibly new indirect branch target if this call gets fixed */ - Instruction_t* newindirtarg=insn->GetFallthrough(); + Instruction_t* newindirtarg=insn->getFallthrough(); /* Disassemble the instruction */ - DecodedInstruction_t disasm(insn); + auto disasmp=DecodedInstruction_t::factory (insn); + auto &disasm=*disasmp; /* if this instruction is an inserted call instruction than we don't need to * convert it for correctness' sake. */ - if(insn->GetAddress()->GetVirtualOffset()==0) + if(insn->getAddress()->getVirtualOffset()==0) return; /* if the first byte isn't a call opcode, there's some odd prefixing and we aren't handling it. * this comes up most frequently in a call gs:0x10 instruction where an override prefix specifes the gs: part. */ - if((insn->GetDataBits()[0]&0x40)==0x40) + if((insn->getDataBits()[0]&0x40)==0x40) { // ignore rex prefixes } - else if( (insn->GetDataBits()[0]!=(char)0xff) && - (insn->GetDataBits()[0]!=(char)0xe8) && - (insn->GetDataBits()[0]!=(char)0x9a) ) + else if( (insn->getDataBits()[0]!=(char)0xff) && + (insn->getDataBits()[0]!=(char)0xe8) && + (insn->getDataBits()[0]!=(char)0x9a) ) { cout<<"Found odd prefixing.\n Not handling **********************************************"<<endl; assert(0); @@ -530,55 +533,61 @@ void fix_call(Instruction_t* insn, FileIR_t *firp, bool can_unpin) if(getenv("VERBOSE_FIX_CALLS")) { - cout<<"Doing a fix_call on "<<std::hex<<insn->GetAddress()->GetVirtualOffset()<< " which is "<<disasm.getDisassembly() /*.CompleteInstr*/<<endl; + cout<<"Doing a fix_call on "<<std::hex<<insn->getAddress()->getVirtualOffset()<< " which is "<<disasm.getDisassembly() /*.CompleteInstr*/<<endl; } - virtual_offset_t next_addr=insn->GetAddress()->GetVirtualOffset() + insn->GetDataBits().length(); + VirtualOffset_t next_addr=insn->getAddress()->getVirtualOffset() + insn->getDataBits().length(); /* create a new instruction and a new addresss for it that do not correspond to any original program address */ - Instruction_t *callinsn=new Instruction_t(); - AddressID_t *calladdr=new AddressID_t; - calladdr->SetFileID(insn->GetAddress()->GetFileID()); + /* + Instruction_t *callinsn=new Instruction_t(); + firp->getInstructions().insert(callinsn); + */ + auto callinsn=firp->addNewInstruction(); + /* + AddressID_t *calladdr=new AddressID_t; + firp->getAddresses().insert(calladdr); + calladdr->setFileID(insn->getAddress()->getFileID()); + */ + auto calladdr=firp->addNewAddress(insn->getAddress()->getFileID(),0); /* set the fields in the new instruction */ - callinsn->SetAddress(calladdr); - callinsn->SetTarget(insn->GetTarget()); - callinsn->SetFallthrough(NULL); - callinsn->SetFunction(insn->GetFunction()); - callinsn->SetComment(insn->GetComment()+" Jump part"); + callinsn->setAddress(calladdr); + callinsn->setTarget(insn->getTarget()); + callinsn->setFallthrough(NULL); + callinsn->setFunction(insn->getFunction()); + callinsn->setComment(insn->getComment()+" Jump part"); /* handle ib targets */ - callinsn->SetIBTargets(insn->GetIBTargets()); - insn->SetIBTargets(NULL); + callinsn->setIBTargets(insn->getIBTargets()); + insn->setIBTargets(NULL); // We need the control transfer instruction to be from the orig program because // if for some reason it's fallthrough/target isn't in the DB, we need to correctly // emit fallthrough/target rules - callinsn->SetOriginalAddressID(insn->GetOriginalAddressID()); - insn->SetOriginalAddressID(BaseObj_t::NOT_IN_DATABASE); + callinsn->setOriginalAddressID(insn->getOriginalAddressID()); + insn->setOriginalAddressID(BaseObj_t::NOT_IN_DATABASE); /* set the new instruction's data bits to be a jmp instead of a call */ string newbits=""; /* add 4 (8) if it's an esp(rsp) indirect branch for x86-32 (-64) */ - callinsn->SetDataBits(insn->GetDataBits()); - convert_to_jump(callinsn,firp->GetArchitectureBitWidth()/8); + callinsn->setDataBits(insn->getDataBits()); + convert_to_jump(callinsn,firp->getArchitectureBitWidth()/8); /* the jump instruction should NOT be indirectly reachable. We should * land at the push */ - fix_other_pcrel(firp, callinsn, insn->GetAddress()->GetVirtualOffset()); - callinsn->SetIndirectBranchTargetAddress(NULL); + fix_other_pcrel(firp, callinsn, insn->getAddress()->getVirtualOffset()); + callinsn->setIndirectBranchTargetAddress(NULL); /* add the new insn and new address into the list of valid calls and addresses */ - firp->GetAddresses().insert(calladdr); - firp->GetInstructions().insert(callinsn); /* Convert the old call instruction into a push return_address instruction */ - insn->SetFallthrough(callinsn); - insn->SetTarget(NULL); + insn->setFallthrough(callinsn); + insn->setTarget(NULL); newbits=string(""); newbits.resize(5); newbits[0]=0x68; /* assemble an instruction push next_addr */ @@ -586,63 +595,73 @@ void fix_call(Instruction_t* insn, FileIR_t *firp, bool can_unpin) newbits[2]=(next_addr>>8) & 0xff; newbits[3]=(next_addr>>16) & 0xff; newbits[4]=(next_addr>>24) & 0xff; - insn->SetDataBits(newbits); - insn->SetComment(insn->GetComment()+" Push part"); + insn->setDataBits(newbits); + insn->setComment(insn->getComment()+" Push part"); /* create a relocation for this instruction */ + /* Relocation_t* reloc=new Relocation_t; - if(firp->GetArchitectureBitWidth()==32) - { - reloc->SetOffset(1); - reloc->SetType("32-bit"); - } - else - { - assert(firp->GetArchitectureBitWidth()==64); - reloc->SetOffset(0); - reloc->SetType("push64"); - } + insn->getRelocations().insert(reloc); + firp->getRelocations().insert(reloc); + */ + auto reloc= firp->getArchitectureBitWidth()==32 ? firp->addNewRelocation(insn, 1, "32-bit") : + /* + reloc->setOffset(1); + reloc->setType("32-bit"); + */ + firp->getArchitectureBitWidth()==64 ? firp->addNewRelocation(insn, 0, "push64") : + /* + reloc->setOffset(0); + reloc->setType("push64"); + */ + throw invalid_argument("odd bit width?"); - insn->GetRelocations().insert(reloc); - firp->GetRelocations().insert(reloc); /* If the fallthrough is not marked as indirectly branchable-to, then mark it so */ - if(newindirtarg && !newindirtarg->GetIndirectBranchTargetAddress()) + if(newindirtarg && !newindirtarg->getIndirectBranchTargetAddress()) { /* create a new address for the IBTA */ + /* AddressID_t* newaddr = new AddressID_t; assert(newaddr); - newaddr->SetFileID(newindirtarg->GetAddress()->GetFileID()); - newaddr->SetVirtualOffset(newindirtarg->GetAddress()->GetVirtualOffset()); + newaddr->setFileID(newindirtarg->getAddress()->getFileID()); + newaddr->setVirtualOffset(newindirtarg->getAddress()->getVirtualOffset()); + firp->getAddresses().insert(newaddr); + */ + auto newaddr=firp->addNewAddress(newindirtarg->getAddress()->getFileID(), newindirtarg->getAddress()->getVirtualOffset()); /* set the instruction and include this address in the list of addrs */ - newindirtarg->SetIndirectBranchTargetAddress(newaddr); - firp->GetAddresses().insert(newaddr); + newindirtarg->setIndirectBranchTargetAddress(newaddr); // if we're marking this as an IBTA, determine whether we can unpin it or not if(can_unpin) { if(getenv("VERBOSE_FIX_CALLS")) { - cout<<"Setting unpin for type="<< reloc->GetType()<< " address=" - <<hex<<insn->GetBaseID()<<":"<<insn->getDisassembly()<<endl; + cout<<"setting unpin for type="<< reloc->getType()<< " address=" + <<hex<<insn->getBaseID()<<":"<<insn->getDisassembly()<<endl; } // set newindirtarg as unpinned - newindirtarg->GetIndirectBranchTargetAddress()->SetVirtualOffset(0); - reloc->SetWRT(newindirtarg); + newindirtarg->getIndirectBranchTargetAddress()->setVirtualOffset(0); + reloc->setWRT(newindirtarg); } } // mark in the IR what the fallthrough of this insn is. + /* Relocation_t* fix_call_reloc=new Relocation_t(); - fix_call_reloc->SetOffset(0); - fix_call_reloc->SetType("fix_call_fallthrough"); - fix_call_reloc->SetWRT(newindirtarg); - callinsn->GetRelocations().insert(fix_call_reloc); - firp->GetRelocations().insert(fix_call_reloc); - + callinsn->getRelocations().insert(fix_call_reloc); + firp->getRelocations().insert(fix_call_reloc); + */ + auto fix_call_reloc=firp->addNewRelocation(callinsn, 0, "fix_call_fallthrough", newindirtarg); + (void)fix_call_reloc; // not used, just give to IR + /* + fix_call_reloc->setOffset(0); + fix_call_reloc->setType("fix_call_fallthrough"); + fix_call_reloc->setWRT(newindirtarg); + */ } @@ -652,8 +671,8 @@ void fix_call(Instruction_t* insn, FileIR_t *firp, bool can_unpin) bool is_call(Instruction_t* insn) { /* Disassemble the instruction */ - DecodedInstruction_t disasm(insn); - return disasm.isCall(); // (disasm.Instruction.BranchType==CallType); + auto disasm=DecodedInstruction_t::factory (insn); + return disasm->isCall(); } bool can_skip_safe_function(Instruction_t *call_insn) @@ -662,31 +681,31 @@ bool can_skip_safe_function(Instruction_t *call_insn) return false; if (!is_call(call_insn)) return false; - Instruction_t *target=call_insn->GetTarget(); + Instruction_t *target=call_insn->getTarget(); if (!target) return false; - Function_t* func=target->GetFunction(); + auto func=target->getFunction(); if (!func) return false; /* if the call instruction isn't to a function entry point */ - if(func->GetEntryPoint()!=target) + if(func->getEntryPoint()!=target) { return false; } - if (func->IsSafe()) + if (func->isSafe()) { - cout << "Function " << func->GetName() << " is safe" << endl; + cout << "Function " << func->getName() << " is safe" << endl; } - return func->IsSafe(); + return func->isSafe(); } template <class T> struct insn_less : binary_function <T,T,bool> { bool operator() (const T& x, const T& y) const { - return x->GetBaseID() < y->GetBaseID() ;} + return x->getBaseID() < y->getBaseID() ;} }; @@ -696,15 +715,18 @@ template <class T> struct insn_less : binary_function <T,T,bool> { void mark_as_unpinned_ibt(FileIR_t* firp, Instruction_t* ret_point) { if( ret_point == NULL ) return; - if( ret_point->GetIndirectBranchTargetAddress() != NULL ) return; + if( ret_point->getIndirectBranchTargetAddress() != NULL ) return; + /* auto newaddr = new AddressID_t; assert(newaddr); - newaddr->SetFileID(ret_point->GetAddress()->GetFileID()); - newaddr->SetVirtualOffset(0); // unpinne + newaddr->setFileID(ret_point->getAddress()->getFileID()); + newaddr->setVirtualOffset(0); // unpinne - firp->GetAddresses().insert(newaddr); - ret_point->SetIndirectBranchTargetAddress(newaddr); + firp->getAddresses().insert(newaddr); + */ + auto newaddr=firp->addNewAddress(ret_point->getAddress()->getFileID(),0); + ret_point->setIndirectBranchTargetAddress(newaddr); } @@ -715,7 +737,7 @@ void mark_as_unpinned_ibt(FileIR_t* firp, Instruction_t* ret_point) void fix_all_calls(FileIR_t* firp, bool fix_all) { - auto sorted_insns = set<Instruction_t*,insn_less<Instruction_t*> >(ALLOF(firp->GetInstructions())); + auto sorted_insns = set<Instruction_t*,insn_less<Instruction_t*> >(ALLOF(firp->getInstructions())); for(auto insn : sorted_insns) { @@ -755,8 +777,8 @@ void fix_all_calls(FileIR_t* firp, bool fix_all) else { if(getenv("VERBOSE_FIX_CALLS")) - cout<<"No fix needed, marking ret site IBT, for "<<insn->GetAddress()->GetVirtualOffset()<<":"<<insn->getDisassembly()<<endl; - mark_as_unpinned_ibt(firp, insn->GetFallthrough()); + cout<<"No fix needed, marking ret site IBT, for "<<insn->getAddress()->getVirtualOffset()<<":"<<insn->getDisassembly()<<endl; + mark_as_unpinned_ibt(firp, insn->getFallthrough()); not_fixed_calls++; } } @@ -764,7 +786,7 @@ void fix_all_calls(FileIR_t* firp, bool fix_all) else { if(getenv("VERBOSE_FIX_CALLS")) - cout<<"Not a call "<<insn->GetAddress()->GetVirtualOffset()<<":"<<insn->getDisassembly()<<endl; + cout<<"Not a call "<<insn->getAddress()->getVirtualOffset()<<":"<<insn->getDisassembly()<<endl; not_calls++; } } @@ -792,10 +814,10 @@ void fix_all_calls(FileIR_t* firp, bool fix_all) // void fix_other_pcrel(FileIR_t* firp, Instruction_t *insn, uintptr_t virt_offset) { - DecodedInstruction_t disasm(insn); - const auto &operands=disasm.getOperands(); - const auto relop_it=find_if(ALLOF(operands),[](const DecodedOperand_t& op) - { return op.isPcrel() ; } ); + auto disasm=DecodedInstruction_t::factory(insn); + const auto &operands=disasm->getOperands(); + const auto relop_it=find_if(ALLOF(operands),[](const shared_ptr<DecodedOperand_t>& op) + { return op->isPcrel() ; } ); const bool is_rel= relop_it!=operands.end(); /* if this has already been fixed, we can skip it */ @@ -804,26 +826,26 @@ void fix_other_pcrel(FileIR_t* firp, Instruction_t *insn, uintptr_t virt_offset) if(is_rel) { - const auto the_arg=*relop_it; - const auto mt=firp->GetArchitecture()->getMachineType(); + const auto &the_arg=*(relop_it->get()); + const auto mt=firp->getArchitecture()->getMachineType(); if(mt==admtAarch64) { // figure out how to rewrite pcrel arm insns, then change the virt addr - // insn->GetAddress()->SetVirtualOffset(0); + // insn->getAddress()->setVirtualOffset(0); } else if(mt==admtX86_64 || mt==admtI386) { assert(the_arg.isMemory()); - auto offset=disasm.getMemoryDisplacementOffset(the_arg, insn); + auto offset=disasm->getMemoryDisplacementOffset(&the_arg, insn); assert(offset>=0 && offset <=15); auto size=the_arg.getMemoryDisplacementEncodingSize(); assert(size==1 || size==2 || size==4 || size==8); if(getenv("VERBOSE_FIX_CALLS")) { - cout<<"Found insn with pcrel memory operand: "<<disasm.getDisassembly()/*.CompleteInstr */ - <<" Displacement="<<std::hex<<the_arg.getMemoryDisplacement() /*the_arg->Memory.Displacement*/<<std::dec - <<" size="<<the_arg.getMemoryDisplacementEncodingSize() /*the_arg->Memory.DisplacementSize*/<<" Offset="<<offset; + cout<<"Found insn with pcrel memory operand: "<<disasm->getDisassembly() + <<" Displacement="<<std::hex<<the_arg.getMemoryDisplacement() << dec + <<" size="<<the_arg.getMemoryDisplacementEncodingSize() <<" Offset="<<offset; } /* convert [rip_pc+displacement] addresssing mode into [rip_0+displacement] where rip_pc is the actual PC of the insn, @@ -832,7 +854,7 @@ void fix_other_pcrel(FileIR_t* firp, Instruction_t *insn, uintptr_t virt_offset) */ /* get the data */ - string data=insn->GetDataBits(); + string data=insn->getDataBits(); char cstr[20]={}; memcpy(cstr,data.c_str(), data.length()); void *offsetptr=&cstr[offset]; @@ -859,22 +881,26 @@ void fix_other_pcrel(FileIR_t* firp, Instruction_t *insn, uintptr_t virt_offset) /* put the data back into the insn */ data.replace(0, data.length(), cstr, data.length()); - insn->SetDataBits(data); + insn->setDataBits(data); other_fixes++; - disasm=DecodedInstruction_t(insn); + disasm=DecodedInstruction_t::factory(insn); if(getenv("VERBOSE_FIX_CALLS")) - cout<<" Converted to: "<<disasm.getDisassembly() /*CompleteInstr*/<<endl; + cout<<" Converted to: "<<disasm->getDisassembly() << endl; // and it's important to set the VO to 0, so that the pcrel-ness is calculated correctly. - insn->GetAddress()->SetVirtualOffset(0); + insn->getAddress()->setVirtualOffset(0); } // now that we've done the rewriting, go ahead and add the reloc. + /* auto reloc=new Relocation_t(BaseObj_t::NOT_IN_DATABASE, 0,"pcrel"); - insn->GetRelocations().insert(reloc); - firp->GetRelocations().insert(reloc); + insn->getRelocations().insert(reloc); + firp->getRelocations().insert(reloc); + */ + auto reloc=firp->addNewRelocation(insn,0,"pcrel"); + (void)reloc; // not used, only given to the IR } } @@ -885,14 +911,17 @@ void fix_safefr(FileIR_t* firp, Instruction_t *insn, uintptr_t virt_offset) if(virt_offset==0 || virt_offset==(uintptr_t)-1) return; - for(auto reloc : insn->GetRelocations()) + for(auto reloc : insn->getRelocations()) { assert(reloc); - if( reloc->GetType() == "safefr" ) + if( reloc->getType() == "safefr" ) { - auto addr=new AddressID_t(BaseObj_t::NOT_IN_DATABASE, insn->GetAddress()->GetFileID(), 0); - firp->GetAddresses().insert(addr); - insn->SetAddress(addr); + /* + auto addr=new AddressID_t(BaseObj_t::NOT_IN_DATABASE, insn->getAddress()->getFileID(), 0); + firp->getAddresses().insert(addr); + */ + auto addr=firp->addNewAddress(insn->getAddress()->getFileID(), 0); + insn->setAddress(addr); } } } @@ -901,10 +930,10 @@ void fix_safefr(FileIR_t* firp, Instruction_t *insn, uintptr_t virt_offset) void fix_other_pcrel(FileIR_t* firp) { - for(auto insn : firp->GetInstructions()) + for(auto insn : firp->getInstructions()) { - fix_other_pcrel(firp,insn, insn->GetAddress()->GetVirtualOffset()); - fix_safefr(firp,insn, insn->GetAddress()->GetVirtualOffset()); + fix_other_pcrel(firp,insn, insn->getAddress()->getVirtualOffset()); + fix_safefr(firp,insn, insn->getAddress()->getVirtualOffset()); } cout << "# ATTRIBUTE fix_calls::other_fixes="<<std::dec<<other_fixes<<endl; } @@ -981,7 +1010,7 @@ int parseArgs(const vector<string> step_args) return 0; } -db_id_t variant_id=BaseObj_t::NOT_IN_DATABASE; +DatabaseID_t variant_id=BaseObj_t::NOT_IN_DATABASE; int executeStep(IRDBObjects_t *const irdb_objects) @@ -992,26 +1021,26 @@ int executeStep(IRDBObjects_t *const irdb_objects) { /* setup the interface to the sql server */ const auto pqxx_interface=irdb_objects->getDBInterface(); - BaseObj_t::SetInterface(pqxx_interface); + BaseObj_t::setInterface(pqxx_interface); auto pidp = irdb_objects->addVariant(variant_id); cout<<"Fixing calls->push/jmp in variant "<<*pidp<< "." <<endl; - assert(pidp->IsRegistered()==true); + assert(pidp->isRegistered()==true); - for(const auto &this_file : pidp->GetFiles()) + for(const auto &this_file : pidp->getFiles()) { assert(this_file); // read the db - auto firp = irdb_objects->addFileIR(variant_id, this_file->GetBaseID()); + auto firp = irdb_objects->addFileIR(variant_id, this_file->getBaseID()); assert(firp && pidp); eh_frame_ranges.clear(); - int elfoid=firp->GetFile()->GetELFOID(); + int elfoid=firp->getFile()->getELFOID(); pqxx::largeobject lo(elfoid); - lo.to_file(pqxx_interface->GetTransaction(),"readeh_tmp_file.exe"); + lo.to_file(pqxx_interface->getTransaction(),"readeh_tmp_file.exe"); EXEIO::exeio* elfiop=new EXEIO::exeio; elfiop->load(string("readeh_tmp_file.exe")); EXEIO::dump::header(cout,*elfiop); @@ -1044,7 +1073,7 @@ int executeStep(IRDBObjects_t *const irdb_objects) return 0; } -void range(virtual_offset_t a, virtual_offset_t b) +void range(VirtualOffset_t a, VirtualOffset_t b) { // we've found examples of ranges being 0 sized, and it's a bit weird what that means. // it applies to 0 instructions? @@ -1074,22 +1103,22 @@ std::string getStepName(void) const override }; // end class FixCalls_t -shared_ptr<Transform_SDK::TransformStep_t> curInvocation; +shared_ptr<TransformStep_t> curInvocation; -bool possible_target(virtual_offset_t p, virtual_offset_t from_addr, ibt_provenance_t prov) +bool possible_target(VirtualOffset_t p, VirtualOffset_t from_addr, ibt_provenance_t prov) { assert(curInvocation); return (dynamic_cast<FixCalls_t*>(curInvocation.get()))->possible_target(p,from_addr,prov); } -void range(virtual_offset_t start, virtual_offset_t end) +void range(VirtualOffset_t start, VirtualOffset_t end) { assert(curInvocation); return (dynamic_cast<FixCalls_t*>(curInvocation.get()))->range(start,end); } extern "C" -shared_ptr<Transform_SDK::TransformStep_t> GetTransformStep(void) +shared_ptr<TransformStep_t> getTransformStep(void) { curInvocation.reset(new FixCalls_t()); return curInvocation; diff --git a/ir_builders/read_ehframe.cpp b/ir_builders/read_ehframe.cpp index 5fef4dc7a..1ea7a13a3 100644 --- a/ir_builders/read_ehframe.cpp +++ b/ir_builders/read_ehframe.cpp @@ -22,7 +22,7 @@ -#include <libIRDB-core.hpp> +#include <irdb-core> #include <libIRDB-cfg.hpp> #include <utils.hpp> #include <iostream> @@ -42,8 +42,8 @@ #include "fill_in_indtargs.hpp" -using namespace libIRDB; using namespace std; +using namespace IRDB_SDK; @@ -797,7 +797,7 @@ void linear_search_fdes (struct object *ob, fde *this_fde, int offset) cout<<"absptr pc_end 0x"<<std::hex<<(pc_begin+pc_range+offset)<<endl; } #ifndef TEST - extern void range(virtual_offset_t, virtual_offset_t); + extern void range(VirtualOffset_t, VirtualOffset_t); range(pc_begin,pc_begin+pc_range); #endif if (pc_begin == 0) @@ -819,7 +819,7 @@ void linear_search_fdes (struct object *ob, fde *this_fde, int offset) } #ifndef TEST - extern void range(virtual_offset_t, virtual_offset_t); + extern void range(VirtualOffset_t, VirtualOffset_t); range(pc_begin,pc_begin+pc_range); #endif @@ -847,7 +847,7 @@ void linear_search_fdes (struct object *ob, fde *this_fde, int offset) void read_ehframe(FileIR_t* virp, EXEIO::exeio* exeiop) { - ptrsize=virp->GetArchitectureBitWidth()/(8*sizeof(char)); + ptrsize=virp->getArchitectureBitWidth()/(8*sizeof(char)); // 64/8 = 8 // 32/8 = 4 @@ -856,18 +856,16 @@ void read_ehframe(FileIR_t* virp, EXEIO::exeio* exeiop) if(!elfiop) return; // skip entire analysis for non-elf files as eh-frame is way different. - const auto eh_frame_it=find_if(virp->GetDataScoops().begin(), virp->GetDataScoops().end(), - [](const DataScoop_t* scoop) { return scoop->GetName()==".eh_frame"; }); + const auto eh_frame_it=find_if(virp->getDataScoops().begin(), virp->getDataScoops().end(), + [](const DataScoop_t* scoop) { return scoop->getName()==".eh_frame"; }); // either no eh_frame in the elf file, or fill_in_indtargs removed it because // it was asked to import the EH IR. - if(eh_frame_it==virp->GetDataScoops().end()) + if(eh_frame_it==virp->getDataScoops().end()) return; int secndx=0; int secnum=elfiop->sections.size(); - //ELFIO::Elf_Half strndx = elfiop->get_section_name_str_index(); - //const char* strtab=elfiop->sections[strndx]->get_data(); /* Locate desired section */ bool found=false; @@ -895,9 +893,7 @@ void read_ehframe(FileIR_t* virp, EXEIO::exeio* exeiop) cout<<"Found .eh_frame section addr is "<<std::dec<<eh_frame_addr<<endl; int total_size=0; -// char *p=&strtab[ sechdrs[secndx+1].sh_name]; const char *p=elfiop->sections[secndx+1]->get_name().c_str(); -#if 1 if (strcmp(".gcc_except_table",p)!=0) { cout<<"Did not find .gcc_except_table immediately after .eh_frame\n"; @@ -909,32 +905,15 @@ void read_ehframe(FileIR_t* virp, EXEIO::exeio* exeiop) (elfiop->sections[eh_frame_index+1]->get_address()+ elfiop->sections[eh_frame_index+1]->get_size() ) - (uintptr_t)eh_frame_addr; } -#else - total_size=elfiop->sections[eh_frame_index]->get_size()+1; -#endif eh_frame_data_total_size=total_size; -#if 0 - // collect eh_frame and gcc_except_table into one memory region - eh_frame_data=(char*)calloc(1,total_size); - memcpy(eh_frame_data,elfiop->sections[eh_frame_index]->get_data(), - elfiop->sections[eh_frame_index]->get_size()); - - if (strcmp(".gcc_except_table",p)==0) - { - memcpy(eh_frame_data+elfiop->sections[eh_frame_index]->get_size(), - elfiop->sections[eh_frame_index+1]->get_data(), - elfiop->sections[eh_frame_index+1]->get_size()); - } -#else // calc the size needed to safely walk the EH frame data. apparently walking assumes a null value in memory // after the section is loaded (or properly using eh_frame_hdr, which we aren't doing) //eh_frame_data=(char*)elfiop->sections[eh_frame_index]->get_data(); int newsize=elfiop->sections[eh_frame_index]->get_size()+4; eh_frame_data=(char*)calloc(1,newsize); memcpy(eh_frame_data, (void*)elfiop->sections[eh_frame_index]->get_data(), elfiop->sections[eh_frame_index]->get_size()); -#endif uintptr_t offset; // careful with offset and eh_offset as it can only be used for eh_frame_data offsetting, not offsetting into other addrs. @@ -943,7 +922,6 @@ void read_ehframe(FileIR_t* virp, EXEIO::exeio* exeiop) struct object ob; register_frame_info( eh_frame_data, &ob); -//classify_object_over_fdes (struct object *ob, fde *this_fde) classify_object_over_fdes(&ob,ob.u.single); linear_search_fdes (&ob,ob.u.single,offset); diff --git a/ir_builders/split_eh_frame.cpp b/ir_builders/split_eh_frame.cpp index 1da5b084d..b1c96c7e2 100644 --- a/ir_builders/split_eh_frame.cpp +++ b/ir_builders/split_eh_frame.cpp @@ -1,4 +1,4 @@ -#include <libIRDB-core.hpp> +#include <irdb-core> #include <iostream> #include <iomanip> #include <fstream> @@ -20,16 +20,37 @@ using namespace std; using namespace EXEIO; -using namespace libIRDB; +using namespace IRDB_SDK; using namespace EHP; #define ALLOF(s) begin(s), end(s) + +struct EhProgramPlaceHolder_t +{ + uint8_t caf; + int8_t daf; + int8_t rr; + uint8_t ptrsize; // needed for interpreting programs + IRDB_SDK::EhProgramListing_t cie_program; + IRDB_SDK::EhProgramListing_t fde_program; + + //IRDB_SDK::EhProgramListing_t& getCIEProgram() { return cie_program; } + //IRDB_SDK::EhProgramListing_t& getFDEProgram() { return fde_program; } + const IRDB_SDK::EhProgramListing_t& getCIEProgram() const { return cie_program; } + const IRDB_SDK::EhProgramListing_t& getFDEProgram() const { return fde_program; } + uint8_t getCodeAlignmentFactor() const { return caf; } + int8_t getDataAlignmentFactor() const { return daf; } + int8_t getReturnRegNumber() const { return rr; } + uint8_t getPointerSize() const { return ptrsize; } + +}; + template <int ptrsize> bool split_eh_frame_impl_t<ptrsize>::lsda_call_site_appliesTo(const LSDACallSite_t& cs, const Instruction_t* insn) const { - assert(insn && insn->GetAddress()); - auto insn_addr=insn->GetAddress()->GetVirtualOffset(); + assert(insn && insn->getAddress()); + auto insn_addr=insn->getAddress()->getVirtualOffset(); const auto call_site_addr=cs.getCallSiteAddress(); const auto call_site_end_addr=cs.getCallSiteEndAddress(); @@ -54,20 +75,18 @@ void split_eh_frame_impl_t<ptrsize>::lsda_call_site_build_ir assert(lsda_call_site_appliesTo(cs,insn)); // find landing pad instruction. - auto lp_insn=(Instruction_t*)NULL; + auto lp_insn=(IRDB_SDK::Instruction_t*)NULL; auto lp_it=om.find(landing_pad_addr); if(lp_it!=om.end()) lp_insn=lp_it->second; // create the callsite. - auto new_ehcs = new EhCallSite_t(BaseObj_t::NOT_IN_DATABASE, tt_encoding, lp_insn); - firp->GetAllEhCallSites().insert(new_ehcs); - insn->SetEhCallSite(new_ehcs); + auto new_ehcs = firp->addEhCallSite_t(insn, tt_encoding, lp_insn); //cout<<"landing pad addr : 0x"<<hex<<landing_pad_addr<<endl; if(action_table.size() == 0 ) { - new_ehcs->SetHasCleanup(); + new_ehcs->setHasCleanup(); // cout<<"Destructors to call, but no exceptions to catch"<<endl; } else @@ -77,12 +96,17 @@ void split_eh_frame_impl_t<ptrsize>::lsda_call_site_build_ir const auto action=p->getAction(); if(action==0) { - new_ehcs->GetTTOrderVector().push_back(action); + auto new_ttov=new_ehcs->getTTOrderVector(); + new_ttov.push_back(action); + new_ehcs->setTTOrderVector(new_ttov); //cout<<"Cleanup only (no catches) ."<<endl; } else if(action>0) { - new_ehcs->GetTTOrderVector().push_back(action); + auto new_ttov=new_ehcs->getTTOrderVector(); + new_ttov.push_back(action); + new_ehcs->setTTOrderVector(new_ttov); + // new_ehcs->getTTOrderVector().push_back(action); const auto index=action - 1; //cout<<"Catch for type: "; // the type table reveral was done during parsing, type table is right-side-up now. @@ -90,21 +114,25 @@ void split_eh_frame_impl_t<ptrsize>::lsda_call_site_build_ir auto wrt=(DataScoop_t*)NULL; if(type_table.at(index)->getTypeInfoPointer()!=0) { - wrt=firp->FindScoop(type_table.at(index)->getTypeInfoPointer()); + wrt=firp->findScoop(type_table.at(index)->getTypeInfoPointer()); assert(wrt); } const auto offset=index*type_table.at(index)->getTTEncodingSize(); auto addend=0; if(wrt!=NULL) - addend=type_table.at(index)->getTypeInfoPointer()-wrt->GetStart()->GetVirtualOffset(); + addend=type_table.at(index)->getTypeInfoPointer()-wrt->getStart()->getVirtualOffset(); + /* auto newreloc=new Relocation_t(BaseObj_t::NOT_IN_DATABASE, offset, "type_table_entry", wrt, addend); - new_ehcs->GetRelocations().insert(newreloc); - firp->GetRelocations().insert(newreloc); + new_ehcs->getRelocations().insert(newreloc); + firp->getRelocations().insert(newreloc); + */ + auto newreloc=firp->addNewRelocation(new_ehcs,offset, "type_table_entry", wrt, addend); + (void)newreloc; // just give it to the ir //if(wrt==NULL) // cout<<"Catch all in type table"<<endl; //else - // cout<<"Catch for type at "<<wrt->GetName()<<"+0x"<<hex<<addend<<"."<<endl; + // cout<<"Catch for type at "<<wrt->getName()<<"+0x"<<hex<<addend<<"."<<endl; } else if(action<0) { @@ -117,7 +145,7 @@ void split_eh_frame_impl_t<ptrsize>::lsda_call_site_build_ir } // this isn't right at all, but pretend it's a cleanup! - new_ehcs->SetHasCleanup(); + new_ehcs->setHasCleanup(); //cout<<"Cleanup only (no catches) ."<<endl; } else @@ -156,8 +184,8 @@ void split_eh_frame_impl_t<ptrsize>::lsda_build_ir(const LSDA_t& lsda, Instructi template <int ptrsize> bool split_eh_frame_impl_t<ptrsize>::fde_contents_appliesTo(const FDEContents_t& fde, const Instruction_t* insn) const { - assert(insn && insn->GetAddress()); - auto insn_addr=insn->GetAddress()->GetVirtualOffset(); + assert(insn && insn->getAddress()); + auto insn_addr=insn->getAddress()->getVirtualOffset(); const auto fde_start_addr=fde.getStartAddress(); const auto fde_end_addr=fde.getEndAddress(); return ( fde_start_addr<=insn_addr && insn_addr<fde_end_addr ); @@ -173,7 +201,7 @@ void split_eh_frame_impl_t<ptrsize>::fde_contents_build_ir(const FDEContents_t& const auto lsda_addr=fde.getLSDAAddress(); // assert this is the right FDE. - assert( fde_start_addr<= insn->GetAddress()->GetVirtualOffset() && insn->GetAddress()->GetVirtualOffset() <= fde_end_addr); + assert( fde_start_addr<= insn->getAddress()->getVirtualOffset() && insn->getAddress()->getVirtualOffset() <= fde_end_addr); //eh_pgm.print(fde_start_addr); if(lsda_addr!=0) @@ -183,10 +211,9 @@ void split_eh_frame_impl_t<ptrsize>::fde_contents_build_ir(const FDEContents_t& template <int ptrsize> bool split_eh_frame_impl_t<ptrsize>::init_offset_map() { - //for_each(firp->GetInstructions().begin(), firp->GetInstructions().end(), [&](Instruction_t* i) - for(const auto i : firp->GetInstructions()) + for(const auto i : firp->getInstructions()) { - offset_to_insn_map[i->GetAddress()->GetVirtualOffset()]=i; + offset_to_insn_map[i->getAddress()->getVirtualOffset()]=i; }; return false; } @@ -198,27 +225,28 @@ void split_eh_frame_impl_t<ptrsize>::build_ir() const class whole_pgm_t { public: - whole_pgm_t(EhProgram_t* _pgm, uint64_t _personality) - : hashcode(hashPgm(_pgm)), pgm(_pgm), personality(_personality) + whole_pgm_t(EhProgramPlaceHolder_t& _pgm, EhProgram_t* cp, uint64_t _personality) + : hashcode(hashPgm(_pgm)), pgm(_pgm), cached_pgm(cp), personality(_personality) { } - EhProgram_t* getProgram() const { return pgm; } + void setCachedProgram(EhProgram_t* cp) { cached_pgm=cp; } + EhProgram_t* getCachedProgram() const { return cached_pgm; } uint64_t getPersonality() const { return personality; } private: - static uint64_t hashPgm(const EhProgram_t* vec) + static uint64_t hashPgm(const EhProgramPlaceHolder_t& vec) { - assert(vec); - auto seed = vec->GetCIEProgram().size() + vec->GetFDEProgram().size(); + auto seed = vec.getCIEProgram().size() + vec.getFDEProgram().size(); auto hash_fn=hash<string>(); - for(const auto& i : vec->GetCIEProgram()) + for(const auto& i : vec.getCIEProgram()) seed ^= hash_fn(i) + 0x9e3779b9 + (seed << 6) + (seed >> 2); - for(const auto& i : vec->GetFDEProgram()) + for(const auto& i : vec.getFDEProgram()) seed ^= hash_fn(i) + 0x9e3779b9 + (seed << 6) + (seed >> 2); return seed; }; uint64_t hashcode; - EhProgram_t* pgm; + EhProgramPlaceHolder_t pgm; + EhProgram_t* cached_pgm; uint64_t personality; friend struct EhProgramComparator_t; @@ -232,27 +260,27 @@ void split_eh_frame_impl_t<ptrsize>::build_ir() const { bool operator() (const whole_pgm_t& lhs, const whole_pgm_t& rhs) { - const auto &a=*(lhs.pgm); - const auto &b=*(rhs.pgm); + const auto &a=(lhs.pgm); + const auto &b=(rhs.pgm); if(lhs.hashcode == rhs.hashcode) return make_tuple( - a.GetCIEProgram(), - a.GetFDEProgram(), - a.GetCodeAlignmentFactor(), - a.GetDataAlignmentFactor(), - a.GetReturnRegNumber(), - a.GetPointerSize(), + a.getCIEProgram(), + a.getFDEProgram(), + a.getCodeAlignmentFactor(), + a.getDataAlignmentFactor(), + a.getReturnRegNumber(), + a.getPointerSize(), lhs.personality ) < make_tuple( - b.GetCIEProgram(), - b.GetFDEProgram(), - b.GetCodeAlignmentFactor(), - b.GetDataAlignmentFactor(), - b.GetReturnRegNumber(), - b.GetPointerSize(), + b.getCIEProgram(), + b.getFDEProgram(), + b.getCodeAlignmentFactor(), + b.getDataAlignmentFactor(), + b.getReturnRegNumber(), + b.getPointerSize(), rhs.personality ); else @@ -268,17 +296,7 @@ void split_eh_frame_impl_t<ptrsize>::build_ir() const // find the right cie and fde, and build the IR from those for this instruction. auto build_ir_insn=[&](Instruction_t* insn) -> void { - /* - const auto tofind=fde_contents_t<ptrsize>( insn->GetAddress()->GetVirtualOffset(), insn->GetAddress()->GetVirtualOffset()+1 ); - const auto fie_it=fdes.find(tofind); - */ - const auto find_addr=insn->GetAddress()->GetVirtualOffset(); - /* - too slow - const auto finder=[&](const shared_ptr<FDEContents_t>& fde) -> bool - { return fde->getStartAddress() <= find_addr && find_addr < fde->getEndAddress(); }; - const auto fie_ptr_it=find_if ( ALLOF(*fdes), finder); - */ + const auto find_addr=insn->getAddress()->getVirtualOffset(); static auto fie_ptr=shared_ptr<FDEContents_t>(); static auto cie_instructions=shared_ptr<EHProgramInstructionVector_t>(); static auto fde_instructions=shared_ptr<EHProgramInstructionVector_t>(); @@ -303,18 +321,17 @@ void split_eh_frame_impl_t<ptrsize>::build_ir() const if(getenv("EHIR_VERBOSE")!=NULL) { - cout<<hex<<insn->GetAddress()->GetVirtualOffset()<<":" - <<insn->GetBaseID()<<":"<<insn->getDisassembly()<<" -> "<<endl; - //fie_it->GetCIE().print(); + cout<<hex<<insn->getAddress()->getVirtualOffset()<<":" + <<insn->getBaseID()<<":"<<insn->getDisassembly()<<" -> "<<endl; fie_ptr->print(); } const auto fde_addr=fie_ptr->getStartAddress(); - const auto caf=fie_ptr->getCIE().getCAF(); - const auto daf=fie_ptr->getCIE().getDAF(); - const auto return_reg=fie_ptr->getCIE().getReturnRegister(); + const auto caf=(uint8_t)fie_ptr->getCIE().getCAF(); + const auto daf=(int8_t)fie_ptr->getCIE().getDAF(); + const auto return_reg=(int8_t)fie_ptr->getCIE().getReturnRegister(); const auto personality=fie_ptr->getCIE().getPersonality(); - const auto insn_addr=insn->GetAddress()->GetVirtualOffset(); + const auto insn_addr=insn->getAddress()->getVirtualOffset(); auto import_pgm = [&](EhProgramListing_t& out_pgm_final, const shared_ptr<EHProgramInstructionVector_t> &in_pgm_instructions_ptr) -> void { @@ -354,8 +371,6 @@ void split_eh_frame_impl_t<ptrsize>::build_ir() const } else { - // string to_push(insn.GetBytes().begin(),insn.GetBytes().end()); - // out_pgm.push_back(to_push); out_pgm.push_back(insn_ptr); } @@ -372,21 +387,22 @@ void split_eh_frame_impl_t<ptrsize>::build_ir() const ); }; - // build an eh program on the stack; - auto ehpgm=EhProgram_t(BaseObj_t::NOT_IN_DATABASE,caf,daf,return_reg, ptrsize); - import_pgm(ehpgm.GetCIEProgram(), cie_instructions); - import_pgm(ehpgm.GetFDEProgram(), fde_instructions); + // build an eh program on the stack; + // + auto ehpgm=EhProgramPlaceHolder_t({caf,daf,return_reg, ptrsize, {}, {}}); + import_pgm(ehpgm.cie_program, cie_instructions); + import_pgm(ehpgm.fde_program, fde_instructions); - if(getenv("EHIR_VERBOSE")!=NULL) - ehpgm.print(); + //if(getenv("EHIR_VERBOSE")!=NULL) + // ehpgm.print(); // see if we've already built this one. - auto ehpgm_it = eh_program_cache.find(whole_pgm_t(&ehpgm, personality)) ; + auto ehpgm_it = eh_program_cache.find(whole_pgm_t(ehpgm, nullptr, personality)) ; if(ehpgm_it != eh_program_cache.end()) { // yes, use the cached program. - insn->SetEhProgram(ehpgm_it->getProgram()); + insn->setEhProgram(ehpgm_it->getCachedProgram()); if(getenv("EHIR_VERBOSE")!=NULL) cout<<"Re-using existing Program!"<<endl; reusedpgms++; @@ -398,19 +414,21 @@ void split_eh_frame_impl_t<ptrsize>::build_ir() const cout<<"Allocating new Program!"<<endl; // allocate a new pgm in the heap so we can give it to the IR. + /* auto newehpgm=new EhProgram_t(ehpgm); // copy constructor assert(newehpgm); - firp->GetAllEhPrograms().insert(newehpgm); + firp->getAllEhPrograms().insert(newehpgm); + insn->setEhProgram(newehpgm); + */ + auto newehpgm=firp->addEhProgram(insn, ehpgm.caf, ehpgm.daf,ehpgm.rr, ehpgm.ptrsize, ehpgm.cie_program, ehpgm.fde_program); // allocate a relocation for the personality and give it to the IR. - auto personality_scoop=firp->FindScoop(personality); + auto personality_scoop=firp->findScoop(personality); auto personality_insn_it=offset_to_insn_map.find(personality); auto personality_insn=personality_insn_it==offset_to_insn_map.end() ? (Instruction_t*)NULL : personality_insn_it->second; auto personality_obj = personality_scoop ? (BaseObj_t*)personality_scoop : (BaseObj_t*)personality_insn; - auto addend= personality_scoop ? personality - personality_scoop->GetStart()->GetVirtualOffset() : 0; - auto newreloc=new Relocation_t(BaseObj_t::NOT_IN_DATABASE, 0, "personality", personality_obj, addend); + auto addend= personality_scoop ? personality - personality_scoop->getStart()->getVirtualOffset() : 0; assert(personality==0 || personality_obj!=NULL); - assert(newreloc); if(personality_obj==NULL) { @@ -421,26 +439,28 @@ void split_eh_frame_impl_t<ptrsize>::build_ir() const { if(getenv("EHIR_VERBOSE")!=NULL) cout<<"Found personality scoop: 0x"<<hex<<personality<<" -> " - <<personality_scoop->GetName()<<"+0x"<<hex<<addend<<endl; + <<personality_scoop->getName()<<"+0x"<<hex<<addend<<endl; } else if(personality_insn) { if(getenv("EHIR_VERBOSE")!=NULL) cout<<"Found personality insn: 0x"<<hex<<personality<<" -> " - <<personality_insn->GetBaseID()<<":"<<personality_insn->getDisassembly()<<endl; + <<personality_insn->getBaseID()<<":"<<personality_insn->getDisassembly()<<endl; } else assert(0); - newehpgm->GetRelocations().insert(newreloc); - firp->GetRelocations().insert(newreloc); - - - // record for this insn - insn->SetEhProgram(newehpgm); + /* + auto newreloc=new Relocation_t(BaseObj_t::NOT_IN_DATABASE, 0, "personality", personality_obj, addend); + assert(newreloc); + newehpgm->getRelocations().insert(newreloc); + firp->getRelocations().insert(newreloc); + */ + auto newreloc=firp->addNewRelocation(newehpgm,0, "personality", personality_obj, addend); + (void)newreloc; // not used, just give it to the IR // update cache. - eh_program_cache.insert(whole_pgm_t(newehpgm,personality)); + eh_program_cache.insert( whole_pgm_t(ehpgm,newehpgm,personality)); } // build the IR from the FDE. @@ -450,25 +470,25 @@ void split_eh_frame_impl_t<ptrsize>::build_ir() const { if(getenv("EHIR_VERBOSE")!=NULL) { - cout<<hex<<insn->GetAddress()->GetVirtualOffset()<<":" - <<insn->GetBaseID()<<":"<<insn->getDisassembly()<<" has no FDE "<<endl; + cout<<hex<<insn->getAddress()->getVirtualOffset()<<":" + <<insn->getBaseID()<<":"<<insn->getDisassembly()<<" has no FDE "<<endl; } } }; - +#if 0 auto remove_reloc=[&](Relocation_t* r) -> void { - firp->GetRelocations().erase(r); + firp->getRelocations().erase(r); delete r; }; auto remove_address=[&](AddressID_t* a) -> void { - firp->GetAddresses().erase(a); - for(auto &r : a->GetRelocations()) remove_reloc(r); - for(auto &r : firp->GetRelocations()) assert(r->GetWRT() != a); + firp->getAddresses().erase(a); + for(auto &r : a->getRelocations()) remove_reloc(r); + for(auto &r : firp->getRelocations()) assert(r->getWRT() != a); delete a; }; @@ -476,48 +496,40 @@ void split_eh_frame_impl_t<ptrsize>::build_ir() const { if(s==NULL) return; - firp->GetDataScoops().erase(s); - remove_address(s->GetStart()); - remove_address(s->GetEnd()); - for(auto &r : s->GetRelocations()) remove_reloc(r); - for(auto &r : firp->GetRelocations()) assert(r->GetWRT() != s); + firp->getDataScoops().erase(s); + remove_address(s->getStart()); + remove_address(s->getEnd()); + for(auto &r : s->getRelocations()) remove_reloc(r); + for(auto &r : firp->getRelocations()) assert(r->getWRT() != s); delete s; }; +#endif - for(Instruction_t* i : firp->GetInstructions()) + for(Instruction_t* i : firp->getInstructions()) { build_ir_insn(i); } - cout<<"# ATTRIBUTE Split_Exception_Handler::total_eh_programs_created="<<dec<<firp->GetAllEhPrograms().size()<<endl; + cout<<"# ATTRIBUTE Split_Exception_Handler::total_eh_programs_created="<<dec<<firp->getAllEhPrograms().size()<<endl; cout<<"# ATTRIBUTE Split_Exception_Handler::total_eh_programs_reused="<<dec<<reusedpgms<<endl; - cout<<"# ATTRIBUTE Split_Exception_Handler::total_eh_programs="<<dec<<firp->GetAllEhPrograms().size()+reusedpgms<<endl; + cout<<"# ATTRIBUTE Split_Exception_Handler::total_eh_programs="<<dec<<firp->getAllEhPrograms().size()+reusedpgms<<endl; cout<<"# ATTRIBUTE Split_Exception_Handler::pct_eh_programs="<<std::fixed - <<((float)firp->GetAllEhPrograms().size()/((float)firp->GetAllEhPrograms().size()+reusedpgms))*100.00 + <<((float)firp->getAllEhPrograms().size()/((float)firp->getAllEhPrograms().size()+reusedpgms))*100.00 <<"%" <<endl; cout<<"# ATTRIBUTE Split_Exception_Handler::pct_eh_programs_reused="<<std::fixed - <<((float)reusedpgms/((float)firp->GetAllEhPrograms().size()+reusedpgms))*100.00 + <<((float)reusedpgms/((float)firp->getAllEhPrograms().size()+reusedpgms))*100.00 <<"%"<<endl; - remove_scoop(eh_frame_scoop); - remove_scoop(eh_frame_hdr_scoop); - remove_scoop(gcc_except_table_scoop); + firp->removeScoop(eh_frame_scoop); + firp->removeScoop(eh_frame_hdr_scoop); + firp->removeScoop(gcc_except_table_scoop); } template <int ptrsize> -libIRDB::Instruction_t* split_eh_frame_impl_t<ptrsize>::find_lp(libIRDB::Instruction_t* i) const +Instruction_t* split_eh_frame_impl_t<ptrsize>::find_lp(Instruction_t* i) const { - const auto find_addr=i->GetAddress()->GetVirtualOffset(); - //const auto tofind=fde_contents_t<ptrsize>( i->GetAddress()->GetVirtualOffset(), i->GetAddress()->GetVirtualOffset()+1); - //const auto fde_it=fdes.find(tofind); - /* too slow - const auto fde_ptr_it=find_if - ( - ALLOF(*fdes), - [&](const shared_ptr<FDEContents_t>& fde) { return fde->getStartAddress() <= find_addr && find_addr < fde->getEndAddress(); } - ); - */ + const auto find_addr=i->getAddress()->getVirtualOffset(); const auto fde_ptr=eh_frame_parser->findFDE(find_addr); if(fde_ptr==nullptr) @@ -566,21 +578,20 @@ split_eh_frame_impl_t<ptrsize>::split_eh_frame_impl_t(FileIR_t* p_firp) // function to find a scoop by name. auto lookup_scoop_by_name=[&](const string &the_name) -> DataScoop_t* { - //auto scoop_it=find_if(ALLOF(firp->GetDataScoops()), [the_name](DataScoop_t* scoop) const auto scoop_it=find_if( - firp->GetDataScoops().begin(), - firp->GetDataScoops().end(), + firp->getDataScoops().begin(), + firp->getDataScoops().end(), [the_name](DataScoop_t* scoop) { - return scoop->GetName()==the_name; + return scoop->getName()==the_name; }); - if(scoop_it!=firp->GetDataScoops().end()) + if(scoop_it!=firp->getDataScoops().end()) return *scoop_it; return NULL; }; - auto scoop_address=[&](const DataScoop_t* p) -> uint64_t { return p==NULL ? 0 : p->GetStart()->GetVirtualOffset(); }; - auto scoop_contents=[&](const DataScoop_t* p) -> string { return p==NULL ? "" : p->GetContents(); }; + auto scoop_address=[&](const DataScoop_t* p) -> uint64_t { return p==NULL ? 0 : p->getStart()->getVirtualOffset(); }; + auto scoop_contents=[&](const DataScoop_t* p) -> string { return p==NULL ? "" : p->getContents(); }; eh_frame_scoop=lookup_scoop_by_name(".eh_frame"); eh_frame_hdr_scoop=lookup_scoop_by_name(".eh_frame_hdr"); @@ -602,7 +613,7 @@ split_eh_frame_impl_t<ptrsize>::split_eh_frame_impl_t(FileIR_t* p_firp) unique_ptr<split_eh_frame_t> split_eh_frame_t::factory(FileIR_t *firp) { - if( firp->GetArchitectureBitWidth()==64) + if( firp->getArchitectureBitWidth()==64) return unique_ptr<split_eh_frame_t>(new split_eh_frame_impl_t<8>(firp)); else return unique_ptr<split_eh_frame_t>(new split_eh_frame_impl_t<4>(firp)); diff --git a/ir_builders/split_eh_frame.hpp b/ir_builders/split_eh_frame.hpp index 0e0d69063..2e1a2b08e 100644 --- a/ir_builders/split_eh_frame.hpp +++ b/ir_builders/split_eh_frame.hpp @@ -1,7 +1,7 @@ #ifndef eh_frame_hpp #define eh_frame_hpp -#include <libIRDB-core.hpp> +#include <irdb-core> #include <iostream> #include <iomanip> #include <fstream> @@ -20,7 +20,7 @@ -using OffsetMap_t = std::map<libIRDB::virtual_offset_t, libIRDB::Instruction_t*>; +using OffsetMap_t = std::map<IRDB_SDK::VirtualOffset_t, IRDB_SDK::Instruction_t*>; class split_eh_frame_t { @@ -28,9 +28,9 @@ class split_eh_frame_t virtual void build_ir() const =0; virtual void print() const=0; - virtual libIRDB::Instruction_t* find_lp(libIRDB::Instruction_t*) const =0; + virtual IRDB_SDK::Instruction_t* find_lp(IRDB_SDK::Instruction_t*) const =0; - static std::unique_ptr<split_eh_frame_t> factory(libIRDB::FileIR_t *firp); + static std::unique_ptr<split_eh_frame_t> factory(IRDB_SDK::FileIR_t *firp); }; @@ -39,10 +39,10 @@ class split_eh_frame_impl_t : public split_eh_frame_t { private: - libIRDB::FileIR_t* firp; - libIRDB::DataScoop_t* eh_frame_scoop; - libIRDB::DataScoop_t* eh_frame_hdr_scoop; - libIRDB::DataScoop_t* gcc_except_table_scoop; + IRDB_SDK::FileIR_t* firp; + IRDB_SDK::DataScoop_t* eh_frame_scoop; + IRDB_SDK::DataScoop_t* eh_frame_hdr_scoop; + IRDB_SDK::DataScoop_t* gcc_except_table_scoop; OffsetMap_t offset_to_insn_map; std::unique_ptr<const EHP::EHFrameParser_t> eh_frame_parser; @@ -53,43 +53,43 @@ class split_eh_frame_impl_t : public split_eh_frame_t bool lsda_call_site_appliesTo ( const EHP::LSDACallSite_t& cs, - const libIRDB::Instruction_t* insn + const IRDB_SDK::Instruction_t* insn ) const; void lsda_call_site_build_ir ( const EHP::LSDACallSite_t& cs, - libIRDB::Instruction_t* insn, + IRDB_SDK::Instruction_t* insn, /* const std::vector<lsda_type_table_entry_t <ptrsize> > &*/ std::shared_ptr<EHP::TypeTableVector_t> type_table_ptr, const uint8_t& tt_encoding ) const; void lsda_build_ir ( const EHP::LSDA_t& lsda, - libIRDB::Instruction_t* insn + IRDB_SDK::Instruction_t* insn ) const; bool fde_contents_appliesTo ( const EHP::FDEContents_t& fde, - const libIRDB::Instruction_t* insn + const IRDB_SDK::Instruction_t* insn ) const; void fde_contents_build_ir ( const EHP::FDEContents_t& fde, - libIRDB::Instruction_t* insn + IRDB_SDK::Instruction_t* insn ) const; public: - split_eh_frame_impl_t(libIRDB::FileIR_t* p_firp); + split_eh_frame_impl_t(IRDB_SDK::FileIR_t* p_firp); void print() const; void build_ir() const; - libIRDB::Instruction_t* find_lp(libIRDB::Instruction_t*) const ; + IRDB_SDK::Instruction_t* find_lp(IRDB_SDK::Instruction_t*) const ; }; -void split_eh_frame(libIRDB::FileIR_t* firp); +void split_eh_frame(IRDB_SDK::FileIR_t* firp); #endif diff --git a/libElfDep/include/libElfDep.hpp b/libElfDep/include/libElfDep.hpp index b4444eba3..5646a89ba 100644 --- a/libElfDep/include/libElfDep.hpp +++ b/libElfDep/include/libElfDep.hpp @@ -16,26 +16,26 @@ class ElfDependencies_t : public Transform { public: - ElfDependencies_t(FileIR_t* firp); + ElfDependencies_t(IRDB_SDK::FileIR_t* firp); void prependLibraryDepedencies(const string& libName) { transformer->prependLibraryDepedencies(libName); } void appendLibraryDepedencies(const string& libName) { transformer->appendLibraryDepedencies(libName); } // return scoop and offset - pair<DataScoop_t*,int> appendGotEntry(const string &symbolName) { return transformer->appendGotEntry(symbolName); } + pair<IRDB_SDK::DataScoop_t*,int> appendGotEntry(const string &symbolName) { return transformer->appendGotEntry(symbolName); } // return instruction that's the plt entry. - Instruction_t* appendPltEntry(const string &symbolName) { return transformer->appendPltEntry(symbolName); } + IRDB_SDK::Instruction_t* appendPltEntry(const string &symbolName) { return transformer->appendPltEntry(symbolName); } private: class ElfDependenciesBase_t : public Transform { public: - ElfDependenciesBase_t(FileIR_t* firp) : Transform(NULL, firp, NULL) {} + ElfDependenciesBase_t(IRDB_SDK::FileIR_t* firp) : Transform(NULL, firp, NULL) {} virtual void prependLibraryDepedencies(const string &libraryName)=0; virtual void appendLibraryDepedencies(const string &libraryName)=0; - virtual pair<DataScoop_t*,int> appendGotEntry(const string &name)=0; - virtual Instruction_t* appendPltEntry(const string &name)=0; + virtual pair<IRDB_SDK::DataScoop_t*,int> appendGotEntry(const string &name)=0; + virtual IRDB_SDK::Instruction_t* appendPltEntry(const string &name)=0; }; @@ -44,19 +44,18 @@ class ElfDependencies_t : public Transform { public: - ElfDependenciesImpl_t(FileIR_t* fipr); + ElfDependenciesImpl_t(IRDB_SDK::FileIR_t* fipr); virtual void prependLibraryDepedencies(const string& libraryName); virtual void appendLibraryDepedencies(const string& libraryName); - virtual pair<DataScoop_t*,int> appendGotEntry(const string& name); - virtual Instruction_t* appendPltEntry(const string& name); + virtual pair<IRDB_SDK::DataScoop_t*,int> appendGotEntry(const string& name); + virtual IRDB_SDK::Instruction_t* appendPltEntry(const string& name); private: bool add_dl_support(); - Instruction_t* find_runtime_resolve(DataScoop_t* gotplt_scoop); - DataScoop_t* add_got_entry(const std::string& name); - //bool add_got_entries(); + IRDB_SDK::Instruction_t* find_runtime_resolve(IRDB_SDK::DataScoop_t* gotplt_scoop); + IRDB_SDK::DataScoop_t* add_got_entry(const std::string& name); bool add_libdl_as_needed_support(string libName); bool execute(); diff --git a/libElfDep/src/SConscript b/libElfDep/src/SConscript index 9da08bd9c..b0d62b5a7 100644 --- a/libElfDep/src/SConscript +++ b/libElfDep/src/SConscript @@ -9,6 +9,7 @@ myenv.Replace(SECURITY_TRANSFORMS_HOME=os.environ['SECURITY_TRANSFORMS_HOME']) files="elfdep.cpp" cpppath=''' + $IRDB_SDK/include $SECURITY_TRANSFORMS_HOME/libIRDB/include $SECURITY_TRANSFORMS_HOME/libtransform/include $SECURITY_TRANSFORMS_HOME/libEXEIO/include/ diff --git a/libElfDep/src/elfdep.cpp b/libElfDep/src/elfdep.cpp index b2d3bcd12..0f8499253 100644 --- a/libElfDep/src/elfdep.cpp +++ b/libElfDep/src/elfdep.cpp @@ -40,106 +40,106 @@ using namespace libTransform; // static helpers // use this to determine whether a scoop has a given name. -static struct ScoopFinder : binary_function<const DataScoop_t*,const string,bool> +static struct ScoopFinder : binary_function<const IRDB_SDK::DataScoop_t*,const string,bool> { // declare a simple scoop finder function that finds scoops by name - bool operator()(const DataScoop_t* scoop, const string& name) const + bool operator()(const IRDB_SDK::DataScoop_t* scoop, const string& name) const { - return (scoop->GetName() == name); + return (scoop->getName() == name); }; } finder; -static DataScoop_t* find_scoop(FileIR_t *firp,const string &name) +static IRDB_SDK::DataScoop_t* find_scoop(IRDB_SDK::FileIR_t *firp,const string &name) { - auto it=find_if(firp->GetDataScoops().begin(), firp->GetDataScoops().end(), bind2nd(finder, name)) ; - if( it != firp->GetDataScoops().end() ) + auto it=find_if(firp->getDataScoops().begin(), firp->getDataScoops().end(), bind2nd(finder, name)) ; + if( it != firp->getDataScoops().end() ) return *it; return NULL; }; -static unsigned int add_to_scoop(const string &str, DataScoop_t* scoop) +static unsigned int add_to_scoop(const string &str, IRDB_SDK::DataScoop_t* scoop) { // assert that this scoop is unpinned. may need to enable --step move_globals --step-option move_globals:--cfi - assert(scoop->GetStart()->GetVirtualOffset()==0); + assert(scoop->getStart()->getVirtualOffset()==0); int len=str.length(); - scoop->SetContents(scoop->GetContents()+str); - virtual_offset_t oldend=scoop->GetEnd()->GetVirtualOffset(); + scoop->setContents(scoop->getContents()+str); + virtual_offset_t oldend=scoop->getEnd()->getVirtualOffset(); virtual_offset_t newend=oldend+len; - scoop->GetEnd()->SetVirtualOffset(newend); + scoop->getEnd()->setVirtualOffset(newend); return oldend+1; }; template<int ptrsize> -static void insert_into_scoop_at(const string &str, DataScoop_t* scoop, FileIR_t* firp, const unsigned int at) +static void insert_into_scoop_at(const string &str, IRDB_SDK::DataScoop_t* scoop, IRDB_SDK::FileIR_t* firp, const unsigned int at) { // assert that this scoop is unpinned. may need to enable --step move_globals --step-option move_globals:--cfi - assert(scoop->GetStart()->GetVirtualOffset()==0); + assert(scoop->getStart()->getVirtualOffset()==0); int len=str.length(); - string new_scoop_contents=scoop->GetContents(); + string new_scoop_contents=scoop->getContents(); new_scoop_contents.insert(at,str); - scoop->SetContents(new_scoop_contents); + scoop->setContents(new_scoop_contents); - virtual_offset_t oldend=scoop->GetEnd()->GetVirtualOffset(); + virtual_offset_t oldend=scoop->getEnd()->getVirtualOffset(); virtual_offset_t newend=oldend+len; - scoop->GetEnd()->SetVirtualOffset(newend); + scoop->getEnd()->setVirtualOffset(newend); // update each reloc to point to the new location. - for_each(scoop->GetRelocations().begin(), scoop->GetRelocations().end(), [str,at](Relocation_t* reloc) + for_each(scoop->getRelocations().begin(), scoop->getRelocations().end(), [str,at](IRDB_SDK::Relocation_t* reloc) { - if((unsigned int)reloc->GetOffset()>=at) - reloc->SetOffset(reloc->GetOffset()+str.size()); + if((unsigned int)reloc->getOffset()>=at) + reloc->setOffset(reloc->getOffset()+str.size()); }); // check relocations for pointers to this object. // we'll update dataptr_to_scoop relocs, but nothing else // so assert if we find something else - for_each(firp->GetRelocations().begin(), firp->GetRelocations().end(), [scoop](Relocation_t* reloc) + for_each(firp->getRelocations().begin(), firp->getRelocations().end(), [scoop](IRDB_SDK::Relocation_t* reloc) { - DataScoop_t* wrt=dynamic_cast<DataScoop_t*>(reloc->GetWRT()); - assert(wrt != scoop || reloc->GetType()=="dataptr_to_scoop"); + auto wrt=dynamic_cast<libIRDB::DataScoop_t*>(reloc->getWRT()); + assert(wrt != scoop || reloc->getType()=="dataptr_to_scoop"); }); // for each scoop - for_each(firp->GetDataScoops().begin(), firp->GetDataScoops().end(), [&str,scoop,firp,at](DataScoop_t* scoop_to_update) + for_each(firp->getDataScoops().begin(), firp->getDataScoops().end(), [&str,scoop,firp,at](IRDB_SDK::DataScoop_t* scoop_to_update) { // for each relocation for that scoop - for_each(scoop_to_update->GetRelocations().begin(), scoop_to_update->GetRelocations().end(), [&str,scoop,firp,scoop_to_update,at](Relocation_t* reloc) + for_each(scoop_to_update->getRelocations().begin(), scoop_to_update->getRelocations().end(), [&str,scoop,firp,scoop_to_update,at](IRDB_SDK::Relocation_t* reloc) { // if it's a reloc that's wrt scoop - DataScoop_t* wrt=dynamic_cast<DataScoop_t*>(reloc->GetWRT()); + auto wrt=dynamic_cast<libIRDB::DataScoop_t*>(reloc->getWRT()); if(wrt==scoop) { // then we need to update the scoop - if(reloc->GetType()=="dataptr_to_scoop") + if(reloc->getType()=="dataptr_to_scoop") { - string contents=scoop_to_update->GetContents(); + string contents=scoop_to_update->getContents(); // subtract the stringsize from the (implicitly stored) addend // taking pointer size into account. switch(ptrsize) { case 4: { - unsigned int val=*((unsigned int*)&contents.c_str()[reloc->GetOffset()]); + unsigned int val=*((unsigned int*)&contents.c_str()[reloc->getOffset()]); if(val>=at) val +=str.size(); - contents.replace(reloc->GetOffset(), ptrsize, (const char*)&val, ptrsize); + contents.replace(reloc->getOffset(), ptrsize, (const char*)&val, ptrsize); break; } case 8: { - unsigned long long val=*((long long*)&contents.c_str()[reloc->GetOffset()]); + unsigned long long val=*((long long*)&contents.c_str()[reloc->getOffset()]); if(val>=at) val +=str.size(); - contents.replace(reloc->GetOffset(), ptrsize, (const char*)&val, ptrsize); + contents.replace(reloc->getOffset(), ptrsize, (const char*)&val, ptrsize); break; } default: assert(0); } - scoop_to_update->SetContents(contents); + scoop_to_update->setContents(contents); } } @@ -149,7 +149,7 @@ static void insert_into_scoop_at(const string &str, DataScoop_t* scoop, FileIR_t }; template<int ptrsize> -static void prefix_scoop(const string &str, DataScoop_t* scoop, FileIR_t* firp) +static void prefix_scoop(const string &str, IRDB_SDK::DataScoop_t* scoop, IRDB_SDK::FileIR_t* firp) { insert_into_scoop_at<ptrsize>(str,scoop,firp,0); }; @@ -160,15 +160,15 @@ static void prefix_scoop(const string &str, DataScoop_t* scoop, FileIR_t* firp) // constructors -ElfDependencies_t::ElfDependencies_t(FileIR_t* firp) +ElfDependencies_t::ElfDependencies_t(IRDB_SDK::FileIR_t* firp) : Transform(NULL,firp,NULL) { typedef ElfDependencies_t::ElfDependenciesImpl_t<Elf64_Sym, Elf64_Rela, Elf64_Dyn, R_X86_64_GLOB_DAT, 32, 8> ElfDependencies64_t; typedef ElfDependencies_t::ElfDependenciesImpl_t<Elf32_Sym, Elf32_Rel, Elf32_Dyn, R_386_GLOB_DAT, 8, 4> ElfDependencies32_t; - if(firp->GetArchitectureBitWidth()==32) + if(firp->getArchitectureBitWidth()==32) transformer.reset(new ElfDependencies32_t(firp)); - else if(firp->GetArchitectureBitWidth()==64) + else if(firp->getArchitectureBitWidth()==64) transformer.reset(new ElfDependencies64_t(firp)); else assert(0); @@ -176,21 +176,21 @@ ElfDependencies_t::ElfDependencies_t(FileIR_t* firp) template<typename T_Elf_Sym, typename T_Elf_Rela, typename T_Elf_Dyn, int reloc_type, int rela_shift, int ptrsize> -ElfDependencies_t::ElfDependenciesImpl_t<T_Elf_Sym,T_Elf_Rela,T_Elf_Dyn,reloc_type,rela_shift,ptrsize>::ElfDependenciesImpl_t(FileIR_t* firp) +ElfDependencies_t::ElfDependenciesImpl_t<T_Elf_Sym,T_Elf_Rela,T_Elf_Dyn,reloc_type,rela_shift,ptrsize>::ElfDependenciesImpl_t(IRDB_SDK::FileIR_t* firp) : ElfDependencies_t::ElfDependenciesBase_t(firp) { } template<typename T_Elf_Sym, typename T_Elf_Rela, typename T_Elf_Dyn, int reloc_type, int rela_shift, int ptrsize> -pair<DataScoop_t*,int> ElfDependencies_t::ElfDependenciesImpl_t<T_Elf_Sym,T_Elf_Rela,T_Elf_Dyn,reloc_type,rela_shift,ptrsize>::appendGotEntry(const string &name) +pair<IRDB_SDK::DataScoop_t*,int> ElfDependencies_t::ElfDependenciesImpl_t<T_Elf_Sym,T_Elf_Rela,T_Elf_Dyn,reloc_type,rela_shift,ptrsize>::appendGotEntry(const string &name) { auto got_scoop=add_got_entry(name); return {got_scoop,0}; } template<typename T_Elf_Sym, typename T_Elf_Rela, typename T_Elf_Dyn, int reloc_type, int rela_shift, int ptrsize> -Instruction_t* ElfDependencies_t::ElfDependenciesImpl_t<T_Elf_Sym,T_Elf_Rela,T_Elf_Dyn,reloc_type,rela_shift,ptrsize>::appendPltEntry(const string &name) +IRDB_SDK::Instruction_t* ElfDependencies_t::ElfDependenciesImpl_t<T_Elf_Sym,T_Elf_Rela,T_Elf_Dyn,reloc_type,rela_shift,ptrsize>::appendPltEntry(const string &name) { static int labelcounter=0; @@ -204,9 +204,9 @@ Instruction_t* ElfDependencies_t::ElfDependenciesImpl_t<T_Elf_Sym,T_Elf_Rela,T_E auto newreloc=new Relocation_t(BaseObj_t::NOT_IN_DATABASE, 0, "pcrel", got_scoop); - newinsn->GetRelocations().insert(newreloc); - getFileIR()->GetRelocations().insert(newreloc); - newinsn->GetAddress()->SetFileID(getFileIR()->GetFile()->GetBaseID()); + dynamic_cast<libIRDB::Instruction_t*>(newinsn)->GetRelocations().insert(newreloc); + dynamic_cast<libIRDB::FileIR_t*>(getFileIR())->GetRelocations().insert(newreloc); + newinsn->getAddress()->setFileID(getFileIR()->getFile()->getBaseID()); return newinsn; } @@ -219,28 +219,28 @@ Instruction_t* ElfDependencies_t::ElfDependenciesImpl_t<T_Elf_Sym,T_Elf_Rela,T_E // we need a use case to test this code -- it was copied from CFI. template<typename T_Elf_Sym, typename T_Elf_Rela, typename T_Elf_Dyn, int reloc_type, int rela_shift, int ptrsize> -Instruction_t* ElfDependencies_t::ElfDependenciesImpl_t<T_Elf_Sym,T_Elf_Rela,T_Elf_Dyn,reloc_type,rela_shift,ptrsize>::find_runtime_resolve(DataScoop_t* gotplt_scoop) +IRDB_SDK::Instruction_t* ElfDependencies_t::ElfDependenciesImpl_t<T_Elf_Sym,T_Elf_Rela,T_Elf_Dyn,reloc_type,rela_shift,ptrsize>::find_runtime_resolve(IRDB_SDK::DataScoop_t* gotplt_scoop) { const auto firp=getFileIR(); // find any data_to_insn_ptr reloc for the gotplt scoop - auto it=find_if(gotplt_scoop->GetRelocations().begin(), gotplt_scoop->GetRelocations().end(), [](Relocation_t* reloc) + auto it=find_if(gotplt_scoop->getRelocations().begin(), gotplt_scoop->getRelocations().end(), [](IRDB_SDK::Relocation_t* reloc) { - return reloc->GetType()=="data_to_insn_ptr"; + return reloc->getType()=="data_to_insn_ptr"; }); // there _should_ be one. - assert(it!=gotplt_scoop->GetRelocations().end()); + assert(it!=gotplt_scoop->getRelocations().end()); Relocation_t* reloc=*it; - Instruction_t* wrt=dynamic_cast<Instruction_t*>(reloc->GetWRT()); + auto wrt=dynamic_cast<Instruction_t*>(reloc->getWRT()); assert(wrt); // should be a WRT assert(wrt->getDisassembly().find("push ") != string::npos); // should be push K insn - return wrt->GetFallthrough(); // jump to the jump, or not.. doesn't matter. zopt will fix + return wrt->getFallthrough(); // jump to the jump, or not.. doesn't matter. zopt will fix } template<typename T_Elf_Sym, typename T_Elf_Rela, typename T_Elf_Dyn, int reloc_type, int rela_shift, int ptrsize> -DataScoop_t* ElfDependencies_t::ElfDependenciesImpl_t<T_Elf_Sym,T_Elf_Rela,T_Elf_Dyn,reloc_type,rela_shift,ptrsize>::add_got_entry(const std::string& name) +IRDB_SDK::DataScoop_t* ElfDependencies_t::ElfDependenciesImpl_t<T_Elf_Sym,T_Elf_Rela,T_Elf_Dyn,reloc_type,rela_shift,ptrsize>::add_got_entry(const std::string& name) { - const auto firp=getFileIR(); + const auto firp=dynamic_cast<libIRDB::FileIR_t*>(getFileIR()); // find relevant scoops auto dynamic_scoop=find_scoop(firp,".dynamic"); // auto gotplt_scoop=find_scoop(firp,".got.plt"); @@ -252,7 +252,7 @@ DataScoop_t* ElfDependencies_t::ElfDependenciesImpl_t<T_Elf_Sym,T_Elf_Rela,T_Elf auto relscoop=relaplt_scoop!=NULL ? relaplt_scoop : relplt_scoop; auto gnu_version_scoop=find_scoop(firp,".gnu.version"); assert(gnu_version_scoop); - assert(gnu_version_scoop->GetStart()->GetVirtualOffset()==0); + assert(gnu_version_scoop->getStart()->getVirtualOffset()==0); if (!relscoop) throw std::logic_error("Cannot find rela.plt or rel.plt. Did you remember to use move_globals with --elf_tables?"); @@ -263,9 +263,9 @@ DataScoop_t* ElfDependencies_t::ElfDependenciesImpl_t<T_Elf_Sym,T_Elf_Rela,T_Elf // create a new, unpinned, rw+relro scoop that's an empty pointer. - AddressID_t* start_addr=new AddressID_t(BaseObj_t::NOT_IN_DATABASE, firp->GetFile()->GetBaseID(), 0); - AddressID_t* end_addr=new AddressID_t(BaseObj_t::NOT_IN_DATABASE, firp->GetFile()->GetBaseID(), ptrsize-1); - DataScoop_t* external_func_addr_scoop=new DataScoop_t(BaseObj_t::NOT_IN_DATABASE, + auto start_addr=new AddressID_t(BaseObj_t::NOT_IN_DATABASE, firp->getFile()->getBaseID(), 0); + auto end_addr=new AddressID_t(BaseObj_t::NOT_IN_DATABASE, firp->getFile()->getBaseID(), ptrsize-1); + auto external_func_addr_scoop=new DataScoop_t(BaseObj_t::NOT_IN_DATABASE, name, start_addr,end_addr, NULL, 6, true, new_got_entry_str); firp->GetAddresses().insert(start_addr); @@ -291,9 +291,9 @@ DataScoop_t* ElfDependencies_t::ElfDependenciesImpl_t<T_Elf_Sym,T_Elf_Rela,T_Elf // find the rela count. can't insert before that. int rela_count=0; - for(int i=0;i+sizeof(T_Elf_Dyn)<dynamic_scoop->GetSize(); i+=sizeof(T_Elf_Dyn)) + for(int i=0;i+sizeof(T_Elf_Dyn)<dynamic_scoop->getSize(); i+=sizeof(T_Elf_Dyn)) { - T_Elf_Dyn &dyn_entry=*(T_Elf_Dyn*)&dynamic_scoop->GetContents().c_str()[i]; + T_Elf_Dyn &dyn_entry=*(T_Elf_Dyn*)&dynamic_scoop->getContents().c_str()[i]; if(dyn_entry.d_tag==DT_RELACOUNT) // diff than rela size. { // add to the size @@ -314,15 +314,15 @@ DataScoop_t* ElfDependencies_t::ElfDependenciesImpl_t<T_Elf_Sym,T_Elf_Rela,T_Elf unsigned int at=rela_count*sizeof(T_Elf_Rela); insert_into_scoop_at<ptrsize>(dl_rel_str, relscoop, firp, at); - Relocation_t* dl_reloc=new Relocation_t(BaseObj_t::NOT_IN_DATABASE, at+((uintptr_t)&dl_rel.r_offset -(uintptr_t)&dl_rel), "dataptr_to_scoop", external_func_addr_scoop); - relscoop->GetRelocations().insert(dl_reloc); + auto dl_reloc=new Relocation_t(BaseObj_t::NOT_IN_DATABASE, at+((uintptr_t)&dl_rel.r_offset -(uintptr_t)&dl_rel), "dataptr_to_scoop", external_func_addr_scoop); + dynamic_cast<libIRDB::Instruction_t*>(relscoop)->GetRelocations().insert(dl_reloc); firp->GetRelocations().insert(dl_reloc); - for(int i=0;i+sizeof(T_Elf_Dyn)<dynamic_scoop->GetSize(); i+=sizeof(T_Elf_Dyn)) + for(int i=0;i+sizeof(T_Elf_Dyn)<dynamic_scoop->getSize(); i+=sizeof(T_Elf_Dyn)) { // cast the index'd c_str to an Elf_Dyn pointer and deref it to assign to a // reference structure. That way editing the structure directly edits the string. - T_Elf_Dyn &dyn_entry=*(T_Elf_Dyn*)&dynamic_scoop->GetContents().c_str()[i]; + T_Elf_Dyn &dyn_entry=*(T_Elf_Dyn*)&dynamic_scoop->getContents().c_str()[i]; if(dyn_entry.d_tag==DT_RELASZ) // add to the size dyn_entry.d_un.d_val+=sizeof(T_Elf_Rela); @@ -416,7 +416,7 @@ bool ElfDependencies_t::ElfDependenciesImpl_t<T_Elf_Sym,T_Elf_Rela,T_Elf_Dyn,rel template<typename T_Elf_Sym, typename T_Elf_Rela, typename T_Elf_Dyn, int reloc_type, int rela_shift, int ptrsize> void ElfDependencies_t::ElfDependenciesImpl_t<T_Elf_Sym,T_Elf_Rela,T_Elf_Dyn,reloc_type,rela_shift,ptrsize>::appendLibraryDepedencies(const string &libraryName) { - const auto firp=getFileIR(); + const auto firp=dynamic_cast<FileIR_t*>(getFileIR()); auto dynamic_scoop=find_scoop(firp,".dynamic"); auto dynstr_scoop=find_scoop(firp,".dynstr"); @@ -426,7 +426,7 @@ void ElfDependencies_t::ElfDependenciesImpl_t<T_Elf_Sym,T_Elf_Rela,T_Elf_Dyn,rel throw std::logic_error("Cannot change libraries in statically linked program"); // may need to enable --step move_globals --step-option move_globals:--cfi - if(dynamic_scoop->GetStart()->GetVirtualOffset()!=0) + if(dynamic_scoop->getStart()->getVirtualOffset()!=0) { cerr<<"Cannot find relocation-scoop pair: Did you enable '--step move_globals --step-option move_globals:--cfi' ? "<<endl; exit(1); @@ -449,9 +449,9 @@ void ElfDependencies_t::ElfDependenciesImpl_t<T_Elf_Sym,T_Elf_Rela,T_Elf_Dyn,rel while(1) { // assert we don't run off the end. - assert((index+1)*sizeof(T_Elf_Dyn) <= dynamic_scoop->GetContents().size()); + assert((index+1)*sizeof(T_Elf_Dyn) <= dynamic_scoop->getContents().size()); - const auto dyn_ptr=(T_Elf_Dyn*) & dynamic_scoop->GetContents().c_str()[index*sizeof(T_Elf_Dyn)]; + const auto dyn_ptr=(T_Elf_Dyn*) & dynamic_scoop->getContents().c_str()[index*sizeof(T_Elf_Dyn)]; if(memcmp(dyn_ptr,&null_dynamic_entry,sizeof(T_Elf_Dyn)) == 0 ) { @@ -460,14 +460,16 @@ void ElfDependencies_t::ElfDependenciesImpl_t<T_Elf_Sym,T_Elf_Rela,T_Elf_Dyn,rel for(auto i=0U; i<sizeof(T_Elf_Dyn); i++) { // copy new_dynamic_entry ontop of null entry. - dynamic_scoop->GetContents()[index*sizeof(T_Elf_Dyn) + i ] = ((char*)&new_dynamic_entry)[i]; + auto str=dynamic_scoop->getContents(); + str[index*sizeof(T_Elf_Dyn) + i ] = ((char*)&new_dynamic_entry)[i]; + dynamic_scoop->setContents(str); } // check if there's room for the new null entry - if((index+2)*sizeof(T_Elf_Dyn) <= dynamic_scoop->GetContents().size()) + if((index+2)*sizeof(T_Elf_Dyn) <= dynamic_scoop->getContents().size()) { /* yes */ - const auto next_entry=(T_Elf_Dyn*)&dynamic_scoop->GetContents().c_str()[(index+1)*sizeof(T_Elf_Dyn)]; + const auto next_entry=(T_Elf_Dyn*)&dynamic_scoop->getContents().c_str()[(index+1)*sizeof(T_Elf_Dyn)]; // assert it's actually null assert(memcmp(next_entry,&null_dynamic_entry,sizeof(T_Elf_Dyn)) == 0 ); } @@ -499,7 +501,7 @@ void ElfDependencies_t::ElfDependenciesImpl_t<T_Elf_Sym,T_Elf_Rela,T_Elf_Dyn,rel throw std::logic_error("Cannot change libraries in statically linked program"); // may need to enable --step move_globals --step-option move_globals:--cfi - if(dynamic_scoop->GetStart()->GetVirtualOffset()!=0) + if(dynamic_scoop->getStart()->getVirtualOffset()!=0) { cerr<<"Cannot find relocation-scoop pair: Did you enable '--step move_globals --step-option move_globals:--cfi' ? "<<endl; exit(1); diff --git a/libIRDB/include/cfg/BasicBlock.hpp b/libIRDB/include/cfg/BasicBlock.hpp index 7e6475280..3abf761d6 100644 --- a/libIRDB/include/cfg/BasicBlock.hpp +++ b/libIRDB/include/cfg/BasicBlock.hpp @@ -21,7 +21,7 @@ class BasicBlock_t; typedef std::set<BasicBlock_t*> BasicBlockSet_t; -typedef std::vector<Instruction_t*> InstructionVector_t; +typedef std::vector<IRDB_SDK::Instruction_t*> InstructionVector_t; class BasicBlock_t { @@ -37,7 +37,7 @@ class BasicBlock_t BasicBlockSet_t& GetSuccessors() { return successors; } BasicBlockSet_t& GetIndirectTargets() { return indirect_targets; } BasicBlock_t* GetFallthrough(); - BasicBlock_t* GetTarget(); + BasicBlock_t* getTarget(); // for const correctness if you aren't modifying. const InstructionVector_t& GetInstructions() const { return instructions; } @@ -48,13 +48,13 @@ class BasicBlock_t bool EndsInBranch(); bool EndsInIndirectBranch(); bool EndsInConditionalBranch(); - Instruction_t* GetBranchInstruction(); + IRDB_SDK::Instruction_t* GetBranchInstruction(); void dump(std::ostream &os=std::cout) const { os<<*this; } protected: - void BuildBlock( Instruction_t* insn, - const std::map<Instruction_t*,BasicBlock_t*> &insn2block_map + void BuildBlock( IRDB_SDK::Instruction_t* insn, + const std::map<IRDB_SDK::Instruction_t*,BasicBlock_t*> &insn2block_map ); diff --git a/libIRDB/include/cfg/CFG.hpp b/libIRDB/include/cfg/CFG.hpp index 8bf1d0b2f..f254fe734 100644 --- a/libIRDB/include/cfg/CFG.hpp +++ b/libIRDB/include/cfg/CFG.hpp @@ -24,9 +24,9 @@ typedef std::set<CFG_EdgeTypeEnum> CFG_EdgeType; class ControlFlowGraph_t { public: - ControlFlowGraph_t(Function_t* func); + ControlFlowGraph_t(IRDB_SDK::Function_t* func); BasicBlock_t* GetEntry() const { return entry; } - Function_t* GetFunction() const { return function; } + IRDB_SDK::Function_t* getFunction() const { return function; } BasicBlockSet_t& GetBlocks() { return blocks; } const BasicBlockSet_t& GetBlocks() const { return blocks; } void dump(std::ostream &os=std::cout) const { os<<*this; } @@ -35,15 +35,15 @@ class ControlFlowGraph_t private: // methods - void Build(Function_t *func); - void alloc_blocks(const InstructionSet_t &starts, map<Instruction_t*,BasicBlock_t*>& insn2block_map); - void build_blocks(const map<Instruction_t*,BasicBlock_t*>& insn2block_map); - void find_unblocked_instructions(InstructionSet_t &starts, Function_t* func); + void Build(IRDB_SDK::Function_t *func); + void alloc_blocks(const IRDB_SDK::InstructionSet_t &starts, map<IRDB_SDK::Instruction_t*,BasicBlock_t*>& insn2block_map); + void build_blocks(const map<IRDB_SDK::Instruction_t*,BasicBlock_t*>& insn2block_map); + void find_unblocked_instructions(InstructionSet_t &starts, IRDB_SDK::Function_t* func); // data BasicBlockSet_t blocks; BasicBlock_t* entry; - Function_t* function; + IRDB_SDK::Function_t* function; /* friends */ public: diff --git a/libIRDB/include/cfg/callgraph.hpp b/libIRDB/include/cfg/callgraph.hpp index 7403cfdd4..f60221c7c 100644 --- a/libIRDB/include/cfg/callgraph.hpp +++ b/libIRDB/include/cfg/callgraph.hpp @@ -28,7 +28,7 @@ typedef enum { DEFAULT_HELL_NODE = 0 } HellNodeType; class CallGraphNode_t { public: - CallGraphNode_t(libIRDB::Function_t* f = NULL) { + CallGraphNode_t(IRDB_SDK::Function_t* f = NULL) { if (f) { SetFunction(f); } else { @@ -39,7 +39,7 @@ class CallGraphNode_t bool IsHellnode() const { return m_isHellNode; } - libIRDB::Function_t* GetFunction() const { + IRDB_SDK::Function_t* getFunction() const { assert(!m_isHellNode); if (m_isHellNode) return NULL; @@ -63,7 +63,7 @@ class CallGraphNode_t } private: - void SetFunction(Function_t* const f) { + void SetFunction(IRDB_SDK::Function_t* const f) { assert(f); m_node.func = f; m_isHellNode = false; @@ -72,22 +72,22 @@ class CallGraphNode_t private: bool m_isHellNode; union { - libIRDB::Function_t* func; + IRDB_SDK::Function_t* func; HellNodeType hellNodeType; } m_node; }; typedef std::pair<CallGraphNode_t*,CallGraphNode_t*> CallGraphEdge_t; typedef std::set<CallGraphNode_t*> CallGraphNodeSet_t; -typedef libIRDB::Instruction_t* CallSite_t; +typedef IRDB_SDK::Instruction_t* CallSite_t; typedef std::set<CallSite_t> CallSiteSet_t; class Callgraph_t { public: Callgraph_t(); - ~Callgraph_t(); - void AddFile(libIRDB::FileIR_t* const firp); + virtual ~Callgraph_t(); + void AddFile(IRDB_SDK::FileIR_t* const firp); bool EdgeExists(const CallGraphEdge_t& edge) { @@ -105,7 +105,7 @@ class Callgraph_t CallGraphNodeSet_t& GetCalleesOfNode(CallGraphNode_t* const node) { return callees[node]; } - void GetAncestors(Function_t* const fn, CallGraphNodeSet_t& ancestors, bool skipHellNode = false); + void GetAncestors(IRDB_SDK::Function_t* const fn, CallGraphNodeSet_t& ancestors, bool skipHellNode = false); void GetAncestors(CallGraphNode_t* const node, CallGraphNodeSet_t& ancestors, bool skipHellNode = false); CallSiteSet_t& GetCallSites(CallGraphNode_t* const n1) @@ -120,8 +120,8 @@ class Callgraph_t s << "HELLNODE" << n1->GetHellNodeType(); return s.str(); } else { - assert(n1->GetFunction()); - return n1->GetFunction()->GetName(); + assert(n1->getFunction()); + return n1->getFunction()->getName(); } } @@ -132,11 +132,11 @@ class Callgraph_t CallGraphNode_t& GetDefaultHellNode() { return default_hellnode; } - CallGraphNode_t* FindNode(Function_t* const fn); + CallGraphNode_t* FindNode(IRDB_SDK::Function_t* const fn); private: // create nodes from functions - void CreateNodes(libIRDB::FileIR_t *firp); + void CreateNodes(IRDB_SDK::FileIR_t *firp); // mark the given insn as a call site. void MarkCallSite(Instruction_t* const insn); @@ -146,7 +146,7 @@ class Callgraph_t typedef std::map<CallGraphNode_t*, CallGraphNodeSet_t > CGNodeToCGNodeSetMap_t; typedef std::map<CallGraphNode_t*, CallSiteSet_t > NodeToCallSiteSetMap_t; - typedef std::map<Function_t*, CallGraphNode_t*> FunctionToCGNodeMap_t; + typedef std::map<IRDB_SDK::Function_t*, CallGraphNode_t*> FunctionToCGNodeMap_t; CGNodeToCGNodeSetMap_t callers; // map a callee to its callees CGNodeToCGNodeSetMap_t callees; // map a caller to its callers diff --git a/libIRDB/include/core/IRDB_Objects.hpp b/libIRDB/include/core/IRDB_Objects.hpp index 859d9177e..aaa34b8ab 100644 --- a/libIRDB/include/core/IRDB_Objects.hpp +++ b/libIRDB/include/core/IRDB_Objects.hpp @@ -1,48 +1,45 @@ #ifndef IRDB_Objects_h #define IRDB_Objects_h -#include <map> -#include <utility> -#include <memory> - +namespace libIRDB +{ // TODO: Should really use unordered maps but was getting build errors // *** A toolchain step should NOT delete pointers to any variant, file IR, or file object stored // in a IRFiles_t object. I have made pointers shared where possible to communicate this. *** -class IRDBObjects_t +class IRDBObjects_t : virtual public IRDB_SDK::IRDBObjects_t { public: - using FileSet_t = std::set<File_t*>; IRDBObjects_t() { pqxx_interface = std::unique_ptr<pqxxDB_t>(new pqxxDB_t()); // set up interface to the sql server - BaseObj_t::SetInterface(pqxx_interface.get()); + BaseObj_t::setInterface(pqxx_interface.get()); }; - ~IRDBObjects_t(); + virtual ~IRDBObjects_t(); // Add/delete file IRs for a variant. // Step does not have ownership of fileIR (can't make assumptions about its // lifetime!), and a call to DeleteFileIR will render any pointers to that fileIR dangling. // AddFileIR returns the added IR or the preexistent IR if it was already added. - FileIR_t* addFileIR(const db_id_t variant_id, const db_id_t file_id); // Returns NULL if no such file exists - void deleteFileIR(const db_id_t file_id); + IRDB_SDK::FileIR_t* addFileIR(const IRDB_SDK::DatabaseID_t variant_id, const IRDB_SDK::DatabaseID_t file_id); // Returns NULL if no such file exists + void deleteFileIR(const IRDB_SDK::DatabaseID_t file_id); // Add or delete a variant // Step does not have ownership of variant (can't make assumptions about its lifetime!), and a call to DeleteVariant will render any pointers to that variant dangling. // Deleting a variant does NOT write its files' IRs, but DOES delete them! // AddVariant returns the added variant or the preexistent variant if it was already added. - VariantID_t* addVariant(const db_id_t variant_id); - void deleteVariant(db_id_t variant_id); + IRDB_SDK::VariantID_t* addVariant(const IRDB_SDK::DatabaseID_t variant_id); + void deleteVariant(IRDB_SDK::DatabaseID_t variant_id); // Get DB interface - pqxxDB_t* getDBInterface() const; - pqxxDB_t* resetDBInterface(); + IRDB_SDK::pqxxDB_t* getDBInterface() const; + IRDB_SDK::pqxxDB_t* resetDBInterface(); // Write back variants and file IRs. Does NOT commit changes. - int writeBackFileIR(const db_id_t file_id, std::ostream *verbose_logging=nullptr); - int writeBackVariant(const db_id_t variant_id); // Does NOT write back its files' IRs + int writeBackFileIR(const IRDB_SDK::DatabaseID_t file_id, std::ostream *verbose_logging=nullptr); + int writeBackVariant(const IRDB_SDK::DatabaseID_t variant_id); // Does NOT write back its files' IRs int writeBackAll(std::ostream* verbose_logging=nullptr); // Returns -1 if any writes fail. void deleteAll(void); @@ -53,7 +50,7 @@ class IRDBObjects_t std::unique_ptr<pqxxDB_t> pqxx_interface; // type aliases of maps. maps allow speed of finding needed files, file IRs // and/or variants that have already been read from the DB - using IdToVariantMap_t = std::map<db_id_t, std::unique_ptr<VariantID_t>>; + using IdToVariantMap_t = std::map<IRDB_SDK::DatabaseID_t, std::unique_ptr<VariantID_t>>; struct FileIRInfo_t { File_t * file; @@ -64,15 +61,16 @@ class IRDBObjects_t } }; - using IdToFileIRInfoMap_t = std::map<db_id_t, FileIRInfo_t>; + using IdToFileIRInfoMap_t = std::map<IRDB_SDK::DatabaseID_t, FileIRInfo_t>; IdToVariantMap_t variant_map; IdToFileIRInfoMap_t file_IR_map; // minor helper - bool filesAlreadyPresent(const std::set<File_t*>&) const; + bool filesAlreadyPresent(const FileSet_t&) const; }; -#endif +} +#endif diff --git a/libIRDB/include/core/address.hpp b/libIRDB/include/core/address.hpp index e0f7e17df..f6b341b56 100644 --- a/libIRDB/include/core/address.hpp +++ b/libIRDB/include/core/address.hpp @@ -18,18 +18,22 @@ * */ +namespace libIRDB +{ + // // An address in a variant. // -typedef uintptr_t virtual_offset_t; -class AddressID_t : public BaseObj_t +using virtual_offset_t = IRDB_SDK::VirtualOffset_t; +class AddressID_t : virtual public IRDB_SDK::AddressID_t, public BaseObj_t { public: + virtual ~AddressID_t() {} AddressID_t() : BaseObj_t(NULL), fileID(NOT_IN_DATABASE), virtual_offset(0) - { SetBaseID(NOT_IN_DATABASE); } + { setBaseID(NOT_IN_DATABASE); } AddressID_t(db_id_t myid, db_id_t myfileID, virtual_offset_t voff) : BaseObj_t(NULL), fileID(myfileID), virtual_offset(voff) - { SetBaseID(myid); } + { setBaseID(myid); } AddressID_t& operator=(const AddressID_t &rhs) { if (this != &rhs) @@ -41,18 +45,18 @@ class AddressID_t : public BaseObj_t return *this; } - db_id_t GetFileID() const { return fileID; } - void SetFileID(db_id_t thefileID) { fileID=thefileID; } + db_id_t getFileID() const { return fileID; } + void setFileID(db_id_t thefileID) { fileID=thefileID; } - virtual_offset_t GetVirtualOffset() { return virtual_offset; } - void SetVirtualOffset(virtual_offset_t voff) { virtual_offset=voff; } + virtual_offset_t getVirtualOffset() const { return virtual_offset; } + void setVirtualOffset(virtual_offset_t voff) { virtual_offset=voff; } std::vector<std::string> WriteToDB(File_t *vid, db_id_t newid, bool p_withHeader); - inline bool operator<(const AddressID_t& cmp) const + bool operator<(const AddressID_t& cmp) const { return fileID < cmp.fileID || (fileID == cmp.fileID && virtual_offset < cmp.virtual_offset);} - inline bool operator!=(const AddressID_t& cmp) const + bool operator!=(const AddressID_t& cmp) const { return fileID != cmp.fileID || virtual_offset != cmp.virtual_offset; } @@ -65,3 +69,4 @@ class AddressID_t : public BaseObj_t void Register(VariantID_t *vid); }; +} diff --git a/libIRDB/include/core/archdesc.hpp b/libIRDB/include/core/archdesc.hpp index dc84aee5d..e7299d450 100644 --- a/libIRDB/include/core/archdesc.hpp +++ b/libIRDB/include/core/archdesc.hpp @@ -18,21 +18,25 @@ * */ +namespace libIRDB +{ + -enum ADFileType_t { AD_ELF, AD_CGC, AD_PE, AD_NONE }; -enum ADMachineType_t { admtAarch64, admtX86_64, admtI386, admtNone }; +using ADFileType_t = IRDB_SDK::ADFileType_t; +using ADMachineType_t = IRDB_SDK::ADMachineType_t; -class ArchitectureDescription_t +class ArchitectureDescription_t : virtual public IRDB_SDK::ArchitectureDescription_t { public: - ArchitectureDescription_t() : bits(0), ft(AD_NONE), mt(admtNone) {} + virtual ~ArchitectureDescription_t() {} + ArchitectureDescription_t() : bits(0), ft(IRDB_SDK::adftNone), mt(IRDB_SDK::admtNone) {} - int GetBitWidth() const { return bits; } - void SetBitWidth(const int _bits) { bits=_bits; } + int getBitWidth() const { return bits; } + void setBitWidth(const int _bits) { bits=_bits; } - ADFileType_t GetFileType() const { return ft; } - void SetFileType(const ADFileType_t t) { ft=t; } + ADFileType_t getFileType() const { return ft; } + void setFileType(const ADFileType_t t) { ft=t; } ADMachineType_t getMachineType() const { return mt; } void setMachineType(const ADMachineType_t t) { mt=t; } @@ -44,3 +48,4 @@ class ArchitectureDescription_t ADMachineType_t mt; }; +} diff --git a/libIRDB/include/core/baseobj.hpp b/libIRDB/include/core/baseobj.hpp index 05f690020..00abd21a1 100644 --- a/libIRDB/include/core/baseobj.hpp +++ b/libIRDB/include/core/baseobj.hpp @@ -19,37 +19,34 @@ */ -typedef uintptr_t virtual_offset_t; -typedef int db_id_t; - - -class Relocation_t; -typedef std::set<Relocation_t*> RelocationSet_t; +namespace libIRDB +{ +using virtual_offset_t = IRDB_SDK::VirtualOffset_t; +using db_id_t = IRDB_SDK::DatabaseID_t; +using RelocationSet_t = IRDB_SDK::RelocationSet_t; // A base class for something that all objects have, for now just a DOIP. // see .cpp file for method descriptions. -class BaseObj_t +class BaseObj_t : virtual public IRDB_SDK::BaseObj_t { public: + virtual ~BaseObj_t() {} BaseObj_t(doip_t* doip); - virtual ~BaseObj_t() { /* management of doips is explicit */ } - - static void SetInterface(DBinterface_t *dbintr); + // static void SetInterface(DBinterface_t *dbintr); static DBinterface_t* GetInterface() {return dbintr;} // get and set the ID - db_id_t GetBaseID() const {return base_id; } - db_id_t GetDoipID() const { return doip ? doip->GetBaseID() : NOT_IN_DATABASE; } - void SetDoipID(doip_t *dp) { doip=dp; } - void SetBaseID(db_id_t id) {base_id=id; } - - static const db_id_t NOT_IN_DATABASE; + db_id_t getBaseID() const {return base_id; } + db_id_t getDoipID() const { return doip ? doip->GetBaseID() : NOT_IN_DATABASE; } + void setDoipID(IRDB_SDK::Doip_t *dp) { doip=dynamic_cast<doip_t*>(dp); if(dp) assert(doip); } + void setBaseID(db_id_t id) {base_id=id; } virtual RelocationSet_t& GetRelocations() { return relocs; } - virtual const RelocationSet_t& GetRelocations() const { return relocs; } + virtual const RelocationSet_t& getRelocations() const { return relocs; } + virtual void setRelocations(const RelocationSet_t& rels) { relocs=rels; } protected: @@ -59,5 +56,8 @@ class BaseObj_t doip_t* doip; db_id_t base_id; // -1 means not yet in the DB. RelocationSet_t relocs; + + friend class IRDB_SDK::BaseObj_t; }; +} diff --git a/libIRDB/include/core/basetypes.hpp b/libIRDB/include/core/basetypes.hpp index d47084900..16cd27493 100644 --- a/libIRDB/include/core/basetypes.hpp +++ b/libIRDB/include/core/basetypes.hpp @@ -18,6 +18,38 @@ * */ -typedef uintptr_t virtual_offset_t; -typedef int db_id_t; -typedef int schema_version_t; + +namespace libIRDB +{ + using virtual_offset_t = IRDB_SDK::VirtualOffset_t; + using db_id_t = IRDB_SDK::DatabaseID_t; + using schema_version_t = IRDB_SDK::SchemaVersionID_t; + + // forward decls + class AddressID_t; + class ArchitectureDescription_t; + class BaseObj_t; + class DatabaseError_t; + class DBinterface_t; + class Doip_t; + class EhProgram_t; + class EhCallSite_t; + class File_t; + class FileIR_t; + class Function_t; + class ICFS_t; + class Instruction_t; + class IRDBObjects_t; + class pqxxDB_t; + class Relocation_t; + class DataScoop_t; + class Type_t; + class BasicType_t; + class PointerType_t; + class AggregateType_t; + class FuncType_t; + class VariantID_t; + class DecodedInstructionDispatcher_t; + class DecodedOperandDispatcher_t; + +} diff --git a/libIRDB/include/core/dbinterface.hpp b/libIRDB/include/core/dbinterface.hpp index 96954be9e..fb4836ab1 100644 --- a/libIRDB/include/core/dbinterface.hpp +++ b/libIRDB/include/core/dbinterface.hpp @@ -18,11 +18,14 @@ * */ +namespace libIRDB +{ +using DatabaseErrorType_t = IRDB_SDK::DatabaseErrorType_t; -class DatabaseError_t +class DatabaseError_t : virtual public IRDB_SDK::DatabaseError_t { public: - enum DatabaseErrorType_t {VariantNotInDatabase, VariantTableNotRegistered}; + virtual ~DatabaseError_t() { } DatabaseError_t(DatabaseErrorType_t the_err) : err(the_err) {} DatabaseErrorType_t GetErrorCode() const { return err; } private: @@ -33,16 +36,17 @@ std::ostream& operator<<(std::ostream& output, const DatabaseError_t& p); // an interface to a database -class DBinterface_t +class DBinterface_t : virtual public IRDB_SDK::DBinterface_t { public: DBinterface_t() {}; virtual ~DBinterface_t() {}; - virtual void IssueQuery(std::string query)=0; - virtual void MoveToNextRow()=0; - virtual std::string GetResultColumn(std::string colname)=0; - virtual bool IsDone()=0; - virtual void Commit()=0; + virtual void issueQuery(std::string query)=0; + virtual void moveToNextRow()=0; + virtual std::string getResultColumn(std::string colname)=0; + virtual bool isDone()=0; + virtual void commit()=0; }; +} diff --git a/libIRDB/include/core/decode.hpp b/libIRDB/include/core/decode.hpp index c78aed0fc..79bd8617f 100644 --- a/libIRDB/include/core/decode.hpp +++ b/libIRDB/include/core/decode.hpp @@ -1,37 +1,10 @@ -#ifndef libdecode_decode_hpp -#define libdecode_decode_hpp - -#define USEMETA - -#if defined(USEMETA) -#include <core/decode_dispatch.hpp> -#include <core/operand_dispatch.hpp> -#elif defined(USECS) -#include <core/decode_csx86.hpp> -#include <core/operand_csx86.hpp> -#pragma "Error: Source did not adaquately specify a disassembler. " -#endif - namespace libIRDB { -using namespace std; -using namespace libIRDB; - - -#if defined(USEMETA) -typedef DecodedInstructionDispatcher_t DecodedInstruction_t; -typedef DecodedOperandDispatcher_t DecodedOperand_t; -typedef DecodedOperandMetaVector_t DecodedOperandVector_t; -#elif defined(USECS) -typedef DecodedInstructionCapstoneX86_t DecodedInstruction_t; -typedef DecodedOperandCapstoneX86_t DecodedOperand_t; -typedef DecodedOperandCapstoneVector_t DecodedOperandVector_t; -#else -#pragma "Error: Source did not adaquately specify a disassembler. " -#endif +using DecodedInstruction_t = IRDB_SDK::DecodedInstruction_t; +using DecodedOperand_t = IRDB_SDK::DecodedOperand_t; +using DecodedOperandVector_t = IRDB_SDK::DecodedOperandVector_t; } -#endif diff --git a/libIRDB/include/core/decode_base.hpp b/libIRDB/include/core/decode_base.hpp index 3df694697..5cbbcee82 100644 --- a/libIRDB/include/core/decode_base.hpp +++ b/libIRDB/include/core/decode_base.hpp @@ -1,10 +1,4 @@ -#ifndef libirdb_decodecsbase_hpp -#define libirdb_decodecsbase_hpp - -#include <stdint.h> -#include <vector> -#include <memory> - +#if 0 namespace libIRDB { @@ -12,10 +6,8 @@ using namespace libIRDB; using namespace std; class DecodedOperandCapstone_t; -class DecodedInstructionDispatcher_t; -typedef vector<shared_ptr<DecodedOperandCapstone_t> > DecodedOperandCapstoneVector_t; -class DecodedInstructionCapstone_t +class DecodedInstructionCapstone_t : virtual public IRDB_SDK::DecodedInstruction_t { public: virtual ~DecodedInstructionCapstone_t(){} @@ -37,20 +29,19 @@ class DecodedInstructionCapstone_t virtual bool hasRelevantOperandSizePrefix() const =0; virtual bool hasRexWPrefix() const =0; virtual bool hasImplicitlyModifiedRegs() const =0; - virtual virtual_offset_t getMemoryDisplacementOffset(const DecodedOperandCapstone_t& t, const Instruction_t* insn) const =0; + virtual virtual_offset_t getMemoryDisplacementOffset(const IRDB_SDK::DecodedOperand_t& t, const Instruction_t* insn) const =0; // 0-based. first operand is numbered 0. virtual bool hasOperand(const int op_num) const =0; - virtual shared_ptr<DecodedOperandCapstone_t> getOperand(const int op_num) const =0; - virtual DecodedOperandCapstoneVector_t getOperands() const =0; + virtual shared_ptr<IRDB_SDK::DecodedOperand_t> getOperand(const int op_num) const =0; + virtual DecodedOperandVector_t getOperands() const =0; private: - static unique_ptr<DecodedInstructionCapstone_t> factory(const libIRDB::Instruction_t* i); - static unique_ptr<DecodedInstructionCapstone_t> factory(const virtual_offset_t start_addr, const void *data, uint32_t max_len); - static unique_ptr<DecodedInstructionCapstone_t> factory(const virtual_offset_t start_addr, const void *data, const void* endptr); - - friend class DecodedInstructionDispatcher_t; + // static unique_ptr<DecodedInstructionCapstone_t> factory(const Instruction_t* i); + // static unique_ptr<DecodedInstructionCapstone_t> factory(const IRDB_SDK::VirtualOffset_t start_addr, const void *data, uint32_t max_len); + // static unique_ptr<DecodedInstructionCapstone_t> factory(const IRDB_SDK::VirtualOffset_t start_addr, const void *data, const void* endptr); + // friend class DecodedInstructionDispatcher_t; }; diff --git a/libIRDB/include/core/decode_csarm.hpp b/libIRDB/include/core/decode_csarm.hpp index 9a1201357..b517d7d04 100644 --- a/libIRDB/include/core/decode_csarm.hpp +++ b/libIRDB/include/core/decode_csarm.hpp @@ -1,11 +1,3 @@ -#ifndef libirdb_decodecsarm_hpp -#define libirdb_decodecsarm_hpp - -#include <stdint.h> -#include <vector> -#include <memory> -#include <core/decode_base.hpp> -#include <core/operand_base.hpp> namespace libIRDB { @@ -14,14 +6,10 @@ using namespace libIRDB; using namespace std; class DecodedOperandCapstoneARM64_t; -class DecodedInstructionCapstoneARM64_t : public DecodedInstructionCapstone_t +class DecodedInstructionCapstoneARM64_t : virtual public IRDB_SDK::DecodedInstruction_t { public: DecodedInstructionCapstoneARM64_t()=delete; - DecodedInstructionCapstoneARM64_t(const Instruction_t*); - DecodedInstructionCapstoneARM64_t(const virtual_offset_t start_addr, const void *data, uint32_t max_len); - DecodedInstructionCapstoneARM64_t(const virtual_offset_t start_addr, const void *data, const void* endptr); - DecodedInstructionCapstoneARM64_t(const DecodedInstructionCapstoneARM64_t& copy); DecodedInstructionCapstoneARM64_t& operator=(const DecodedInstructionCapstoneARM64_t& copy); virtual ~DecodedInstructionCapstoneARM64_t(); @@ -44,12 +32,12 @@ class DecodedInstructionCapstoneARM64_t : public DecodedInstructionCapstone_t virtual bool hasRelevantOperandSizePrefix() const override; virtual bool hasRexWPrefix() const override; virtual bool hasImplicitlyModifiedRegs() const override; - virtual virtual_offset_t getMemoryDisplacementOffset(const DecodedOperandCapstone_t& t, const Instruction_t* insn) const override; + virtual IRDB_SDK::VirtualOffset_t getMemoryDisplacementOffset(const DecodedOperand_t* t, const IRDB_SDK::Instruction_t* insn) const override; // 0-based. first operand is numbered 0. virtual bool hasOperand(const int op_num) const override; - virtual std::shared_ptr<DecodedOperandCapstone_t> getOperand(const int op_num) const override; - virtual DecodedOperandCapstoneVector_t getOperands() const override; + virtual std::shared_ptr<DecodedOperand_t> getOperand(const int op_num) const override; + virtual DecodedOperandVector_t getOperands() const override; private: @@ -70,12 +58,15 @@ class DecodedInstructionCapstoneARM64_t : public DecodedInstructionCapstone_t static CapstoneHandle_t *cs_handle; + friend class IRDB_SDK::DecodedInstruction_t; friend class DecodedOperandCapstoneARM64_t; DecodedInstructionCapstoneARM64_t(const shared_ptr<void> &my_insn); - + DecodedInstructionCapstoneARM64_t(const Instruction_t*); + DecodedInstructionCapstoneARM64_t(const virtual_offset_t start_addr, const void *data, uint32_t max_len); + DecodedInstructionCapstoneARM64_t(const virtual_offset_t start_addr, const void *data, const void* endptr); + DecodedInstructionCapstoneARM64_t(const DecodedInstructionCapstoneARM64_t& copy); }; } -#endif diff --git a/libIRDB/include/core/decode_csx86.hpp b/libIRDB/include/core/decode_csx86.hpp index a832f6142..c7e85d91b 100644 --- a/libIRDB/include/core/decode_csx86.hpp +++ b/libIRDB/include/core/decode_csx86.hpp @@ -1,11 +1,3 @@ -#ifndef libirdb_decodecsx86_hpp -#define libirdb_decodecsx86_hpp - -#include <stdint.h> -#include <vector> -#include <memory> -#include <core/decode_base.hpp> -#include <core/operand_base.hpp> namespace libIRDB { @@ -14,14 +6,10 @@ using namespace libIRDB; using namespace std; class DecodedOperandCapstoneX86_t; -class DecodedInstructionCapstoneX86_t : public DecodedInstructionCapstone_t +class DecodedInstructionCapstoneX86_t : virtual public DecodedInstruction_t { public: DecodedInstructionCapstoneX86_t()=delete; - DecodedInstructionCapstoneX86_t(const Instruction_t*); - DecodedInstructionCapstoneX86_t(const virtual_offset_t start_addr, const void *data, uint32_t max_len); - DecodedInstructionCapstoneX86_t(const virtual_offset_t start_addr, const void *data, const void* endptr); - DecodedInstructionCapstoneX86_t(const DecodedInstructionCapstoneX86_t& copy); DecodedInstructionCapstoneX86_t& operator=(const DecodedInstructionCapstoneX86_t& copy); virtual ~DecodedInstructionCapstoneX86_t(); @@ -44,12 +32,12 @@ class DecodedInstructionCapstoneX86_t : public DecodedInstructionCapstone_t virtual bool hasRelevantOperandSizePrefix() const override; virtual bool hasRexWPrefix() const override; virtual bool hasImplicitlyModifiedRegs() const override; - virtual virtual_offset_t getMemoryDisplacementOffset(const DecodedOperandCapstone_t& t, const Instruction_t* insn) const override; + virtual IRDB_SDK::VirtualOffset_t getMemoryDisplacementOffset(const DecodedOperand_t* t, const IRDB_SDK::Instruction_t* insn) const override; // 0-based. first operand is numbered 0. virtual bool hasOperand(const int op_num) const override; - virtual std::shared_ptr<DecodedOperandCapstone_t> getOperand(const int op_num) const override; - virtual DecodedOperandCapstoneVector_t getOperands() const override; + virtual std::shared_ptr<DecodedOperand_t> getOperand(const int op_num) const override; + virtual DecodedOperandVector_t getOperands() const override; private: @@ -70,12 +58,15 @@ class DecodedInstructionCapstoneX86_t : public DecodedInstructionCapstone_t static CapstoneHandle_t *cs_handle; + friend class DecodedInstruction_t; friend class DecodedOperandCapstoneX86_t; DecodedInstructionCapstoneX86_t(const shared_ptr<void> &my_insn); - + DecodedInstructionCapstoneX86_t(const Instruction_t*); + DecodedInstructionCapstoneX86_t(const virtual_offset_t start_addr, const void *data, uint32_t max_len); + DecodedInstructionCapstoneX86_t(const virtual_offset_t start_addr, const void *data, const void* endptr); + DecodedInstructionCapstoneX86_t(const DecodedInstructionCapstoneX86_t& copy); }; } -#endif diff --git a/libIRDB/include/core/decode_dispatch.hpp b/libIRDB/include/core/decode_dispatch.hpp index 2e4e64b7f..491df5ca2 100644 --- a/libIRDB/include/core/decode_dispatch.hpp +++ b/libIRDB/include/core/decode_dispatch.hpp @@ -1,12 +1,3 @@ -#ifndef libirdb_decode_dispatch_hpp -#define libirdb_decode_dispatch_hpp - -#include <stdint.h> -#include <vector> -#include <core/decode_csx86.hpp> -#include <core/operand_csx86.hpp> -#include <core/decode_csarm.hpp> -#include <core/operand_csarm.hpp> namespace libIRDB { @@ -17,7 +8,7 @@ using namespace std; class DecodedOperandDispatcher_t; typedef std::vector<DecodedOperandDispatcher_t> DecodedOperandMetaVector_t; -class DecodedInstructionDispatcher_t +class DecodedInstructionDispatcher_t : virtual public IRDB_SDK::DecodedInstruction_t { public: DecodedInstructionDispatcher_t()=delete; @@ -47,12 +38,12 @@ class DecodedInstructionDispatcher_t bool hasRelevantOperandSizePrefix() const; bool hasRexWPrefix() const; bool hasImplicitlyModifiedRegs() const; - virtual_offset_t getMemoryDisplacementOffset(const DecodedOperandDispatcher_t& t, const Instruction_t* insn) const; + IRDB_SDK::VirtualOffset_t getMemoryDisplacementOffset(const IRDB_SDK::DecodedOperand_t* t, const IRDB_SDK::Instruction_t* insn) const; // 0-based. first operand is numbered 0. bool hasOperand(const int op_num) const; - DecodedOperandDispatcher_t getOperand(const int op_num) const; - DecodedOperandMetaVector_t getOperands() const; + shared_ptr<IRDB_SDK::DecodedOperand_t> getOperand(const int op_num) const; + IRDB_SDK::DecodedOperandVector_t getOperands() const; private: @@ -62,4 +53,3 @@ class DecodedInstructionDispatcher_t } -#endif diff --git a/libIRDB/include/core/doip.hpp b/libIRDB/include/core/doip.hpp index 7a491b35c..e379150cd 100644 --- a/libIRDB/include/core/doip.hpp +++ b/libIRDB/include/core/doip.hpp @@ -18,21 +18,18 @@ * */ +namespace libIRDB +{ + // The Digital Object Identifier for Peasoup. -class doip_t +class doip_t : virtual public IRDB_SDK::Doip_t { public: + virtual ~doip_t(){} doip_t(db_id_t did, int conf, std::string tool_name , std::string comment); db_id_t GetBaseID() const { return did; } - -#if 0 - operator<<(); // output - operator==(); // comparison operators - // compare confidence levels of two datum - operator<(); -#endif private: db_id_t did; @@ -40,3 +37,4 @@ class doip_t std::string tool_name; std::string comment; }; +} diff --git a/libIRDB/include/core/eh.hpp b/libIRDB/include/core/eh.hpp index 6c3da494c..96068ab1f 100644 --- a/libIRDB/include/core/eh.hpp +++ b/libIRDB/include/core/eh.hpp @@ -18,14 +18,19 @@ * */ +namespace libIRDB +{ +using EhProgramInstruction_t = IRDB_SDK::EhProgramInstruction_t; +using EhProgramListing_t = IRDB_SDK::EhProgramListing_t; +using EhProgramSet_t = IRDB_SDK::EhProgramSet_t; +using TTOrderVector_t = IRDB_SDK::TTOrderVector_t; +using EhCallSiteSet_t = IRDB_SDK::EhCallSiteSet_t; -typedef std::string EhProgramInstruction_t; -typedef std::vector<EhProgramInstruction_t> EhProgramListing_t; - -class EhProgram_t : public BaseObj_t +class EhProgram_t : public BaseObj_t, virtual public IRDB_SDK::EhProgram_t { public: + virtual ~EhProgram_t(){} EhProgram_t(const EhProgram_t& orig) : BaseObj_t(NULL) @@ -36,50 +41,51 @@ class EhProgram_t : public BaseObj_t data_alignment_factor=orig.data_alignment_factor; return_register=orig.return_register; ptrsize=orig.ptrsize; - SetBaseID(BaseObj_t::NOT_IN_DATABASE); - GetRelocations()=orig.GetRelocations(); + setBaseID(BaseObj_t::NOT_IN_DATABASE); + GetRelocations()=orig.getRelocations(); } - EhProgram_t(db_id_t id, const uint64_t caf, const int64_t daf, const uint8_t rr, const uint8_t p_ptrsize) + EhProgram_t(db_id_t id, const uint64_t caf, const int64_t daf, const uint8_t rr, const uint8_t p_ptrsize, + const EhProgramListing_t& ciep, const EhProgramListing_t& fdep) : BaseObj_t(NULL), - code_alignment_factor(0), - data_alignment_factor(0), + code_alignment_factor(caf), + data_alignment_factor(daf), return_register(rr), - ptrsize(p_ptrsize) + ptrsize(p_ptrsize) , + cie_program(ciep), + fde_program(fdep) { - SetDataAlignmentFactor(daf); - SetCodeAlignmentFactor(caf); - SetBaseID(id); + setBaseID(id); } EhProgramListing_t& GetCIEProgram() { return cie_program; } - const EhProgramListing_t& GetCIEProgram() const { return cie_program; } + const EhProgramListing_t& getCIEProgram() const { return cie_program; } EhProgramListing_t& GetFDEProgram() { return fde_program; } - const EhProgramListing_t& GetFDEProgram() const { return fde_program; } + const EhProgramListing_t& getFDEProgram() const { return fde_program; } - uint64_t GetCodeAlignmentFactor() const { return code_alignment_factor; } - void SetCodeAlignmentFactor(const uint64_t caf) + uint64_t getCodeAlignmentFactor() const { return code_alignment_factor; } + void setCodeAlignmentFactor(const uint64_t caf) { if ( ((uint8_t)caf) != caf ) throw std::logic_error(std::string()+"Invalid code alignment factor in call to "+__FUNCTION__); code_alignment_factor=(uint8_t)caf; } - int64_t GetDataAlignmentFactor() const { return data_alignment_factor; } - void SetDataAlignmentFactor(const int64_t daf) + int64_t getDataAlignmentFactor() const { return data_alignment_factor; } + void setDataAlignmentFactor(const int64_t daf) { if ( (( int8_t)daf) != daf ) throw std::logic_error(std::string()+"Invalid datat alignment factor in call to "+__FUNCTION__); data_alignment_factor=(int8_t)daf; } - int64_t GetReturnRegNumber() const { return return_register; } - void SetReturnRegNumber(const uint8_t rr) { return_register=rr; } + int64_t getReturnRegNumber() const { return return_register; } + void setReturnRegNumber(const uint8_t rr) { return_register=rr; } std::vector<std::string> WriteToDB(File_t* fid); // writes to DB, ID is not -1. - uint8_t GetPointerSize() const { return ptrsize; } + uint8_t getPointerSize() const { return ptrsize; } friend bool operator<(const EhProgram_t&a, const EhProgram_t&b); @@ -88,48 +94,49 @@ class EhProgram_t : public BaseObj_t private: - EhProgramListing_t cie_program; - EhProgramListing_t fde_program; uint8_t code_alignment_factor; int8_t data_alignment_factor; int8_t return_register; uint8_t ptrsize; // needed for interpreting programs + EhProgramListing_t cie_program; + EhProgramListing_t fde_program; }; bool operator<(const EhProgram_t&a, const EhProgram_t&b); -typedef std::set<EhProgram_t*> EhProgramSet_t; -typedef std::vector<int> TTOrderVector_t; -class EhCallSite_t : public BaseObj_t +class EhCallSite_t : public BaseObj_t, virtual public IRDB_SDK::EhCallSite_t { public: - EhCallSite_t(const db_id_t id, const uint64_t enc=0, Instruction_t* lp=NULL) : + virtual ~EhCallSite_t(){} + EhCallSite_t(const db_id_t id, const uint64_t enc=0, IRDB_SDK::Instruction_t* lp=NULL) : BaseObj_t(NULL), tt_encoding(enc), landing_pad(lp) - { SetBaseID(id); } + { setBaseID(id); } - uint64_t GetTTEncoding() const { return tt_encoding; } - void SetTTEncoding(const uint64_t p_tt) { tt_encoding=p_tt; } + uint64_t getTTEncoding() const { return tt_encoding; } + void setTTEncoding(const uint64_t p_tt) { tt_encoding=p_tt; } - Instruction_t* GetLandingPad() const { return landing_pad; } - void SetLandingPad(Instruction_t* lp) { landing_pad=lp; } + IRDB_SDK::Instruction_t* getLandingPad() const { return landing_pad; } + void setLandingPad(IRDB_SDK::Instruction_t* lp) { landing_pad=dynamic_cast<Instruction_t*>(lp); if(lp) assert(landing_pad); } - bool GetHasCleanup() const ; - void SetHasCleanup(bool p_has_cleanup=true) ; + bool getHasCleanup() const ; + void setHasCleanup(bool p_has_cleanup=true) ; TTOrderVector_t& GetTTOrderVector() { return ttov; } - const TTOrderVector_t& GetTTOrderVector() const { return ttov; } + const TTOrderVector_t& getTTOrderVector() const { return ttov; } + void setTTOrderVector(const TTOrderVector_t& p_ttov) { ttov=p_ttov; } std::string WriteToDB(File_t* fid); // writes to DB, ID is not -1. + private: uint64_t tt_encoding; - Instruction_t* landing_pad; + IRDB_SDK::Instruction_t* landing_pad; TTOrderVector_t ttov; }; -typedef std::set<EhCallSite_t*> EhCallSiteSet_t; +} diff --git a/libIRDB/include/core/file.hpp b/libIRDB/include/core/file.hpp index 8c30dc9a7..da3db353a 100644 --- a/libIRDB/include/core/file.hpp +++ b/libIRDB/include/core/file.hpp @@ -18,10 +18,13 @@ * */ +namespace libIRDB +{ // An ELF file as represented by the DB -class File_t : public BaseObj_t +class File_t : public BaseObj_t, virtual public IRDB_SDK::File_t { public: + virtual ~File_t(){} // create new item. File_t( const db_id_t &file_id, const db_id_t &orig_fid, const std::string &url, const std::string &hash, const std::string &arch, const int &elfoid, @@ -34,22 +37,22 @@ class File_t : public BaseObj_t File_t(db_id_t file_id) : BaseObj_t(NULL) { (void)file_id; assert(0);} // read from DB void WriteToDB() { assert(0); } // writes to DB ID is not -1. - std::string GetAddressTableName() const { return address_table_name; } - std::string GetFunctionTableName() const { return function_table_name; } - std::string GetInstructionTableName() const { return instruction_table_name; } - std::string GetICFSTableName() const { return icfs_table_name; } - std::string GetICFSMapTableName() const { return icfs_map_table_name; } - std::string GetRelocationsTableName() const { return relocs_table_name; } - std::string GetTypesTableName() const { return types_table_name; } - std::string GetScoopTableName() const { return scoop_table_name; } - std::string GetEhProgramTableName() const { return ehpgm_table_name; } - std::string GetEhCallSiteTableName() const { return ehcss_table_name; } - std::string GetURL() const { return url; } + std::string getAddressTableName() const { return address_table_name; } + std::string getFunctionTableName() const { return function_table_name; } + std::string getInstructionTableName() const { return instruction_table_name; } + std::string getICFSTableName() const { return icfs_table_name; } + std::string getICFSMapTableName() const { return icfs_map_table_name; } + std::string getRelocationsTableName() const { return relocs_table_name; } + std::string getTypesTableName() const { return types_table_name; } + std::string getScoopTableName() const { return scoop_table_name; } + std::string getEhProgramTableName() const { return ehpgm_table_name; } + std::string getEhCallSiteTableName() const { return ehcss_table_name; } + std::string getURL() const { return url; } void CreateTables(); - int GetELFOID() const { return elfoid; }; - db_id_t GetFileID() const {return orig_fid; }; + int getELFOID() const { return elfoid; }; + db_id_t getFileID() const {return orig_fid; }; friend class FileIR_t; friend class Function_t; @@ -83,3 +86,4 @@ class File_t : public BaseObj_t std::string ehcss_table_name; int elfoid; }; +} diff --git a/libIRDB/include/core/fileir.hpp b/libIRDB/include/core/fileir.hpp index be61b6b23..2240d2b5c 100644 --- a/libIRDB/include/core/fileir.hpp +++ b/libIRDB/include/core/fileir.hpp @@ -18,17 +18,17 @@ * */ -#include "type.hpp" - - +namespace libIRDB +{ -typedef std::set<Function_t*> FunctionSet_t; -typedef std::set<AddressID_t*> AddressSet_t; +using namespace std; +using FunctionSet_t = IRDB_SDK::FunctionSet_t; +using AddressSet_t = IRDB_SDK::AddressSet_t ; // A variant of a problem, this // may be an original variant // (i.e., and unmodified Variant) or a modified variant. -class FileIR_t : public BaseObj_t +class FileIR_t : public BaseObj_t, virtual public IRDB_SDK::FileIR_t { public: @@ -37,32 +37,32 @@ class FileIR_t : public BaseObj_t virtual ~FileIR_t(); // DB operations - void WriteToDB(std::ostream *verbose_logging=&std::cerr); + void writeToDB(std::ostream *verbose_logging=&std::cerr); // accessors and mutators in one - FunctionSet_t& GetFunctions() { return funcs; } - const FunctionSet_t& GetFunctions() const { return funcs; } + FunctionSet_t& GetFunctions() { return funcs; } + const FunctionSet_t& getFunctions() const { return funcs; } - InstructionSet_t& GetInstructions() { return insns; } - const InstructionSet_t& GetInstructions() const { return insns; } + InstructionSet_t& GetInstructions() { return insns; } + const InstructionSet_t& getInstructions() const { return insns; } - AddressSet_t& GetAddresses() { return addrs; } - const AddressSet_t& GetAddresses() const { return addrs; } + AddressSet_t& GetAddresses() { return addrs; } + const AddressSet_t& getAddresses() const { return addrs; } - RelocationSet_t& GetRelocations() { return relocs; } - const RelocationSet_t& GetRelocations() const { return relocs; } + RelocationSet_t& GetRelocations() { return relocs; } + const RelocationSet_t& getRelocations() const { return relocs; } - DataScoopSet_t& GetDataScoops() { return scoops; } - const DataScoopSet_t& GetDataScoops() const { return scoops; } + DataScoopSet_t& GetDataScoops() { return scoops; } + const DataScoopSet_t& getDataScoops() const { return scoops; } - ICFSSet_t& GetAllICFS() { return icfs_set; } - const ICFSSet_t& GetAllICFS() const { return icfs_set; } + ICFSSet_t& GetAllICFS() { return icfs_set; } + const ICFSSet_t& getAllICFS() const { return icfs_set; } - EhProgramSet_t& GetAllEhPrograms() { return eh_pgms; } - const EhProgramSet_t& GetAllEhPrograms() const { return eh_pgms; } + EhProgramSet_t& GetAllEhPrograms() { return eh_pgms; } + const EhProgramSet_t& getAllEhPrograms() const { return eh_pgms; } - EhCallSiteSet_t& GetAllEhCallSites() { return eh_css; } - const EhCallSiteSet_t& GetAllEhCallSites() const { return eh_css; } + EhCallSiteSet_t& GetAllEhCallSites() { return eh_css; } + const EhCallSiteSet_t& getAllEhCallSites() const { return eh_css; } // generate the spri rules into the output file, fout. void GenerateSPRI(std::ostream &fout, bool with_ilr=false); @@ -70,37 +70,83 @@ class FileIR_t : public BaseObj_t // generate spri, assume that orig_varirp is the original variant. void GenerateSPRI(FileIR_t *orig_varirp, std::ostream &fout, bool with_ilr=false); - void SetBaseIDS(); - db_id_t GetMaxBaseID(); + void setBaseIDS(); + IRDB_SDK::DatabaseID_t getMaxBaseID() const; - File_t* GetFile() const { return fileptr; } + File_t* getFile() const { return fileptr; } // Used for modifying a large number of instructions. AssembleRegistry // assembles the assembly isntructions for each registered instruction // and clears the registry. RegisterAssembly registers the instruction // to be assembled later. - void AssembleRegistry(); - void RegisterAssembly(Instruction_t *instr, std::string assembly); - void UnregisterAssembly(Instruction_t *instr); - std::string LookupAssembly(Instruction_t *instr); + void assembleRegistry(); + void registerAssembly(IRDB_SDK::Instruction_t *instr, string assembly); + void unregisterAssembly(IRDB_SDK::Instruction_t *instr); + string lookupAssembly(IRDB_SDK::Instruction_t *instr); //Needed for inserting assembly before an instruction. //if orig is not registered, the function returns, otherwise //the instruction/assembly mapping of orig->assembly is altered to //updated->assembly //removes the mapping for orig->assembly from the map. - void ChangeRegistryKey(Instruction_t* orig, Instruction_t* updated); + void changeRegistryKey(IRDB_SDK::Instruction_t* orig, IRDB_SDK::Instruction_t* updated); + + void setArchitecture(); - static int GetArchitectureBitWidth() ; - static void SetArchitecture(const int width, const ADMachineType_t mt); - void SetArchitecture(); - static const ArchitectureDescription_t* GetArchitecture() { return archdesc; } + static void setArchitecture(const int width, const IRDB_SDK::ADMachineType_t mt); + // static const IRDB_SDK::ArchitectureDescription_t* getArchitecture() { return archdesc; } // Lookup a scoop by address - DataScoop_t* FindScoop(const libIRDB::virtual_offset_t &addr); + IRDB_SDK::DataScoop_t* findScoop(const IRDB_SDK::VirtualOffset_t &addr) const; + + void splitScoop(IRDB_SDK::DataScoop_t *tosplit, const IRDB_SDK::VirtualOffset_t &addr, size_t size, + IRDB_SDK::DataScoop_t* &before, IRDB_SDK::DataScoop_t* &containing, IRDB_SDK::DataScoop_t* &after, IRDB_SDK::DatabaseID_t *max_id=NULL); + + virtual IRDB_SDK::EhCallSite_t* addEhCallSite_t(IRDB_SDK::Instruction_t* for_insn, const uint64_t enc=0, IRDB_SDK::Instruction_t* lp=nullptr) ; + + virtual IRDB_SDK::Relocation_t* addNewRelocation( + IRDB_SDK::BaseObj_t* from_obj, + int32_t _offset, + string _type, + IRDB_SDK::BaseObj_t* p_wrt_obj=nullptr, + int32_t p_addend=0) ; + virtual EhProgram_t* addEhProgram( + IRDB_SDK::Instruction_t* insn=nullptr, + const uint64_t caf=1, + const int64_t daf=1, + const uint8_t rr=1, + const uint8_t p_ptrsize=8, + const EhProgramListing_t& p_cie_program={}, + const EhProgramListing_t& p_fde_program={} + ) ; + virtual IRDB_SDK::AddressID_t* addNewAddress(const IRDB_SDK::DatabaseID_t& myfileID, const IRDB_SDK::VirtualOffset_t& voff) ; + virtual IRDB_SDK::ICFS_t* addNewICFS ( + IRDB_SDK::Instruction_t* insn=nullptr, + const IRDB_SDK::InstructionSet_t& targets={}, + const IRDB_SDK::ICFSAnalysisStatus_t& status=IRDB_SDK::iasAnalysisIncomplete); + virtual IRDB_SDK::Instruction_t* addNewInstruction( + IRDB_SDK::AddressID_t* addr=nullptr, + IRDB_SDK::Function_t* func=nullptr, + const string& bits="", + const string& comment="user-added", + IRDB_SDK::AddressID_t* indTarg=nullptr); + + virtual IRDB_SDK::DataScoop_t* addNewDataScoop( + const string& p_name="user-added", + IRDB_SDK::AddressID_t* p_start=nullptr, + IRDB_SDK::AddressID_t* p_end=nullptr, + IRDB_SDK::Type_t* p_type=nullptr, + uint8_t p_permissions=0, + bool p_is_relro=false, + const string &p_contents="", + IRDB_SDK::DatabaseID_t id=BaseObj_t::NOT_IN_DATABASE); + + virtual void removeScoop(IRDB_SDK::DataScoop_t* s) ; + virtual void moveRelocation(IRDB_SDK::Relocation_t* reloc, IRDB_SDK::Instruction_t* from, IRDB_SDK::Instruction_t* to) ; + + + - void SplitScoop(DataScoop_t *tosplit, const libIRDB::virtual_offset_t &addr, size_t size, - DataScoop_t* &before,DataScoop_t* &containing, DataScoop_t* &after, db_id_t *max_id=NULL); private: @@ -109,7 +155,7 @@ class FileIR_t : public BaseObj_t #define ASM_REG_MAX_SIZE 500000 - typedef std::map<Instruction_t*,std::string> registry_type; + typedef std::map<Instruction_t*,string> registry_type; // a pointer to the original variants IR, NULL means not yet loaded. FileIR_t* orig_variant_ir_p; @@ -130,54 +176,56 @@ class FileIR_t : public BaseObj_t EhProgramSet_t eh_pgms; EhCallSiteSet_t eh_css; - std::map<db_id_t,AddressID_t*> ReadAddrsFromDB(); - std::map<db_id_t,EhProgram_t*> ReadEhPgmsFromDB(); + map<db_id_t,AddressID_t*> ReadAddrsFromDB(); + map<db_id_t,EhProgram_t*> ReadEhPgmsFromDB(); - std::map<db_id_t,EhCallSite_t*> ReadEhCallSitesFromDB + map<db_id_t,EhCallSite_t*> ReadEhCallSitesFromDB ( - std::map<EhCallSite_t*,db_id_t> &unresolvedEhCssLandingPads + map<EhCallSite_t*,db_id_t> &unresolvedEhCssLandingPads ); - std::map<db_id_t,Function_t*> ReadFuncsFromDB + map<db_id_t,Function_t*> ReadFuncsFromDB ( - std::map<db_id_t,AddressID_t*> &addrMap, - std::map<db_id_t,Type_t*> &typeMap, - std::map<Function_t*,db_id_t> &entry_points + map<db_id_t,AddressID_t*> &addrMap, + map<db_id_t,Type_t*> &typeMap, + map<Function_t*,db_id_t> &entry_points ); - std::map<db_id_t,DataScoop_t*> ReadScoopsFromDB + map<db_id_t,DataScoop_t*> ReadScoopsFromDB ( - std::map<db_id_t,AddressID_t*> &addrMap, - std::map<db_id_t,Type_t*> &typeMap + map<db_id_t,AddressID_t*> &addrMap, + map<db_id_t,Type_t*> &typeMap ); - std::map<db_id_t,Instruction_t*> ReadInsnsFromDB + map<db_id_t,Instruction_t*> ReadInsnsFromDB ( - const std::map<db_id_t,Function_t*> &funcMap, - const std::map<db_id_t,AddressID_t*> &addrMap, - const std::map<db_id_t,EhProgram_t*> &ehpgmMap, - const std::map<db_id_t,EhCallSite_t*> &ehcsMap, - std::map<db_id_t,Instruction_t*> &addressToInstructionMap, - std::map<Instruction_t*, db_id_t> &unresolvedICFS + const map<db_id_t,Function_t*> &funcMap, + const map<db_id_t,AddressID_t*> &addrMap, + const map<db_id_t,EhProgram_t*> &ehpgmMap, + const map<db_id_t,EhCallSite_t*> &ehcsMap, + map<db_id_t,Instruction_t*> &addressToInstructionMap, + map<Instruction_t*, db_id_t> &unresolvedICFS ); void ReadRelocsFromDB ( - std::map<db_id_t,BaseObj_t*> &insnMap + map<db_id_t,BaseObj_t*> &insnMap ); - std::map<db_id_t, Type_t*> ReadTypesFromDB(TypeSet_t& types); - void ReadAllICFSFromDB(std::map<db_id_t,Instruction_t*> &addr2insnMap, - std::map<Instruction_t*, db_id_t> &unresolvedICFS); + map<db_id_t, Type_t*> ReadTypesFromDB(TypeSet_t& types); + void ReadAllICFSFromDB(map<db_id_t,Instruction_t*> &addr2insnMap, + map<Instruction_t*, db_id_t> &unresolvedICFS); - void CleanupICFS(std::ostream *verbose_logging=&std::cerr); - void GarbageCollectICFS(std::ostream *verbose_logging=&std::cerr); - void DedupICFS(std::ostream *verbose_logging=&std::cerr); + void CleanupICFS(ostream *verbose_logging=&cerr); + void GarbageCollectICFS(ostream *verbose_logging=&cerr); + void DedupICFS(ostream *verbose_logging=&cerr); - std::clock_t ReadIRDB_start; - std::clock_t ReadIRDB_end; + clock_t ReadIRDB_start; + clock_t ReadIRDB_end; + friend IRDB_SDK::FileIR_t; }; +} diff --git a/libIRDB/include/core/function.hpp b/libIRDB/include/core/function.hpp index a4d80aaa6..50731fd87 100644 --- a/libIRDB/include/core/function.hpp +++ b/libIRDB/include/core/function.hpp @@ -18,44 +18,45 @@ * */ -#include "core/type.hpp" - +namespace libIRDB +{ // The basic Function of a variant. -class Function_t : public BaseObj_t +class Function_t : public BaseObj_t, virtual public IRDB_SDK::Function_t { public: + virtual ~Function_t() {} Function_t() : BaseObj_t(NULL) {} // create a new function not in the db // create a function that's already in the DB - Function_t(db_id_t id, std::string name, int size, int oa_size, bool use_fp, bool is_safe, FuncType_t *, Instruction_t *entry); + Function_t(db_id_t id, std::string name, int size, int oa_size, bool use_fp, bool is_safe, IRDB_SDK::FuncType_t *, IRDB_SDK::Instruction_t *entry); InstructionSet_t& GetInstructions() { return my_insns; } - const InstructionSet_t& GetInstructions() const { return my_insns; } + const InstructionSet_t& getInstructions() const { return my_insns; } - int GetStackFrameSize() const { return stack_frame_size; } - const std::string& GetName() const { return name; } - uint32_t GetOutArgsRegionSize() const { return out_args_region_size; } + const int getStackFrameSize() const { return stack_frame_size; } + const std::string& getName() const { return name; } + uint32_t getOutArgsRegionSize() const { return out_args_region_size; } - void SetStackFrameSize(int size) { stack_frame_size=size; } - void SetName(std::string newname) { name=newname; } - void SetOutArgsRegionSize(uint32_t oa_size) {out_args_region_size=oa_size;} + void setStackFrameSize(int size) { stack_frame_size=size; } + void setName(std::string newname) { name=newname; } + void setOutArgsRegionSize(uint32_t oa_size) {out_args_region_size=oa_size;} - void SetEntryPoint(Instruction_t *insn) {entry_point=insn;} - Instruction_t* GetEntryPoint() const { return entry_point;} + void setEntryPoint(IRDB_SDK::Instruction_t *insn) { entry_point=dynamic_cast<Instruction_t*>(insn); if(insn) assert(entry_point); } + IRDB_SDK::Instruction_t* getEntryPoint() const { return entry_point;} std::string WriteToDB(File_t *fid, db_id_t newid); - bool GetUseFramePointer() const { return use_fp; } - void SetUseFramePointer(bool useFP) { use_fp = useFP; } + bool getUseFramePointer() const { return use_fp; } + void setUseFramePointer(bool useFP) { use_fp = useFP; } - void SetSafe(bool safe) { is_safe = safe; } - bool IsSafe() const { return is_safe; } + void setSafe(bool safe) { is_safe = safe; } + bool isSafe() const { return is_safe; } - void SetType(FuncType_t *t) { function_type = t; } - FuncType_t* GetType() const { return function_type; } + void setType(IRDB_SDK::FuncType_t *t) ; // { function_type = dynamic_cast<FuncType_t*>(t); if(t) assert(function_type); } + IRDB_SDK::FuncType_t* getType() const ; // { return function_type; } - int GetNumArguments() const; + int getNumArguments() const; private: Instruction_t *entry_point; @@ -68,3 +69,4 @@ class Function_t : public BaseObj_t FuncType_t *function_type; }; +} diff --git a/libIRDB/include/core/icfs.hpp b/libIRDB/include/core/icfs.hpp index f74bb02c7..c18efe782 100644 --- a/libIRDB/include/core/icfs.hpp +++ b/libIRDB/include/core/icfs.hpp @@ -18,10 +18,11 @@ * */ -class Instruction_t; -typedef std::set<Instruction_t*> InstructionSet_t; - -typedef enum ICFS_Analysis_Status_t { ICFS_Analysis_Incomplete, ICFS_Analysis_Module_Complete, ICFS_Analysis_Complete } ICFS_Analysis_Status_t; +namespace libIRDB +{ +using InstructionSet_t = IRDB_SDK::InstructionSet_t; +using ICFS_Analysis_Status_t = IRDB_SDK::ICFSAnalysisStatus_t; +using ICFSSet_t = IRDB_SDK::ICFSSet_t; // these must match the allowed values for type icfs_analysis_result in Postgres DB #define ICFS_ANALYSIS_INCOMPLETE_STR "icfs_analysis_incomplete" @@ -29,44 +30,45 @@ typedef enum ICFS_Analysis_Status_t { ICFS_Analysis_Incomplete, ICFS_Analysis_Mo #define ICFS_ANALYSIS_COMPLETE_STR "icfs_analysis_complete" // Keep track of instruction control flow sets -class ICFS_t : public InstructionSet_t, public BaseObj_t +class ICFS_t : virtual public InstructionSet_t, public BaseObj_t, virtual public IRDB_SDK::ICFS_t { public: - ICFS_t(): BaseObj_t(NULL), m_icfs_analysis_status(ICFS_Analysis_Incomplete) {} + virtual ~ICFS_t(){} + ICFS_t(): BaseObj_t(NULL), m_icfs_analysis_status(IRDB_SDK::iasAnalysisIncomplete) {} ICFS_t(const ICFS_Analysis_Status_t p_status) : BaseObj_t(NULL), m_icfs_analysis_status(p_status) {} - ICFS_t(db_id_t p_set_id, const ICFS_Analysis_Status_t p_status = ICFS_Analysis_Incomplete); + ICFS_t(db_id_t p_set_id, const ICFS_Analysis_Status_t p_status = IRDB_SDK::iasAnalysisIncomplete); ICFS_t(db_id_t p_set_id, const std::string); std::string WriteToDB(File_t *fid); // this is bad -- you loose data with this operator=. - void SetTargets(const InstructionSet_t &other) + void setTargets(const InstructionSet_t &other) { InstructionSet_t::operator=(other); } - void AddTargets(const InstructionSet_t &other) + void addTargets(const InstructionSet_t &other) { insert(std::begin(other), std::end(other)); } - bool IsIncomplete() const { - return GetAnalysisStatus() == ICFS_Analysis_Incomplete; + bool isIncomplete() const { + return getAnalysisStatus() == IRDB_SDK::iasAnalysisIncomplete; } - bool IsComplete() const { - return GetAnalysisStatus() == ICFS_Analysis_Complete; + bool isComplete() const { + return getAnalysisStatus() == IRDB_SDK::iasAnalysisComplete; } - bool IsModuleComplete() const { - return GetAnalysisStatus() == ICFS_Analysis_Module_Complete; + bool isModuleComplete() const { + return getAnalysisStatus() == IRDB_SDK::iasAnalysisModuleComplete; } - void SetAnalysisStatus(const ICFS_Analysis_Status_t p_status) { + void setAnalysisStatus(const ICFS_Analysis_Status_t p_status) { m_icfs_analysis_status = p_status; } - ICFS_Analysis_Status_t GetAnalysisStatus() const { + ICFS_Analysis_Status_t getAnalysisStatus() const { return m_icfs_analysis_status; } @@ -74,4 +76,4 @@ class ICFS_t : public InstructionSet_t, public BaseObj_t ICFS_Analysis_Status_t m_icfs_analysis_status; }; -typedef std::set<ICFS_t*> ICFSSet_t; +} diff --git a/libIRDB/include/core/instruction.hpp b/libIRDB/include/core/instruction.hpp index f5ab68608..0a332983d 100644 --- a/libIRDB/include/core/instruction.hpp +++ b/libIRDB/include/core/instruction.hpp @@ -18,64 +18,56 @@ * */ -class Function_t; // forward decls. -class EhProgram_t; // forward decls. -class EhCallSite_t; // forward decls. - -#define MAX_INSN_SIZE 32 // x86 really declares this as 16, but we'll allow - // for bigger instructions, maybe from other machines? +namespace libIRDB +{ -typedef std::set<Relocation_t*> RelocationSet_t; +using RelocationSet_t = IRDB_SDK::RelocationSet_t; // The basic instruction of a variant. -class Instruction_t : public BaseObj_t +class Instruction_t : public BaseObj_t, virtual public IRDB_SDK::Instruction_t { public: + virtual ~Instruction_t(){} Instruction_t(); Instruction_t(db_id_t id, AddressID_t *addr, Function_t *func, db_id_t orig_id, std::string data, std::string callback, std::string comment, AddressID_t *my_indTarg, db_id_t doip_id); - AddressID_t* GetAddress() const { return my_address; } - Function_t* GetFunction() const { return my_function; } - db_id_t GetOriginalAddressID() const { return orig_address_id; } - Instruction_t* GetFallthrough() const { return fallthrough; } - Instruction_t* GetTarget() const { return target; } - ICFS_t* GetIBTargets() const { return icfs; } + IRDB_SDK::AddressID_t* getAddress() const { return my_address; } + IRDB_SDK::Function_t* getFunction() const ; // { return my_function; } + db_id_t getOriginalAddressID() const { return orig_address_id; } + IRDB_SDK::Instruction_t* getFallthrough() const { return fallthrough; } + IRDB_SDK::Instruction_t* getTarget() const { return target; } + IRDB_SDK::ICFS_t* getIBTargets() const { return icfs; } - // prefer the copy method, since it's inline, compiler will optimize appropriately - // const& rets are just an optimization anyhow.... - //const std::string& GetDataBits() const { return data; } - //const std::string& GetComment() const { return comment; } - //const std::string& GetCallback() const { return callback; } - std::string GetDataBits() const { return data; } - std::string GetCallback() const { return callback; } - std::string GetComment() const { return comment; } - EhProgram_t* GetEhProgram() const { return eh_pgm; } - EhCallSite_t* GetEhCallSite() const { return eh_cs; } + std::string getDataBits() const { return data; } + std::string getCallback() const { return callback; } + std::string getComment() const { return comment; } + IRDB_SDK::EhProgram_t* getEhProgram() const ; // { return eh_pgm; } + IRDB_SDK::EhCallSite_t* getEhCallSite() const ; // { return eh_cs; } - void SetAddress(AddressID_t* newaddr) { my_address=newaddr; } - void SetFunction(Function_t* func ) { my_function=func;} - void SetOriginalAddressID(db_id_t origid) { orig_address_id=origid; /* you shouldn't do this, unless you know what you're doing! */} - void SetFallthrough(Instruction_t* i) { fallthrough=i; } - void SetTarget(Instruction_t* i) { target=i; } - void SetIBTargets(ICFS_t *p_icfs) { icfs=p_icfs; } - void SetDataBits(std::string orig) { data=orig; } - void SetCallback(std::string orig) { callback=orig; } - void SetComment(std::string orig) { comment=orig; } - void SetEhProgram(EhProgram_t* orig) { eh_pgm=orig; } - void SetEhCallSite(EhCallSite_t* orig) { eh_cs=orig; } + void setAddress(IRDB_SDK::AddressID_t* newaddr) ; // { my_address=newaddr; } + void setFunction(IRDB_SDK::Function_t* func ) ; // { my_function=func;} + void setOriginalAddressID(db_id_t origid) { orig_address_id=origid; /* you shouldn't do this, unless you know what you're doing! */} + void setFallthrough(IRDB_SDK::Instruction_t* i) ; // { fallthrough=i; } + void setTarget(IRDB_SDK::Instruction_t* i) ; // { target=i; } + void setIBTargets(IRDB_SDK::ICFS_t *p_icfs) ; // { icfs=p_icfs; } + void setDataBits(std::string orig) { data=orig; } + void setCallback(std::string orig) { callback=orig; } + void setComment(std::string orig) { comment=orig; } + void setEhProgram(IRDB_SDK::EhProgram_t* orig) ; // { eh_pgm=orig; } + void setEhCallSite(IRDB_SDK::EhCallSite_t* orig); // { eh_cs=orig; } - AddressID_t* GetIndirectBranchTargetAddress() { return indTarg; } - void SetIndirectBranchTargetAddress(AddressID_t* myIndTarg) { indTarg=myIndTarg; } + IRDB_SDK::AddressID_t* getIndirectBranchTargetAddress() const; // { return indTarg; } + void setIndirectBranchTargetAddress(IRDB_SDK::AddressID_t* myIndTarg) ; // { indTarg=myIndTarg; } void WriteToDB() { assert(0); } std::vector<std::string> WriteToDB(File_t *fid, db_id_t newid); // int Disassemble(DISASM &d) const; std::string getDisassembly() const; - bool Assemble(std::string assembly); + bool assemble(std::string assembly); - bool IsFunctionExit() const; + bool isFunctionExit() const; //static bool SetsStackPointer(DISASM *disasm); //static bool SetsStackPointer(ARGTYPE* arg); @@ -96,3 +88,4 @@ class Instruction_t : public BaseObj_t EhProgram_t* eh_pgm; EhCallSite_t* eh_cs; }; +} diff --git a/libIRDB/include/core/operand_base.hpp b/libIRDB/include/core/operand_base.hpp index e5de31bdb..7c408fc3f 100644 --- a/libIRDB/include/core/operand_base.hpp +++ b/libIRDB/include/core/operand_base.hpp @@ -1,7 +1,4 @@ -#ifndef libRIDB_decodedoperandcsbase_hpp -#define libRIDB_decodedoperandcsbase_hpp - -#include <memory> +#if 0 namespace libIRDB { @@ -9,7 +6,7 @@ using namespace std; using namespace libIRDB; -class DecodedOperandCapstone_t +class DecodedOperandCapstone_t : virtual public IRDB_SDK::DecodedOperand_t { public: virtual bool isConstant() const=0; diff --git a/libIRDB/include/core/operand_csarm.hpp b/libIRDB/include/core/operand_csarm.hpp index a88fa0740..da26a2105 100644 --- a/libIRDB/include/core/operand_csarm.hpp +++ b/libIRDB/include/core/operand_csarm.hpp @@ -1,9 +1,3 @@ -#ifndef libRIDB_decodedoperandcsarm_hpp -#define libRIDB_decodedoperandcsarm_hpp - -#include <memory> -#include <core/decode_base.hpp> -#include <core/operand_base.hpp> namespace libIRDB { @@ -11,8 +5,9 @@ namespace libIRDB using namespace std; using namespace libIRDB; +class DecodedOperandCapstoneARM64_t; -class DecodedOperandCapstoneARM64_t : public DecodedOperandCapstone_t +class DecodedOperandCapstoneARM64_t : virtual public IRDB_SDK::DecodedOperand_t { public: DecodedOperandCapstoneARM64_t() =delete; @@ -60,4 +55,3 @@ class DecodedOperandCapstoneARM64_t : public DecodedOperandCapstone_t }; } -#endif diff --git a/libIRDB/include/core/operand_csx86.hpp b/libIRDB/include/core/operand_csx86.hpp index 53013b00b..2c2a25082 100644 --- a/libIRDB/include/core/operand_csx86.hpp +++ b/libIRDB/include/core/operand_csx86.hpp @@ -1,9 +1,3 @@ -#ifndef libRIDB_decodedoperandcsx86_hpp -#define libRIDB_decodedoperandcsx86_hpp - -#include <memory> -#include <core/decode_base.hpp> -#include <core/operand_base.hpp> namespace libIRDB { @@ -11,13 +5,12 @@ namespace libIRDB using namespace std; using namespace libIRDB; +class DecodedInstructionCapstoneX86_t; -class DecodedOperandCapstoneX86_t : public DecodedOperandCapstone_t +class DecodedOperandCapstoneX86_t : virtual public IRDB_SDK::DecodedOperand_t { public: DecodedOperandCapstoneX86_t() =delete; - //DecodedOperandCapstoneX86_t& operator=(const DecodedOperandCapstoneX86_t& copy); - //DecodedOperandCapstoneX86_t(const DecodedOperandCapstoneX86_t& copy); virtual ~DecodedOperandCapstoneX86_t(); virtual bool isConstant() const override; @@ -63,4 +56,3 @@ class DecodedOperandCapstoneX86_t : public DecodedOperandCapstone_t }; } -#endif diff --git a/libIRDB/include/core/operand_dispatch.hpp b/libIRDB/include/core/operand_dispatch.hpp index e7edd8c9c..7d7087668 100644 --- a/libIRDB/include/core/operand_dispatch.hpp +++ b/libIRDB/include/core/operand_dispatch.hpp @@ -1,8 +1,3 @@ -#ifndef libRIDB_decodedoperand_dispatch_hpp -#define libRIDB_decodedoperand_dispatch_hpp - -#include <core/decode_csx86.hpp> -#include <core/operand_csx86.hpp> namespace libIRDB { @@ -10,7 +5,7 @@ using namespace std; using namespace libIRDB; -class DecodedOperandDispatcher_t +class DecodedOperandDispatcher_t : virtual public IRDB_SDK::DecodedOperand_t { public: DecodedOperandDispatcher_t() =delete; @@ -58,4 +53,3 @@ class DecodedOperandDispatcher_t }; } -#endif diff --git a/libIRDB/include/core/pqxxdb.hpp b/libIRDB/include/core/pqxxdb.hpp index 9b2f3c1a4..031bd6353 100644 --- a/libIRDB/include/core/pqxxdb.hpp +++ b/libIRDB/include/core/pqxxdb.hpp @@ -18,25 +18,27 @@ * */ +namespace libIRDB +{ -class pqxxDB_t : public DBinterface_t +class pqxxDB_t : public DBinterface_t, virtual public IRDB_SDK::pqxxDB_t { public: pqxxDB_t(); - ~pqxxDB_t() override + virtual ~pqxxDB_t() override { // do nothing }; - void IssueQuery(std::string query); - void IssueQuery(std::stringstream & query); - void MoveToNextRow(); - std::string GetResultColumn(std::string colname); - bool IsDone(); - void Commit(); + void issueQuery(std::string query); + void issueQuery(std::stringstream & query); + void moveToNextRow(); + std::string getResultColumn(std::string colname); + bool isDone(); + void commit(); - pqxx::connection& GetConnection() { return conn; } - pqxx::work& GetTransaction() { return txn; } + pqxx::connection& getConnection() { return conn; } + pqxx::work& getTransaction() { return txn; } private: pqxx::connection conn; @@ -45,3 +47,4 @@ class pqxxDB_t : public DBinterface_t pqxx::result::const_iterator results_iter; }; +} diff --git a/libIRDB/include/core/reloc.hpp b/libIRDB/include/core/reloc.hpp index 0f352c19a..bcd911010 100644 --- a/libIRDB/include/core/reloc.hpp +++ b/libIRDB/include/core/reloc.hpp @@ -18,34 +18,37 @@ * */ +namespace libIRDB +{ + // An ELF file as represented by the DB -class Relocation_t : public BaseObj_t +class Relocation_t : public BaseObj_t, virtual public IRDB_SDK::Relocation_t { public: // create new item. + virtual ~Relocation_t() {} Relocation_t() : BaseObj_t(NULL), offset(0), wrt_obj(NULL), addend(0) {} // new reloc w/no data // a reloc read from the DB - Relocation_t(db_id_t reloc_id, int _offset, std::string _type, BaseObj_t* p_wrt_obj=NULL, int32_t p_addend=0) : - BaseObj_t(NULL), offset(_offset), type(_type), wrt_obj(p_wrt_obj), addend(p_addend) { SetBaseID(reloc_id); } + Relocation_t(db_id_t reloc_id, int _offset, std::string _type, IRDB_SDK::BaseObj_t* p_wrt_obj=NULL, int32_t p_addend=0) : + BaseObj_t(NULL), offset(_offset), type(_type), wrt_obj(p_wrt_obj), addend(p_addend) { setBaseID(reloc_id); } -// Relocation_t(db_id_t reloc_id) : BaseObj_t(NULL), type(""), wrt_obj(NULL), addend(0) { assert(0);} // read from DB void WriteToDB() { assert(0); } // writes to DB ID is not -1. std::vector<std::string> WriteToDB(File_t* fid, BaseObj_t* insn); // writes to DB, ID is not -1. - void SetOffset(int off) { offset=off;} - int GetOffset() const { return offset; } - void SetType(std::string ty) { type=ty;} - std::string GetType() const { return type; } + void setOffset(int off) { offset=off;} + int getOffset() const { return offset; } + void setType(std::string ty) { type=ty;} + std::string getType() const { return type; } - void SetAddend(uint32_t p_addend) { addend=p_addend;} - uint32_t GetAddend() const { return addend; } + void setAddend(uint32_t p_addend) { addend=p_addend;} + uint32_t getAddend() const { return addend; } /* get and set "with respect to" field */ - void SetWRT(libIRDB::BaseObj_t* WRT) { wrt_obj=WRT;} - libIRDB::BaseObj_t* GetWRT() const { return wrt_obj; } + void setWRT(IRDB_SDK::BaseObj_t* WRT) { wrt_obj=dynamic_cast<BaseObj_t*>(WRT); if(WRT) assert(wrt_obj); } + IRDB_SDK::BaseObj_t* getWRT() const { return wrt_obj; } friend class FileIR_t; friend class Function_t; @@ -58,6 +61,7 @@ class Relocation_t : public BaseObj_t std::string type; // a string that describes the relocation type. // possible values: 32-bit, pcrel - BaseObj_t* wrt_obj; + IRDB_SDK::BaseObj_t* wrt_obj; int32_t addend; }; +} diff --git a/libIRDB/include/core/scoop.hpp b/libIRDB/include/core/scoop.hpp index 6dc37fd3a..1985de0c0 100644 --- a/libIRDB/include/core/scoop.hpp +++ b/libIRDB/include/core/scoop.hpp @@ -18,12 +18,13 @@ * */ -#ifndef libirdb_data_scoop_hpp -#define libirdb_data_scoop_hpp + +namespace libIRDB +{ class DataScoopByAddressComp_t; -class DataScoop_t : public BaseObj_t +class DataScoop_t : public BaseObj_t, virtual public IRDB_SDK::DataScoop_t { public: @@ -58,40 +59,40 @@ class DataScoop_t : public BaseObj_t contents(p_contents) { assert(start && end); - SetBaseID(id); + setBaseID(id); } virtual ~DataScoop_t() { /* management of addresses and types is explicit */ } - const std::string GetName() const { return name; } - const std::string& GetContents() const { return contents; } - std::string &GetContents() { return contents; } - libIRDB::AddressID_t* GetStart() const { return start; } - libIRDB::AddressID_t* GetEnd() const { return end; } - libIRDB::Type_t* GetType() const { return type; } - libIRDB::virtual_offset_t GetSize() { assert(start && end); return end->GetVirtualOffset() - start->GetVirtualOffset() + 1 ; } + const std::string getName() const { return name; } + const std::string& getContents() const { return contents; } + std::string &getContents() { return contents; } + IRDB_SDK::AddressID_t* getStart() const { return start; } + IRDB_SDK::AddressID_t* getEnd() const { return end; } + IRDB_SDK::Type_t* getType() const { return type; } + IRDB_SDK::VirtualOffset_t getSize() const { assert(start && end); return end->getVirtualOffset() - start->getVirtualOffset() + 1 ; } bool isReadable() const { return (permissions & permissions_r) == permissions_r; } bool isWriteable() const { return (permissions & permissions_w) == permissions_w; }; bool isExecuteable() const { return (permissions & permissions_x) == permissions_x; }; bool isRelRo() const { return is_relro; }; - int getRawPerms() const { return permissions; } + uint8_t getRawPerms() const { return permissions; } void setRawPerms(int newperms) { permissions=newperms; } - void SetName(const std::string &n) { name=n; } - void SetContents(const std::string &n) { contents=n; } - void SetStart( libIRDB::AddressID_t* addr) { assert(addr); start=addr; } - void SetEnd( libIRDB::AddressID_t* addr ) { assert(addr); end=addr; } - void SetType( libIRDB::Type_t* t) { type=t; } + void setName(const std::string &n) { name=n; } + void setContents(const std::string &n) { contents=n; } + void setStart( IRDB_SDK::AddressID_t* addr) { assert(addr); start=dynamic_cast<AddressID_t*>(addr); assert(start); } + void setEnd ( IRDB_SDK::AddressID_t* addr) { assert(addr); end =dynamic_cast<AddressID_t*>(addr); assert(end ); } + void setType( IRDB_SDK::Type_t* t) { type=dynamic_cast<Type_t*>(t); } - void SetReadable() { permissions |= permissions_r; } - void SetWriteable() { permissions |= permissions_w; } - void SetExecuteable() { permissions |= permissions_x; } - void SetRelRo() { is_relro = true; } + void setReadable() { permissions |= permissions_r; } + void setWriteable() { permissions |= permissions_w; } + void setExecuteable() { permissions |= permissions_x; } + void setRelRo() { is_relro = true; } - void ClearReadable() { permissions &= ~permissions_r; } - void ClearWriteable() { permissions &= ~permissions_w; } - void ClearExecuteable() { permissions &= ~permissions_x; } - void ClearRelRo() { is_relro=false; } + void clearReadable() { permissions &= ~permissions_r; } + void clearWriteable() { permissions &= ~permissions_w; } + void clearExecuteable() { permissions &= ~permissions_x; } + void clearRelRo() { is_relro=false; } std::string WriteToDB(File_t *fid, db_id_t newid); std::string WriteToDBRange(File_t *fid, db_id_t newid, int start, int end, std::string table_name); @@ -104,9 +105,9 @@ class DataScoop_t : public BaseObj_t const static int permissions_x=1; std::string name; - libIRDB::AddressID_t* start; - libIRDB::AddressID_t* end; - libIRDB::Type_t* type; + AddressID_t* start; + AddressID_t* end; + Type_t* type; int permissions; bool is_relro; std::string contents; @@ -125,12 +126,12 @@ class DataScoopByAddressComp_t { ) throw std::logic_error("Cannot order scoops that have null elements."); - return std::make_tuple(lhs->start->GetVirtualOffset(), lhs) < - std::make_tuple(rhs->start->GetVirtualOffset(), rhs); + return std::make_tuple(lhs->start->getVirtualOffset(), lhs) < + std::make_tuple(rhs->start->getVirtualOffset(), rhs); } }; -typedef std::set<DataScoop_t*> DataScoopSet_t; -typedef std::set<DataScoop_t*, DataScoopByAddressComp_t> DataScoopByAddressSet_t; +using DataScoopSet_t = IRDB_SDK::DataScoopSet_t; +using DataScoopByAddressSet_t = std::set<DataScoop_t*, DataScoopByAddressComp_t>; -#endif +} diff --git a/libIRDB/include/core/transform_step.h b/libIRDB/include/core/transform_step.h index 4069c60f5..7e6d40926 100644 --- a/libIRDB/include/core/transform_step.h +++ b/libIRDB/include/core/transform_step.h @@ -1,10 +1,8 @@ -#ifndef TransformStep_h -#define TransformStep_h -namespace Transform_SDK +namespace libIRDB { - class TransformStep_t + class TransformStep_t : virtual public IRDB_SDK::TransformStep_t { public: // Step names must be unique, allows arguments to @@ -17,7 +15,7 @@ namespace Transform_SDK return 0; // success } - virtual int executeStep(libIRDB::IRDBObjects_t *const irdb_objects) + virtual int executeStep(IRDB_SDK::IRDBObjects_t *const irdb_objects) { return 0; // success } @@ -30,6 +28,5 @@ namespace Transform_SDK } extern "C" -std::shared_ptr<Transform_SDK::TransformStep_t> GetTransformStep(void); +std::shared_ptr<IRDB_SDK::TransformStep_t> GetTransformStep(void); -#endif diff --git a/libIRDB/include/core/type.hpp b/libIRDB/include/core/type.hpp index 88e83384d..da04eb8b8 100644 --- a/libIRDB/include/core/type.hpp +++ b/libIRDB/include/core/type.hpp @@ -18,32 +18,20 @@ * */ -#ifndef _IRDB_TYPE_H_ -#define _IRDB_TYPE_H_ - -// add as many types as you want here -// MUST MATCH code in meds2pdb!!! -typedef enum IRDB_Type { - T_UNKNOWN = 0, // must be 0, leave this value alone - T_NUMERIC = 1, T_POINTER = 2, - T_VOID = 10, T_VARIADIC = 11, T_INT = 12, T_CHAR = 13, T_FLOAT = 14, T_DOUBLE = 15, - T_TYPEDEF = 21, T_SUBTYPE = 22, - T_FUNC = 100, T_AGGREGATE = 101 -} IRDB_Type; - -class Type_t; - -typedef std::set<Type_t*> TypeSet_t; -typedef std::vector<Type_t*> TypeVector_t; +namespace libIRDB +{ +using IRDB_Type = IRDB_SDK::IRDBType_t; +using TypeSet_t = IRDB_SDK::TypeSet_t; +using TypeVector_t = IRDB_SDK::TypeVector_t; -class Type_t : public BaseObj_t +class Type_t : public BaseObj_t, virtual public IRDB_SDK::Type_t { public: Type_t() : BaseObj_t(NULL) { - typeID = T_UNKNOWN; + typeID = IRDB_SDK::itUnknown; } Type_t(db_id_t dbid, IRDB_Type t, std::string n) : BaseObj_t(NULL) { - SetBaseID(dbid); + setBaseID(dbid); typeID = t; name = n; } @@ -51,49 +39,49 @@ class Type_t : public BaseObj_t virtual std::string WriteToDB(File_t *fid, db_id_t newid) = 0; - std::string GetName() const { return name; } - void SetName(std::string newname) { name=newname; } - IRDB_Type GetTypeID() const { return typeID; } - void SetTypeID(IRDB_Type t) { typeID = t; } + std::string getName() const { return name; } + void setName(const std::string& newname) { name=newname; } + IRDB_Type getTypeID() const { return typeID; } + void setTypeID(IRDB_Type t) { typeID = t; } - virtual bool IsUnknownType() const { return typeID == T_UNKNOWN; } - virtual bool IsVariadicType() const { return typeID == T_VARIADIC; } - virtual bool IsAggregateType() const { return typeID == T_AGGREGATE; } - virtual bool IsFuncType() const { return typeID == T_FUNC; } - virtual bool IsBasicType() const { return false; } - virtual bool IsPointerType() const { return false; } - virtual bool IsNumericType() const { return false; } + virtual bool isUnknownType() const { return typeID == IRDB_SDK::itUnknown; } + virtual bool isVariadicType() const { return typeID == IRDB_SDK::itVariadic; } + virtual bool isAggregateType() const { return typeID == IRDB_SDK::itAggregate; } + virtual bool isFuncType() const { return typeID == IRDB_SDK::itFunc; } + virtual bool isBasicType() const { return false; } + virtual bool isPointerType() const { return false; } + virtual bool isNumericType() const { return false; } private: std::string name; IRDB_Type typeID; }; -class BasicType_t : public Type_t +class BasicType_t : public Type_t, virtual public IRDB_SDK::BasicType_t { public: BasicType_t() : Type_t() {} BasicType_t(db_id_t id, IRDB_Type type, std::string p_name) : Type_t(id, type, p_name) {} virtual ~BasicType_t() {} - virtual bool IsBasicType() const { return true; } - virtual bool IsNumericType() const; + virtual bool isBasicType() const { return true; } + virtual bool isNumericType() const; std::string WriteToDB(File_t *fid, db_id_t newid); }; -class PointerType_t : public Type_t +class PointerType_t : public Type_t, virtual public IRDB_SDK::PointerType_t { public: - PointerType_t() : Type_t() { SetTypeID(T_POINTER); referentType = NULL; } - PointerType_t(db_id_t id, Type_t* ref, std::string p_name) : Type_t(id, T_POINTER, p_name) { - SetReferentType(ref); + PointerType_t() : Type_t() { setTypeID(IRDB_SDK::itPointer); referentType = NULL; } + PointerType_t(db_id_t id, Type_t* ref, std::string p_name) : Type_t(id, IRDB_SDK::itPointer, p_name) { + setReferentType(ref); } virtual ~PointerType_t() {} - virtual bool IsPointerType() const { return true; } + virtual bool isPointerType() const { return true; } - Type_t* GetReferentType() const { return referentType; } - void SetReferentType(Type_t* r) { referentType = r; } + IRDB_SDK::Type_t* getReferentType() const { return referentType; } + void setReferentType(IRDB_SDK::Type_t* r) { referentType = dynamic_cast<Type_t*>(r); if(r) assert(referentType); } std::string WriteToDB(File_t *fid, db_id_t newid); @@ -101,22 +89,22 @@ class PointerType_t : public Type_t Type_t* referentType; }; -class AggregateType_t : public Type_t +class AggregateType_t : public Type_t, virtual public IRDB_SDK::AggregateType_t { public: - AggregateType_t() : Type_t() { SetTypeID(T_AGGREGATE); } - AggregateType_t(db_id_t id, std::string p_name) : Type_t(id, T_AGGREGATE, p_name) {} + AggregateType_t() : Type_t() { setTypeID(IRDB_SDK::itAggregate); } + AggregateType_t(db_id_t id, std::string p_name) : Type_t(id, IRDB_SDK::itAggregate, p_name) {} virtual ~AggregateType_t() {} - virtual bool IsAggregateType() const { return true; } + virtual bool isAggregateType() const { return true; } - void AddAggregatedType(Type_t *t, int pos); - virtual size_t GetNumAggregatedTypes() const { return refTypes.size(); } - Type_t* GetAggregatedType(unsigned int pos) const { + void addAggregatedType(IRDB_SDK::Type_t *t, int pos); + virtual size_t getNumAggregatedTypes() const { return refTypes.size(); } + IRDB_SDK::Type_t* getAggregatedType(unsigned int pos) const { return (pos < (unsigned int)refTypes.size()) ? refTypes.at(pos) : NULL; } std::string toString() { - return GetName(); + return getName(); } std::string WriteToDB(File_t *fid, db_id_t newid); @@ -125,21 +113,21 @@ class AggregateType_t : public Type_t TypeVector_t refTypes; }; -class FuncType_t : public Type_t +class FuncType_t : public Type_t, virtual public IRDB_SDK::FuncType_t { public: - FuncType_t() : Type_t() { SetTypeID(T_FUNC); _init(); } - FuncType_t(db_id_t id, std::string p_name) : Type_t(id, T_FUNC, p_name) { _init(); } + FuncType_t() : Type_t() { setTypeID(IRDB_SDK::itFunc); _init(); } + FuncType_t(db_id_t id, std::string p_name) : Type_t(id, IRDB_SDK::itFunc, p_name) { _init(); } virtual ~FuncType_t() {} - virtual bool IsFuncType() const { return true; } + virtual bool isFuncType() const { return true; } std::string WriteToDB(File_t *fid, db_id_t newid); - Type_t* GetReturnType() const { return returnType; } - void SetReturnType(Type_t *t) { returnType = t; } - AggregateType_t* GetArgumentsType() const { return argsType; } - void SetArgumentsType(AggregateType_t *t) { argsType = t; } + IRDB_SDK::Type_t* getReturnType() const { return returnType; } + void setReturnType(IRDB_SDK::Type_t *t) { returnType = dynamic_cast<Type_t*>(t); if(t) assert(returnType); } + IRDB_SDK::AggregateType_t* getArgumentsType() const { return argsType; } + void setArgumentsType(IRDB_SDK::AggregateType_t *t) { argsType = dynamic_cast<AggregateType_t*>(t); if(t) assert(argsType); } private: void _init() { @@ -152,4 +140,4 @@ class FuncType_t : public Type_t AggregateType_t* argsType; }; -#endif +} diff --git a/libIRDB/include/core/variantid.hpp b/libIRDB/include/core/variantid.hpp index ce17a1f36..578ff647e 100644 --- a/libIRDB/include/core/variantid.hpp +++ b/libIRDB/include/core/variantid.hpp @@ -18,46 +18,38 @@ * */ +namespace libIRDB +{ #define CURRENT_SCHEMA 2 -class VariantID_t; - -std::ostream& operator<<(std::ostream& out, const libIRDB::VariantID_t& pid); +using FileSet_t = IRDB_SDK::FileSet_t; -using FileSet_t = std::set<File_t*>; - -class VariantID_t : public BaseObj_t +class VariantID_t : public BaseObj_t, virtual public IRDB_SDK::VariantID_t { public: VariantID_t(); // create a Variant ID not in the database VariantID_t(db_id_t pid); // read from the DB ~VariantID_t(); // Deletes the File_t objects -- beware dangling File_t* in FileIR_t objects! - bool IsRegistered(); - bool Register(); // accesses DB + bool isRegistered() const; + bool registerID(); // accesses DB - VariantID_t* Clone(bool deep=true); // accesses DB + IRDB_SDK::VariantID_t* clone(bool deep=true); // accesses DB void WriteToDB(); void DropFromDB(); - FileSet_t& GetFiles() { return files; } - const FileSet_t& GetFiles() const { return files; } + const FileSet_t& getFiles() const { return files; } - std::string GetName() { return name; } - void SetName(std::string newname) { name=newname;} + std::string getName() const { return name; } + void setName(std::string newname) { name=newname;} - File_t* GetMainFile() const; + IRDB_SDK::File_t* getMainFile() const; - friend std::ostream& libIRDB::operator<<(std::ostream& out, const VariantID_t& pid); - //friend class FileIR_T; - //friend class Function_t; - //friend class AddressID_t; - //friend class Instruction_t; - db_id_t GetOriginalVariantID() const { return orig_pid;} + db_id_t getOriginalVariantID() const { return orig_pid;} void CloneFiles(FileSet_t& files); File_t* CloneFile(File_t* fptr); @@ -77,3 +69,8 @@ class VariantID_t : public BaseObj_t }; + + + +} + diff --git a/libIRDB/include/libIRDB-cfg.hpp b/libIRDB/include/libIRDB-cfg.hpp index 45d80eb6d..3546227c6 100644 --- a/libIRDB/include/libIRDB-cfg.hpp +++ b/libIRDB/include/libIRDB-cfg.hpp @@ -33,6 +33,8 @@ namespace libIRDB { + using namespace std; + #include <cfg/BasicBlock.hpp> #include <cfg/CFG.hpp> #include <cfg/callgraph.hpp> diff --git a/libIRDB/include/libIRDB-core.hpp b/libIRDB/include/libIRDB-core.hpp index 5c0940768..e5d92b940 100644 --- a/libIRDB/include/libIRDB-core.hpp +++ b/libIRDB/include/libIRDB-core.hpp @@ -31,12 +31,8 @@ #include <ctime> #include <stdint.h> -namespace libIRDB -{ - -class VariantID_t; // forward decl for many classes -class File_t; // forward decl for many classes -class Instruction_t; // forward decl for many classes +// include SDK +#include <irdb-core> #include <core/basetypes.hpp> #include <core/dbinterface.hpp> @@ -57,9 +53,6 @@ class Instruction_t; // forward decl for many classes #include <core/pqxxdb.hpp> #include <core/IRDB_Objects.hpp> #include <core/transform_step.h> - -}; - #include <core/decode.hpp> #endif diff --git a/libIRDB/include/syscall/syscall.hpp b/libIRDB/include/syscall/syscall.hpp index 857c15805..d929a85e6 100644 --- a/libIRDB/include/syscall/syscall.hpp +++ b/libIRDB/include/syscall/syscall.hpp @@ -24,30 +24,19 @@ typedef enum { SNT_Unknown=-1, -#ifdef CGC - SNT_terminate=1, - SNT_transmit=2, - SNT_receive=3, - SNT_fdwait=4, - SNT_allocate=5, - SNT_deallocate=6, - SNT_random=7 -#else -/* LINUX here? */ -#endif } SyscallNumber_t; class SyscallSite_t { public: - SyscallSite_t(libIRDB::Instruction_t* p_site, libIRDB::SyscallNumber_t p_num) : site(p_site), num(p_num) {} + SyscallSite_t(IRDB_SDK::Instruction_t* p_site, libIRDB::SyscallNumber_t p_num) : site(p_site), num(p_num) {} bool operator<(const libIRDB::SyscallSite_t& rhs) const { return this->site < rhs.site; } - libIRDB::Instruction_t* GetSyscallSite() { return site; } - libIRDB::Instruction_t* GetSite() const { return site; } + IRDB_SDK::Instruction_t* GetSyscallSite() { return site; } + IRDB_SDK::Instruction_t* GetSite() const { return site; } libIRDB::SyscallNumber_t GetSyscallNumber() const { return num; } private: - libIRDB::Instruction_t* site; + IRDB_SDK::Instruction_t* site; libIRDB::SyscallNumber_t num; }; typedef std::set<SyscallSite_t> SyscallSiteSet_t; @@ -55,14 +44,14 @@ typedef std::set<SyscallSite_t> SyscallSiteSet_t; class Syscalls_t { public: - Syscalls_t(FileIR_t *the_firp=NULL) { if(the_firp) FindSystemCalls(the_firp); } + Syscalls_t(IRDB_SDK::FileIR_t *the_firp=NULL) { if(the_firp) FindSystemCalls(the_firp); } - bool FindSystemCalls(const libIRDB::FileIR_t* firp); + bool FindSystemCalls(const IRDB_SDK::FileIR_t* firp); const libIRDB::SyscallSiteSet_t& GetSyscalls() {return syscalls;} protected: - libIRDB::SyscallNumber_t FindSystemCallNumber(libIRDB::Instruction_t* insn, + libIRDB::SyscallNumber_t FindSystemCallNumber(IRDB_SDK::Instruction_t* insn, const libIRDB::InstructionPredecessors_t& preds); private: diff --git a/libIRDB/include/util/IBT_Provenance.hpp b/libIRDB/include/util/IBT_Provenance.hpp index 07f2b0bf7..898d36fdd 100644 --- a/libIRDB/include/util/IBT_Provenance.hpp +++ b/libIRDB/include/util/IBT_Provenance.hpp @@ -8,7 +8,7 @@ class IBTProvenance_t private: // types - using InsnProvMap_t = std::map<const Instruction_t*, Provenance_t>; + using InsnProvMap_t = std::map<const IRDB_SDK::Instruction_t*, Provenance_t>; // data InsnProvMap_t prov_map; @@ -19,12 +19,12 @@ class IBTProvenance_t void AddProvs(const Provenance_t& p, const InstructionSet_t& after) ; public: - IBTProvenance_t(const FileIR_t* f=NULL) {Init(); if(f) AddFile(f);} + IBTProvenance_t(const IRDB_SDK::FileIR_t* f=NULL) {Init(); if(f) AddFile(f);} virtual ~IBTProvenance_t() {} // default destructor not OK for some reason? - void AddFile(const FileIR_t* ); + void AddFile(const IRDB_SDK::FileIR_t* ); - const Provenance_t& operator[] (const Instruction_t* i) const + const Provenance_t& operator[] (const IRDB_SDK::Instruction_t* i) const { const auto it=prov_map.find(i); if (it!= prov_map.end()) diff --git a/libIRDB/include/util/Provenance.hpp b/libIRDB/include/util/Provenance.hpp index 73a14041a..1e5a8af49 100644 --- a/libIRDB/include/util/Provenance.hpp +++ b/libIRDB/include/util/Provenance.hpp @@ -10,7 +10,7 @@ class Provenance_t enum class ProvType { IndJump = 0, IndCall = 1, Ret = 2 }; std::bitset<3> prov; public: - Provenance_t() {prov = bitset<3>();} + Provenance_t() {prov = std::bitset<3>();} virtual ~Provenance_t() {;} void addReturn() diff --git a/libIRDB/include/util/insn_preds.hpp b/libIRDB/include/util/insn_preds.hpp index ac05f41c6..b91c39518 100644 --- a/libIRDB/include/util/insn_preds.hpp +++ b/libIRDB/include/util/insn_preds.hpp @@ -25,18 +25,18 @@ class InstructionPredecessors_t { private: - typedef std::map<const Instruction_t*, InstructionSet_t> PredMap_t; + typedef std::map<const IRDB_SDK::Instruction_t*, InstructionSet_t> PredMap_t; public: - InstructionPredecessors_t(const FileIR_t* f=NULL) {Init(); if(f) AddFile(f);} + InstructionPredecessors_t(const IRDB_SDK::FileIR_t* f=NULL) {Init(); if(f) AddFile(f);} virtual ~InstructionPredecessors_t() {;} - virtual void AddFile(const FileIR_t* ); + virtual void AddFile(const IRDB_SDK::FileIR_t* ); - InstructionSet_t& operator[] (const Instruction_t* i) + InstructionSet_t& operator[] (const IRDB_SDK::Instruction_t* i) { return pred_map[i]; } - const InstructionSet_t& operator[] (const Instruction_t* i) const + const InstructionSet_t& operator[] (const IRDB_SDK::Instruction_t* i) const { PredMap_t::const_iterator it=pred_map.find(i); if (it!= pred_map.end()) @@ -50,8 +50,8 @@ class InstructionPredecessors_t private: - virtual void AddPred(const Instruction_t* before, const Instruction_t* after); - virtual void AddPreds(const Instruction_t* before, const InstructionSet_t& after); + virtual void AddPred(const IRDB_SDK::Instruction_t* before, const IRDB_SDK::Instruction_t* after); + virtual void AddPreds(const IRDB_SDK::Instruction_t* before, const IRDB_SDK::InstructionSet_t& after); PredMap_t pred_map; }; diff --git a/libIRDB/include/util/params.hpp b/libIRDB/include/util/params.hpp index 758ad7241..842c83835 100644 --- a/libIRDB/include/util/params.hpp +++ b/libIRDB/include/util/params.hpp @@ -1,10 +1,10 @@ #ifndef _PARAMS_H #define _PARAMS_H -extern bool IsParameterWrite(const libIRDB::FileIR_t *firp, libIRDB::Instruction_t* insn, std::string& output_dst); -extern bool CallFollows(const libIRDB::FileIR_t *firp, libIRDB::Instruction_t* insn, const std::string& arg_str, const std::string & = ""); -extern bool LeaFlowsIntoCall(const libIRDB::FileIR_t *firp, libIRDB::Instruction_t* insn); -extern bool LeaFlowsIntoPrintf(const libIRDB::FileIR_t *firp, libIRDB::Instruction_t* insn); -extern bool FlowsIntoCall(const libIRDB::FileIR_t *firp, libIRDB::Instruction_t* insn); +extern bool IsParameterWrite(const IRDB_SDK::FileIR_t *firp, IRDB_SDK::Instruction_t* insn, std::string& output_dst); +extern bool CallFollows(const IRDB_SDK::FileIR_t *firp, IRDB_SDK::Instruction_t* insn, const std::string& arg_str, const std::string & = ""); +extern bool LeaFlowsIntoCall(const IRDB_SDK::FileIR_t *firp, IRDB_SDK::Instruction_t* insn); +extern bool LeaFlowsIntoPrintf(const IRDB_SDK::FileIR_t *firp, IRDB_SDK::Instruction_t* insn); +extern bool FlowsIntoCall(const IRDB_SDK::FileIR_t *firp, IRDB_SDK::Instruction_t* insn); #endif diff --git a/libIRDB/include/utils.hpp b/libIRDB/include/utils.hpp index 6f4a9046e..bde052743 100644 --- a/libIRDB/include/utils.hpp +++ b/libIRDB/include/utils.hpp @@ -75,10 +75,7 @@ inline bool is_in_set(const std::set<S>& container, const S& key) template <class T, class S> inline S const& find_map_object( const std::map< T , S > &a_map, const T& key) { - typename std::map< T , S >::const_iterator it; - - it=a_map.find(key); - + const auto it=a_map.find(key); assert(it!=a_map.end()); return (*it).second; diff --git a/libIRDB/src/cfg/BasicBlock.cpp b/libIRDB/src/cfg/BasicBlock.cpp index ccba987cd..db79f64fb 100644 --- a/libIRDB/src/cfg/BasicBlock.cpp +++ b/libIRDB/src/cfg/BasicBlock.cpp @@ -28,6 +28,8 @@ using namespace libIRDB; using namespace std; +#define ALLOF(a) begin((a)), end((a)) + BasicBlock_t::BasicBlock_t() : is_exit_block(false) { @@ -37,11 +39,11 @@ BasicBlock_t::BasicBlock_t() void BasicBlock_t::BuildBlock ( - Instruction_t* insn, - const map<Instruction_t*,BasicBlock_t*> &insn2block_map + IRDB_SDK::Instruction_t* insn, + const map<IRDB_SDK::Instruction_t*,BasicBlock_t*> &insn2block_map ) { - const auto &func=insn->GetFunction(); + const auto &func=insn->getFunction(); assert(insn); /* loop through the instructions for this block */ while(insn) @@ -49,8 +51,8 @@ void BasicBlock_t::BuildBlock /* insert this instruction */ instructions.push_back(insn); - Instruction_t* target_insn=insn->GetTarget(); - Instruction_t* ft_insn=insn->GetFallthrough(); + auto target_insn=insn->getTarget(); + auto ft_insn=insn->getFallthrough(); /* determine if there's a target block */ BasicBlock_t* target_block=NULL; @@ -70,27 +72,27 @@ void BasicBlock_t::BuildBlock } /* This is also the end of the block if this is a function exit instruction */ - if(insn->IsFunctionExit()) + if(insn->isFunctionExit()) { is_exit_block=true; } // handle fixed-call fallthroughs. - for_each(insn->GetRelocations().begin(), insn->GetRelocations().end(), [this,&insn2block_map](Relocation_t* reloc) + for_each(ALLOF(insn->getRelocations()), [this,&insn2block_map](IRDB_SDK::Relocation_t* reloc) { // and has a reloc that's a pcrel with a WRT object // possible for a call to have a null fallthrouth (and consequently null WRT) // becauase the call may be the last insn in a section, etc. - if( reloc->GetType()==string("fix_call_fallthrough") && reloc->GetWRT()!=NULL) + if( reloc->getType()==string("fix_call_fallthrough") && reloc->getWRT()!=NULL) { - assert(reloc->GetWRT()!=NULL); - Instruction_t* fix_call_fallthrough_insn=dynamic_cast<Instruction_t*>(reloc->GetWRT()); + assert(reloc->getWRT()!=NULL); + auto fix_call_fallthrough_insn=dynamic_cast<Instruction_t*>(reloc->getWRT()); assert(fix_call_fallthrough_insn); // this block has a fallthrough to the return block. if(is_in_container(insn2block_map,fix_call_fallthrough_insn)) { - BasicBlock_t* fix_call_fallthrough_blk=find_map_object(insn2block_map,fix_call_fallthrough_insn); + BasicBlock_t* fix_call_fallthrough_blk=find_map_object(insn2block_map,static_cast<IRDB_SDK::Instruction_t*>(fix_call_fallthrough_insn)); successors.insert(fix_call_fallthrough_blk); fix_call_fallthrough_blk->GetPredecessors().insert(this); } @@ -116,7 +118,7 @@ void BasicBlock_t::BuildBlock break; /* check for a fallthrough out of the function */ - if(ft_insn && ft_insn->GetFunction() != func) // !is_in_container(func->GetInstructions(),ft_insn)) + if(ft_insn && ft_insn->getFunction() != func) break; @@ -128,11 +130,11 @@ void BasicBlock_t::BuildBlock insn=instructions[instructions.size()-1]; // get last instruction. assert(insn); - if(insn->GetIBTargets()) + if(insn->getIBTargets()) { - for_each(insn->GetIBTargets()->begin(), insn->GetIBTargets()->end(), [this,&insn2block_map,func](Instruction_t* target) + for_each(ALLOF(*insn->getIBTargets()), [this,&insn2block_map,func](IRDB_SDK::Instruction_t* target) { - if(is_in_container(insn2block_map,target) && target!=func->GetEntryPoint()) // don't link calls to the entry block. + if(is_in_container(insn2block_map,target) && target!=func->getEntryPoint()) // don't link calls to the entry block. { BasicBlock_t* target_block=find_map_object(insn2block_map,target); target_block->GetPredecessors().insert(this); @@ -151,7 +153,7 @@ std::ostream& libIRDB::operator<<(std::ostream& os, const BasicBlock_t& block) for(auto i=0U;i<block.instructions.size();i++) { const auto insn=block.instructions[i]; - os<<"\t Instruction "<<std::dec<<i<<" at " << std::hex << insn->GetAddress()->GetVirtualOffset() << " with id " << std::dec << insn->GetBaseID() << " " << insn->GetComment() << endl; + os<<"\t Instruction "<<std::dec<<i<<" at " << std::hex << insn->getAddress()->getVirtualOffset() << " with id " << std::dec << insn->getBaseID() << " " << insn->getComment() << endl; } os<<"\t ---- done block print -----" <<endl; os<<endl; @@ -165,8 +167,8 @@ bool BasicBlock_t::EndsInBranch() const auto branch=instructions[instructions.size()-1]; assert(branch); - const auto d=DecodedInstruction_t(branch); - return d.isBranch(); + const auto d=DecodedInstruction_t::factory(branch); + return d->isBranch(); } @@ -175,13 +177,14 @@ bool BasicBlock_t::EndsInIndirectBranch() const auto *branch=instructions[instructions.size()-1]; assert(branch); - const auto d=DecodedInstruction_t(branch); + const auto p_d=DecodedInstruction_t::factory(branch); + const auto &d =*p_d; if(d.isReturn()) return true; if(d.isUnconditionalBranch() || d.isCall()) { - if(!d.getOperand(0).isConstant()) + if(!d.getOperand(0)->isConstant()) /* not a constant type */ return true; return false; @@ -195,12 +198,12 @@ bool BasicBlock_t::EndsInConditionalBranch() return false; const auto branch=instructions[instructions.size()-1]; assert(branch); - const auto d=DecodedInstruction_t(branch); + const auto d=DecodedInstruction_t::factory(branch); - return d.isConditionalBranch(); + return d->isConditionalBranch(); } -Instruction_t* BasicBlock_t::GetBranchInstruction() +IRDB_SDK::Instruction_t* BasicBlock_t::GetBranchInstruction() { if(!EndsInBranch()) diff --git a/libIRDB/src/cfg/CFG.cpp b/libIRDB/src/cfg/CFG.cpp index 7757814ff..36be933e2 100644 --- a/libIRDB/src/cfg/CFG.cpp +++ b/libIRDB/src/cfg/CFG.cpp @@ -30,43 +30,43 @@ using namespace libIRDB; /* * FindTargets - locate all possible instructions that are the target of a jump instruction */ -static InstructionSet_t FindBlockStarts(Function_t* func) +static InstructionSet_t FindBlockStarts(IRDB_SDK::Function_t* func) { InstructionSet_t targets; InstructionSet_t found_fallthrough_to; - if(func->GetEntryPoint()) + if(func->getEntryPoint()) /* the entry point of the function is a target instruction for this CFG */ - targets.insert(func->GetEntryPoint()); + targets.insert(func->getEntryPoint()); /* for each instruction, decide if it's a block start based on whether or not * it can be indirectly branched to. Also mark direct targets as block starts. */ - for(InstructionSet_t::iterator it=func->GetInstructions().begin(); - it!=func->GetInstructions().end(); + for(auto it=func->getInstructions().begin(); + it!=func->getInstructions().end(); ++it ) { /* Get the instruction */ - Instruction_t* insn=*it; + auto insn=*it; /* If this instruction might be an indirect branch target, then mark it as a block start */ - if(insn->GetIndirectBranchTargetAddress()) + if(insn->getIndirectBranchTargetAddress()) { targets.insert(insn); } /* get target and fallthrough */ - Instruction_t* target=insn->GetTarget(); - Instruction_t* ft=insn->GetFallthrough(); + auto target=insn->getTarget(); + auto ft=insn->getFallthrough(); /* if this instruction has a target, and the target is in this function, mark the target as a block start */ - if(target && is_in_container(func->GetInstructions(), target)) + if(target && is_in_container(func->getInstructions(), target)) targets.insert(target); /* there is a target, and a failthrough, and the fallthrough is in this function */ - if(target && ft && is_in_container(func->GetInstructions(), ft)) + if(target && ft && is_in_container(func->getInstructions(), ft)) targets.insert(ft); // we already found a fallthrough to ft, so we have 2+ fallthroughs to ft. mark it as a control flow merge. @@ -82,14 +82,14 @@ static InstructionSet_t FindBlockStarts(Function_t* func) return targets; } -ControlFlowGraph_t::ControlFlowGraph_t(Function_t* func) : - entry(NULL), function(func) +ControlFlowGraph_t::ControlFlowGraph_t(IRDB_SDK::Function_t* func) : + entry(NULL), function(dynamic_cast<Function_t*>(func)) { Build(func); } -void ControlFlowGraph_t::alloc_blocks(const InstructionSet_t &starts, map<Instruction_t*,BasicBlock_t*>& insn2block_map) +void ControlFlowGraph_t::alloc_blocks(const InstructionSet_t &starts, map<IRDB_SDK::Instruction_t*,BasicBlock_t*>& insn2block_map) { /* create a basic block for each instruction that starts a block */ for(const auto &insn : starts) @@ -106,7 +106,7 @@ void ControlFlowGraph_t::alloc_blocks(const InstructionSet_t &starts, map<Instru } } -void ControlFlowGraph_t::build_blocks(const map<Instruction_t*,BasicBlock_t*>& insn2block_map) +void ControlFlowGraph_t::build_blocks(const map<IRDB_SDK::Instruction_t*,BasicBlock_t*>& insn2block_map) { /* Ask the basic block to set the fields for each block that need to be set */ @@ -126,7 +126,7 @@ void ControlFlowGraph_t::build_blocks(const map<Instruction_t*,BasicBlock_t*>& i } -void ControlFlowGraph_t::find_unblocked_instructions(InstructionSet_t &starts, Function_t* func) +void ControlFlowGraph_t::find_unblocked_instructions(InstructionSet_t &starts, IRDB_SDK::Function_t* func) { auto mapped_instructions=InstructionSet_t(); auto missed_instructions=InstructionSet_t(); @@ -134,23 +134,23 @@ void ControlFlowGraph_t::find_unblocked_instructions(InstructionSet_t &starts, F mapped_instructions.insert(ALLOF(block->GetInstructions())); auto my_inserter=inserter(missed_instructions,missed_instructions.end()); - set_difference(ALLOF(func->GetInstructions()), ALLOF(mapped_instructions), my_inserter); + set_difference(ALLOF(func->getInstructions()), ALLOF(mapped_instructions), my_inserter); starts.insert(ALLOF(missed_instructions)); } -void ControlFlowGraph_t::Build(Function_t* func) +void ControlFlowGraph_t::Build(IRDB_SDK::Function_t* func) { auto starts=FindBlockStarts(func); - auto insn2block_map=map<Instruction_t*,BasicBlock_t*> (); + auto insn2block_map=map<IRDB_SDK::Instruction_t*,BasicBlock_t*> (); alloc_blocks(starts, insn2block_map); build_blocks(insn2block_map); /* record the entry block */ - if(func->GetEntryPoint()) - entry=insn2block_map[func->GetEntryPoint()]; + if(func->getEntryPoint()) + entry=insn2block_map[func->getEntryPoint()]; /* most functions are done now. */ /* however, if a function has a (direct) side entrance, @@ -184,12 +184,12 @@ CFG_EdgeType ControlFlowGraph_t::GetEdgeType(const BasicBlock_t *p_src, const Ba auto edgeType = CFG_EdgeType(); - if (last_in_src->GetFallthrough() == first_in_tgt) + if (last_in_src->getFallthrough() == first_in_tgt) { edgeType.insert(CFG_FallthroughEdge); } - if (last_in_src->GetTarget() == first_in_tgt) + if (last_in_src->getTarget() == first_in_tgt) { edgeType.insert(CFG_TargetEdge); } diff --git a/libIRDB/src/cfg/SConscript b/libIRDB/src/cfg/SConscript index bed584038..ae9c12470 100644 --- a/libIRDB/src/cfg/SConscript +++ b/libIRDB/src/cfg/SConscript @@ -11,6 +11,7 @@ files= ''' BasicBlock.cpp callgraph.cpp CFG.cpp domgraph.cpp criticaledge.cpp ''' cpppath=''' + $IRDB_SDK/include/ $SECURITY_TRANSFORMS_HOME/include/ $SECURITY_TRANSFORMS_HOME/libIRDB/include/ ''' diff --git a/libIRDB/src/cfg/callgraph.cpp b/libIRDB/src/cfg/callgraph.cpp index 68b0784a5..e126f5620 100644 --- a/libIRDB/src/cfg/callgraph.cpp +++ b/libIRDB/src/cfg/callgraph.cpp @@ -46,45 +46,35 @@ Callgraph_t::~Callgraph_t() static bool IsCallSite(Instruction_t* insn) { - //DISASM insnd; - //Disassemble(insn,insnd); - //return NULL!=(strstr(insnd.Instruction.Mnemonic,"call")); - - const auto d=DecodedInstruction_t(insn); - return d.isCall(); + const auto d=DecodedInstruction_t::factory(insn); + return d->isCall(); } static bool IsTailJmpSite(Instruction_t* insn) { - //DISASM insnd; - //Disassemble(insn,insnd); - const auto d=DecodedInstruction_t(insn); - // if(strstr(insnd.Instruction.Mnemonic,"jmp")==NULL) - if(d.isBranch()) + const auto d=DecodedInstruction_t::factory(insn); + if(d->isBranch()) return false; - if(insn->GetTarget()==NULL) + if(insn->getTarget()==NULL) return true; - if(insn->GetFunction() != insn->GetTarget()->GetFunction()) + if(insn->getFunction() != insn->getTarget()->getFunction()) return true; return false; } static bool IsPushJmpSite(Instruction_t* insn) { - //DISASM insnd; - //Disassemble(insn,insnd); - const auto d=DecodedInstruction_t(insn); - if(d.getMnemonic()!="push" || insn->GetFallthrough()==NULL) + const auto d=DecodedInstruction_t::factory(insn); + if(d->getMnemonic()!="push" || insn->getFallthrough()==NULL) return false; - if(insn->GetRelocations().size()==0) + if(insn->getRelocations().size()==0) return false; - const auto d2=DecodedInstruction_t(insn->GetFallthrough()); - //if(strstr(insnd.Instruction.Mnemonic,"jmp")==NULL) - if(!d2.isBranch()) + const auto d2=DecodedInstruction_t::factory(insn->getFallthrough()); + if(!d2->isBranch()) return false; return true; @@ -92,12 +82,12 @@ static bool IsPushJmpSite(Instruction_t* insn) void Callgraph_t::MarkCallSite(Instruction_t* insn) { - Function_t* from_func=insn->GetFunction(); - Instruction_t* to_insn=insn->GetTarget(); - Function_t* to_func= to_insn==NULL? NULL : to_insn->GetFunction(); + auto from_func=insn->getFunction(); + auto to_insn=insn->getTarget(); + auto to_func= to_insn==NULL? NULL : to_insn->getFunction(); - CallGraphNode_t* from_node = FindNode(from_func); - CallGraphNode_t* to_node = FindNode(to_func); + auto from_node = FindNode(from_func); + auto to_node = FindNode(to_func); if (!from_node) from_node = &GetDefaultHellNode(); @@ -110,40 +100,40 @@ void Callgraph_t::MarkCallSite(Instruction_t* insn) callers[to_node].insert(from_node); } -void Callgraph_t::CreateNodes(libIRDB::FileIR_t *firp) +void Callgraph_t::CreateNodes(IRDB_SDK::FileIR_t *firp) { - set<Function_t*> &fns=firp->GetFunctions(); - for(set<Function_t*>::iterator it=fns.begin(); fns.end() != it; ++it) + const FunctionSet_t &fns=firp->getFunctions(); + for(auto it=fns.begin(); fns.end() != it; ++it) { - Function_t *fn=*it; + auto fn=*it; if (fn) { - CallGraphNode_t *newnode = new CallGraphNode_t(fn); + auto newnode = new CallGraphNode_t(fn); nodes[fn] = newnode; // cout << "Added CGNode: " << GetNodeName(newnode) << endl; } } } -void Callgraph_t::AddFile(libIRDB::FileIR_t* const firp) +void Callgraph_t::AddFile(IRDB_SDK::FileIR_t* const firp) { // Create CG Nodes from functions CreateNodes(firp); // for each instruction - auto &insns=firp->GetInstructions(); + auto &insns=firp->getInstructions(); for(auto it=insns.begin(); insns.end() != it; ++it) { - auto insn=*it; + auto insn=dynamic_cast<Instruction_t*>(*it); if(IsCallSite(insn) || IsTailJmpSite(insn)) MarkCallSite(insn); if(IsPushJmpSite(insn)) - MarkCallSite(insn->GetFallthrough()); + MarkCallSite(dynamic_cast<Instruction_t*>(insn->getFallthrough())); - if(insn->GetFunction() && insn->GetFunction()->GetEntryPoint()==insn - && insn->GetIndirectBranchTargetAddress()) + if(insn->getFunction() && insn->getFunction()->getEntryPoint()==insn + && insn->getIndirectBranchTargetAddress()) { - auto node = FindNode(insn->GetFunction()); + auto node = FindNode(insn->getFunction()); assert(node); callees[&GetDefaultHellNode()].insert(node); callers[node].insert(&GetDefaultHellNode()); @@ -245,12 +235,12 @@ cerr << "adding " << GetNodeName(*it) << " to ancestor list " << hex << *it << d } } -CallGraphNode_t* Callgraph_t::FindNode(Function_t* const fn) +CallGraphNode_t* Callgraph_t::FindNode(IRDB_SDK::Function_t* const fn) { return nodes[fn]; } -void Callgraph_t::GetAncestors(Function_t* const fn, CallGraphNodeSet_t &ancestors, bool skipHellNode) +void Callgraph_t::GetAncestors(IRDB_SDK::Function_t* const fn, CallGraphNodeSet_t &ancestors, bool skipHellNode) { auto node = FindNode(fn); if (node) diff --git a/libIRDB/src/cfg/domgraph.cpp b/libIRDB/src/cfg/domgraph.cpp index e5fb3a6d1..228a13673 100644 --- a/libIRDB/src/cfg/domgraph.cpp +++ b/libIRDB/src/cfg/domgraph.cpp @@ -287,20 +287,20 @@ ostream& libIRDB::operator<<(ostream& os, const DominatorGraph_t& dg) { assert(blk); const BasicBlockSet_t& blk_dominates=dg.GetDominators(blk); - Instruction_t* first_insn=*(blk->GetInstructions().begin()); + auto first_insn=*(blk->GetInstructions().begin()); assert(first_insn); - os<<"\tBlock entry id:" <<blk->GetInstructions()[0]->GetBaseID()<<endl; + os<<"\tBlock entry id:" <<blk->GetInstructions()[0]->getBaseID()<<endl; os<<"\t\tDominated by: "; for_each(blk_dominates.begin(), blk_dominates.end(), [&os](const BasicBlock_t* dom) { - os<<dom->GetInstructions()[0]->GetBaseID()<<", "; + os<<dom->GetInstructions()[0]->getBaseID()<<", "; }); os<<endl; const BasicBlock_t* idom=dg.GetImmediateDominator(blk); if(idom) - os<<"\t\tImmediate Dominator: "<<hex<<idom->GetInstructions()[0]->GetBaseID()<<endl; + os<<"\t\tImmediate Dominator: "<<hex<<idom->GetInstructions()[0]->getBaseID()<<endl; else os<<"\t\tNo Immed Dominator."<<endl; diff --git a/libIRDB/src/core/IRDB_Objects.cpp b/libIRDB/src/core/IRDB_Objects.cpp index 34c05f812..d6100b046 100644 --- a/libIRDB/src/core/IRDB_Objects.cpp +++ b/libIRDB/src/core/IRDB_Objects.cpp @@ -19,7 +19,7 @@ IRDBObjects_t::~IRDBObjects_t() // explicitly deleted. } -FileIR_t* IRDBObjects_t::addFileIR(const db_id_t variant_id, const db_id_t file_id) +IRDB_SDK::FileIR_t* IRDBObjects_t::addFileIR(const IRDB_SDK::DatabaseID_t variant_id, const IRDB_SDK::DatabaseID_t file_id) { const auto it = file_IR_map.find(file_id); @@ -44,12 +44,12 @@ FileIR_t* IRDBObjects_t::addFileIR(const db_id_t variant_id, const db_id_t file_ } // make sure static variable is set in the calling module -- IMPORTANT - the_fileIR->SetArchitecture(); + the_fileIR->setArchitecture(); return the_fileIR.get(); } } -int IRDBObjects_t::writeBackFileIR(const db_id_t file_id, ostream *verbose_logging) +int IRDBObjects_t::writeBackFileIR(const IRDB_SDK::DatabaseID_t file_id, ostream *verbose_logging) { const auto it = file_IR_map.find(file_id); @@ -61,28 +61,28 @@ int IRDBObjects_t::writeBackFileIR(const db_id_t file_id, ostream *verbose_loggi try { - // cout<<"Writing changes for "<<the_file->GetURL()<<endl; + // cout<<"Writing changes for "<<the_file->getURL()<<endl; // make sure static variable is set in the calling module -- IMPORTANT const auto & the_fileIR = (it->second).fileIR; - the_fileIR->SetArchitecture(); - the_fileIR->WriteToDB(verbose_logging); + the_fileIR->setArchitecture(); + the_fileIR->writeToDB(verbose_logging); return 0; } catch (DatabaseError_t pnide) { - cerr << "Unexpected database error: " << pnide << "file url: " << the_file->GetURL() << endl; + cerr << "Unexpected database error: " << pnide << "file url: " << the_file->getURL() << endl; return -1; } catch (...) { - cerr << "Unexpected error file url: " << the_file->GetURL() << endl; + cerr << "Unexpected error file url: " << the_file->getURL() << endl; return -1; } assert(0); // should not reach } -void IRDBObjects_t::deleteFileIR(const db_id_t file_id) +void IRDBObjects_t::deleteFileIR(const IRDB_SDK::DatabaseID_t file_id) { const auto it = file_IR_map.find(file_id); @@ -96,19 +96,19 @@ void IRDBObjects_t::deleteFileIR(const db_id_t file_id) } } -bool IRDBObjects_t::filesAlreadyPresent(const set<File_t*>& the_files) const +bool IRDBObjects_t::filesAlreadyPresent(const FileSet_t& the_files) const { // look for a missing file - const auto missing_file_it=find_if(ALLOF(the_files), [&](const File_t* const f) + const auto missing_file_it=find_if(ALLOF(the_files), [&](const IRDB_SDK::File_t* const f) { - return (file_IR_map.find(f->GetBaseID()) == file_IR_map.end()); + return (file_IR_map.find(f->getBaseID()) == file_IR_map.end()); }); // return true if no files missing return missing_file_it==the_files.end(); } -VariantID_t* IRDBObjects_t::addVariant(const db_id_t variant_id) +IRDB_SDK::VariantID_t* IRDBObjects_t::addVariant(const IRDB_SDK::DatabaseID_t variant_id) { const auto var_it = variant_map.find(variant_id); @@ -120,23 +120,23 @@ VariantID_t* IRDBObjects_t::addVariant(const db_id_t variant_id) variant_map[variant_id].reset(new VariantID_t(variant_id)); auto the_variant = variant_map[variant_id].get(); - assert(the_variant->IsRegistered()==true); + assert(the_variant->isRegistered()==true); // disallow variants that share shallow copies to both be read in // to prevent desynchronization. - assert(!filesAlreadyPresent(the_variant->GetFiles())); + assert(!filesAlreadyPresent(the_variant->getFiles())); // add files - for(auto &curr_file : the_variant->GetFiles()) + for(auto &curr_file : the_variant->getFiles()) { - file_IR_map[curr_file->GetBaseID()]=FileIRInfo_t(); - file_IR_map[curr_file->GetBaseID()].file = curr_file; + file_IR_map[curr_file->getBaseID()]=FileIRInfo_t(); + file_IR_map[curr_file->getBaseID()].file = dynamic_cast<File_t*>(curr_file); } return the_variant; } -int IRDBObjects_t::writeBackVariant(const db_id_t variant_id) +int IRDBObjects_t::writeBackVariant(const IRDB_SDK::DatabaseID_t variant_id) { const auto it = variant_map.find(variant_id); @@ -163,7 +163,7 @@ int IRDBObjects_t::writeBackVariant(const db_id_t variant_id) } -void IRDBObjects_t::deleteVariant(const db_id_t variant_id) +void IRDBObjects_t::deleteVariant(const IRDB_SDK::DatabaseID_t variant_id) { const auto var_it = variant_map.find(variant_id); @@ -171,9 +171,9 @@ void IRDBObjects_t::deleteVariant(const db_id_t variant_id) return; // remove files and file IRs - for(const auto file : var_it->second->GetFiles()) + for(const auto file : var_it->second->getFiles()) { - file_IR_map.erase(file->GetBaseID()); + file_IR_map.erase(file->getBaseID()); } // remove variant @@ -187,7 +187,7 @@ int IRDBObjects_t::writeBackAll(ostream *verbose_logging) // Write back FileIRs for(auto &file_pair : file_IR_map) { - const int result = IRDBObjects_t::writeBackFileIR((file_pair.second.file)->GetBaseID(), verbose_logging); + const int result = IRDBObjects_t::writeBackFileIR((file_pair.second.file)->getBaseID(), verbose_logging); if(result != 0) { ret_status = -1; @@ -197,7 +197,7 @@ int IRDBObjects_t::writeBackAll(ostream *verbose_logging) // Write back Variants for(auto & variant_pair : variant_map) { - const int result = IRDBObjects_t::writeBackVariant((variant_pair.second)->GetBaseID()); + const int result = IRDBObjects_t::writeBackVariant((variant_pair.second)->getBaseID()); if(result != 0) { ret_status = -1; @@ -211,19 +211,19 @@ void IRDBObjects_t::deleteAll(void) // Delete Variants (also deletes all files) for( auto &variant_pair : variant_map) { - IRDBObjects_t::deleteVariant((variant_pair.second)->GetBaseID()); + IRDBObjects_t::deleteVariant((variant_pair.second)->getBaseID()); } } -pqxxDB_t* IRDBObjects_t::getDBInterface() const +IRDB_SDK::pqxxDB_t* IRDBObjects_t::getDBInterface() const { return pqxx_interface.get(); } -pqxxDB_t* IRDBObjects_t::resetDBInterface() +IRDB_SDK::pqxxDB_t* IRDBObjects_t::resetDBInterface() { pqxx_interface.reset(new pqxxDB_t()); // Aborts if Commit() has not been called - BaseObj_t::SetInterface(pqxx_interface.get()); + BaseObj_t::setInterface(pqxx_interface.get()); return pqxx_interface.get(); } @@ -235,7 +235,20 @@ void IRDBObjects_t::tidyIR(void) { const auto &file_ir_info = variant_pair.second; auto fileIR=file_ir_info.fileIR.get(); - fileIR->AssembleRegistry(); - fileIR->SetBaseIDS(); + fileIR->assembleRegistry(); + fileIR->setBaseIDS(); } } + +void FileIR_t::moveRelocation(IRDB_SDK::Relocation_t* reloc, IRDB_SDK::Instruction_t* from, IRDB_SDK::Instruction_t* to) +{ + auto irdb_from=dynamic_cast<libIRDB::Instruction_t*>(from); + auto irdb_to =dynamic_cast<libIRDB::Instruction_t*>(to); + + irdb_to ->GetRelocations().insert(reloc); + irdb_from->GetRelocations().erase (reloc); + + + +} + diff --git a/libIRDB/src/core/SConscript b/libIRDB/src/core/SConscript index af03160b9..70baa09a8 100644 --- a/libIRDB/src/core/SConscript +++ b/libIRDB/src/core/SConscript @@ -28,9 +28,7 @@ files= ''' decode_csarm.cpp operand_csarm.cpp IRDB_Objects.cpp - decode_dispatch.cpp decode_base.cpp - operand_dispatch.cpp ''' unused_files=''' decode_bea.cpp @@ -41,6 +39,7 @@ unused_files=''' cpppath=''' . + $IRDB_SDK/include/ $SECURITY_TRANSFORMS_HOME/include/ $SECURITY_TRANSFORMS_HOME/libIRDB/include/ $SECURITY_TRANSFORMS_HOME/libcapstone/include/capstone/ @@ -51,7 +50,7 @@ libpath=''' #globs=glob.glob(os.environ['SECURITY_TRANSFORMS_HOME']+'/libcapstone/zipr_unpack/*.o') -myenv.Append(CCFLAGS=" -Wall -std=c++11 ") +myenv.Append(CCFLAGS=" -Wall -std=c++11 -fmax-errors=2 ") myenv.Append(LIBPATH=libpath) myenv=myenv.Clone(CPPPATH=Split(cpppath)) diff --git a/libIRDB/src/core/address.cpp b/libIRDB/src/core/address.cpp index f06a0783a..ec764782a 100644 --- a/libIRDB/src/core/address.cpp +++ b/libIRDB/src/core/address.cpp @@ -31,8 +31,8 @@ vector<string> AddressID_t::WriteToDB(File_t *fid, db_id_t newid, bool p_withHea { assert(fid); - if(GetBaseID()==NOT_IN_DATABASE) - SetBaseID(newid); + if(getBaseID()==NOT_IN_DATABASE) + setBaseID(newid); /* string q; @@ -46,10 +46,10 @@ vector<string> AddressID_t::WriteToDB(File_t *fid, db_id_t newid, bool p_withHea q += */ return { - to_string(GetBaseID()), + to_string(getBaseID()), to_string(fileID), to_string(virtual_offset), - to_string(GetDoipID()) + to_string(getDoipID()) }; } diff --git a/libIRDB/src/core/baseobj.cpp b/libIRDB/src/core/baseobj.cpp index 900303f9f..90cef65fd 100644 --- a/libIRDB/src/core/baseobj.cpp +++ b/libIRDB/src/core/baseobj.cpp @@ -25,8 +25,8 @@ /* * initialize the DB interface */ -DBinterface_t* BaseObj_t::dbintr=NULL; -const db_id_t BaseObj_t::NOT_IN_DATABASE=-1; +DBinterface_t* BaseObj_t::dbintr=nullptr; +const db_id_t IRDB_SDK::BaseObj_t::NOT_IN_DATABASE=-1; /* * BaseObj_t constructor @@ -39,8 +39,9 @@ BaseObj_t::BaseObj_t(doip_t* _doip) : doip(_doip), base_id(BaseObj_t::NOT_IN_DAT /* * Set the database interface to be used for the base object class. */ -void BaseObj_t::SetInterface(DBinterface_t *dbi) +void IRDB_SDK::BaseObj_t::setInterface(IRDB_SDK::DBinterface_t *dbi) { - dbintr=dbi; + ::libIRDB::BaseObj_t::dbintr=dynamic_cast<libIRDB::DBinterface_t*>(dbi); + assert(::libIRDB::BaseObj_t::dbintr); } diff --git a/libIRDB/src/core/dbinterface.cpp b/libIRDB/src/core/dbinterface.cpp index 742c76bc6..f408adb28 100644 --- a/libIRDB/src/core/dbinterface.cpp +++ b/libIRDB/src/core/dbinterface.cpp @@ -23,9 +23,9 @@ #include <iostream> #include <stdlib.h> -using namespace libIRDB; +using namespace std; -std::ostream& libIRDB::operator<<(std::ostream& output, const DatabaseError_t& p) +ostream& libIRDB::operator<<(ostream& output, const libIRDB::DatabaseError_t& p) { switch(p.GetErrorCode()) { @@ -36,10 +36,18 @@ std::ostream& libIRDB::operator<<(std::ostream& output, const DatabaseError_t& p output<<"Variant not detected in database"; break; default: - std::cerr<<"Cannot print database error code, aborting program...\n"; - exit(-100); + output<<"Cannot print database error code."; + break; } + return output; +} +ostream& IRDB_SDK::operator<<(ostream& output, const IRDB_SDK::DatabaseError_t& p) +{ + const auto p_p = &p; + const auto real_p=dynamic_cast<const libIRDB::DatabaseError_t* const>(p_p); + assert(real_p); + output << *real_p; return output; } diff --git a/libIRDB/src/core/decode_base.cpp b/libIRDB/src/core/decode_base.cpp index b32a8d11d..ea40fe099 100644 --- a/libIRDB/src/core/decode_base.cpp +++ b/libIRDB/src/core/decode_base.cpp @@ -12,28 +12,32 @@ using namespace std; using namespace libIRDB; -unique_ptr<DecodedInstructionCapstone_t> DecodedInstructionCapstone_t::factory(const libIRDB::Instruction_t* i) +unique_ptr<IRDB_SDK::DecodedInstruction_t> IRDB_SDK::DecodedInstruction_t::factory(const IRDB_SDK::Instruction_t* p_i) { - auto op=FileIR_t::GetArchitecture()->getMachineType()==admtAarch64 ? (DecodedInstructionCapstone_t*)new DecodedInstructionCapstoneARM64_t(i) : - FileIR_t::GetArchitecture()->getMachineType()==admtX86_64 ? (DecodedInstructionCapstone_t*)new DecodedInstructionCapstoneX86_t (i) : - FileIR_t::GetArchitecture()->getMachineType()==admtI386 ? (DecodedInstructionCapstone_t*)new DecodedInstructionCapstoneX86_t (i) : + const auto i=dynamic_cast<const libIRDB::Instruction_t*>(p_i); + assert(i); + auto op=IRDB_SDK::FileIR_t::getArchitecture()->getMachineType()==IRDB_SDK::admtAarch64 ? (IRDB_SDK::DecodedInstruction_t*)new DecodedInstructionCapstoneARM64_t(i) : + IRDB_SDK::FileIR_t::getArchitecture()->getMachineType()==IRDB_SDK::admtX86_64 ? (IRDB_SDK::DecodedInstruction_t*)new DecodedInstructionCapstoneX86_t (i) : + IRDB_SDK::FileIR_t::getArchitecture()->getMachineType()==IRDB_SDK::admtI386 ? (IRDB_SDK::DecodedInstruction_t*)new DecodedInstructionCapstoneX86_t (i) : throw invalid_argument("Unknown machine type"); - return unique_ptr<DecodedInstructionCapstone_t>(op); + return unique_ptr<DecodedInstruction_t>(op); } -unique_ptr<DecodedInstructionCapstone_t> DecodedInstructionCapstone_t::factory(const virtual_offset_t start_addr, const void *data, uint32_t max_len) + +unique_ptr<IRDB_SDK::DecodedInstruction_t> IRDB_SDK::DecodedInstruction_t::factory(const IRDB_SDK::VirtualOffset_t start_addr, const void *data, uint32_t max_len) { - auto op=FileIR_t::GetArchitecture()->getMachineType()==admtAarch64 ? (DecodedInstructionCapstone_t*)new DecodedInstructionCapstoneARM64_t(start_addr,data,max_len) : - FileIR_t::GetArchitecture()->getMachineType()==admtX86_64 ? (DecodedInstructionCapstone_t*)new DecodedInstructionCapstoneX86_t (start_addr,data,max_len) : - FileIR_t::GetArchitecture()->getMachineType()==admtI386 ? (DecodedInstructionCapstone_t*)new DecodedInstructionCapstoneX86_t (start_addr,data,max_len) : + auto op=IRDB_SDK::FileIR_t::getArchitecture()->getMachineType()==IRDB_SDK::admtAarch64 ? (IRDB_SDK::DecodedInstruction_t*)new DecodedInstructionCapstoneARM64_t(start_addr,data,max_len) : + IRDB_SDK::FileIR_t::getArchitecture()->getMachineType()==IRDB_SDK::admtX86_64 ? (IRDB_SDK::DecodedInstruction_t*)new DecodedInstructionCapstoneX86_t (start_addr,data,max_len) : + IRDB_SDK::FileIR_t::getArchitecture()->getMachineType()==IRDB_SDK::admtI386 ? (IRDB_SDK::DecodedInstruction_t*)new DecodedInstructionCapstoneX86_t (start_addr,data,max_len) : throw invalid_argument("Unknown machine type"); - return unique_ptr<DecodedInstructionCapstone_t>(op); + return unique_ptr<DecodedInstruction_t>(op); } -unique_ptr<DecodedInstructionCapstone_t> DecodedInstructionCapstone_t::factory(const virtual_offset_t start_addr, const void *data, const void* endptr) + +unique_ptr<IRDB_SDK::DecodedInstruction_t> IRDB_SDK::DecodedInstruction_t::factory(const IRDB_SDK::VirtualOffset_t start_addr, const void *data, const void* endptr) { - auto op=FileIR_t::GetArchitecture()->getMachineType()==admtAarch64 ? (DecodedInstructionCapstone_t*)new DecodedInstructionCapstoneARM64_t(start_addr,data,endptr) : - FileIR_t::GetArchitecture()->getMachineType()==admtX86_64 ? (DecodedInstructionCapstone_t*)new DecodedInstructionCapstoneX86_t (start_addr,data,endptr) : - FileIR_t::GetArchitecture()->getMachineType()==admtI386 ? (DecodedInstructionCapstone_t*)new DecodedInstructionCapstoneX86_t (start_addr,data,endptr) : + auto op=IRDB_SDK::FileIR_t::getArchitecture()->getMachineType()==IRDB_SDK::admtAarch64 ? (IRDB_SDK::DecodedInstruction_t*)new DecodedInstructionCapstoneARM64_t(start_addr,data,endptr) : + IRDB_SDK::FileIR_t::getArchitecture()->getMachineType()==IRDB_SDK::admtX86_64 ? (IRDB_SDK::DecodedInstruction_t*)new DecodedInstructionCapstoneX86_t (start_addr,data,endptr) : + IRDB_SDK::FileIR_t::getArchitecture()->getMachineType()==IRDB_SDK::admtI386 ? (IRDB_SDK::DecodedInstruction_t*)new DecodedInstructionCapstoneX86_t (start_addr,data,endptr) : throw invalid_argument("Unknown machine type"); - return unique_ptr<DecodedInstructionCapstone_t>(op); + return unique_ptr<DecodedInstruction_t>(op); } diff --git a/libIRDB/src/core/decode_csarm.cpp b/libIRDB/src/core/decode_csarm.cpp index 61bbafb21..d48057dd3 100644 --- a/libIRDB/src/core/decode_csarm.cpp +++ b/libIRDB/src/core/decode_csarm.cpp @@ -1,5 +1,10 @@ #include <libIRDB-core.hpp> +#include <core/decode_base.hpp> +#include <core/decode_csarm.hpp> +#include <core/operand_base.hpp> +#include <core/operand_csarm.hpp> + #include <capstone.h> #include <arm64.h> @@ -121,13 +126,13 @@ DecodedInstructionCapstoneARM64_t::DecodedInstructionCapstoneARM64_t(const Instr if(!cs_handle) cs_handle=new CapstoneHandle_t(NULL); if(!i) throw std::invalid_argument("No instruction given to DecodedInstruction_t(Instruction_t*)"); - const auto length=i->GetDataBits().size(); - const auto &databits=i->GetDataBits(); + const auto length=i->getDataBits().size(); + const auto &databits=i->getDataBits(); const auto data=databits.data(); - const auto address=i->GetAddress()->GetVirtualOffset(); + const auto address=i->getAddress()->getVirtualOffset(); Disassemble(address,data,length); - if(!valid()) throw std::invalid_argument("The Instruction_t::GetDataBits field is not a valid instruction."); + if(!valid()) throw std::invalid_argument("The Instruction_t::getDataBits field is not a valid instruction."); } DecodedInstructionCapstoneARM64_t::DecodedInstructionCapstoneARM64_t(const virtual_offset_t start_addr, const void *data, uint32_t max_len) @@ -236,23 +241,23 @@ bool DecodedInstructionCapstoneARM64_t::hasOperand(const int op_num) const } // 0-based. first operand is numbered 0. -shared_ptr<DecodedOperandCapstone_t> DecodedInstructionCapstoneARM64_t::getOperand(const int op_num) const +shared_ptr<DecodedOperand_t> DecodedInstructionCapstoneARM64_t::getOperand(const int op_num) const { if(!valid()) throw std::logic_error(string("Called ")+__FUNCTION__+" on invalid instruction"); if(!hasOperand(op_num)) throw std::logic_error(string("Called ")+__FUNCTION__+" on without hasOperand()==true"); - return shared_ptr<DecodedOperandCapstone_t>(new DecodedOperandCapstoneARM64_t(my_insn,(uint8_t)op_num)); + return shared_ptr<DecodedOperand_t>(new DecodedOperandCapstoneARM64_t(my_insn,(uint8_t)op_num)); } -DecodedOperandCapstoneVector_t DecodedInstructionCapstoneARM64_t::getOperands() const +DecodedOperandVector_t DecodedInstructionCapstoneARM64_t::getOperands() const { if(!valid()) throw std::logic_error(string("Called ")+__FUNCTION__+" on invalid instruction"); const auto the_insn=static_cast<cs_insn*>(my_insn.get()); const auto &arm = (the_insn->detail->arm64); const auto opcount=arm.op_count; - auto ret_val=DecodedOperandCapstoneVector_t(); + auto ret_val=DecodedOperandVector_t(); for(auto i=0;i<opcount;i++) ret_val.push_back(getOperand(i)); @@ -319,7 +324,7 @@ uint32_t DecodedInstructionCapstoneARM64_t::getPrefixCount() const return 0; } -virtual_offset_t DecodedInstructionCapstoneARM64_t::getMemoryDisplacementOffset(const DecodedOperandCapstone_t& t, const Instruction_t* insn) const +IRDB_SDK::VirtualOffset_t DecodedInstructionCapstoneARM64_t::getMemoryDisplacementOffset(const IRDB_SDK::DecodedOperand_t* t, const IRDB_SDK::Instruction_t* insn) const { if(!valid()) throw std::logic_error(string("Called ")+__FUNCTION__+" on invalid instruction"); assert(0); diff --git a/libIRDB/src/core/decode_csx86.cpp b/libIRDB/src/core/decode_csx86.cpp index c249bf782..9b2e5e20a 100644 --- a/libIRDB/src/core/decode_csx86.cpp +++ b/libIRDB/src/core/decode_csx86.cpp @@ -1,5 +1,9 @@ #include <libIRDB-core.hpp> +#include <core/decode_base.hpp> +#include <core/decode_csx86.hpp> +#include <core/operand_base.hpp> +#include <core/operand_csx86.hpp> #include <capstone.h> #include <x86.h> @@ -14,11 +18,13 @@ using namespace std; #define ALLOF(a) begin(a),end(a) + + DecodedInstructionCapstoneX86_t::CapstoneHandle_t* DecodedInstructionCapstoneX86_t::cs_handle=NULL ; DecodedInstructionCapstoneX86_t::CapstoneHandle_t::CapstoneHandle_t(FileIR_t* firp) { - const auto width=FileIR_t::GetArchitectureBitWidth(); + const auto width=FileIR_t::getArchitectureBitWidth(); const auto mode = (width==64) ? CS_MODE_64: CS_MODE_32; static_assert(sizeof(csh)==sizeof(handle), "Capstone handle size is unexpected. Has CS changed?"); auto err = cs_open(CS_ARCH_X86, mode, (csh*)&handle); @@ -76,7 +82,7 @@ class CapstoneHandle_t CapstoneHandle_t(FileIR_t* firp=NULL) { - const auto width=FileIR_t::GetArchitectureBitWidth(); + const auto width=FileIR_t::getArchitectureBitWidth(); const auto mode = (width==64) ? CS_MODE_64: CS_MODE_32; auto err = cs_open(CS_ARCH_X86, mode, &handle); @@ -197,13 +203,13 @@ DecodedInstructionCapstoneX86_t::DecodedInstructionCapstoneX86_t(const Instructi if(!cs_handle) cs_handle=new CapstoneHandle_t(NULL); if(!i) throw std::invalid_argument("No instruction given to DecodedInstruction_t(Instruction_t*)"); - const auto length=i->GetDataBits().size(); - const auto &databits=i->GetDataBits(); + const auto length=i->getDataBits().size(); + const auto &databits=i->getDataBits(); const auto data=databits.data(); - const auto address=i->GetAddress()->GetVirtualOffset(); + const auto address=i->getAddress()->getVirtualOffset(); Disassemble(address,data,length); - if(!valid()) throw std::invalid_argument("The Instruction_t::GetDataBits field is not a valid instruction."); + if(!valid()) throw std::invalid_argument("The Instruction_t::getDataBits field is not a valid instruction."); } DecodedInstructionCapstoneX86_t::DecodedInstructionCapstoneX86_t(const virtual_offset_t start_addr, const void *data, uint32_t max_len) @@ -397,23 +403,23 @@ bool DecodedInstructionCapstoneX86_t::hasOperand(const int op_num) const } // 0-based. first operand is numbered 0. -shared_ptr<DecodedOperandCapstone_t> DecodedInstructionCapstoneX86_t::getOperand(const int op_num) const +shared_ptr<DecodedOperand_t> DecodedInstructionCapstoneX86_t::getOperand(const int op_num) const { if(!valid()) throw std::logic_error(string("Called ")+__FUNCTION__+" on invalid instruction"); if(!hasOperand(op_num)) throw std::logic_error(string("Called ")+__FUNCTION__+" on without hasOperand()==true"); - return shared_ptr<DecodedOperandCapstone_t>(new DecodedOperandCapstoneX86_t(my_insn,(uint8_t)op_num)); + return shared_ptr<DecodedOperand_t>(new DecodedOperandCapstoneX86_t(my_insn,(uint8_t)op_num)); } -DecodedOperandCapstoneVector_t DecodedInstructionCapstoneX86_t::getOperands() const +IRDB_SDK::DecodedOperandVector_t DecodedInstructionCapstoneX86_t::getOperands() const { if(!valid()) throw std::logic_error(string("Called ")+__FUNCTION__+" on invalid instruction"); const auto the_insn=static_cast<cs_insn*>(my_insn.get()); const auto &x86 = (the_insn->detail->x86); const auto opcount=x86.op_count; - auto ret_val=DecodedOperandCapstoneVector_t(); + auto ret_val=IRDB_SDK::DecodedOperandVector_t(); for(auto i=0;i<opcount;i++) ret_val.push_back(getOperand(i)); @@ -588,8 +594,9 @@ uint32_t DecodedInstructionCapstoneX86_t::getPrefixCount() const return count_with_rex; } -virtual_offset_t DecodedInstructionCapstoneX86_t::getMemoryDisplacementOffset(const DecodedOperandCapstone_t& t, const Instruction_t* insn) const +IRDB_SDK::VirtualOffset_t DecodedInstructionCapstoneX86_t::getMemoryDisplacementOffset(const IRDB_SDK::DecodedOperand_t* p_t, const IRDB_SDK::Instruction_t* insn) const { + auto &t = *p_t; if(!valid()) throw std::logic_error(string("Called ")+__FUNCTION__+" on invalid instruction"); const auto the_insn=static_cast<cs_insn*>(my_insn.get()); @@ -633,14 +640,14 @@ virtual_offset_t DecodedInstructionCapstoneX86_t::getMemoryDisplacementOffset(co const auto disp_start=the_insn->size-imm_size-disp_size; const auto imm_start=the_insn->size-imm_size; - const auto candidate_disp_eq = disp_size==4 ? *(int32_t*)(&insn->GetDataBits().c_str()[disp_start])==(int32_t)disp : - disp_size==2 ? *(int16_t*)(&insn->GetDataBits().c_str()[disp_start])==(int16_t)disp : - disp_size==1 ? *(int8_t *)(&insn->GetDataBits().c_str()[disp_start])==(int8_t )disp : (assert(0),false); - - const auto candidate_imm_eq = imm_size==8 ? *(int64_t*)(&insn->GetDataBits().c_str()[imm_start])==(int64_t)imm : - imm_size==4 ? *(int32_t*)(&insn->GetDataBits().c_str()[imm_start])==(int32_t)imm : - imm_size==2 ? *(int16_t*)(&insn->GetDataBits().c_str()[imm_start])==(int16_t)imm : - imm_size==1 ? *(int8_t *)(&insn->GetDataBits().c_str()[imm_start])==(int8_t )imm : (int64_t)(assert(0),false); + const auto candidate_disp_eq = disp_size==4 ? *(int32_t*)(&insn->getDataBits().c_str()[disp_start])==(int32_t)disp : + disp_size==2 ? *(int16_t*)(&insn->getDataBits().c_str()[disp_start])==(int16_t)disp : + disp_size==1 ? *(int8_t *)(&insn->getDataBits().c_str()[disp_start])==(int8_t )disp : (assert(0),false); + + const auto candidate_imm_eq = imm_size==8 ? *(int64_t*)(&insn->getDataBits().c_str()[imm_start])==(int64_t)imm : + imm_size==4 ? *(int32_t*)(&insn->getDataBits().c_str()[imm_start])==(int32_t)imm : + imm_size==2 ? *(int16_t*)(&insn->getDataBits().c_str()[imm_start])==(int16_t)imm : + imm_size==1 ? *(int8_t *)(&insn->getDataBits().c_str()[imm_start])==(int8_t )imm : (int64_t)(assert(0),false); if(candidate_disp_eq && candidate_imm_eq) return disp_start; diff --git a/libIRDB/src/core/decode_dispatch.cpp b/libIRDB/src/core/decode_dispatch.cpp index ad7fd9f87..2f0c405e2 100644 --- a/libIRDB/src/core/decode_dispatch.cpp +++ b/libIRDB/src/core/decode_dispatch.cpp @@ -1,8 +1,17 @@ #include <libIRDB-core.hpp> +#include <core/decode_base.hpp> +#include <core/decode_csx86.hpp> +#include <core/decode_csarm.hpp> + +#include <core/operand_base.hpp> +#include <core/operand_csx86.hpp> +#include <core/operand_csarm.hpp> + #include <core/decode_dispatch.hpp> #include <core/operand_dispatch.hpp> + using namespace libIRDB; using namespace std; @@ -83,9 +92,9 @@ bool DecodedInstructionDispatcher_t::hasOperand(const int op_num) const } // 0-based. first operand is numbered 0. -DecodedOperandDispatcher_t DecodedInstructionDispatcher_t::getOperand(const int op_num) const +unique_ptr<DecodedOperand_t> DecodedInstructionDispatcher_t::getOperand(const int op_num) const { - return DecodedOperandDispatcher_t(cs->getOperand(op_num)); + return unique_ptr<DecodedOperand_t>(new DecodedOperandDispatcher_t(cs->getOperand(op_num))); } DecodedOperandMetaVector_t DecodedInstructionDispatcher_t::getOperands() const diff --git a/libIRDB/src/core/eh.cpp b/libIRDB/src/core/eh.cpp index 664ad8805..e69358518 100644 --- a/libIRDB/src/core/eh.cpp +++ b/libIRDB/src/core/eh.cpp @@ -32,9 +32,9 @@ using namespace std; bool libIRDB::operator<(const EhProgram_t&a, const EhProgram_t&b) { - return tie(a.cie_program,a.fde_program,a.code_alignment_factor,a.data_alignment_factor,a.return_register, a.ptrsize, a.GetRelocations()) + return tie(a.cie_program,a.fde_program,a.code_alignment_factor,a.data_alignment_factor,a.return_register, a.ptrsize, a.getRelocations()) < - tie(b.cie_program,b.fde_program,b.code_alignment_factor,b.data_alignment_factor,b.return_register, b.ptrsize, b.GetRelocations()); + tie(b.cie_program,b.fde_program,b.code_alignment_factor,b.data_alignment_factor,b.return_register, b.ptrsize, b.getRelocations()); } namespace std @@ -92,15 +92,9 @@ vector<std::string> EhProgram_t::WriteToDB(File_t* fid) // writes to DB, ID i string encoded_cie_program=vec_to_encoded_string(cie_program); string encoded_fde_program=vec_to_encoded_string(fde_program); -/* - string q; - q ="insert into " + fid->GetEhProgramTableName(); - q+="(eh_pgm_id,caf,daf,return_register,ptrsize,cie_program,fde_program) "+ - string(" VALUES (") + -*/ return { - to_string(GetBaseID()), + to_string(getBaseID()), to_string(+code_alignment_factor), to_string(+data_alignment_factor), to_string(+return_register), @@ -129,36 +123,36 @@ std::string EhCallSite_t::WriteToDB(File_t* fid) // writes to DB, ID is not - auto landing_pad_id=BaseObj_t::NOT_IN_DATABASE; if(landing_pad != NULL) - landing_pad_id=landing_pad->GetBaseID(); + landing_pad_id=landing_pad->getBaseID(); const auto ttov_str=vec_to_string(ttov); - q ="insert into " + fid->GetEhCallSiteTableName(); + q ="insert into " + fid->getEhCallSiteTableName(); q+="(ehcs_id,tt_encoding,ttov,lp_insn_id) "+ string(" VALUES (") + - string("'") + to_string(GetBaseID()) + string("', ") + + string("'") + to_string(getBaseID()) + string("', ") + string("'") + to_string(+tt_encoding) + string("', ") + string("'") + ttov_str + string("', ") + string("'") + to_string(landing_pad_id) + string("') ;"); return q; } -bool EhCallSite_t::GetHasCleanup() const +bool EhCallSite_t::getHasCleanup() const { const auto ttov_it=find(ttov.begin(), ttov.end(), 0); return ttov_it!=ttov.end(); } -void EhCallSite_t::SetHasCleanup(bool p_has_cleanup) +void EhCallSite_t::setHasCleanup(bool p_has_cleanup) { if(p_has_cleanup) { - if(!GetHasCleanup()) + if(!getHasCleanup()) ttov.push_back(0); } else { - if(GetHasCleanup()) + if(getHasCleanup()) { const auto ttov_it=find(ttov.begin(), ttov.end(), 0); ttov.erase(ttov_it); diff --git a/libIRDB/src/core/file.cpp b/libIRDB/src/core/file.cpp index 7aa10476f..58306e47a 100644 --- a/libIRDB/src/core/file.cpp +++ b/libIRDB/src/core/file.cpp @@ -56,7 +56,7 @@ File_t::File_t(const db_id_t &myfile_id, const db_id_t &my_orig_fid, const std:: ehcss_table_name(ehcss), elfoid(myoid) { - SetBaseID(myfile_id); + setBaseID(myfile_id); } @@ -90,6 +90,6 @@ void File_t::CreateTables() buffer << t.rdbuf(); - dbintr->IssueQuery(buffer.str().c_str()); + dbintr->issueQuery(buffer.str().c_str()); } diff --git a/libIRDB/src/core/fileir.cpp b/libIRDB/src/core/fileir.cpp index 39c1a6f74..a86282e6f 100644 --- a/libIRDB/src/core/fileir.cpp +++ b/libIRDB/src/core/fileir.cpp @@ -77,8 +77,8 @@ static void UpdateEntryPoints( db_id_t func_entry_id=(*it).second; assert(func_entry_id==-1 || insnMap.at(func_entry_id)); - func->SetEntryPoint(insnMap.at(func_entry_id)); -// cout<<"Function named "<<func->GetName()<< " getting entry point set to "<<insnMap[func_entry_id]->GetComment()<<"."<<endl; + func->setEntryPoint(insnMap.at(func_entry_id)); +// cout<<"Function named "<<func->getName()<< " getting entry point set to "<<insnMap[func_entry_id]->getComment()<<"."<<endl; } } @@ -93,7 +93,7 @@ static void UpdateUnresolvedEhCallSites( const auto& insnid=i.second; const auto& insn=insnMap.at(insnid); assert(insn); - ehcs->SetLandingPad(insn); + ehcs->setLandingPad(insn); } } @@ -110,45 +110,25 @@ FileIR_t::FileIR_t(const VariantID_t &newprogid, File_t* fid) orig_variant_ir_p=NULL; if(fid==NULL) - fileptr=newprogid.GetMainFile(); + fileptr=dynamic_cast<File_t*>(newprogid.getMainFile()); else fileptr=fid; - if(progid.IsRegistered()) + if(progid.isRegistered()) { ReadFromDB(); - SetArchitecture(); + setArchitecture(); } } FileIR_t::~FileIR_t() { - for(std::set<Function_t*>::const_iterator i=funcs.begin(); i!=funcs.end(); ++i) - { - delete *i; - } - - - for(std::set<Instruction_t*>::const_iterator i=insns.begin(); i!=insns.end(); ++i) - { - delete *i; - } - - for(std::set<AddressID_t*>::const_iterator i=addrs.begin(); i!=addrs.end(); ++i) - { - delete *i; - } - - for(std::set<Relocation_t*>::const_iterator i=relocs.begin(); i!=relocs.end(); ++i) - { - delete *i; - } - - for(std::set<Type_t*>::const_iterator i=types.begin(); i!=types.end(); ++i) - { - delete *i; - } + for(auto i : funcs ) delete i; + for(auto i : insns ) delete i; + for(auto i : addrs ) delete i; + for(auto i : relocs) delete i; + for(auto i : types ) delete i; // @todo: clear icfs_t } @@ -193,8 +173,11 @@ void FileIR_t::ReadFromDB() } -void FileIR_t::ChangeRegistryKey(Instruction_t *orig, Instruction_t *updated) +void FileIR_t::changeRegistryKey(IRDB_SDK::Instruction_t *p_orig, IRDB_SDK::Instruction_t *p_updated) { + auto orig=dynamic_cast<libIRDB::Instruction_t*>(p_orig); + auto updated=dynamic_cast<libIRDB::Instruction_t*>(p_updated); + if(assembly_registry.find(orig) != assembly_registry.end()) { assembly_registry[updated] = assembly_registry[orig]; @@ -203,7 +186,7 @@ void FileIR_t::ChangeRegistryKey(Instruction_t *orig, Instruction_t *updated) } } -void FileIR_t::AssembleRegistry() +void FileIR_t::assembleRegistry() { if(assembly_registry.size() == 0) return; @@ -221,14 +204,11 @@ void FileIR_t::AssembleRegistry() if(!asmFile.is_open()) assert(false); - asmFile<<"BITS "<<std::dec<<GetArchitectureBitWidth()<<endl; + asmFile<<"BITS "<<std::dec<<getArchitectureBitWidth()<<endl; - for(registry_type::iterator it = assembly_registry.begin(); - it != assembly_registry.end(); - it++ - ) + for(auto it : assembly_registry) { - asmFile<<it->second<<endl; + asmFile<<it.second<<endl; } asmFile.close(); @@ -236,11 +216,6 @@ void FileIR_t::AssembleRegistry() actual_exit = command_to_stream(command,cout); // system(command.c_str()); assert(actual_exit == 0); - - //DISASM disasm; - //memset(&disasm, 0, sizeof(DISASM)); - //disasm.Archi=GetArchitectureBitWidth(); - ifstream binreader; unsigned int filesize; binreader.open(binaryOutputFile.c_str(),ifstream::in|ifstream::binary); @@ -256,8 +231,6 @@ void FileIR_t::AssembleRegistry() binreader.read((char*)binary_stream,filesize); binreader.close(); - //unsigned int instr_index = 0; - //for(unsigned int index=0; index < filesize; instr_index++) unsigned int index = 0; registry_type::iterator reg_val = assembly_registry.begin(); @@ -271,12 +244,13 @@ void FileIR_t::AssembleRegistry() // disasm.EIP = (UIntPtr)&binary_stream[index]; // int instr_len = Disasm(&disasm); - const auto disasm=DecodedInstruction_t + const auto p_disasm=DecodedInstruction_t::factory ( /* fake start addr doesn't matter */0x1000, (void*)&binary_stream[index], (void*)&binary_stream[filesize] ); + const auto& disasm=*p_disasm; assert(disasm.valid()); const auto instr_len=disasm.length(); @@ -288,8 +262,8 @@ void FileIR_t::AssembleRegistry() rawBits[i] = binary_stream[index]; } - instr->SetDataBits(rawBits); -// *verbose_logging << "doing instruction:" << ((Instruction_t*)instr)->getDisassembly() << " comment: " << ((Instruction_t*)instr)->GetComment() << endl; + instr->setDataBits(rawBits); +// *verbose_logging << "doing instruction:" << ((Instruction_t*)instr)->getDisassembly() << " comment: " << ((Instruction_t*)instr)->getComment() << endl; reg_val++; } @@ -300,18 +274,24 @@ void FileIR_t::AssembleRegistry() } -void FileIR_t::RegisterAssembly(Instruction_t *instr, string assembly) +void FileIR_t::registerAssembly(IRDB_SDK::Instruction_t *p_instr, string assembly) { + auto instr=dynamic_cast<Instruction_t*>(p_instr); + assert(instr); assembly_registry[instr] = assembly; } -void FileIR_t::UnregisterAssembly(Instruction_t *instr) +void FileIR_t::unregisterAssembly(IRDB_SDK::Instruction_t *p_instr) { + auto instr=dynamic_cast<Instruction_t*>(p_instr); + assert(instr); assembly_registry.erase(instr); } -std::string FileIR_t::LookupAssembly(Instruction_t *instr) +std::string FileIR_t::lookupAssembly(IRDB_SDK::Instruction_t *p_instr) { + auto instr=dynamic_cast<Instruction_t*>(p_instr); + assert(instr); if (assembly_registry.find(instr) != assembly_registry.end()) return assembly_registry[instr]; else @@ -329,23 +309,23 @@ std::map<db_id_t,Function_t*> FileIR_t::ReadFuncsFromDB auto q=std::string("select * from ") + fileptr->function_table_name + " ; "; - dbintr->IssueQuery(q); + dbintr->issueQuery(q); - while(!dbintr->IsDone()) + while(!dbintr->isDone()) { // function_id | file_id | name | stack_frame_size | out_args_region_size | use_frame_pointer | is_safe | doip_id - db_id_t fid=atoi(dbintr->GetResultColumn("function_id").c_str()); - db_id_t entry_point_id=atoi(dbintr->GetResultColumn("entry_point_id").c_str()); - std::string name=dbintr->GetResultColumn("name"); - int sfsize=atoi(dbintr->GetResultColumn("stack_frame_size").c_str()); - int oasize=atoi(dbintr->GetResultColumn("out_args_region_size").c_str()); - db_id_t function_type_id=atoi(dbintr->GetResultColumn("type_id").c_str()); + db_id_t fid=atoi(dbintr->getResultColumn("function_id").c_str()); + db_id_t entry_point_id=atoi(dbintr->getResultColumn("entry_point_id").c_str()); + std::string name=dbintr->getResultColumn("name"); + int sfsize=atoi(dbintr->getResultColumn("stack_frame_size").c_str()); + int oasize=atoi(dbintr->getResultColumn("out_args_region_size").c_str()); + db_id_t function_type_id=atoi(dbintr->getResultColumn("type_id").c_str()); // postgresql encoding of boolean can be 'true', '1', 'T', 'y' bool useFP=false; bool isSafe=false; - string useFPString=dbintr->GetResultColumn("use_frame_pointer"); - string isSafeString=dbintr->GetResultColumn("is_safe"); + string useFPString=dbintr->getResultColumn("use_frame_pointer"); + string isSafeString=dbintr->getResultColumn("is_safe"); const char *useFPstr=useFPString.c_str(); const char *isSafestr=isSafeString.c_str(); if (strlen(useFPstr) > 0) @@ -361,7 +341,7 @@ std::map<db_id_t,Function_t*> FileIR_t::ReadFuncsFromDB } // handle later? - //db_id_t doipid=atoi(dbintr->GetResultColumn("doip_id").c_str()); + //db_id_t doipid=atoi(dbintr->getResultColumn("doip_id").c_str()); FuncType_t* fnType = NULL; if (typesMap.count(function_type_id) > 0) @@ -376,7 +356,7 @@ std::map<db_id_t,Function_t*> FileIR_t::ReadFuncsFromDB funcs.insert(newfunc); - dbintr->MoveToNextRow(); + dbintr->moveToNextRow(); } return idMap; @@ -390,9 +370,9 @@ std::map<db_id_t,EhCallSite_t*> FileIR_t::ReadEhCallSitesFromDB { auto ehcsMap=std::map<db_id_t,EhCallSite_t*>(); - std::string q= "select * from " + fileptr->GetEhCallSiteTableName() + " ; "; + std::string q= "select * from " + fileptr->getEhCallSiteTableName() + " ; "; - for(dbintr->IssueQuery(q); !dbintr->IsDone(); dbintr->MoveToNextRow()) + for(dbintr->issueQuery(q); !dbintr->isDone(); dbintr->moveToNextRow()) { const auto string_to_vec=[&](const string& str ) -> vector<int> { @@ -410,10 +390,10 @@ std::map<db_id_t,EhCallSite_t*> FileIR_t::ReadEhCallSitesFromDB */ - const auto eh_cs_id=atoi(dbintr->GetResultColumn("ehcs_id").c_str()); - const auto tt_encoding=atoi(dbintr->GetResultColumn("tt_encoding").c_str()); - const auto &ttov=string(dbintr->GetResultColumn("ttov").c_str()); - const auto lp_insn_id=atoi(dbintr->GetResultColumn("lp_insn_id").c_str()); + const auto eh_cs_id=atoi(dbintr->getResultColumn("ehcs_id").c_str()); + const auto tt_encoding=atoi(dbintr->getResultColumn("tt_encoding").c_str()); + const auto &ttov=string(dbintr->getResultColumn("ttov").c_str()); + const auto lp_insn_id=atoi(dbintr->getResultColumn("lp_insn_id").c_str()); auto newEhCs=new EhCallSite_t(eh_cs_id,tt_encoding,NULL); // create the call site with an unresolved LP newEhCs->GetTTOrderVector()=string_to_vec(ttov); @@ -431,7 +411,7 @@ std::map<db_id_t,EhProgram_t*> FileIR_t::ReadEhPgmsFromDB() auto idMap = std::map<db_id_t,EhProgram_t*>(); auto q=std::string("select * from ") + fileptr->ehpgm_table_name + " ; "; - dbintr->IssueQuery(q); + dbintr->issueQuery(q); auto decode_pgm=[](const string& encoded_pgm, EhProgramListing_t& decoded_pgm) { @@ -484,7 +464,7 @@ std::map<db_id_t,EhProgram_t*> FileIR_t::ReadEhPgmsFromDB() }; - while(!dbintr->IsDone()) + while(!dbintr->isDone()) { /* * eh_pgm_id integer, @@ -496,21 +476,21 @@ std::map<db_id_t,EhProgram_t*> FileIR_t::ReadEhPgmsFromDB() */ - const auto eh_pgm_id=atoi(dbintr->GetResultColumn("eh_pgm_id").c_str()); - const auto caf=atoi(dbintr->GetResultColumn("caf").c_str()); - const auto daf=atoi(dbintr->GetResultColumn("daf").c_str()); - const auto rr=atoi(dbintr->GetResultColumn("return_register").c_str()); - const auto ptrsize=atoi(dbintr->GetResultColumn("ptrsize").c_str()); - const auto& encoded_cie_program = dbintr->GetResultColumn("cie_program"); - const auto& encoded_fde_program = dbintr->GetResultColumn("fde_program"); + const auto eh_pgm_id=atoi(dbintr->getResultColumn("eh_pgm_id").c_str()); + const auto caf=atoi(dbintr->getResultColumn("caf").c_str()); + const auto daf=atoi(dbintr->getResultColumn("daf").c_str()); + const auto rr=atoi(dbintr->getResultColumn("return_register").c_str()); + const auto ptrsize=atoi(dbintr->getResultColumn("ptrsize").c_str()); + const auto& encoded_cie_program = dbintr->getResultColumn("cie_program"); + const auto& encoded_fde_program = dbintr->getResultColumn("fde_program"); - auto new_ehpgm=new EhProgram_t(eh_pgm_id, caf, daf, rr, ptrsize); + auto new_ehpgm=new EhProgram_t(eh_pgm_id, caf, daf, rr, ptrsize, {}, {}); decode_pgm(encoded_cie_program, new_ehpgm->GetCIEProgram()); decode_pgm(encoded_fde_program, new_ehpgm->GetFDEProgram()); idMap[eh_pgm_id]=new_ehpgm; eh_pgms.insert(new_ehpgm); - dbintr->MoveToNextRow(); + dbintr->moveToNextRow(); } return idMap; @@ -525,9 +505,9 @@ std::map<db_id_t,AddressID_t*> FileIR_t::ReadAddrsFromDB std::string q= "select * from " + fileptr->address_table_name + " ; "; - dbintr->IssueQuery(q); + dbintr->issueQuery(q); - while(!dbintr->IsDone()) + while(!dbintr->isDone()) { // address_id integer PRIMARY KEY, // file_id integer REFERENCES file_info, @@ -535,12 +515,12 @@ std::map<db_id_t,AddressID_t*> FileIR_t::ReadAddrsFromDB // doip_id integer DEFAULT -1 - db_id_t aid=atoi(dbintr->GetResultColumn("address_id").c_str()); - db_id_t file_id=atoi(dbintr->GetResultColumn("file_id").c_str()); - virtual_offset_t vaddr=strtovo(dbintr->GetResultColumn("vaddress_offset")); + db_id_t aid=atoi(dbintr->getResultColumn("address_id").c_str()); + db_id_t file_id=atoi(dbintr->getResultColumn("file_id").c_str()); + virtual_offset_t vaddr=strtovo(dbintr->getResultColumn("vaddress_offset")); // handle later? - //db_id_t doipid=atoi(dbintr->GetResultColumn("doip_id").c_str()); + //db_id_t doipid=atoi(dbintr->getResultColumn("doip_id").c_str()); AddressID_t *newaddr=new AddressID_t(aid,file_id,vaddr); @@ -550,7 +530,7 @@ std::map<db_id_t,AddressID_t*> FileIR_t::ReadAddrsFromDB addrs.insert(newaddr); - dbintr->MoveToNextRow(); + dbintr->moveToNextRow(); } return idMap; @@ -587,9 +567,9 @@ std::map<db_id_t,Instruction_t*> FileIR_t::ReadInsnsFromDB std::string q= "select * from " + fileptr->instruction_table_name + " ; "; - dbintr->IssueQuery(q); + dbintr->issueQuery(q); - while(!dbintr->IsDone()) + while(!dbintr->isDone()) { // address_id integer REFERENCES #PROGNAME#_address, @@ -604,23 +584,23 @@ std::map<db_id_t,Instruction_t*> FileIR_t::ReadInsnsFromDB // doip_id integer DEFAULT -1 - db_id_t instruction_id=atoi(dbintr->GetResultColumn("instruction_id").c_str()); - db_id_t aid=atoi(dbintr->GetResultColumn("address_id").c_str()); - db_id_t parent_func_id=atoi(dbintr->GetResultColumn("parent_function_id").c_str()); - db_id_t orig_address_id=atoi(dbintr->GetResultColumn("orig_address_id").c_str()); - db_id_t fallthrough_address_id=atoi(dbintr->GetResultColumn("fallthrough_address_id").c_str()); - db_id_t targ_address_id=atoi(dbintr->GetResultColumn("target_address_id").c_str()); - db_id_t icfs_id=atoi(dbintr->GetResultColumn("icfs_id").c_str()); - db_id_t eh_pgm_id=atoi(dbintr->GetResultColumn("ehpgm_id").c_str()); - db_id_t eh_cs_id=atoi(dbintr->GetResultColumn("ehcss_id").c_str()); - std::string encoded_data=(dbintr->GetResultColumn("data")); + db_id_t instruction_id=atoi(dbintr->getResultColumn("instruction_id").c_str()); + db_id_t aid=atoi(dbintr->getResultColumn("address_id").c_str()); + db_id_t parent_func_id=atoi(dbintr->getResultColumn("parent_function_id").c_str()); + db_id_t orig_address_id=atoi(dbintr->getResultColumn("orig_address_id").c_str()); + db_id_t fallthrough_address_id=atoi(dbintr->getResultColumn("fallthrough_address_id").c_str()); + db_id_t targ_address_id=atoi(dbintr->getResultColumn("target_address_id").c_str()); + db_id_t icfs_id=atoi(dbintr->getResultColumn("icfs_id").c_str()); + db_id_t eh_pgm_id=atoi(dbintr->getResultColumn("ehpgm_id").c_str()); + db_id_t eh_cs_id=atoi(dbintr->getResultColumn("ehcss_id").c_str()); + std::string encoded_data=(dbintr->getResultColumn("data")); std::string data=encoded_to_raw_string(encoded_data); - std::string callback=(dbintr->GetResultColumn("callback")); - std::string comment=(dbintr->GetResultColumn("comment")); - db_id_t indirect_branch_target_address_id = atoi(dbintr->GetResultColumn("ind_target_address_id").c_str()); - db_id_t doipid=atoi(dbintr->GetResultColumn("doip_id").c_str()); + std::string callback=(dbintr->getResultColumn("callback")); + std::string comment=(dbintr->getResultColumn("comment")); + db_id_t indirect_branch_target_address_id = atoi(dbintr->getResultColumn("ind_target_address_id").c_str()); + db_id_t doipid=atoi(dbintr->getResultColumn("doip_id").c_str()); - std::string isIndStr=(dbintr->GetResultColumn("ind_target_address_id")); + std::string isIndStr=(dbintr->getResultColumn("ind_target_address_id")); auto indTarg=(AddressID_t*)NULL; if (indirect_branch_target_address_id != NOT_IN_DATABASE) @@ -635,13 +615,13 @@ std::map<db_id_t,Instruction_t*> FileIR_t::ReadInsnsFromDB orig_address_id, data, callback, comment, indTarg, doipid); - if(eh_pgm_id != NOT_IN_DATABASE) newinsn->SetEhProgram(ehpgmMap.at(eh_pgm_id)); - if(eh_cs_id != NOT_IN_DATABASE) newinsn->SetEhCallSite(ehcsMap.at(eh_cs_id)); + if(eh_pgm_id != NOT_IN_DATABASE) newinsn->setEhProgram(ehpgmMap.at(eh_pgm_id)); + if(eh_cs_id != NOT_IN_DATABASE) newinsn->setEhCallSite(ehcsMap.at(eh_cs_id)); if(parent_func) { parent_func->GetInstructions().insert(newinsn); - newinsn->SetFunction(funcMap.at(parent_func_id)); + newinsn->setFunction(funcMap.at(parent_func_id)); } //std::cout<<"Found address "<<aid<<"."<<std::endl; @@ -655,7 +635,7 @@ std::map<db_id_t,Instruction_t*> FileIR_t::ReadInsnsFromDB if (icfs_id == NOT_IN_DATABASE) { - newinsn->SetIBTargets(NULL); + newinsn->setIBTargets(NULL); } else { @@ -664,18 +644,18 @@ std::map<db_id_t,Instruction_t*> FileIR_t::ReadInsnsFromDB unresolvedICFS[newinsn] = icfs_id; } - dbintr->MoveToNextRow(); + dbintr->moveToNextRow(); } for(std::map<db_id_t,Instruction_t*>::const_iterator i=idMap.begin(); i!=idMap.end(); ++i) { Instruction_t *instr=(*i).second; - db_id_t fallthroughid=fallthroughs[instr->GetBaseID()]; + db_id_t fallthroughid=fallthroughs[instr->getBaseID()]; if(idMap[fallthroughid]) - instr->SetFallthrough(idMap[fallthroughid]); - db_id_t targetid=targets[instr->GetBaseID()]; + instr->setFallthrough(idMap[fallthroughid]); + db_id_t targetid=targets[instr->getBaseID()]; if(idMap[targetid]) - instr->SetTarget(idMap[targetid]); + instr->setTarget(idMap[targetid]); } @@ -688,19 +668,19 @@ void FileIR_t::ReadRelocsFromDB ) { std::string q= "select * from " + fileptr->relocs_table_name + " ; "; - dbintr->IssueQuery(q); + dbintr->issueQuery(q); - while(!dbintr->IsDone()) + while(!dbintr->isDone()) { - db_id_t reloc_id=atoi(dbintr->GetResultColumn("reloc_id").c_str()); - int reloc_offset=atoi(dbintr->GetResultColumn("reloc_offset").c_str()); - std::string reloc_type=(dbintr->GetResultColumn("reloc_type")); - db_id_t instruction_id=atoi(dbintr->GetResultColumn("instruction_id").c_str()); + db_id_t reloc_id=atoi(dbintr->getResultColumn("reloc_id").c_str()); + int reloc_offset=atoi(dbintr->getResultColumn("reloc_offset").c_str()); + std::string reloc_type=(dbintr->getResultColumn("reloc_type")); + db_id_t instruction_id=atoi(dbintr->getResultColumn("instruction_id").c_str()); // handle later? - //db_id_t doipid=atoi(dbintr->GetResultColumn("doip_id").c_str()); - db_id_t wrt_id=atoi(dbintr->GetResultColumn("wrt_id").c_str()); - uint32_t addend=atoi(dbintr->GetResultColumn("addend").c_str()); + //db_id_t doipid=atoi(dbintr->getResultColumn("doip_id").c_str()); + db_id_t wrt_id=atoi(dbintr->getResultColumn("wrt_id").c_str()); + uint32_t addend=atoi(dbintr->getResultColumn("addend").c_str()); BaseObj_t* wrt_obj=objMap[wrt_id]; // might be null. @@ -711,13 +691,13 @@ void FileIR_t::ReadRelocsFromDB objMap[instruction_id]->GetRelocations().insert(reloc); relocs.insert(reloc); - dbintr->MoveToNextRow(); + dbintr->moveToNextRow(); } } -void FileIR_t::WriteToDB(ostream *verbose_logging) +void FileIR_t::writeToDB(ostream *verbose_logging) { // const auto WriteIRDB_start = clock(); @@ -725,113 +705,120 @@ void FileIR_t::WriteToDB(ostream *verbose_logging) assert(pqIntr); //Resolve (assemble) any instructions in the registry. - AssembleRegistry(); + assembleRegistry(); /* assign each item a unique ID */ - SetBaseIDS(); + setBaseIDS(); CleanupICFS(verbose_logging); db_id_t j=-1; - dbintr->IssueQuery(string("TRUNCATE TABLE ")+ fileptr->instruction_table_name + string(" cascade;")); - dbintr->IssueQuery(string("TRUNCATE TABLE ")+ fileptr->icfs_table_name + string(" cascade;")); - dbintr->IssueQuery(string("TRUNCATE TABLE ")+ fileptr->icfs_map_table_name + string(" cascade;")); - dbintr->IssueQuery(string("TRUNCATE TABLE ")+ fileptr->function_table_name + string(" cascade;")); - dbintr->IssueQuery(string("TRUNCATE TABLE ")+ fileptr->address_table_name + string(" cascade;")); - dbintr->IssueQuery(string("TRUNCATE TABLE ")+ fileptr->relocs_table_name + string(" cascade;")); - dbintr->IssueQuery(string("TRUNCATE TABLE ")+ fileptr->types_table_name + string(" cascade;")); - dbintr->IssueQuery(string("TRUNCATE TABLE ")+ fileptr->scoop_table_name + string(" cascade;")); - dbintr->IssueQuery(string("TRUNCATE TABLE ")+ fileptr->scoop_table_name+"_part2"+ string(" cascade;")); - dbintr->IssueQuery(string("TRUNCATE TABLE ")+ fileptr->ehpgm_table_name + string(" cascade;")); - dbintr->IssueQuery(string("TRUNCATE TABLE ")+ fileptr->ehcss_table_name + string(" cascade;")); + dbintr->issueQuery(string("TRUNCATE TABLE ")+ fileptr->instruction_table_name + string(" cascade;")); + dbintr->issueQuery(string("TRUNCATE TABLE ")+ fileptr->icfs_table_name + string(" cascade;")); + dbintr->issueQuery(string("TRUNCATE TABLE ")+ fileptr->icfs_map_table_name + string(" cascade;")); + dbintr->issueQuery(string("TRUNCATE TABLE ")+ fileptr->function_table_name + string(" cascade;")); + dbintr->issueQuery(string("TRUNCATE TABLE ")+ fileptr->address_table_name + string(" cascade;")); + dbintr->issueQuery(string("TRUNCATE TABLE ")+ fileptr->relocs_table_name + string(" cascade;")); + dbintr->issueQuery(string("TRUNCATE TABLE ")+ fileptr->types_table_name + string(" cascade;")); + dbintr->issueQuery(string("TRUNCATE TABLE ")+ fileptr->scoop_table_name + string(" cascade;")); + dbintr->issueQuery(string("TRUNCATE TABLE ")+ fileptr->scoop_table_name+"_part2"+ string(" cascade;")); + dbintr->issueQuery(string("TRUNCATE TABLE ")+ fileptr->ehpgm_table_name + string(" cascade;")); + dbintr->issueQuery(string("TRUNCATE TABLE ")+ fileptr->ehcss_table_name + string(" cascade;")); /* and now that everything has an ID, let's write to the DB */ // write out the types string q=string(""); - for(std::set<Type_t*>::const_iterator t=types.begin(); t!=types.end(); ++t) + for(auto t=types.begin(); t!=types.end(); ++t) { - q+=(*t)->WriteToDB(fileptr,j); // @TODO: wtf is j? + auto real_t=dynamic_cast<Type_t*>(*t); + assert(real_t); + q+=real_t->WriteToDB(fileptr,j); // @TODO: wtf is j? if(q.size()>1024*1024) { - dbintr->IssueQuery(q); + dbintr->issueQuery(q); q=string(""); } } - dbintr->IssueQuery(q); + dbintr->issueQuery(q); // write out functions auto withHeader=true; q=string(""); - for(std::set<Function_t*>::const_iterator f=funcs.begin(); f!=funcs.end(); ++f) + for(auto f=funcs.begin(); f!=funcs.end(); ++f) { - q+=(*f)->WriteToDB(fileptr,j); + auto real_f=dynamic_cast<Function_t*>(*f); + assert(real_f); + q+=real_f->WriteToDB(fileptr,j); if(q.size()>1024*1024) { - dbintr->IssueQuery(q); + dbintr->issueQuery(q); q=string(""); } } - dbintr->IssueQuery(q); + dbintr->issueQuery(q); // write out addresses - pqxx::tablewriter W_addrs(pqIntr->GetTransaction(),fileptr->address_table_name); + pqxx::tablewriter W_addrs(pqIntr->getTransaction(),fileptr->address_table_name); for(const auto &a : addrs) { - W_addrs << a->WriteToDB(fileptr,j,withHeader); + auto real_a=dynamic_cast<AddressID_t*>(a); + assert(real_a); + W_addrs << real_a->WriteToDB(fileptr,j,withHeader); } W_addrs.complete(); // write out instructions - pqxx::tablewriter W(pqIntr->GetTransaction(),fileptr->instruction_table_name); - for(std::set<Instruction_t*>::const_iterator i=insns.begin(); i!=insns.end(); ++i) + pqxx::tablewriter W(pqIntr->getTransaction(),fileptr->instruction_table_name); + for(auto i=insns.begin(); i!=insns.end(); ++i) { - Instruction_t const * const insnp=*i; + auto insnp=dynamic_cast<Instruction_t*>(*i); //DISASM disasm; //Disassemble(insnp,disasm); - const auto disasm=DecodedInstruction_t(insnp); + const auto p_disasm=DecodedInstruction_t::factory(insnp); + const auto& disasm=*p_disasm; - if(insnp->GetOriginalAddressID() == NOT_IN_DATABASE) + if(insnp->getOriginalAddressID() == NOT_IN_DATABASE) { - // if(insnp->GetFallthrough()==NULL && disasm.Instruction.BranchType!=RetType && disasm.Instruction.BranchType!=JmpType ) - if(insnp->GetFallthrough()==NULL && !disasm.isReturn() && !disasm.isUnconditionalBranch()) + // if(insnp->getFallthrough()==NULL && disasm.Instruction.BranchType!=RetType && disasm.Instruction.BranchType!=JmpType ) + if(insnp->getFallthrough()==NULL && !disasm.isReturn() && !disasm.isUnconditionalBranch()) { // instructions that fall through are required to either specify a fallthrough that's // in the IRDB, or have an associated "old" instruction. // without these bits of information, the new instruction can't possibly execute correctly. // and we won't have the information necessary to emit spri. - *verbose_logging << "NULL fallthrough: offending instruction:" << ((Instruction_t*)insnp)->getDisassembly() << " comment: " << ((Instruction_t*)insnp)->GetComment() << endl; + *verbose_logging << "NULL fallthrough: offending instruction:" << ((Instruction_t*)insnp)->getDisassembly() << " comment: " << ((Instruction_t*)insnp)->getComment() << endl; assert(0); abort(); } - //if(insnp->GetTarget()==NULL && disasm.Instruction.BranchType!=0 && + //if(insnp->getTarget()==NULL && disasm.Instruction.BranchType!=0 && // disasm.Instruction.BranchType!=RetType && // // not an indirect branch // ((disasm.Instruction.BranchType!=JmpType && disasm.Instruction.BranchType!=CallType) || // disasm.Argument1.ArgType&CONSTANT_TYPE)) - if(insnp->GetTarget()==NULL && disasm.isBranch() && !disasm.isReturn() && + if(insnp->getTarget()==NULL && disasm.isBranch() && !disasm.isReturn() && // not an indirect branch - ( (!disasm.isUnconditionalBranch() && !disasm.isCall()) || disasm.getOperand(0).isConstant()) + ( (!disasm.isUnconditionalBranch() && !disasm.isCall()) || disasm.getOperand(0)->isConstant()) ) { // direct branches are required to either specify a target that's // in the IRDB, or have an associated "old" instruction. // without these bits of information, the new instruction can't possibly execute correctly. // and we won't have the information necessary to emit spri. - *verbose_logging << "Call must have a target; offending instruction:" << ((Instruction_t*)insnp)->getDisassembly() << " comment: " << ((Instruction_t*)insnp)->GetComment() << endl; + *verbose_logging << "Call must have a target; offending instruction:" << ((Instruction_t*)insnp)->getDisassembly() << " comment: " << ((Instruction_t*)insnp)->getComment() << endl; assert(0); abort(); } } - const auto &insn_values=(*i)->WriteToDB(fileptr,j); + const auto &insn_values=insnp->WriteToDB(fileptr,j); W << insn_values; } @@ -839,166 +826,158 @@ void FileIR_t::WriteToDB(ostream *verbose_logging) // icfs - for (ICFSSet_t::iterator it = GetAllICFS().begin(); it != GetAllICFS().end(); ++it) + for (auto it = GetAllICFS().begin(); it != GetAllICFS().end(); ++it) { - ICFS_t* icfs = *it; + ICFS_t* icfs = dynamic_cast<ICFS_t*>(*it); assert(icfs); string q = icfs->WriteToDB(fileptr); - dbintr->IssueQuery(q); + dbintr->issueQuery(q); } // scoops - for(DataScoopSet_t::const_iterator it=scoops.begin(); it!=scoops.end(); ++it) + for(auto it=scoops.begin(); it!=scoops.end(); ++it) { - DataScoop_t* scoop = *it; + DataScoop_t* scoop = dynamic_cast<DataScoop_t*>(*it); assert(scoop); string q = scoop->WriteToDB(fileptr,j); - dbintr->IssueQuery(q); + dbintr->issueQuery(q); } // ehpgms - pqxx::tablewriter W_eh(pqIntr->GetTransaction(),fileptr->ehpgm_table_name); + pqxx::tablewriter W_eh(pqIntr->getTransaction(),fileptr->ehpgm_table_name); for(const auto& i : eh_pgms) { - W_eh << i->WriteToDB(fileptr); + W_eh << dynamic_cast<EhProgram_t*>(i)->WriteToDB(fileptr); } W_eh.complete(); // eh css for(const auto& i : eh_css) { - string q = i->WriteToDB(fileptr); - dbintr->IssueQuery(q); + string q = dynamic_cast<EhCallSite_t*>(i)->WriteToDB(fileptr); + dbintr->issueQuery(q); } // all relocs - pqxx::tablewriter W_reloc(pqIntr->GetTransaction(),fileptr->relocs_table_name); + pqxx::tablewriter W_reloc(pqIntr->getTransaction(),fileptr->relocs_table_name); // eh css relocs for(const auto& i : eh_css) { - const auto &relocs=i->GetRelocations(); + const auto &relocs=i->getRelocations(); for(auto& reloc : relocs) - W_reloc << reloc->WriteToDB(fileptr,i); + W_reloc << dynamic_cast<Relocation_t*>(reloc)->WriteToDB(fileptr,dynamic_cast<BaseObj_t*>(i)); } // eh pgms relocs for(const auto& i : eh_pgms) { - const auto &relocs=i->GetRelocations(); + const auto &relocs=i->getRelocations(); for(auto& reloc : relocs) - W_reloc << reloc->WriteToDB(fileptr,i); + W_reloc << dynamic_cast<Relocation_t*>(reloc)->WriteToDB(fileptr,dynamic_cast<BaseObj_t*>(i)); } // scoops relocs for(const auto& i : scoops) { - const auto &relocs=i->GetRelocations(); + const auto &relocs=i->getRelocations(); for(auto& reloc : relocs) - W_reloc << reloc->WriteToDB(fileptr,i); + W_reloc << dynamic_cast<Relocation_t*>(reloc)->WriteToDB(fileptr,dynamic_cast<BaseObj_t*>(i)); } // write out instruction's relocs for(const auto& i : insns) { - const auto &relocs=i->GetRelocations(); + const auto &relocs=i->getRelocations(); for(auto& reloc : relocs) - W_reloc << reloc->WriteToDB(fileptr,i); + W_reloc << dynamic_cast<Relocation_t*>(reloc)->WriteToDB(fileptr,dynamic_cast<BaseObj_t*>(i)); } W_reloc.complete(); -/* std::cout << std::dec; - - const auto WriteIRDB_end = clock(); - const auto read_time = (double)(ReadIRDB_end-ReadIRDB_start)/ CLOCKS_PER_SEC; - const auto write_time = (double)(WriteIRDB_end-WriteIRDB_start)/ CLOCKS_PER_SEC; - const auto wall_time = (double)(WriteIRDB_end-ReadIRDB_start)/ CLOCKS_PER_SEC; - const auto transform_time=wall_time - read_time - write_time; - std::cout << std::fixed << std::setprecision(2) << "#ATTRIBUTE ReadIRDB_WallClock=" << read_time <<endl; - std::cout << std::fixed << std::setprecision(2) << "#ATTRIBUTE WriteIRDB_WallClock=" << write_time << endl; - std::cout << std::fixed << std::setprecision(2) << "#ATTRIBUTE TotalIRDB_WallClock=" << wall_time << endl; - std::cout << std::fixed << std::setprecision(2) << "#ATTRIBUTE TransformIRDB_WallClock=" << transform_time << endl; -*/ - } -db_id_t FileIR_t::GetMaxBaseID() +db_id_t FileIR_t::getMaxBaseID() const { #define MAX(a,b) (((a)>(b)) ? (a) : (b)) /* find the highest database ID */ db_id_t j=0; for(auto i=funcs.begin(); i!=funcs.end(); ++i) - j=MAX(j,(*i)->GetBaseID()); + j=MAX(j,(*i)->getBaseID()); for(auto i=addrs.begin(); i!=addrs.end(); ++i) - j=MAX(j,(*i)->GetBaseID()); + j=MAX(j,(*i)->getBaseID()); for(auto i=insns.begin(); i!=insns.end(); ++i) - j=MAX(j,(*i)->GetBaseID()); + j=MAX(j,(*i)->getBaseID()); for(auto i=relocs.begin(); i!=relocs.end(); ++i) - j=MAX(j,(*i)->GetBaseID()); + j=MAX(j,(*i)->getBaseID()); for(auto i=types.begin(); i!=types.end(); ++i) - j=MAX(j,(*i)->GetBaseID()); + j=MAX(j,(*i)->getBaseID()); for(auto i=scoops.begin(); i!=scoops.end(); ++i) - j=MAX(j,(*i)->GetBaseID()); + j=MAX(j,(*i)->getBaseID()); for(auto i=icfs_set.begin(); i!=icfs_set.end(); ++i) - j=MAX(j,(*i)->GetBaseID()); + j=MAX(j,(*i)->getBaseID()); for(auto i=eh_pgms.begin(); i!=eh_pgms.end(); ++i) - j=MAX(j,(*i)->GetBaseID()); + j=MAX(j,(*i)->getBaseID()); for(auto i=eh_css.begin(); i!=eh_css.end(); ++i) - j=MAX(j,(*i)->GetBaseID()); + j=MAX(j,(*i)->getBaseID()); return j+1; // easy to off-by-one this so we do it for a user just in case. } -void FileIR_t::SetBaseIDS() +void FileIR_t::setBaseIDS() { - auto j=GetMaxBaseID(); + auto j=getMaxBaseID(); /* increment past the max ID so we don't duplicate */ j++; /* for anything that's not yet in the DB, assign an ID to it */ for(auto i=funcs.begin(); i!=funcs.end(); ++i) - if((*i)->GetBaseID()==NOT_IN_DATABASE) - (*i)->SetBaseID(j++); + if((*i)->getBaseID()==NOT_IN_DATABASE) + (*i)->setBaseID(j++); for(auto i=addrs.begin(); i!=addrs.end(); ++i) - if((*i)->GetBaseID()==NOT_IN_DATABASE) - (*i)->SetBaseID(j++); + if((*i)->getBaseID()==NOT_IN_DATABASE) + (*i)->setBaseID(j++); for(auto i=insns.begin(); i!=insns.end(); ++i) - if((*i)->GetBaseID()==NOT_IN_DATABASE) - (*i)->SetBaseID(j++); + if((*i)->getBaseID()==NOT_IN_DATABASE) + (*i)->setBaseID(j++); for(auto i=relocs.begin(); i!=relocs.end(); ++i) - if((*i)->GetBaseID()==NOT_IN_DATABASE) - (*i)->SetBaseID(j++); + if((*i)->getBaseID()==NOT_IN_DATABASE) + (*i)->setBaseID(j++); for(auto i=types.begin(); i!=types.end(); ++i) - if((*i)->GetBaseID()==NOT_IN_DATABASE) - (*i)->SetBaseID(j++); + if((*i)->getBaseID()==NOT_IN_DATABASE) + (*i)->setBaseID(j++); for(auto i=scoops.begin(); i!=scoops.end(); ++i) - if((*i)->GetBaseID()==NOT_IN_DATABASE) - (*i)->SetBaseID(j++); + if((*i)->getBaseID()==NOT_IN_DATABASE) + (*i)->setBaseID(j++); for(auto i=icfs_set.begin(); i!=icfs_set.end(); ++i) - if((*i)->GetBaseID()==NOT_IN_DATABASE) - (*i)->SetBaseID(j++); + if((*i)->getBaseID()==NOT_IN_DATABASE) + (*i)->setBaseID(j++); for(auto i=eh_pgms.begin(); i!=eh_pgms.end(); ++i) - if((*i)->GetBaseID()==NOT_IN_DATABASE) - (*i)->SetBaseID(j++); + if((*i)->getBaseID()==NOT_IN_DATABASE) + (*i)->setBaseID(j++); for(auto i=eh_css.begin(); i!=eh_css.end(); ++i) - if((*i)->GetBaseID()==NOT_IN_DATABASE) - (*i)->SetBaseID(j++); + if((*i)->getBaseID()==NOT_IN_DATABASE) + (*i)->setBaseID(j++); } -int FileIR_t::GetArchitectureBitWidth() +const IRDB_SDK::ArchitectureDescription_t* IRDB_SDK::FileIR_t::getArchitecture() +{ + return libIRDB::FileIR_t::archdesc; +} + +uint32_t IRDB_SDK::FileIR_t::getArchitectureBitWidth() { - return archdesc->GetBitWidth(); + return libIRDB::FileIR_t::archdesc->getBitWidth(); } -void FileIR_t::SetArchitecture(const int width, const ADMachineType_t mt) +void FileIR_t::setArchitecture(const int width, const ADMachineType_t mt) { if(archdesc==NULL) archdesc=new ArchitectureDescription_t; - archdesc->SetBitWidth(width); + archdesc->setBitWidth(width); archdesc->setMachineType(mt); } -void FileIR_t::SetArchitecture() +void FileIR_t::setArchitecture() { /* the first 16 bytes of an ELF file define the magic number and ELF Class. */ @@ -1012,34 +991,34 @@ void FileIR_t::SetArchitecture() auto myinter=BaseObj_t::GetInterface(); auto *mypqxxintr=dynamic_cast<pqxxDB_t*>(myinter); - const auto elfoid=GetFile()->GetELFOID(); - pqxx::largeobjectaccess loa(mypqxxintr->GetTransaction(), elfoid, PGSTD::ios::in); + const auto elfoid=getFile()->getELFOID(); + pqxx::largeobjectaccess loa(mypqxxintr->getTransaction(), elfoid, PGSTD::ios::in); loa.cread((char*)&hdr_union, sizeof(hdr_union)); const auto e_ident=hdr_union.ehdr32.e_ident; - archdesc=new ArchitectureDescription_t; + libIRDB::FileIR_t::archdesc=new ArchitectureDescription_t; if((e_ident[EI_MAG0]==ELFMAG0) && (e_ident[EI_MAG1]==ELFMAG1) && (e_ident[EI_MAG2]==ELFMAG2) && (e_ident[EI_MAG3]==ELFMAG3)) { - archdesc->SetFileType(AD_ELF); + libIRDB::FileIR_t::archdesc->setFileType(IRDB_SDK::adftELF); } else if((e_ident[EI_MAG0]==ELFMAG0) && (e_ident[EI_MAG1]=='C') && (e_ident[EI_MAG2]=='G') && (e_ident[EI_MAG3]=='C')) { - archdesc->SetFileType(AD_ELF); + libIRDB::FileIR_t::archdesc->setFileType(IRDB_SDK::adftELF); } else if((e_ident[EI_MAG0]=='M') && (e_ident[EI_MAG1]=='Z')) { - archdesc->SetFileType(AD_PE); + libIRDB::FileIR_t::archdesc->setFileType(IRDB_SDK::adftPE); } else { @@ -1048,11 +1027,11 @@ void FileIR_t::SetArchitecture() } - if (archdesc->GetFileType() == AD_PE) + if (libIRDB::FileIR_t::archdesc->getFileType() == IRDB_SDK::adftPE) { // just assume x86-64 bit for Windows, o/w could also extract from file - archdesc->SetBitWidth(64); - archdesc->setMachineType(admtX86_64); + libIRDB::FileIR_t::archdesc->setBitWidth(64); + libIRDB::FileIR_t::archdesc->setMachineType(IRDB_SDK::admtX86_64); } else { @@ -1060,20 +1039,20 @@ void FileIR_t::SetArchitecture() { case ELFCLASS32: { - archdesc->SetBitWidth(32); + libIRDB::FileIR_t::archdesc->setBitWidth(32); if(hdr_union.ehdr32.e_machine!=EM_386) throw std::invalid_argument("Arch not supported. 32-bit archs supported: I386"); - archdesc->setMachineType(admtI386); + libIRDB::FileIR_t::archdesc->setMachineType(IRDB_SDK::admtI386); break; } case ELFCLASS64: { - archdesc->SetBitWidth(64); + libIRDB::FileIR_t::archdesc->setBitWidth(64); const auto mt= - hdr_union.ehdr64.e_machine==EM_AARCH64 ? admtAarch64 : - hdr_union.ehdr64.e_machine==EM_X86_64 ? admtX86_64 : + hdr_union.ehdr64.e_machine==EM_AARCH64 ? IRDB_SDK::admtAarch64 : + hdr_union.ehdr64.e_machine==EM_X86_64 ? IRDB_SDK::admtX86_64 : throw std::invalid_argument("Arch not supported. 64-bit archs supported: Aarch64, X86-64"); - archdesc->setMachineType(mt); + libIRDB::FileIR_t::archdesc->setMachineType(mt); break; } default: @@ -1105,9 +1084,9 @@ std::map<db_id_t, Type_t*> FileIR_t::ReadTypesFromDB (TypeSet_t& types) // cout << "pass1: query: " << q; - dbintr->IssueQuery(q); + dbintr->issueQuery(q); - while(!dbintr->IsDone()) + while(!dbintr->isDone()) { // type_id integer, // type integer DEFAULT 0, -- possible types (0: UNKNOWN) @@ -1117,160 +1096,163 @@ std::map<db_id_t, Type_t*> FileIR_t::ReadTypesFromDB (TypeSet_t& types) // ref_type_id2 integer DEFAULT -1, -- for func types // doip_id integer DEFAULT -1 -- the DOIP - db_id_t tid=atoi(dbintr->GetResultColumn("type_id").c_str()); - IRDB_Type type=(IRDB_Type)atoi(dbintr->GetResultColumn("type").c_str()); - std::string name=dbintr->GetResultColumn("name"); + db_id_t tid=atoi(dbintr->getResultColumn("type_id").c_str()); + IRDB_Type type=(IRDB_Type)atoi(dbintr->getResultColumn("type").c_str()); + std::string name=dbintr->getResultColumn("name"); BasicType_t *t = NULL; // cout << "fileir::ReadFromDB(): pass1: " << name << endl; - switch(type) { - case T_UNKNOWN: - case T_VOID: - case T_NUMERIC: - case T_VARIADIC: - case T_INT: - case T_CHAR: - case T_FLOAT: - case T_DOUBLE: - t = new BasicType_t(tid, type, name); - types.insert(t); - tMap[tid] = t; - break; - - case T_POINTER: - // do nothing for pointers - break; - - default: - cerr << "ReadTypesFromDB(): ERROR: pass 1 should only see basic types or pointer" << endl; - assert(0); - break; + switch(type) + { + case IRDB_SDK::itUnknown: + case IRDB_SDK::itVoid: + case IRDB_SDK::itNumeric: + case IRDB_SDK::itVariadic: + case IRDB_SDK::itInt: + case IRDB_SDK::itChar: + case IRDB_SDK::itFloat: + case IRDB_SDK::itDouble: + t = new BasicType_t(tid, type, name); + types.insert(t); + tMap[tid] = t; + break; + + case IRDB_SDK::itPointer: + // do nothing for pointers + break; + + default: + cerr << "ReadTypesFromDB(): ERROR: pass 1 should only see basic types or pointer" << endl; + assert(0); + break; } - dbintr->MoveToNextRow(); + dbintr->moveToNextRow(); } // end pass1 char query[2048]; // pass2 get pointers - sprintf(query,"select * from %s WHERE type = %d;", fileptr->types_table_name.c_str(), T_POINTER); - dbintr->IssueQuery(query); + sprintf(query,"select * from %s WHERE type = %d;", fileptr->types_table_name.c_str(), IRDB_SDK::itPointer); + dbintr->issueQuery(query); - while(!dbintr->IsDone()) + while(!dbintr->isDone()) { - db_id_t tid=atoi(dbintr->GetResultColumn("type_id").c_str()); - IRDB_Type type=(IRDB_Type)atoi(dbintr->GetResultColumn("type").c_str()); - std::string name=dbintr->GetResultColumn("name"); - db_id_t ref1=atoi(dbintr->GetResultColumn("ref_type_id").c_str()); + db_id_t tid=atoi(dbintr->getResultColumn("type_id").c_str()); + IRDB_Type type=(IRDB_Type)atoi(dbintr->getResultColumn("type").c_str()); + std::string name=dbintr->getResultColumn("name"); + db_id_t ref1=atoi(dbintr->getResultColumn("ref_type_id").c_str()); // cout << "fileir::ReadFromDB(): pass2 (pointers): " << name << endl; - switch(type) { - case T_POINTER: - { + switch(type) + { + case IRDB_SDK::itPointer: + { // cout << " pointer type: ref1: " << ref1 << endl; - Type_t *referentType = NULL; - if (ref1 >= 0) - { - assert(tMap.count(ref1) > 0); - referentType = tMap[ref1]; - } - PointerType_t *ptr = new PointerType_t(tid, referentType, name); - types.insert(ptr); - tMap[tid] = ptr; - } - break; - - default: - cerr << "ReadTypesFromDB(): ERROR: pass3: unhandled type id = " << type << endl; - assert(0); // not yet handled - break; + Type_t *referentType = NULL; + if (ref1 >= 0) + { + assert(tMap.count(ref1) > 0); + referentType = tMap[ref1]; + } + PointerType_t *ptr = new PointerType_t(tid, referentType, name); + types.insert(ptr); + tMap[tid] = ptr; + } + break; + + default: + cerr << "ReadTypesFromDB(): ERROR: pass3: unhandled type id = " << type << endl; + assert(0); // not yet handled + break; } - dbintr->MoveToNextRow(); + dbintr->moveToNextRow(); } // end pass3 // pass3 get all aggregates - sprintf(query,"select * from %s WHERE type = %d order by type_id, pos;", fileptr->types_table_name.c_str(), T_AGGREGATE); - dbintr->IssueQuery(query); + sprintf(query,"select * from %s WHERE type = %d order by type_id, pos;", fileptr->types_table_name.c_str(), IRDB_SDK::itAggregate); + dbintr->issueQuery(query); - while(!dbintr->IsDone()) + while(!dbintr->isDone()) { - db_id_t tid=atoi(dbintr->GetResultColumn("type_id").c_str()); - IRDB_Type type=(IRDB_Type)atoi(dbintr->GetResultColumn("type").c_str()); - std::string name=dbintr->GetResultColumn("name"); - db_id_t ref1=atoi(dbintr->GetResultColumn("ref_type_id").c_str()); - int pos=atoi(dbintr->GetResultColumn("pos").c_str()); + db_id_t tid=atoi(dbintr->getResultColumn("type_id").c_str()); + IRDB_Type type=(IRDB_Type)atoi(dbintr->getResultColumn("type").c_str()); + std::string name=dbintr->getResultColumn("name"); + db_id_t ref1=atoi(dbintr->getResultColumn("ref_type_id").c_str()); + int pos=atoi(dbintr->getResultColumn("pos").c_str()); AggregateType_t *agg = NULL; // cout << "fileir::ReadFromDB(): pass3 (aggregates): " << name << endl; - switch(type) { - case T_AGGREGATE: - { - if (tMap.count(tid) == 0) // new aggregate - { + switch(type) + { + case IRDB_SDK::itAggregate: + { + if (tMap.count(tid) == 0) // new aggregate + { // cout << "fileir::ReadFromDB(): pass3: new aggregate type: typeid: " << tid << " name: " << name << endl; - agg = new AggregateType_t(tid, name); - types.insert(agg); - tMap[tid] = agg; - } - else - agg = dynamic_cast<AggregateType_t*>(tMap[tid]); - - assert(agg); - // ref1 has the id of a basic type, look it up - Type_t *ref = tMap[ref1]; - assert(ref); - agg->AddAggregatedType(ref, pos); - } - break; - - default: - cerr << "ReadTypesFromDB(): ERROR: pass2: unhandled type id = " << type << endl; - assert(0); // not yet handled - break; + agg = new AggregateType_t(tid, name); + types.insert(agg); + tMap[tid] = agg; + } + else + agg = dynamic_cast<AggregateType_t*>(tMap[tid]); + + assert(agg); + // ref1 has the id of a basic type, look it up + Type_t *ref = tMap[ref1]; + assert(ref); + agg->addAggregatedType(ref, pos); + } + break; + + default: + cerr << "ReadTypesFromDB(): ERROR: pass2: unhandled type id = " << type << endl; + assert(0); // not yet handled + break; } - dbintr->MoveToNextRow(); + dbintr->moveToNextRow(); } // end pass3 // pass4 get all functions - sprintf(query,"select * from %s WHERE type = %d;", fileptr->types_table_name.c_str(), T_FUNC); - dbintr->IssueQuery(query); + sprintf(query,"select * from %s WHERE type = %d;", fileptr->types_table_name.c_str(), IRDB_SDK::itFunc); + dbintr->issueQuery(query); - while(!dbintr->IsDone()) + while(!dbintr->isDone()) { - db_id_t tid=atoi(dbintr->GetResultColumn("type_id").c_str()); - IRDB_Type type=(IRDB_Type)atoi(dbintr->GetResultColumn("type").c_str()); - std::string name=dbintr->GetResultColumn("name"); - db_id_t ref1=atoi(dbintr->GetResultColumn("ref_type_id").c_str()); - db_id_t ref2=atoi(dbintr->GetResultColumn("ref_type_id2").c_str()); + db_id_t tid=atoi(dbintr->getResultColumn("type_id").c_str()); + IRDB_Type type=(IRDB_Type)atoi(dbintr->getResultColumn("type").c_str()); + std::string name=dbintr->getResultColumn("name"); + db_id_t ref1=atoi(dbintr->getResultColumn("ref_type_id").c_str()); + db_id_t ref2=atoi(dbintr->getResultColumn("ref_type_id2").c_str()); FuncType_t *fn = NULL; - switch(type) { - case T_FUNC: - { - assert(tMap.count(tid) == 0); - - fn = new FuncType_t(tid, name); - types.insert(fn); - tMap[tid] = fn; - assert(tMap[ref1]); // return type - assert(tMap[ref2]); // argument type (which is an aggregate) - fn->SetReturnType(tMap[ref1]); - AggregateType_t *args = dynamic_cast<AggregateType_t*>(tMap[ref2]); - assert(args); - fn->SetArgumentsType(args); - } - break; - - default: - cerr << "ReadTypesFromDB(): ERROR: pass4: unhandled type id = " << type << endl; - assert(0); // not yet handled - break; + switch(type) + { + case IRDB_SDK::itFunc: + { + assert(tMap.count(tid) == 0); + + fn = new FuncType_t(tid, name); + types.insert(fn); + tMap[tid] = fn; + assert(tMap[ref1]); // return type + assert(tMap[ref2]); // argument type (which is an aggregate) + fn->setReturnType(tMap[ref1]); + AggregateType_t *args = dynamic_cast<AggregateType_t*>(tMap[ref2]); + assert(args); + fn->setArgumentsType(args); + break; + } + default: + cerr << "ReadTypesFromDB(): ERROR: pass4: unhandled type id = " << type << endl; + assert(0); // not yet handled + break; } - dbintr->MoveToNextRow(); + dbintr->moveToNextRow(); } // end pass4 return tMap; @@ -1283,34 +1265,34 @@ void FileIR_t::ReadAllICFSFromDB(std::map<db_id_t,Instruction_t*> &addr2instMap, // retrieve all sets std::string q= "select * from " + fileptr->icfs_table_name + " ; "; - dbintr->IssueQuery(q); + dbintr->issueQuery(q); - while(!dbintr->IsDone()) + while(!dbintr->isDone()) { - db_id_t icfs_id = atoi(dbintr->GetResultColumn("icfs_id").c_str()); - string statusString=dbintr->GetResultColumn("icfs_status"); + db_id_t icfs_id = atoi(dbintr->getResultColumn("icfs_id").c_str()); + string statusString=dbintr->getResultColumn("icfs_status"); ICFS_t* icfs = new ICFS_t(icfs_id, statusString); GetAllICFS().insert(icfs); icfsMap[icfs_id] = icfs; - dbintr->MoveToNextRow(); + dbintr->moveToNextRow(); } ICFSSet_t all_icfs = GetAllICFS(); // for each set, populate its members - for (ICFSSet_t::iterator it = all_icfs.begin(); it != all_icfs.end(); ++it) + for (auto it = all_icfs.begin(); it != all_icfs.end(); ++it) { char query2[2048]; - ICFS_t *icfs = *it; + auto icfs = dynamic_cast<ICFS_t*>(*it); assert(icfs); - int icfsid = icfs->GetBaseID(); + int icfsid = icfs->getBaseID(); sprintf(query2,"select * from %s WHERE icfs_id = %d;", fileptr->icfs_map_table_name.c_str(), icfsid); - dbintr->IssueQuery(query2); - while(!dbintr->IsDone()) + dbintr->issueQuery(query2); + while(!dbintr->isDone()) { - db_id_t address_id = atoi(dbintr->GetResultColumn("address_id").c_str()); + db_id_t address_id = atoi(dbintr->getResultColumn("address_id").c_str()); Instruction_t* instruction = addr2instMap[address_id]; if (instruction) { @@ -1322,15 +1304,15 @@ void FileIR_t::ReadAllICFSFromDB(std::map<db_id_t,Instruction_t*> &addr2instMap, // if we encounter an unresolved address, we should mark the ICFS // as unresolved - dbintr->MoveToNextRow(); + dbintr->moveToNextRow(); } } // backpatch all unresolved instruction -> ICFS std::map<Instruction_t*, db_id_t>::iterator uit; - for (std::map<Instruction_t*, db_id_t>::iterator uit = unresolvedICFS.begin(); uit != unresolvedICFS.end(); ++uit) + for (auto uit = unresolvedICFS.begin(); uit != unresolvedICFS.end(); ++uit) { - Instruction_t* unresolved = uit->first; + auto unresolved = dynamic_cast<Instruction_t*>(uit->first); db_id_t icfs_id = uit->second; assert(unresolved); @@ -1338,7 +1320,7 @@ void FileIR_t::ReadAllICFSFromDB(std::map<db_id_t,Instruction_t*> &addr2instMap, ICFS_t *icfs = icfsMap[icfs_id]; assert(icfs); - unresolved->SetIBTargets(icfs); + unresolved->setIBTargets(icfs); } } @@ -1347,7 +1329,7 @@ void FileIR_t::GarbageCollectICFS(ostream* verbose_logging) auto used_icfs= ICFSSet_t(); // get the IBTarget of each instruction into used_icfs transform( ALLOF(insns), inserter(used_icfs, begin(used_icfs)), - [](const Instruction_t* insn) -> ICFS_t* { return insn->GetIBTargets(); } + [](const IRDB_SDK::Instruction_t* insn) -> IRDB_SDK::ICFS_t* { return insn->getIBTargets(); } ); // we likely inserted null into the set, which we just will remove as a special ase. used_icfs.erase(nullptr); @@ -1358,18 +1340,17 @@ void FileIR_t::GarbageCollectICFS(ostream* verbose_logging) void FileIR_t::DedupICFS(ostream *verbose_logging) { - std::set<ICFS_t> unique_icfs; + std::set<InstructionSet_t> unique_icfs; - ICFSSet_t& all_icfs=this->GetAllICFS(); + auto& all_icfs=this->GetAllICFS(); // detect duplicate icfs ICFSSet_t duplicates; - std::pair<std::set<ICFS_t>::iterator,bool> ret; - for(ICFSSet_t::iterator it=all_icfs.begin(); it!=all_icfs.end(); ++it) + for(auto it=all_icfs.begin(); it!=all_icfs.end(); ++it) { - ICFS_t* p=*it; + auto p=dynamic_cast<ICFS_t*>(*it); assert(p); - ret = unique_icfs.insert( *p ); + auto ret = unique_icfs.insert( *p ); if (!ret.second) { duplicates.insert(p); } @@ -1382,40 +1363,40 @@ void FileIR_t::DedupICFS(ostream *verbose_logging) } // remove duplicate icfs - for(ICFSSet_t::const_iterator it=duplicates.begin(); it!=duplicates.end(); ++it) + for(auto it=duplicates.begin(); it!=duplicates.end(); ++it) { - ICFS_t* icfs = *it; + auto icfs=*it; all_icfs.erase(icfs); } // build duplicate icfs map - std::map<ICFS_t*, ICFS_t*> duplicate_map; - for(ICFSSet_t::const_iterator it=duplicates.begin(); it!=duplicates.end(); ++it) + std::map<IRDB_SDK::ICFS_t*, IRDB_SDK::ICFS_t*> duplicate_map; + for(auto it=duplicates.begin(); it!=duplicates.end(); ++it) { - ICFS_t* icfs = *it; - for(ICFSSet_t::iterator it=all_icfs.begin(); it!=all_icfs.end(); ++it) + auto icfs = *it; + for(auto it=all_icfs.begin(); it!=all_icfs.end(); ++it) { - ICFS_t* t = *it; + auto t = *it; assert(t); if (*icfs == *t) { duplicate_map[icfs] = t; - *verbose_logging << "FileIR_t::DedupICFS(): remap: icfs id " << icfs->GetBaseID() << " --> icsf id " << t->GetBaseID() << endl; + *verbose_logging << "FileIR_t::DedupICFS(): remap: icfs id " << icfs->getBaseID() << " --> icsf id " << t->getBaseID() << endl; break; } } } // reassign ibtargets - for(set<Instruction_t*>::const_iterator it=this->GetInstructions().begin(); + for(auto it=this->GetInstructions().begin(); it!=this->GetInstructions().end(); ++it) { - Instruction_t* instr=*it; - if(instr->GetIBTargets() && duplicate_map[instr->GetIBTargets()]) + auto instr=*it; + if(instr->getIBTargets() && duplicate_map[instr->getIBTargets()]) { - instr->SetIBTargets(duplicate_map[instr->GetIBTargets()]); + instr->setIBTargets(duplicate_map[instr->getIBTargets()]); } } } @@ -1448,12 +1429,12 @@ std::map<db_id_t,DataScoop_t*> FileIR_t::ReadScoopsFromDB // // read part 2 of the scoops. //std::string q= "select * from " + fileptr->scoop_table_name + "_part2 ; "; - //dbintr->IssueQuery(q); - //while(!dbintr->IsDone()) + //dbintr->issueQuery(q); + //while(!dbintr->isDone()) //{ - // db_id_t sid=atoi(dbintr->GetResultColumn("scoop_id").c_str()); - // bonus_contents[sid]=dbintr->GetResultColumn("data"); - // dbintr->MoveToNextRow(); + // db_id_t sid=atoi(dbintr->getResultColumn("scoop_id").c_str()); + // bonus_contents[sid]=dbintr->getResultColumn("data"); + // dbintr->moveToNextRow(); //} @@ -1469,78 +1450,75 @@ std::map<db_id_t,DataScoop_t*> FileIR_t::ReadScoopsFromDB // data bytea -- the actual bytes of the scoop string q= "select scoop_id,name,type_id,start_address_id,end_address_id,permissions,relro from " + fileptr->scoop_table_name + " ; "; - dbintr->IssueQuery(q); - while(!dbintr->IsDone()) + dbintr->issueQuery(q); + while(!dbintr->isDone()) { - db_id_t sid=atoi(dbintr->GetResultColumn("scoop_id").c_str()); - std::string name=dbintr->GetResultColumn("name"); - db_id_t type_id=atoi(dbintr->GetResultColumn("type_id").c_str()); + db_id_t sid=atoi(dbintr->getResultColumn("scoop_id").c_str()); + std::string name=dbintr->getResultColumn("name"); + db_id_t type_id=atoi(dbintr->getResultColumn("type_id").c_str()); Type_t *type=typeMap[type_id]; - db_id_t start_id=atoi(dbintr->GetResultColumn("start_address_id").c_str()); + db_id_t start_id=atoi(dbintr->getResultColumn("start_address_id").c_str()); AddressID_t* start_addr=addrMap[start_id]; - db_id_t end_id=atoi(dbintr->GetResultColumn("end_address_id").c_str()); + db_id_t end_id=atoi(dbintr->getResultColumn("end_address_id").c_str()); AddressID_t* end_addr=addrMap[end_id]; - int permissions=atoi(dbintr->GetResultColumn("permissions").c_str()); - bool is_relro=atoi(dbintr->GetResultColumn("relro").c_str()) != 0 ; + int permissions=atoi(dbintr->getResultColumn("permissions").c_str()); + bool is_relro=atoi(dbintr->getResultColumn("relro").c_str()) != 0 ; DataScoop_t* newscoop=new DataScoop_t(sid,name,start_addr,end_addr,type,permissions,is_relro,""); assert(newscoop); GetDataScoops().insert(newscoop); - dbintr->MoveToNextRow(); + dbintr->moveToNextRow(); scoopMap[sid]=newscoop; } - for(DataScoopSet_t::iterator it=GetDataScoops().begin(); it!=GetDataScoops().end(); ++it) + for(auto it=getDataScoops().begin(); it!=getDataScoops().end(); ++it) { - DataScoop_t* scoop=*it; + DataScoop_t* scoop=dynamic_cast<DataScoop_t*>(*it); - q= "select length(data) from " + fileptr->scoop_table_name + " where scoop_id='"+to_string(scoop->GetBaseID())+"'; "; - dbintr->IssueQuery(q); - if(!dbintr->IsDone()) + q= "select length(data) from " + fileptr->scoop_table_name + " where scoop_id='"+to_string(scoop->getBaseID())+"'; "; + dbintr->issueQuery(q); + if(!dbintr->isDone()) { - int data_len=atoi(dbintr->GetResultColumn("length").c_str()); + int data_len=atoi(dbintr->getResultColumn("length").c_str()); for(int i=0;i<data_len;i+=SCOOP_CHUNK_SIZE) { string start_pos=to_string(i); string len_to_get=to_string(SCOOP_CHUNK_SIZE); string field="substr(data,"+start_pos+","+len_to_get+")"; - q= "select "+field+" from " + fileptr->scoop_table_name + " where scoop_id='"+to_string(scoop->GetBaseID())+"'; "; - dbintr->IssueQuery(q); + q= "select "+field+" from " + fileptr->scoop_table_name + " where scoop_id='"+to_string(scoop->getBaseID())+"'; "; + dbintr->issueQuery(q); - scoop->GetContents()+=dbintr->GetResultColumn("substr"); + scoop->getContents()+=dbintr->getResultColumn("substr"); } } // read part 2 from db - q= "select length(data) from " + fileptr->scoop_table_name + "_part2 where scoop_id='"+to_string(scoop->GetBaseID())+"'; "; - dbintr->IssueQuery(q); - if(!dbintr->IsDone()) + q= "select length(data) from " + fileptr->scoop_table_name + "_part2 where scoop_id='"+to_string(scoop->getBaseID())+"'; "; + dbintr->issueQuery(q); + if(!dbintr->isDone()) { - int part2_len=atoi(dbintr->GetResultColumn("length").c_str()); + int part2_len=atoi(dbintr->getResultColumn("length").c_str()); for(int i=0;i<part2_len; i+=SCOOP_CHUNK_SIZE) { string start_pos=to_string(i); string len_to_get=to_string(SCOOP_CHUNK_SIZE); string field="substr(data,"+start_pos+","+len_to_get+")"; - q= "select "+field+" from " + fileptr->scoop_table_name + "_part2 where scoop_id='"+to_string(scoop->GetBaseID())+"'; "; - dbintr->IssueQuery(q); + q= "select "+field+" from " + fileptr->scoop_table_name + "_part2 where scoop_id='"+to_string(scoop->getBaseID())+"'; "; + dbintr->issueQuery(q); - scoop->GetContents()+=dbintr->GetResultColumn("substr"); + scoop->getContents()+=dbintr->getResultColumn("substr"); } } } - for( DataScoopSet_t::const_iterator it=GetDataScoops().begin(); - it!=GetDataScoops().end(); - ++it - ) + for(auto s : getDataScoops()) { - DataScoop_t* scoop=*it; - assert(scoop->GetContents().size() == scoop->GetSize()); + auto scoop=dynamic_cast<DataScoop_t*>(s); + assert(scoop->getContents().size() == scoop->getSize()); } @@ -1549,37 +1527,42 @@ std::map<db_id_t,DataScoop_t*> FileIR_t::ReadScoopsFromDB // Lookup a scoop by address -DataScoop_t* FileIR_t::FindScoop(const libIRDB::virtual_offset_t &addr) +IRDB_SDK::DataScoop_t* FileIR_t::findScoop(const IRDB_SDK::VirtualOffset_t &addr) const { - for(DataScoopSet_t::iterator it=scoops.begin(); it!=scoops.end(); ++it) + for(auto it=scoops.begin(); it!=scoops.end(); ++it) { + auto s=dynamic_cast<DataScoop_t*>(*it); // we're doing <= in both comparisons here intentionally. // scoop addresses are the start/end address are inclusive // so that start+size-1 == end. - if( (*it)->GetStart()->GetVirtualOffset() <= addr && addr <= (*it)->GetEnd()->GetVirtualOffset() ) + if( s->getStart()->getVirtualOffset() <= addr && addr <= s->getEnd()->getVirtualOffset() ) return *it; } return NULL; } -void FileIR_t::SplitScoop( - DataScoop_t *tosplit, - const libIRDB::virtual_offset_t &addr, +void FileIR_t::splitScoop( + IRDB_SDK::DataScoop_t *p_tosplit, + const IRDB_SDK::VirtualOffset_t &addr, size_t size, - DataScoop_t* &before, - DataScoop_t* &containing, - DataScoop_t* &after, - db_id_t *max_id_ptr /* in and out param */ + IRDB_SDK::DataScoop_t* &p_before, + IRDB_SDK::DataScoop_t* &p_containing, + IRDB_SDK::DataScoop_t* &p_after, + IRDB_SDK::DatabaseID_t *max_id_ptr /* in and out param */ ) { + auto tosplit=dynamic_cast<DataScoop_t*>(p_tosplit); + auto before=dynamic_cast<DataScoop_t*>(p_before); + auto containing=dynamic_cast<DataScoop_t*>(p_containing); + auto after=dynamic_cast<DataScoop_t*>(p_after); // init output params. before=containing=after=NULL; - if(tosplit->GetStart()->GetVirtualOffset() == addr && - tosplit->GetEnd()->GetVirtualOffset() == addr+size-1) + if(tosplit->getStart()->getVirtualOffset() == addr && + tosplit->getEnd()->getVirtualOffset() == addr+size-1) { // no split necessary containing=tosplit; @@ -1588,7 +1571,7 @@ void FileIR_t::SplitScoop( auto calcd_max_id=db_id_t(0); if(max_id_ptr==NULL) - calcd_max_id = GetMaxBaseID(); + calcd_max_id = getMaxBaseID(); auto &max_id = max_id_ptr == NULL ? calcd_max_id : *max_id_ptr ; @@ -1602,8 +1585,8 @@ void FileIR_t::SplitScoop( max_id=rounded_max + multiple; // and skip forward so we're passed the highest. - const bool needs_before = addr!=tosplit->GetStart()->GetVirtualOffset(); - const bool needs_after = addr+size-1 != tosplit->GetEnd()->GetVirtualOffset(); + const bool needs_before = addr!=tosplit->getStart()->getVirtualOffset(); + const bool needs_after = addr+size-1 != tosplit->getEnd()->getVirtualOffset(); if(needs_before) @@ -1612,27 +1595,27 @@ void FileIR_t::SplitScoop( // const AddressID_t* before_start=NULL; const auto before_start=new AddressID_t; - before_start->SetBaseID(max_id++); - before_start->SetFileID(tosplit->GetStart()->GetFileID()); - before_start->SetVirtualOffset(tosplit->GetStart()->GetVirtualOffset()); + before_start->setBaseID(max_id++); + before_start->setFileID(tosplit->getStart()->getFileID()); + before_start->setVirtualOffset(tosplit->getStart()->getVirtualOffset()); // const AddressID_t* before_end=new AddressID_t; const auto before_end=new AddressID_t; - before_end->SetBaseID(max_id++); - before_end->SetFileID(tosplit->GetStart()->GetFileID()); - before_end->SetVirtualOffset(addr-1); + before_end->setBaseID(max_id++); + before_end->setFileID(tosplit->getStart()->getFileID()); + before_end->setVirtualOffset(addr-1); before=new DataScoop_t; - before->SetBaseID(max_id++); - before->SetName(tosplit->GetName()+"3"); - before->SetStart(before_start); - before->SetEnd(before_end); + before->setBaseID(max_id++); + before->setName(tosplit->getName()+"3"); + before->setStart(before_start); + before->setEnd(before_end); before->setRawPerms(tosplit->getRawPerms()); - before->GetContents().resize(before_end->GetVirtualOffset() - before_start->GetVirtualOffset()+1); + before->getContents().resize(before_end->getVirtualOffset() - before_start->getVirtualOffset()+1); // copy bytes - for(virtual_offset_t i=before_start->GetVirtualOffset() ; i <= before_end->GetVirtualOffset(); i++) - before->GetContents()[i-before_start->GetVirtualOffset()] = tosplit->GetContents()[i-tosplit->GetStart()->GetVirtualOffset()]; + for(virtual_offset_t i=before_start->getVirtualOffset() ; i <= before_end->getVirtualOffset(); i++) + before->getContents()[i-before_start->getVirtualOffset()] = tosplit->getContents()[i-tosplit->getStart()->getVirtualOffset()]; GetAddresses().insert(before_start); @@ -1643,26 +1626,26 @@ void FileIR_t::SplitScoop( // setup containing // AddressID_t* containing_start=new AddressID_t; const auto containing_start=new AddressID_t; - containing_start->SetBaseID(max_id++); - containing_start->SetFileID(tosplit->GetStart()->GetFileID()); - containing_start->SetVirtualOffset(addr); + containing_start->setBaseID(max_id++); + containing_start->setFileID(tosplit->getStart()->getFileID()); + containing_start->setVirtualOffset(addr); //AddressID_t* containing_end=new AddressID_t; const auto containing_end=new AddressID_t; - containing_end->SetBaseID(max_id++); - containing_end->SetFileID(tosplit->GetStart()->GetFileID()); - containing_end->SetVirtualOffset(addr+size-1); + containing_end->setBaseID(max_id++); + containing_end->setFileID(tosplit->getStart()->getFileID()); + containing_end->setVirtualOffset(addr+size-1); containing=new DataScoop_t; - containing->SetBaseID(max_id++); - containing->SetName(tosplit->GetName()+"3"); - containing->SetStart(containing_start); - containing->SetEnd(containing_end); + containing->setBaseID(max_id++); + containing->setName(tosplit->getName()+"3"); + containing->setStart(containing_start); + containing->setEnd(containing_end); containing->setRawPerms(tosplit->getRawPerms()); - containing->GetContents().resize(containing_end->GetVirtualOffset() - containing_start->GetVirtualOffset()+1); + containing->getContents().resize(containing_end->getVirtualOffset() - containing_start->getVirtualOffset()+1); // copy bytes - for(virtual_offset_t i=containing_start->GetVirtualOffset() ; i <= containing_end->GetVirtualOffset(); i++) - containing->GetContents()[i-containing_start->GetVirtualOffset()] = tosplit->GetContents()[i-tosplit->GetStart()->GetVirtualOffset()]; + for(virtual_offset_t i=containing_start->getVirtualOffset() ; i <= containing_end->getVirtualOffset(); i++) + containing->getContents()[i-containing_start->getVirtualOffset()] = tosplit->getContents()[i-tosplit->getStart()->getVirtualOffset()]; GetAddresses().insert(containing_start); GetAddresses().insert(containing_end); @@ -1674,26 +1657,26 @@ void FileIR_t::SplitScoop( // setup after // AddressID_t* after_start=new AddressID_t; const auto after_start=new AddressID_t; - after_start->SetBaseID(max_id++); - after_start->SetFileID(tosplit->GetStart()->GetFileID()); - after_start->SetVirtualOffset(addr+size); + after_start->setBaseID(max_id++); + after_start->setFileID(tosplit->getStart()->getFileID()); + after_start->setVirtualOffset(addr+size); // AddressID_t* after_end=new AddressID_t; const auto after_end=new AddressID_t; - after_end->SetBaseID(max_id++); - after_end->SetFileID(tosplit->GetStart()->GetFileID()); - after_end->SetVirtualOffset(tosplit->GetEnd()->GetVirtualOffset()); + after_end->setBaseID(max_id++); + after_end->setFileID(tosplit->getStart()->getFileID()); + after_end->setVirtualOffset(tosplit->getEnd()->getVirtualOffset()); after=new DataScoop_t; - after->SetBaseID(max_id++); - after->SetName(tosplit->GetName()+"3"); - after->SetStart(after_start); - after->SetEnd(after_end); + after->setBaseID(max_id++); + after->setName(tosplit->getName()+"3"); + after->setStart(after_start); + after->setEnd(after_end); after->setRawPerms(tosplit->getRawPerms()); - after->GetContents().resize(after_end->GetVirtualOffset() - after_start->GetVirtualOffset()+1); + after->getContents().resize(after_end->getVirtualOffset() - after_start->getVirtualOffset()+1); // copy bytes - for(virtual_offset_t i=after_start->GetVirtualOffset() ; i <= after_end->GetVirtualOffset(); i++) - after->GetContents()[i-after_start->GetVirtualOffset()] = tosplit->GetContents()[i-tosplit->GetStart()->GetVirtualOffset()]; + for(virtual_offset_t i=after_start->getVirtualOffset() ; i <= after_end->getVirtualOffset(); i++) + after->getContents()[i-after_start->getVirtualOffset()] = tosplit->getContents()[i-tosplit->getStart()->getVirtualOffset()]; GetAddresses().insert(after_start); GetAddresses().insert(after_end); @@ -1706,23 +1689,23 @@ void FileIR_t::SplitScoop( // adjust the reloc's offset accordingly before inserting into the correct scoop's reloc set. while(!tosplit->GetRelocations().empty()) { - Relocation_t* reloc=*(tosplit->GetRelocations().begin()); - tosplit->GetRelocations().erase(tosplit->GetRelocations().begin()); + auto reloc=dynamic_cast<Relocation_t*>(*(tosplit->getRelocations().begin())); + tosplit->GetRelocations().erase(tosplit->getRelocations().begin()); - virtual_offset_t reloc_start=reloc->GetOffset()+tosplit->GetStart()->GetVirtualOffset(); + virtual_offset_t reloc_start=reloc->getOffset()+tosplit->getStart()->getVirtualOffset(); - if(reloc_start < containing->GetStart()->GetVirtualOffset() ) + if(reloc_start < containing->getStart()->getVirtualOffset() ) { before->GetRelocations().insert(reloc); } - else if(reloc_start > containing->GetEnd()->GetVirtualOffset() ) + else if(reloc_start > containing->getEnd()->getVirtualOffset() ) { - reloc->SetOffset(reloc_start-after->GetStart()->GetVirtualOffset()); + reloc->setOffset(reloc_start-after->getStart()->getVirtualOffset()); after->GetRelocations().insert(reloc); } else { - reloc->SetOffset(reloc_start-containing->GetStart()->GetVirtualOffset()); + reloc->setOffset(reloc_start-containing->getStart()->getVirtualOffset()); containing->GetRelocations().insert(reloc); } @@ -1731,41 +1714,177 @@ void FileIR_t::SplitScoop( /* look at each relocation in the IR */ for(auto & r : GetRelocations()) { - if(r->GetWRT()==tosplit) + if(r->getWRT()==tosplit) { - const auto &addend=r->GetAddend(); - const auto containing_start_offset=(containing -> GetStart()->GetVirtualOffset() - - tosplit->GetStart()->GetVirtualOffset()); - const auto containing_end_offset=containing_start_offset+containing->GetSize(); - if(needs_before && addend<before->GetSize()) + const auto &addend=r->getAddend(); + const auto containing_start_offset=(containing -> getStart()->getVirtualOffset() - + tosplit->getStart()->getVirtualOffset()); + const auto containing_end_offset=containing_start_offset+containing->getSize(); + if(needs_before && addend<before->getSize()) { - r->SetWRT(before); + r->setWRT(before); } else if( addend < containing_end_offset) { - r->SetWRT(containing); - r->SetAddend(addend-containing_start_offset); + r->setWRT(containing); + r->setAddend(addend-containing_start_offset); } else { assert(needs_after); - const auto after_start_offset=(after -> GetStart()->GetVirtualOffset() - - tosplit->GetStart()->GetVirtualOffset()); - r->SetWRT(after); - r->SetAddend(addend-after_start_offset); + const auto after_start_offset=(after -> getStart()->getVirtualOffset() - + tosplit->getStart()->getVirtualOffset()); + r->setWRT(after); + r->setAddend(addend-after_start_offset); } } } - GetAddresses().erase(tosplit->GetStart()); - GetAddresses().erase(tosplit->GetEnd()); + GetAddresses().erase(tosplit->getStart()); + GetAddresses().erase(tosplit->getEnd()); GetDataScoops().erase(tosplit); - delete tosplit->GetStart(); - delete tosplit->GetEnd(); + delete tosplit->getStart(); + delete tosplit->getEnd(); delete tosplit; return; } + +IRDB_SDK::EhCallSite_t* FileIR_t::addEhCallSite_t(IRDB_SDK::Instruction_t* for_insn, const uint64_t enc, IRDB_SDK::Instruction_t* lp) +{ + auto new_ehcs = new libIRDB::EhCallSite_t(BaseObj_t::NOT_IN_DATABASE, enc, lp); + GetAllEhCallSites().insert(new_ehcs); + for_insn->setEhCallSite(new_ehcs); + return new_ehcs; + +} + +IRDB_SDK::Relocation_t* FileIR_t::addNewRelocation( + IRDB_SDK::BaseObj_t* p_from_obj, + int32_t p_offset, + string _type, + IRDB_SDK::BaseObj_t* p_wrt_obj, + int32_t p_addend) +{ + const auto from_obj=dynamic_cast<libIRDB::BaseObj_t*>(p_from_obj); + auto newreloc=new libIRDB::Relocation_t(BaseObj_t::NOT_IN_DATABASE, p_offset, "type_table_entry", p_wrt_obj, p_addend); + from_obj->GetRelocations().insert(newreloc); + GetRelocations().insert(newreloc); + + return newreloc; +} + +EhProgram_t* FileIR_t::addEhProgram( + IRDB_SDK::Instruction_t* insn, + const uint64_t caf, + const int64_t daf, + const uint8_t rr, + const uint8_t p_ptrsize, + const EhProgramListing_t& p_cie_program, + const EhProgramListing_t& p_fde_program) +{ + auto newehpgm=new EhProgram_t(BaseObj_t::NOT_IN_DATABASE, caf,daf,rr,p_ptrsize, p_cie_program, p_fde_program); + assert(newehpgm); + GetAllEhPrograms().insert(newehpgm); + if(insn) + insn->setEhProgram(newehpgm); + return newehpgm; +} + + + +void FileIR_t::removeScoop(IRDB_SDK::DataScoop_t* s) +{ + auto remove_reloc=[&](IRDB_SDK::Relocation_t* r) -> void + { + GetRelocations().erase(r); + delete r; + }; + + auto remove_address=[&](IRDB_SDK::AddressID_t* a) -> void + { + GetAddresses().erase(a); + for(auto &r : a->getRelocations()) remove_reloc(r); + for(auto &r : getRelocations()) assert(r->getWRT() != a); + delete a; + }; + + auto remove_scoop=[&] (IRDB_SDK::DataScoop_t* s) -> void + { + if(s==NULL) + return; + GetDataScoops().erase(s); + remove_address(s->getStart()); + remove_address(s->getEnd()); + for(auto &r : s->getRelocations()) remove_reloc(r); + for(auto &r : GetRelocations()) assert(r->getWRT() != s); + delete s; + }; + + remove_scoop(s); +} + +IRDB_SDK::AddressID_t* FileIR_t::addNewAddress(const IRDB_SDK::DatabaseID_t& myfileID, const IRDB_SDK::VirtualOffset_t& voff) +{ + auto newaddr = new libIRDB::AddressID_t(BaseObj_t::NOT_IN_DATABASE, myfileID, voff); + GetAddresses().insert(newaddr); + return newaddr; +} + + +IRDB_SDK::ICFS_t* FileIR_t::addNewICFS( + IRDB_SDK::Instruction_t* insn, + const IRDB_SDK::InstructionSet_t& targets, + const IRDB_SDK::ICFSAnalysisStatus_t& status) +{ + auto newicfs=new libIRDB::ICFS_t(BaseObj_t::NOT_IN_DATABASE, status); + newicfs->setTargets(targets); + if(insn) + insn->setIBTargets(newicfs); + GetAllICFS().insert(newicfs); + return newicfs; +} + +IRDB_SDK::Instruction_t* FileIR_t::addNewInstruction( + IRDB_SDK::AddressID_t* addr, + IRDB_SDK::Function_t* func, + const string& bits, + const string& comment, + IRDB_SDK::AddressID_t* indTarg) +{ + auto irdb_func = dynamic_cast<libIRDB::Function_t* >(func); + auto irdb_addr = dynamic_cast<libIRDB::AddressID_t*>(addr); + auto irdb_indTarg = dynamic_cast<libIRDB::AddressID_t*>(indTarg); + + auto newinsn=new libIRDB::Instruction_t(BaseObj_t::NOT_IN_DATABASE, irdb_addr, irdb_func, BaseObj_t::NOT_IN_DATABASE, bits, "", comment, irdb_indTarg, BaseObj_t::NOT_IN_DATABASE); + + GetInstructions().insert(newinsn); + + if(irdb_func) + irdb_func->GetInstructions().insert(newinsn); + return newinsn; +} + +IRDB_SDK::DataScoop_t* FileIR_t::addNewDataScoop( + const string& p_name, + IRDB_SDK::AddressID_t* p_start, + IRDB_SDK::AddressID_t* p_end, + IRDB_SDK::Type_t* p_type, + uint8_t p_permissions, + bool p_is_relro, + const string& p_contents, + IRDB_SDK::DatabaseID_t id) +{ + auto irdb_start = dynamic_cast<libIRDB::AddressID_t*>(p_start); + auto irdb_end = dynamic_cast<libIRDB::AddressID_t*>(p_end); + auto irdb_type = dynamic_cast<libIRDB::Type_t*> (p_type); + + auto newscoop=new libIRDB::DataScoop_t(id, p_name,irdb_start,irdb_end,irdb_type,p_permissions, p_is_relro, p_contents); + GetDataScoops().insert(newscoop); + return newscoop; +} + + diff --git a/libIRDB/src/core/function.cpp b/libIRDB/src/core/function.cpp index 44e1c5c5b..f6cd4e25b 100644 --- a/libIRDB/src/core/function.cpp +++ b/libIRDB/src/core/function.cpp @@ -25,16 +25,18 @@ using namespace libIRDB; using namespace std; -Function_t::Function_t(db_id_t id, std::string myname, int size, int oa_size, bool useFP, bool isSafe, FuncType_t *fn_type, Instruction_t* entry) - : BaseObj_t(NULL), entry_point(entry) +Function_t::Function_t(db_id_t id, std::string myname, int size, int oa_size, bool useFP, bool isSafe, IRDB_SDK::FuncType_t *fn_type, IRDB_SDK::Instruction_t* entry) + : BaseObj_t(NULL), entry_point(dynamic_cast<Instruction_t*>(entry)) { - SetBaseID(id); + setBaseID(id); name=myname; stack_frame_size=size; out_args_region_size=oa_size; - use_fp = useFP; - SetSafe(isSafe); - function_type = fn_type; + use_fp = useFP; + setSafe(isSafe); + function_type = dynamic_cast<FuncType_t*>(fn_type); + if(entry) assert(entry_point); + if(fn_type) assert(function_type); } string Function_t::WriteToDB(File_t *fid, db_id_t newid) @@ -43,19 +45,19 @@ string Function_t::WriteToDB(File_t *fid, db_id_t newid) int entryid=NOT_IN_DATABASE; if(entry_point) - entryid=entry_point->GetBaseID(); + entryid=entry_point->getBaseID(); - if(GetBaseID()==NOT_IN_DATABASE) - SetBaseID(newid); + if(getBaseID()==NOT_IN_DATABASE) + setBaseID(newid); int function_type_id = NOT_IN_DATABASE; - if (GetType()) - function_type_id = GetType()->GetBaseID(); + if (getType()) + function_type_id = getType()->getBaseID(); string q=string("insert into ")+fid->function_table_name + string(" (function_id, entry_point_id, name, stack_frame_size, out_args_region_size, use_frame_pointer, is_safe, type_id, doip_id) ")+ string(" VALUES (") + - string("'") + to_string(GetBaseID()) + string("', ") + + string("'") + to_string(getBaseID()) + string("', ") + string("'") + to_string(entryid) + string("', ") + string("'") + name + string("', ") + string("'") + to_string(stack_frame_size) + string("', ") + @@ -63,17 +65,30 @@ string Function_t::WriteToDB(File_t *fid, db_id_t newid) string("'") + to_string(use_fp) + string("', ") + string("'") + to_string(is_safe) + string("', ") + string("'") + to_string(function_type_id) + string("', ") + - string("'") + to_string(GetDoipID()) + string("') ; ") ; + string("'") + to_string(getDoipID()) + string("') ; ") ; return q; } -int Function_t::GetNumArguments() const +int Function_t::getNumArguments() const { if (!function_type) return -1; - AggregateType_t *argtype = function_type->GetArgumentsType(); + auto argtype = function_type->getArgumentsType(); if (argtype) - return argtype->GetNumAggregatedTypes(); + return argtype->getNumAggregatedTypes(); else return -1; } + +void Function_t::setType(IRDB_SDK::FuncType_t *t) +{ + function_type = dynamic_cast<FuncType_t*>(t); + if(t) + assert(function_type); +} + +IRDB_SDK::FuncType_t* Function_t::getType() const +{ + return function_type; +} + diff --git a/libIRDB/src/core/generate_spri.cpp b/libIRDB/src/core/generate_spri.cpp index c70a73517..07aab3a7f 100644 --- a/libIRDB/src/core/generate_spri.cpp +++ b/libIRDB/src/core/generate_spri.cpp @@ -28,16 +28,17 @@ #include <map> #include <string.h> #include <assert.h> -//#include <bea_deprecated.hpp> #undef EIP using namespace libIRDB; using namespace std; +#if 0 + // forward decls for this file static string qualified_addressify(FileIR_t* fileIRp, Instruction_t *insn); -static string labelfy(Instruction_t* insn); +static string labelfy(IRDB_SDK::Instruction_t* insn); // @@ -82,7 +83,7 @@ static bool needs_short_branch_rewrite(Instruction_t* newinsn, const DecodedInst /* 64-bit has more needs than this */ // if(disasm.Archi==32) - if(FileIR_t::GetArchitectureBitWidth()==32) + if(FileIR_t::getArchitectureBitWidth()==32) return false; // if(disasm.Instruction.BranchType==0) /* non-branches, jumps, calls and returns don't need this rewrite */ @@ -99,9 +100,9 @@ static bool needs_short_branch_rewrite(Instruction_t* newinsn, const DecodedInst return false; /* all other branches (on x86-64) need further checking */ - if(!newinsn->GetTarget()) /* no specified target, no need to modify it */ + if(!newinsn->getTarget()) /* no specified target, no need to modify it */ return false; - string new_target=labelfy(newinsn->GetTarget()); + string new_target=labelfy(newinsn->getTarget()); if (new_target.c_str()[0]=='0') /* if we're jumping back to the base instruction */ return true; return false; @@ -111,8 +112,9 @@ static bool needs_short_branch_rewrite(Instruction_t* newinsn, const DecodedInst // // create a label for the given instruction // -static string qualified_labelfy(FileIR_t* fileIRp, Instruction_t* insn) +static string qualified_labelfy(FileIR_t* fileIRp, IRDB_SDK::Instruction_t* p_insn) { + auto insn=dynamic_cast<Instruction_t*>(p_insn); if(!needs_spri_rule(insn, insnMap[insn])) return qualified_addressify(fileIRp, insn); @@ -124,13 +126,10 @@ static long long int label_offset=0; static void update_label_offset(FileIR_t *firp) { int max=0; - for(set<Instruction_t*>::iterator it=firp->GetInstructions().begin(); - it!=firp->GetInstructions().end(); - ++it) + for(auto insn : firp->GetInstructions()) { - Instruction_t *insn=*it; - if(insn->GetBaseID()>max) - max=insn->GetBaseID(); + if(insn->getBaseID()>max) + max=insn->getBaseID(); } label_offset+=max+1; } @@ -140,12 +139,14 @@ static long long int IDToSPRIID(int id) return id+label_offset; } -static string labelfy(Instruction_t* insn) +static string labelfy(IRDB_SDK::Instruction_t* p_insn) { + auto insn=dynamic_cast<Instruction_t*>(p_insn); + if(!needs_spri_rule(insn, insnMap[insn])) return addressify(insn); - return string("LI_") + to_string(IDToSPRIID(insn->GetBaseID())); + return string("LI_") + to_string(IDToSPRIID(insn->getBaseID())); } @@ -160,7 +161,7 @@ static string addressify(Instruction_t* insn) if(!old_insn) return labelfy(insn); - s<<"0x"<<std::hex<<old_insn->GetAddress()->GetVirtualOffset(); + s<<"0x"<<std::hex<<old_insn->getAddress()->getVirtualOffset(); return s.str(); @@ -185,7 +186,7 @@ static string URLToFile(string url) static string qualify(FileIR_t* fileIRp) { - return URLToFile(fileIRp->GetFile()->GetURL()) + "+" ; + return URLToFile(fileIRp->getFile()->GetURL()) + "+" ; } @@ -196,10 +197,10 @@ static string qualify_address(FileIR_t* fileIRp, int addr) return ss.str(); } -static string better_qualify_address(FileIR_t* fileIRp, AddressID_t* addr) +static string better_qualify_address(FileIR_t* fileIRp, IRDB_SDK::AddressID_t* addr) { - db_id_t fileID=addr->GetFileID(); - virtual_offset_t off=addr->GetVirtualOffset(); + db_id_t fileID=addr->getFileID(); + virtual_offset_t off=addr->getVirtualOffset(); /* in theory, we could have an address from any file.. * but this appears to be broken. NOT_IN_DATABASE means we're in the spri address space, @@ -253,7 +254,7 @@ static string getPostCallbackLabel(Instruction_t *newinsn) static string get_relocation_string(FileIR_t* fileIRp, ostream& fout, int offset, string type, Instruction_t* insn) { stringstream ss; - ss<<labelfy(insn)<<" rl " << offset << " " << type << " " << URLToFile(fileIRp->GetFile()->GetURL()) << endl; + ss<<labelfy(insn)<<" rl " << offset << " " << type << " " << URLToFile(fileIRp->getFile()->GetURL()) << endl; return ss.str(); } @@ -288,26 +289,26 @@ void emit_jump(FileIR_t* fileIRp, ostream& fout, const DecodedInstruction_t& dis string label=labelfy(newinsn); string complete_instr=disasm.getDisassembly(); - string address_string=disasm.getOperand(0).getString(); + string address_string=disasm.getOperand(0)->getString(); /* if we have a target instruction in the database */ - if(newinsn->GetTarget() || needs_short_branch_rewrite(newinsn,disasm)) + if(newinsn->getTarget() || needs_short_branch_rewrite(newinsn,disasm)) { /* change the target to be symbolic */ /* first get the new target */ string new_target; - if(newinsn->GetTarget()) - new_target=labelfy(newinsn->GetTarget()); + if(newinsn->getTarget()) + new_target=labelfy(newinsn->getTarget()); /* if this is a short branch, write this branch to jump to the next insn */ if(needs_short_branch_rewrite(newinsn,disasm)) { new_target=get_short_branch_label(newinsn); /* also get the real target if it's a short branch */ - if(newinsn->GetTarget()) - original_target=labelfy(newinsn->GetTarget()); + if(newinsn->getTarget()) + original_target=labelfy(newinsn->getTarget()); else original_target=address_string; } @@ -323,7 +324,7 @@ void emit_jump(FileIR_t* fileIRp, ostream& fout, const DecodedInstruction_t& dis //assert(disasm.Argument1.SegmentReg==0); // if(disasm.Archi==64) - if(FileIR_t::GetArchitectureBitWidth()==64) + if(FileIR_t::getArchitectureBitWidth()==64) { auto converted=convert_jump_for_64bit(newinsn,final, emit_later,new_target); (void)converted; // unused? @@ -388,7 +389,7 @@ this will never work again? else { // assert this is the "main" file and no relocation is necessary. - assert(strstr(fileIRp->GetFile()->GetURL().c_str(),"a.ncexe")!=0); + assert(strstr(fileIRp->getFile()->GetURL().c_str(),"a.ncexe")!=0); } } #endif @@ -410,43 +411,17 @@ static string emit_spri_instruction(FileIR_t* fileIRp, Instruction_t *newinsn, o /* Disassemble the instruction */ //int instr_len = Disassemble(newinsn,disasm); - const auto disasm=DecodedInstruction_t(newinsn); - - -// not needed after library fix. -#if 0 - /* if this instruction has a prefix, re-disassemble it showing the segment regs */ - if( - disasm.Prefix.FSPrefix || - disasm.Prefix.SSPrefix || - disasm.Prefix.GSPrefix || - disasm.Prefix.ESPrefix || - disasm.Prefix.CSPrefix || - disasm.Prefix.DSPrefix - ) - - { - memset(&disasm, 0, sizeof(DISASM)); - - disasm.Options = NasmSyntax + PrefixedNumeral + ShowSegmentRegs; - disasm.Archi = fileIRp->GetArchitectureBitWidth(); - disasm.EIP = (UIntPtr)newinsn->GetDataBits().c_str(); - disasm.VirtualAddr = old_insn ? old_insn->GetAddress()->GetVirtualOffset() : 0; - - /* Disassemble the instruction */ - int instr_len = Disasm(&disasm); - } -#endif - + const auto p_disasm=DecodedInstruction_t::factory(newinsn); + const auto &disasm=*p_disasm; string label=labelfy(newinsn); - string complete_instr=disasm.getDisassembly(); //string(disasm.CompleteInstr); - string address_string=disasm.getOperand(0).getString(); // string(disasm.Argument1.ArgMnemonic); + string complete_instr=disasm.getDisassembly(); + string address_string=disasm.getOperand(0)->getString(); /* Emit any callback functions */ - if (!newinsn->GetCallback().empty()) + if (!newinsn->getCallback().empty()) { - fout << "\t"+label+"\t () " << newinsn->GetCallback() << " # acts as a call <callback> insn" << endl; + fout << "\t"+label+"\t () " << newinsn->getCallback() << " # acts as a call <callback> insn" << endl; fout << "\t"+ getPostCallbackLabel(newinsn)+" ** "; } else @@ -470,7 +445,7 @@ static string emit_spri_instruction(FileIR_t* fileIRp, Instruction_t *newinsn, o //(disasm.Argument1.ArgType & CONSTANT_TYPE)!=0 // and has a constant argument type 1 disasm.isBranch() && !disasm.isReturn() && - disasm.getOperand(0).isConstant() + disasm.getOperand(0)->isConstant() ) { emit_jump(fileIRp, fout, disasm,newinsn,old_insn, original_target, emit_later); @@ -553,19 +528,20 @@ static string emit_spri_instruction(FileIR_t* fileIRp, Instruction_t *newinsn, o fout<<endl; } - for(set<Relocation_t*>::iterator it=newinsn->GetRelocations().begin(); it!=newinsn->GetRelocations().end(); ++it) + //for(set<Relocation_t*>::iterator it=newinsn->GetRelocations().begin(); it!=newinsn->GetRelocations().end(); ++it) + for(auto this_reloc : newinsn->getRelocations()) { - Relocation_t* this_reloc=*it; - emit_relocation(fileIRp, fout, this_reloc->GetOffset(),this_reloc->GetType(), newinsn); + //Relocation_t* this_reloc=*it; + emit_relocation(fileIRp, fout, this_reloc->getOffset(),this_reloc->getType(), newinsn); } - ICFS_t *IB_targets = newinsn->GetIBTargets(); + auto IB_targets = newinsn->getIBTargets(); if (NULL != IB_targets) { - if (IB_targets->IsComplete()) + if (IB_targets->isComplete()) { // Iterate through all IB targets and produce SPRI rules for IBTL (IB Target Limitation). - for (InstructionSet_t::iterator TargIter = IB_targets->begin(); TargIter != IB_targets->end(); ++TargIter) + for (auto TargIter = IB_targets->begin(); TargIter != IB_targets->end(); ++TargIter) { fout << "\t" << labelfy(newinsn) << " IL " << qualified_labelfy(fileIRp, *TargIter) << endl; } @@ -582,19 +558,19 @@ static string emit_spri_instruction(FileIR_t* fileIRp, Instruction_t *newinsn, o static bool needs_spri_rule(Instruction_t* newinsn,Instruction_t* oldinsn) { // check if this is an inserted instruction - if(newinsn->GetOriginalAddressID()==BaseObj_t::NOT_IN_DATABASE) + if(newinsn->getOriginalAddressID()==BaseObj_t::NOT_IN_DATABASE) return true; assert(oldinsn); - assert(newinsn->GetOriginalAddressID()==oldinsn->GetAddress()->GetBaseID()); + assert(newinsn->getOriginalAddressID()==oldinsn->getAddress()->getBaseID()); /* We moved the instruction to a new address*/ - if(newinsn->GetAddress()->GetVirtualOffset()!=oldinsn->GetAddress()->GetVirtualOffset()) + if(newinsn->getAddress()->getVirtualOffset()!=oldinsn->getAddress()->getVirtualOffset()) return true; /* We moved the instruction to a new file? */ - if(newinsn->GetAddress()->GetFileID()!=oldinsn->GetAddress()->GetFileID()) + if(newinsn->getAddress()->getFileID()!=oldinsn->getAddress()->getFileID()) { // // coders: verify this is OK before allowing an insn to change files. @@ -604,10 +580,10 @@ static bool needs_spri_rule(Instruction_t* newinsn,Instruction_t* oldinsn) } - Instruction_t *newFT=newinsn->GetFallthrough(); - Instruction_t *newTG=newinsn->GetTarget(); - Instruction_t *oldFT=oldinsn->GetFallthrough(); - Instruction_t *oldTG=oldinsn->GetTarget(); + auto newFT=newinsn->getFallthrough(); + auto newTG=newinsn->getTarget(); + auto oldFT=oldinsn->getFallthrough(); + auto oldTG=oldinsn->getTarget(); // // check that both have a fallthrough or both don't have a fallthrough @@ -621,15 +597,15 @@ static bool needs_spri_rule(Instruction_t* newinsn,Instruction_t* oldinsn) return true; // if there's a fallthrough, but it is different, return true - if(newFT && newFT->GetOriginalAddressID()!=oldFT->GetAddress()->GetBaseID()) + if(newFT && newFT->getOriginalAddressID()!=oldFT->getAddress()->getBaseID()) return true; // if there's a target, but it is different, return true - if(newTG && newTG->GetOriginalAddressID()!=oldTG->GetAddress()->GetBaseID()) + if(newTG && newTG->getOriginalAddressID()!=oldTG->getAddress()->getBaseID()) return true; // data bits themselves changed - if(newinsn->GetDataBits() != oldinsn->GetDataBits()) + if(newinsn->getDataBits() != oldinsn->getDataBits()) return true; return false; @@ -645,10 +621,10 @@ static void emit_spri_rule(FileIR_t* fileIRp, Instruction_t* newinsn, ostream& f Instruction_t* old_insn=insnMap[newinsn]; fout << endl << "# Orig addr: "<<addressify(newinsn)<<" insn_id: "<< std::dec - << newinsn->GetBaseID()<<" with comment "<<newinsn->GetComment()<<endl; - if (newinsn->GetIndirectBranchTargetAddress()) + << newinsn->getBaseID()<<" with comment "<<newinsn->getComment()<<endl; + if (newinsn->getIndirectBranchTargetAddress()) fout << "# Orig addr: "<<addressify(newinsn)<<" indirect branch target: " - <<newinsn->GetIndirectBranchTargetAddress()->GetVirtualOffset() << endl; + <<newinsn->getIndirectBranchTargetAddress()->getVirtualOffset() << endl; bool redirected_addr=false; bool redirected_ibt=false; @@ -666,23 +642,24 @@ static void emit_spri_rule(FileIR_t* fileIRp, Instruction_t* newinsn, ostream& f } /* if this insn is an IB target, emit the redirect appropriately */ - if (newinsn->GetIndirectBranchTargetAddress()) + if (newinsn->getIndirectBranchTargetAddress()) { redirected_ibt=true; /* If the IBT address isn't this insns address, redirect appropriately. * If this insn isn't an unmoved insn target, always redirect appropriately. */ - if((old_insn && (*newinsn->GetIndirectBranchTargetAddress()) != (*old_insn->GetAddress())) - || !redirected_addr) + // if((old_insn && (*newinsn->getIndirectBranchTargetAddress()) != (*old_insn->getAddress())) + // || !redirected_addr) + assert(0); // couldn't make this work { // use the better qualify address to check for file matches. fout << "# because has indir "<<endl; - fout << better_qualify_address(fileIRp,newinsn->GetIndirectBranchTargetAddress()) + fout << better_qualify_address(fileIRp,newinsn->getIndirectBranchTargetAddress()) <<" -> ."<<endl; } /* i don't understand this part. hopefully this is right */ - if(!newinsn->GetCallback().empty()) + if(!newinsn->getCallback().empty()) fout << ". -> "<< getPostCallbackLabel(newinsn) <<endl; } // if there's a corresponding "old" instruction (i.e., in Variant 0, aka from the binary) @@ -693,7 +670,7 @@ static void emit_spri_rule(FileIR_t* fileIRp, Instruction_t* newinsn, ostream& f /* check to see if this address an IBT somewhere else */ /* and we havne't already redirected it */ - if (ibts.find(*old_insn->GetAddress()) == ibts.end() && !redirected_ibt && !redirected_addr) + if (ibts.find(*old_insn->getAddress()) == ibts.end() && !redirected_ibt && !redirected_addr) { // with ILR turned off, we don't try to redirect to 0 @@ -715,7 +692,7 @@ static void emit_spri_rule(FileIR_t* fileIRp, Instruction_t* newinsn, ostream& f // this may be tricky because it seems we are overloading the indirect branch // target address to mean two things for instructions with callbacks. Good luck if // you're reading this. - assert(newinsn->GetCallback().empty()); + assert(newinsn->getCallback().empty()); } @@ -723,17 +700,17 @@ static void emit_spri_rule(FileIR_t* fileIRp, Instruction_t* newinsn, ostream& f /* if there's a fallthrough instruction, jump to it. */ - if(newinsn->GetFallthrough()) + if(newinsn->getFallthrough()) { - fout << ". -> " << qualified_labelfy(fileIRp,newinsn->GetFallthrough())<<endl; + fout << ". -> " << qualified_labelfy(fileIRp,newinsn->getFallthrough())<<endl; } else { //DISASM disasm; //disasm.Options = NasmSyntax + PrefixedNumeral + ShowSegmentRegs; - //disasm.Archi = fileIRp->GetArchitectureBitWidth(); - //disasm.EIP = (UIntPtr)newinsn->GetDataBits().c_str(); - //disasm.VirtualAddr = old_insn ? old_insn->GetAddress()->GetVirtualOffset() : 0; + //disasm.Archi = fileIRp->getArchitectureBitWidth(); + //disasm.EIP = (UIntPtr)newinsn->getDataBits().c_str(); + //disasm.VirtualAddr = old_insn ? old_insn->getAddress()->getVirtualOffset() : 0; const auto disasm=DecodedInstruction_t(newinsn); /* Disassemble the instruction */ @@ -747,7 +724,7 @@ static void emit_spri_rule(FileIR_t* fileIRp, Instruction_t* newinsn, ostream& f { assert(old_insn); /* it's an error to insert a new, non-unconditional branch instruction * and not specify it's fallthrough */ - fout << ". -> " << qualify(fileIRp)<< "0x" << std::hex << old_insn->GetAddress()->GetVirtualOffset()+instr_len <<endl; + fout << ". -> " << qualify(fileIRp)<< "0x" << std::hex << old_insn->getAddress()->getVirtualOffset()+instr_len <<endl; } } @@ -787,8 +764,8 @@ static void generate_insn_to_insn_maps(FileIR_t *fileIRp, FileIR_t *orig_fileIRp /* loop through each insn in the original program */ for( - std::set<Instruction_t*>::const_iterator it=orig_fileIRp->GetInstructions().begin(); - it!=orig_fileIRp->GetInstructions().end(); + auto it=orig_fileIRp->getInstructions().begin(); + it!=orig_fileIRp->getInstructions().end(); ++it ) { @@ -797,12 +774,12 @@ static void generate_insn_to_insn_maps(FileIR_t *fileIRp, FileIR_t *orig_fileIRp assert(insn); /* get it's ID */ - db_id_t address_id=insn->GetAddress()->GetBaseID(); + db_id_t address_id=insn->getAddress()->getBaseID(); assert(address_id!=-1); /* sanity check */ - assert(insn->GetAddress()->GetFileID()!=-1); - assert(insn->GetAddress()->GetVirtualOffset()!=0); + assert(insn->getAddress()->getFileID()!=-1); + assert(insn->getAddress()->getVirtualOffset()!=0); /* insert into map */ idMap[address_id]=insn; @@ -819,7 +796,7 @@ static void generate_insn_to_insn_maps(FileIR_t *fileIRp, FileIR_t *orig_fileIRp Instruction_t *insn=*it; assert(insn); - db_id_t orig_addr=insn->GetOriginalAddressID(); + db_id_t orig_addr=insn->getOriginalAddressID(); /* no mapping if this is true */ if(orig_addr==-1) @@ -841,14 +818,14 @@ void FileIR_t::GenerateSPRI(ostream &fout, bool with_ilr) assert(orig_varidp.IsRegistered()==true); for( - set<File_t*>::iterator it=orig_varidp.GetFiles().begin(); - it!=orig_varidp.GetFiles().end(); + set<File_t*>::iterator it=orig_varidp.getFiles().begin(); + it!=orig_varidp.getFiles().end(); ++it ) { File_t* the_file=*it; - if(the_file->GetBaseID()==fileptr->orig_fid) + if(the_file->getBaseID()==fileptr->orig_fid) { fout <<"# Generating spri for "<< the_file->GetURL()<<endl; @@ -877,7 +854,7 @@ static void generate_IBT_set(FileIR_t* fileIRp) ) { Instruction_t *insn=*it; - AddressID_t *ibt=insn->GetIndirectBranchTargetAddress(); + AddressID_t *ibt=insn->getIndirectBranchTargetAddress(); if(ibt) { @@ -910,24 +887,26 @@ static void generate_unmoved_insn_targets_set(FileIR_t* fileIRp) !needs_spri_rule(insn, insnMap[insn]) ) { - unmoved_insn_targets.insert(insn->GetTarget()); - unmoved_insn_targets.insert(insn->GetFallthrough()); + unmoved_insn_targets.insert(insn->getTarget()); + unmoved_insn_targets.insert(insn->getFallthrough()); } } } - +#endif void FileIR_t::GenerateSPRI(FileIR_t *orig_fileIRp, ostream &fout, bool with_ilr) { + assert(0); + /* //Resolve (assemble) any instructions in the registry. AssembleRegistry(); // give 'this' a name FileIR_t *fileIRp=this; - SetBaseIDS(); // need unique ID to generate unique label name + setBaseIDS(); // need unique ID to generate unique label name // generate the map from new instruction to old instruction needed for this transform. generate_insn_to_insn_maps(fileIRp, orig_fileIRp); @@ -962,5 +941,6 @@ void FileIR_t::GenerateSPRI(FileIR_t *orig_fileIRp, ostream &fout, bool with_ilr update_label_offset(fileIRp); fout<<"#DEBUG: maximum ID is "<<label_offset<<endl; + */ } diff --git a/libIRDB/src/core/icfs.cpp b/libIRDB/src/core/icfs.cpp index a81b5469e..4708e9821 100644 --- a/libIRDB/src/core/icfs.cpp +++ b/libIRDB/src/core/icfs.cpp @@ -27,13 +27,13 @@ using namespace std; static string getICFSAnalysisStatus(const ICFS_Analysis_Status_t p_status) { // strings must match DB definition switch (p_status) { - case ICFS_Analysis_Incomplete: + case IRDB_SDK::iasAnalysisIncomplete: return string("icfs_analysis_incomplete"); break; - case ICFS_Analysis_Module_Complete: + case IRDB_SDK::iasAnalysisModuleComplete: return string("icfs_analysis_module_complete"); break; - case ICFS_Analysis_Complete: + case IRDB_SDK::iasAnalysisComplete: return string("icfs_analysis_complete"); break; default: @@ -47,19 +47,19 @@ static string getICFSAnalysisStatus(const ICFS_Analysis_Status_t p_status) { ICFS_t::ICFS_t(db_id_t p_set_id, const ICFS_Analysis_Status_t p_status) : BaseObj_t(NULL) { - SetBaseID(p_set_id); - SetAnalysisStatus(p_status); + setBaseID(p_set_id); + setAnalysisStatus(p_status); } ICFS_t::ICFS_t(db_id_t p_set_id, const string p_statusString) : BaseObj_t(NULL) { - SetBaseID(p_set_id); + setBaseID(p_set_id); if (p_statusString == "icfs_analysis_incomplete") { - SetAnalysisStatus(ICFS_Analysis_Incomplete); + setAnalysisStatus(IRDB_SDK::iasAnalysisIncomplete); } else if (p_statusString == "icfs_analysis_module_complete") { - SetAnalysisStatus(ICFS_Analysis_Module_Complete); + setAnalysisStatus(IRDB_SDK::iasAnalysisModuleComplete); } else if (p_statusString == "icfs_analysis_complete") { - SetAnalysisStatus(ICFS_Analysis_Complete); + setAnalysisStatus(IRDB_SDK::iasAnalysisComplete); } else { std::cerr << "error: unknown ICFS analysis status string: " << p_statusString << std::endl; assert(0); @@ -70,9 +70,9 @@ string ICFS_t::WriteToDB(File_t *fid) { assert(fid); - db_id_t icfs_id = GetBaseID(); + db_id_t icfs_id = getBaseID(); - string analysis_status = getICFSAnalysisStatus(GetAnalysisStatus()); + string analysis_status = getICFSAnalysisStatus(getAnalysisStatus()); string q=string("insert into ") + fid->icfs_table_name + string(" (icfs_id, icfs_status) VALUES (") + @@ -82,10 +82,10 @@ string ICFS_t::WriteToDB(File_t *fid) for (InstructionSet_t::const_iterator it = this->begin(); it != this->end(); ++it) { - Instruction_t *insn = *it; + auto insn = *it; assert(insn); - db_id_t address_id = insn->GetAddress()->GetBaseID(); + auto address_id = insn->getAddress()->getBaseID(); q += string("insert into ") + fid->icfs_map_table_name + string(" (icfs_id, address_id) VALUES(") + diff --git a/libIRDB/src/core/instruction.cpp b/libIRDB/src/core/instruction.cpp index 7a8768216..422bfbb45 100644 --- a/libIRDB/src/core/instruction.cpp +++ b/libIRDB/src/core/instruction.cpp @@ -46,7 +46,7 @@ Instruction_t::Instruction_t() : eh_pgm(NULL), eh_cs(NULL) { - SetBaseID(NOT_IN_DATABASE); + setBaseID(NOT_IN_DATABASE); } Instruction_t::Instruction_t(db_id_t id, @@ -73,7 +73,7 @@ Instruction_t::Instruction_t(db_id_t id, eh_pgm(NULL), eh_cs(NULL) { - SetBaseID(id); + setBaseID(id); } /* @@ -83,9 +83,9 @@ int Instruction_t::Disassemble(DISASM &disasm) const memset(&disasm, 0, sizeof(DISASM)); disasm.Options = NasmSyntax + PrefixedNumeral; - disasm.Archi = FileIR_t::GetArchitectureBitWidth(); - disasm.EIP = (UIntPtr) GetDataBits().c_str(); - disasm.VirtualAddr = GetAddress()->GetVirtualOffset(); + disasm.Archi = FileIR_t::getArchitectureBitWidth(); + disasm.EIP = (UIntPtr) getDataBits().c_str(); + disasm.VirtualAddr = getAddress()->getVirtualOffset(); int instr_len = Disasm(&disasm); return instr_len; @@ -98,15 +98,15 @@ std::string Instruction_t::getDisassembly() const // Disassemble(this,disasm); // return std::string(disasm.CompleteInstr); - const auto d=DecodedInstruction_t(this); - return d.getDisassembly(); + const auto d=DecodedInstruction_t::factory(this); + return d->getDisassembly(); } // // Given an instruction in assembly, returns the raw bits in a string // On error, return the empty string // -bool Instruction_t::Assemble(string assembly) +bool Instruction_t::assemble(string assembly) { const string assemblyFile = "tmp.asm"; const string binaryOutputFile = "tmp.bin"; @@ -124,7 +124,7 @@ bool Instruction_t::Assemble(string assembly) return false; } - asmFile<<"BITS "<<std::dec<<FileIR_t::GetArchitectureBitWidth()<<endl; + asmFile<<"BITS "<<std::dec<<FileIR_t::getArchitectureBitWidth()<<endl; asmFile<<assembly<<endl; asmFile.close(); @@ -161,7 +161,7 @@ bool Instruction_t::Assemble(string assembly) // should erase those 2 files here - this->SetDataBits(rawBits); + this->setDataBits(rawBits); return true; } @@ -171,29 +171,29 @@ vector<string> Instruction_t::WriteToDB(File_t *fid, db_id_t newid) assert(fid); assert(my_address); - if(GetBaseID()==NOT_IN_DATABASE) - SetBaseID(newid); + if(getBaseID()==NOT_IN_DATABASE) + setBaseID(newid); auto func_id=NOT_IN_DATABASE; - if(my_function) func_id=my_function->GetBaseID(); + if(my_function) func_id=my_function->getBaseID(); auto ft_id=NOT_IN_DATABASE; - if(fallthrough) ft_id=fallthrough->GetBaseID(); + if(fallthrough) ft_id=fallthrough->getBaseID(); auto targ_id=NOT_IN_DATABASE; - if(target) targ_id=target->GetBaseID(); + if(target) targ_id=target->getBaseID(); auto icfs_id=NOT_IN_DATABASE; - if (icfs) icfs_id=icfs->GetBaseID(); + if (icfs) icfs_id=icfs->getBaseID(); auto indirect_bt_id=NOT_IN_DATABASE; - if(indTarg) indirect_bt_id=indTarg->GetBaseID(); + if(indTarg) indirect_bt_id=indTarg->getBaseID(); auto eh_pgm_id=NOT_IN_DATABASE; - if(eh_pgm) eh_pgm_id=eh_pgm->GetBaseID(); + if(eh_pgm) eh_pgm_id=eh_pgm->getBaseID(); auto eh_css_id=NOT_IN_DATABASE; - if(eh_cs) eh_css_id=eh_cs->GetBaseID(); + if(eh_cs) eh_css_id=eh_cs->getBaseID(); ostringstream hex_data; hex_data << setfill('0') << hex;; @@ -202,8 +202,8 @@ vector<string> Instruction_t::WriteToDB(File_t *fid, db_id_t newid) return { - to_string(GetBaseID()), - to_string(my_address->GetBaseID()), + to_string(getBaseID()), + to_string(my_address->getBaseID()), to_string(func_id), to_string(orig_address_id), to_string(ft_id), @@ -215,24 +215,24 @@ vector<string> Instruction_t::WriteToDB(File_t *fid, db_id_t newid) callback, comment, to_string(indirect_bt_id), - to_string(GetDoipID()) }; + to_string(getDoipID()) }; } /* return true if this instructino exits the function -- true if there's no function, because each instruction is it's own function? */ -bool Instruction_t::IsFunctionExit() const +bool Instruction_t::isFunctionExit() const { if(!my_function) return true; /* if there's a target that's outside this function */ - Instruction_t *target=GetTarget(); - if(target && target->GetFunction()!=GetFunction()) // !is_in_set(my_function->GetInstructions(),target)) + auto target=getTarget(); + if(target && target->getFunction()!=getFunction()) // !is_in_set(my_function->GetInstructions(),target)) return true; /* if there's a fallthrough that's outside this function */ - Instruction_t *ft=GetFallthrough(); - if(fallthrough && ft->GetFunction()!=GetFunction()) // !is_in_set(my_function->GetInstructions(),ft)) + auto ft=getFallthrough(); + if(fallthrough && ft->getFunction()!=getFunction()) // !is_in_set(my_function->GetInstructions(),ft)) return true; /* some instructions have no next-isntructions defined in the db, and we call them function exits */ @@ -242,36 +242,23 @@ bool Instruction_t::IsFunctionExit() const return false; } - -/* -bool Instruction_t::SetsStackPointer(ARGTYPE* arg) +IRDB_SDK::Function_t* Instruction_t::getFunction() const { - if((arg->AccessMode & WRITE ) == 0) - return false; - int access_type=arg->ArgType; - - if(access_type==REGISTER_TYPE + GENERAL_REG +REG4) - return true; - return false; - + return my_function; } -bool Instruction_t::SetsStackPointer(DISASM* disasm) -{ - if(strstr(disasm->Instruction.Mnemonic, "push")!=NULL) - return true; - if(strstr(disasm->Instruction.Mnemonic, "pop")!=NULL) - return true; - if(strstr(disasm->Instruction.Mnemonic, "call")!=NULL) - return true; - if(disasm->Instruction.ImplicitModifiedRegs==REGISTER_TYPE+GENERAL_REG+REG4) - return true; - if(SetsStackPointer(&disasm->Argument1)) return true; - if(SetsStackPointer(&disasm->Argument2)) return true; - if(SetsStackPointer(&disasm->Argument3)) return true; +IRDB_SDK::EhProgram_t* Instruction_t::getEhProgram() const { return eh_pgm; } +IRDB_SDK::EhCallSite_t* Instruction_t::getEhCallSite() const { return eh_cs; } +IRDB_SDK::AddressID_t* Instruction_t::getIndirectBranchTargetAddress() const { return indTarg; } + +void Instruction_t::setAddress (IRDB_SDK::AddressID_t* newaddr) { my_address=dynamic_cast<AddressID_t*>(newaddr); } +void Instruction_t::setFunction (IRDB_SDK::Function_t* func ) { my_function=dynamic_cast<Function_t*>(func);} +void Instruction_t::setFallthrough (IRDB_SDK::Instruction_t* i) { fallthrough=dynamic_cast<Instruction_t*>(i); } +void Instruction_t::setTarget (IRDB_SDK::Instruction_t* i) { target=dynamic_cast<Instruction_t*>(i); } +void Instruction_t::setIBTargets (IRDB_SDK::ICFS_t *p_icfs) { icfs=dynamic_cast<ICFS_t*>(p_icfs); } +void Instruction_t::setEhProgram(IRDB_SDK::EhProgram_t* orig) { eh_pgm=dynamic_cast<EhProgram_t*>(orig); } +void Instruction_t::setEhCallSite(IRDB_SDK::EhCallSite_t* orig) { eh_cs=dynamic_cast<EhCallSite_t*>(orig); } +void Instruction_t::setIndirectBranchTargetAddress(IRDB_SDK::AddressID_t* myIndTarg) { indTarg=dynamic_cast<AddressID_t*>(myIndTarg); } - return false; -} -*/ diff --git a/libIRDB/src/core/operand_csarm.cpp b/libIRDB/src/core/operand_csarm.cpp index f269d1ac0..cd628548e 100644 --- a/libIRDB/src/core/operand_csarm.cpp +++ b/libIRDB/src/core/operand_csarm.cpp @@ -1,8 +1,11 @@ #include <libIRDB-core.hpp> #include <memory> -#include <core/operand_csarm.hpp> +#include <core/decode_base.hpp> #include <core/decode_csarm.hpp> +#include <core/operand_base.hpp> +#include <core/operand_csarm.hpp> + using namespace std; using namespace libIRDB; diff --git a/libIRDB/src/core/operand_csx86.cpp b/libIRDB/src/core/operand_csx86.cpp index d7d6c9784..dec388b07 100644 --- a/libIRDB/src/core/operand_csx86.cpp +++ b/libIRDB/src/core/operand_csx86.cpp @@ -1,8 +1,12 @@ #include <libIRDB-core.hpp> #include <memory> -#include <core/operand_csx86.hpp> +#include <core/decode_base.hpp> #include <core/decode_csx86.hpp> +#include <core/operand_base.hpp> +#include <core/operand_csx86.hpp> + + using namespace std; using namespace libIRDB; diff --git a/libIRDB/src/core/pqxxdb.cpp b/libIRDB/src/core/pqxxdb.cpp index f0f1c4232..37fa2e986 100644 --- a/libIRDB/src/core/pqxxdb.cpp +++ b/libIRDB/src/core/pqxxdb.cpp @@ -31,25 +31,25 @@ pqxxDB_t::pqxxDB_t() : DBinterface_t(), txn(conn) /* no other init needed */ } -void pqxxDB_t::IssueQuery(std::string query) +void pqxxDB_t::issueQuery(std::string query) { results=txn.exec(query); results_iter=results.begin(); } -void pqxxDB_t::IssueQuery(std::stringstream & query) +void pqxxDB_t::issueQuery(std::stringstream & query) { results=txn.exec(query); results_iter=results.begin(); } -void pqxxDB_t::MoveToNextRow() +void pqxxDB_t::moveToNextRow() { - assert(!IsDone()); + assert(!isDone()); ++results_iter; } -std::string pqxxDB_t::GetResultColumn(std::string colname) +std::string pqxxDB_t::getResultColumn(std::string colname) { if(results_iter[colname].is_null()) return std::string(""); @@ -61,14 +61,17 @@ std::string pqxxDB_t::GetResultColumn(std::string colname) // return results_iter[colname].as<std::string>(); } -bool pqxxDB_t::IsDone() +bool pqxxDB_t::isDone() { return results_iter==results.end(); } -void pqxxDB_t::Commit() +void pqxxDB_t::commit() { txn.commit(); } - +unique_ptr<IRDB_SDK::pqxxDB_t> IRDB_SDK::pqxxDB_t::factory() +{ + return unique_ptr<IRDB_SDK::pqxxDB_t>(new libIRDB::pqxxDB_t); +} diff --git a/libIRDB/src/core/reloc.cpp b/libIRDB/src/core/reloc.cpp index 4500d27b8..1364f3fa4 100644 --- a/libIRDB/src/core/reloc.cpp +++ b/libIRDB/src/core/reloc.cpp @@ -25,7 +25,7 @@ using namespace std; vector<std::string> Relocation_t::WriteToDB(File_t* fid, BaseObj_t* myinsn) { - db_id_t wrt_id=wrt_obj ? wrt_obj->GetBaseID() : BaseObj_t::NOT_IN_DATABASE; + db_id_t wrt_id=wrt_obj ? wrt_obj->getBaseID() : BaseObj_t::NOT_IN_DATABASE; /* string q; q ="insert into " + fid->relocs_table_name; @@ -33,13 +33,13 @@ vector<std::string> Relocation_t::WriteToDB(File_t* fid, BaseObj_t* myinsn) string(" VALUES (") + */ return { - to_string(GetBaseID()), + to_string(getBaseID()), to_string(offset), (type), - to_string(myinsn->GetBaseID()), + to_string(myinsn->getBaseID()), to_string(addend), to_string(wrt_id), - to_string(GetDoipID()) + to_string(getDoipID()) }; } diff --git a/libIRDB/src/core/scoop.cpp b/libIRDB/src/core/scoop.cpp index ab50f42c2..ab5d093a7 100644 --- a/libIRDB/src/core/scoop.cpp +++ b/libIRDB/src/core/scoop.cpp @@ -42,7 +42,7 @@ string DataScoop_t::WriteToDBRange(File_t *fid, db_id_t newid, int start, int en */ - db_id_t type_id=(GetType() ? GetType()->GetBaseID() : BaseObj_t::NOT_IN_DATABASE); + db_id_t type_id=(getType() ? getType()->getBaseID() : BaseObj_t::NOT_IN_DATABASE); ostringstream hex_data; @@ -50,22 +50,22 @@ string DataScoop_t::WriteToDBRange(File_t *fid, db_id_t newid, int start, int en string q=string("insert into ")+table_name+ string(" (scoop_id, name, type_id, start_address_id, end_address_id, data, permissions, relro) ")+ string(" VALUES (") + - string("'") + to_string(GetBaseID()) + string("', ") + - string("'") + GetName() + string("', ") + + string("'") + to_string(getBaseID()) + string("', ") + + string("'") + getName() + string("', ") + string("'") + to_string(type_id) + string("', ") + - string("'") + to_string(GetStart()->GetBaseID()) + string("', ") + - string("'") + to_string(GetEnd()->GetBaseID()) + string("', ") + + string("'") + to_string(getStart()->getBaseID()) + string("', ") + + string("'") + to_string(getEnd()->getBaseID()) + string("', ") + string("'") + /* empty data field -- for now + */ string("', ") + string("'") + to_string(permissions) + string("', ") + string("'") + to_string(is_relro) + string("'); ") ; // add the table row with empty data field. - dbintr->IssueQuery(q); + dbintr->issueQuery(q); // now try to append the data to the field in chunks. string query_start="update "+table_name+" set data = data || decode('"; - string query_end="', 'hex') where scoop_id="+ string("'") + to_string(GetBaseID()) + string("'; ") ; + string query_end="', 'hex') where scoop_id="+ string("'") + to_string(getBaseID()) + string("'; ") ; hex_data << query_start << setfill('0') << hex; @@ -85,7 +85,7 @@ string DataScoop_t::WriteToDBRange(File_t *fid, db_id_t newid, int start, int en hex_data << query_end; // append this chunk to the db. - dbintr->IssueQuery(hex_data.str()); + dbintr->issueQuery(hex_data.str()); // restart hex_data.str(""); // reset to empty @@ -96,7 +96,7 @@ string DataScoop_t::WriteToDBRange(File_t *fid, db_id_t newid, int start, int en hex_data << query_end; // append this chunk to the db. - dbintr->IssueQuery(hex_data.str()); + dbintr->issueQuery(hex_data.str()); return ""; } diff --git a/libIRDB/src/core/type.cpp b/libIRDB/src/core/type.cpp index 7dc8f2a18..5f05b10dd 100644 --- a/libIRDB/src/core/type.cpp +++ b/libIRDB/src/core/type.cpp @@ -24,10 +24,14 @@ using namespace std; using namespace libIRDB; -bool BasicType_t::IsNumericType() const +bool BasicType_t::isNumericType() const { - int type = GetTypeID(); - return type == T_NUMERIC || type == T_INT || type == T_FLOAT || type == T_DOUBLE || type == T_CHAR; + auto type = getTypeID(); + return type == IRDB_SDK::itNumeric || + type == IRDB_SDK::itInt || + type == IRDB_SDK::itFloat || + type == IRDB_SDK::itDouble || + type == IRDB_SDK::itChar; } /* @@ -47,15 +51,12 @@ string BasicType_t::WriteToDB(File_t *fid, db_id_t newid) { assert(fid); -// if(GetBaseID()==NOT_IN_DATABASE) -// SetBaseID(newid); - string q=string("insert into ")+fid->types_table_name + string(" (type_id, type, name, ref_type_id, pos, ref_type_id2) ")+ string(" VALUES (") + - string("'") + to_string(GetBaseID()) + string("', ") + - string("'") + to_string(GetTypeID()) + string("', ") + - string("'") + GetName() + string("','-1','-1','-1') ; ") ; + string("'") + to_string(getBaseID()) + string("', ") + + string("'") + to_string(getTypeID()) + string("', ") + + string("'") + getName() + string("','-1','-1','-1') ; ") ; // cout << "BasicType_t::WriteToDB(): " << q << endl; return q; @@ -63,14 +64,14 @@ string BasicType_t::WriteToDB(File_t *fid, db_id_t newid) string PointerType_t::WriteToDB(File_t *fid, db_id_t newid) { - assert(fid && GetReferentType()); + assert(fid && getReferentType()); string q=string("insert into ")+fid->types_table_name + string(" (type_id, type, name, ref_type_id,pos,ref_type_id2) ")+ string(" VALUES (") + - string("'") + to_string(GetBaseID()) + string("', ") + - string("'") + to_string(GetTypeID()) + string("', ") + - string("'") + GetName() + string("', ") + - string("'") + to_string(GetReferentType()->GetBaseID()) + + string("'") + to_string(getBaseID()) + string("', ") + + string("'") + to_string(getTypeID()) + string("', ") + + string("'") + getName() + string("', ") + + string("'") + to_string(getReferentType()->getBaseID()) + string("','-1','-1') ; ") ; // cout << "PointerType_t::WriteToDB(): " << q << endl; @@ -80,20 +81,20 @@ string PointerType_t::WriteToDB(File_t *fid, db_id_t newid) string AggregateType_t::WriteToDB(File_t *fid, db_id_t newid) { assert(fid); - assert(GetNumAggregatedTypes() > 0); + assert(getNumAggregatedTypes() > 0); string q; - for (auto i = 0U; i < GetNumAggregatedTypes(); ++i) + for (auto i = 0U; i < getNumAggregatedTypes(); ++i) { - Type_t* t = GetAggregatedType(i); + auto t = getAggregatedType(i); q+=string("insert into ")+fid->types_table_name + string(" (type_id, type, name, ref_type_id, pos,ref_type_id2) ")+ string(" VALUES (") + - string("'") + to_string(GetBaseID()) + string("', ") + - string("'") + to_string(GetTypeID()) + string("', ") + - string("'") + GetName() + string("', ") + - string("'") + to_string(t->GetBaseID()) + string("', ") + + string("'") + to_string(getBaseID()) + string("', ") + + string("'") + to_string(getTypeID()) + string("', ") + + string("'") + getName() + string("', ") + + string("'") + to_string(t->getBaseID()) + string("', ") + string("'") + to_string(i) + string("','-1') ; ") ; } @@ -102,7 +103,7 @@ string AggregateType_t::WriteToDB(File_t *fid, db_id_t newid) return q; } -void AggregateType_t::AddAggregatedType(Type_t *t, int pos) +void AggregateType_t::addAggregatedType(IRDB_SDK::Type_t *t, int pos) { refTypes.push_back(t); @@ -124,16 +125,16 @@ CREATE TABLE #TYP# string FuncType_t::WriteToDB(File_t *fid, db_id_t newid) { assert(fid); - assert(GetReturnType()); - assert(GetArgumentsType()); + assert(getReturnType()); + assert(getArgumentsType()); string q=string("insert into ")+fid->types_table_name + string(" (type_id, type, name, ref_type_id, ref_type_id2,pos) ")+ string(" VALUES (") + - string("'") + to_string(GetBaseID()) + string("', ") + - string("'") + to_string(GetTypeID()) + string("', ") + - string("'") + GetName() + string("', ") + - string("'") + to_string(GetReturnType()->GetBaseID()) + string("', ") + - string("'") + to_string(GetArgumentsType()->GetBaseID()) + + string("'") + to_string(getBaseID()) + string("', ") + + string("'") + to_string(getTypeID()) + string("', ") + + string("'") + getName() + string("', ") + + string("'") + to_string(getReturnType()->getBaseID()) + string("', ") + + string("'") + to_string(getArgumentsType()->getBaseID()) + string("','-1') ; ") ; // cout << "FuncType_t::WriteToDB(): " << q << endl; diff --git a/libIRDB/src/core/variantid.cpp b/libIRDB/src/core/variantid.cpp index df50ce949..f8b9b75cc 100644 --- a/libIRDB/src/core/variantid.cpp +++ b/libIRDB/src/core/variantid.cpp @@ -61,7 +61,7 @@ VariantID_t::VariantID_t(db_id_t pid) : BaseObj_t(NULL) try { - BaseObj_t::dbintr->IssueQuery(q); + BaseObj_t::dbintr->issueQuery(q); } catch (const std::exception &e) { @@ -72,29 +72,29 @@ VariantID_t::VariantID_t(db_id_t pid) : BaseObj_t(NULL) throw DatabaseError_t(DatabaseError_t::VariantTableNotRegistered); }; - if(BaseObj_t::dbintr->IsDone()) + if(BaseObj_t::dbintr->isDone()) throw DatabaseError_t(DatabaseError_t::VariantNotInDatabase); - SetBaseID(atoi(BaseObj_t::dbintr->GetResultColumn("variant_id").c_str())); - schema_ver=atoi(BaseObj_t::dbintr->GetResultColumn("schema_version_id").c_str()); - orig_pid=atoi(BaseObj_t::dbintr->GetResultColumn("orig_variant_id").c_str()); - name=(BaseObj_t::dbintr->GetResultColumn("name")); + setBaseID(atoi(BaseObj_t::dbintr->getResultColumn("variant_id").c_str())); + schema_ver=atoi(BaseObj_t::dbintr->getResultColumn("schema_version_id").c_str()); + orig_pid=atoi(BaseObj_t::dbintr->getResultColumn("orig_variant_id").c_str()); + name=(BaseObj_t::dbintr->getResultColumn("name")); - BaseObj_t::dbintr->MoveToNextRow(); - assert(BaseObj_t::dbintr->IsDone()); + BaseObj_t::dbintr->moveToNextRow(); + assert(BaseObj_t::dbintr->isDone()); ReadFilesFromDB(); } -bool VariantID_t::IsRegistered() +bool VariantID_t::isRegistered() const { - return GetBaseID()!=BaseObj_t::NOT_IN_DATABASE; + return getBaseID()!=BaseObj_t::NOT_IN_DATABASE; } -bool VariantID_t::Register() +bool VariantID_t::registerID() { - assert(!IsRegistered()); + assert(!isRegistered()); std::string q; q="insert into variant_info (schema_version_id,name) " @@ -105,35 +105,35 @@ bool VariantID_t::Register() q+="')"; q+="returning variant_id;"; - dbintr->IssueQuery(q); - assert(!BaseObj_t::dbintr->IsDone()); + dbintr->issueQuery(q); + assert(!BaseObj_t::dbintr->isDone()); - db_id_t newid=atoi(dbintr->GetResultColumn("variant_id").c_str()); + db_id_t newid=atoi(dbintr->getResultColumn("variant_id").c_str()); /* set IDs */ - SetBaseID(newid); + setBaseID(newid); if(NOT_IN_DATABASE==orig_pid) orig_pid=newid; - BaseObj_t::dbintr->MoveToNextRow(); - assert(BaseObj_t::dbintr->IsDone()); + BaseObj_t::dbintr->moveToNextRow(); + assert(BaseObj_t::dbintr->isDone()); return true; } -VariantID_t* VariantID_t::Clone(bool deep) +IRDB_SDK::VariantID_t* VariantID_t::clone(bool deep) { - assert(IsRegistered()); // cannot clone something that's not registered + assert(isRegistered()); // cannot clone something that's not registered // create the new program id VariantID_t *ret=new VariantID_t; // set the inhereted fields - ret->SetName(name+"_cloneof"+to_string(GetBaseID())); + ret->setName(name+"_cloneof"+to_string(getBaseID())); ret->orig_pid=orig_pid; // register the new VID to the database. - ret->Register(); + ret->registerID(); // and write it to the database ret->WriteToDB(); @@ -144,11 +144,11 @@ VariantID_t* VariantID_t::Clone(bool deep) // the old variant depended upon. The new rows will indicate that the // new variant also depends on those files q="insert into variant_dependency (variant_id, file_id, doip_id) select '"; - q+=to_string(ret->GetBaseID()); + q+=to_string(ret->getBaseID()); q+="', file_id, doip_id from variant_dependency where variant_id='"; - q+=to_string(GetBaseID()); + q+=to_string(getBaseID()); q+="';"; - dbintr->IssueQuery(q); + dbintr->issueQuery(q); if(deep) ret->CloneFiles(files); @@ -159,7 +159,10 @@ VariantID_t* VariantID_t::Clone(bool deep) void VariantID_t::CloneFiles(FileSet_t &files) { for(auto fiter=files.begin(); fiter!=files.end(); ++fiter) - files.insert(CloneFile(*fiter)); + { + auto the_file=dynamic_cast<File_t*>(*fiter); + files.insert(CloneFile(the_file)); + } } File_t* VariantID_t::CloneFile(File_t* fptr) @@ -181,15 +184,15 @@ File_t* VariantID_t::CloneFile(File_t* fptr) to_string(fptr->hash) + "', '" + to_string(fptr->arch) + "', '" + to_string(fptr->elfoid) + "', '" + - to_string(fptr->GetDoipID()) + + to_string(fptr->getDoipID()) + "' ) "; q+=" returning file_id; "; - dbintr->IssueQuery(q); - assert(!BaseObj_t::dbintr->IsDone()); + dbintr->issueQuery(q); + assert(!BaseObj_t::dbintr->isDone()); - db_id_t newfid=atoi(dbintr->GetResultColumn("file_id").c_str()); + db_id_t newfid=atoi(dbintr->getResultColumn("file_id").c_str()); std::string atn="atnfid"+to_string(newfid); std::string ftn="ftnfid"+to_string(newfid); @@ -217,10 +220,10 @@ File_t* VariantID_t::CloneFile(File_t* fptr) q+=to_string(newfid); q+="' ; "; - dbintr->IssueQuery(q); + dbintr->issueQuery(q); File_t* newfile=new File_t(newfid, fptr->orig_fid, fptr->url, fptr->hash, fptr->arch, - fptr->elfoid, atn, ftn, itn, icfs, icfsmap, rtn, typ, dtn, ehp, css, fptr->GetDoipID()); + fptr->elfoid, atn, ftn, itn, icfs, icfsmap, rtn, typ, dtn, ehp, css, fptr->getDoipID()); newfile->CreateTables(); @@ -228,57 +231,57 @@ File_t* VariantID_t::CloneFile(File_t* fptr) q="drop table "; q+=itn; q+=" ; "; - dbintr->IssueQuery(q); + dbintr->issueQuery(q); q="drop table "; q+=icfsmap; q+=" ; "; - dbintr->IssueQuery(q); + dbintr->issueQuery(q); q="drop table "; q+=icfs; q+=" ; "; - dbintr->IssueQuery(q); + dbintr->issueQuery(q); q="drop table "; q+=atn; q+=" ; "; - dbintr->IssueQuery(q); + dbintr->issueQuery(q); q="drop table "; q+=ftn; q+=" ; "; - dbintr->IssueQuery(q); + dbintr->issueQuery(q); q="drop table "; q+=rtn; q+=" ; "; - dbintr->IssueQuery(q); + dbintr->issueQuery(q); q="drop table "; q+=typ; q+=" ; "; - dbintr->IssueQuery(q); + dbintr->issueQuery(q); q="drop table "; q+=dtn; q+=" ; "; - dbintr->IssueQuery(q); + dbintr->issueQuery(q); q="drop table "; q+=dtn_part2; q+=" ; "; - dbintr->IssueQuery(q); + dbintr->issueQuery(q); q="drop table "; q+=ehp; q+=" ; "; - dbintr->IssueQuery(q); + dbintr->issueQuery(q); q="drop table "; q+=css; q+=" ; "; - dbintr->IssueQuery(q); + dbintr->issueQuery(q); // next issue SQL to clone each table @@ -287,87 +290,87 @@ File_t* VariantID_t::CloneFile(File_t* fptr) q+=" from "; q+=fptr->address_table_name; q+=" ;"; - dbintr->IssueQuery(q); + dbintr->issueQuery(q); q="select * into "; q+=itn; q+=" from "; q+=fptr->instruction_table_name; q+=" ;"; - dbintr->IssueQuery(q); + dbintr->issueQuery(q); q="select * into "; q+=icfs; q+=" from "; q+=fptr->icfs_table_name; q+=" ;"; - dbintr->IssueQuery(q); + dbintr->issueQuery(q); q="select * into "; q+=icfsmap; q+=" from "; q+=fptr->icfs_map_table_name; q+=" ;"; - dbintr->IssueQuery(q); + dbintr->issueQuery(q); q="select * into "; q+=ftn; q+=" from "; q+=fptr->function_table_name; q+=" ;"; - dbintr->IssueQuery(q); + dbintr->issueQuery(q); q="select * into "; q+=rtn; q+=" from "; q+=fptr->relocs_table_name; q+=" ;"; - dbintr->IssueQuery(q); + dbintr->issueQuery(q); q="select * into "; q+=typ; q+=" from "; q+=fptr->types_table_name; q+=" ;"; - dbintr->IssueQuery(q); + dbintr->issueQuery(q); q="select * into "; q+=dtn; q+=" from "; q+=fptr->scoop_table_name; q+=" ;"; - dbintr->IssueQuery(q); + dbintr->issueQuery(q); q="select * into "; q+=dtn_part2; q+=" from "; q+=fptr->scoop_table_name+"_part2"; q+=" ;"; - dbintr->IssueQuery(q); + dbintr->issueQuery(q); q="select * into "; q+=ehp; q+=" from "; q+=fptr->ehpgm_table_name; q+=" ;"; - dbintr->IssueQuery(q); + dbintr->issueQuery(q); q="select * into "; q+=css; q+=" from "; q+=fptr->ehcss_table_name; q+=" ;"; - dbintr->IssueQuery(q); + dbintr->issueQuery(q); // update the variant dependency table to represent the deep clone q = "update variant_dependency set file_id='" + to_string(newfid) + "' where variant_id='" + - to_string(GetBaseID()) + + to_string(getBaseID()) + "' AND file_id='" + - to_string(fptr->GetBaseID()) + + to_string(fptr->getBaseID()) + "' ;"; - dbintr->IssueQuery(q); + dbintr->issueQuery(q); return newfile; @@ -376,26 +379,25 @@ File_t* VariantID_t::CloneFile(File_t* fptr) void VariantID_t::WriteToDB() { - assert(IsRegistered()); + assert(isRegistered()); std::string q="update variant_info SET "; q+=" schema_version_id = '" + to_string(schema_ver) + "', "; q+=" name = '" + name + "', "; q+=" orig_variant_id = '" + to_string(orig_pid) + "', "; - q+=" doip_id = '" + to_string(GetDoipID()) + "' "; - q+=" where variant_id = '" + to_string(GetBaseID()) + "';"; + q+=" doip_id = '" + to_string(getDoipID()) + "' "; + q+=" where variant_id = '" + to_string(getBaseID()) + "';"; - dbintr->IssueQuery(q); + dbintr->issueQuery(q); } -std::ostream& libIRDB::operator<<(std::ostream& out, const VariantID_t& pid) +std::ostream& IRDB_SDK::operator<<(std::ostream& out, const IRDB_SDK::VariantID_t& pid) { - out << "(" - "variant_id="<<pid.GetBaseID()<<":" - "schema="<<pid.schema_ver<<":" - "orig_pid="<<pid.orig_pid<<":" - "name="<<pid.name<<":" + out << "(" << + "variant_id=" << pid.getBaseID() << ":" << + "orig_pid=" << pid.getOriginalVariantID() << ":" << + "name=" << pid.getName() << ")" ; return out; } @@ -403,21 +405,21 @@ std::ostream& libIRDB::operator<<(std::ostream& out, const VariantID_t& pid) void VariantID_t::DropFromDB() { - assert(IsRegistered()); + assert(isRegistered()); string q; - q+=string("delete from variant_dependency where variant_id = '") + to_string(GetBaseID()) + string("';"); - q+=string("delete from variant_info where variant_id = '") + to_string(GetBaseID()) + string("';"); + q+=string("delete from variant_dependency where variant_id = '") + to_string(getBaseID()) + string("';"); + q+=string("delete from variant_info where variant_id = '") + to_string(getBaseID()) + string("';"); - dbintr->IssueQuery(q); + dbintr->issueQuery(q); - SetBaseID(NOT_IN_DATABASE); + setBaseID(NOT_IN_DATABASE); orig_pid=NOT_IN_DATABASE; schema_ver=CURRENT_SCHEMA; } -File_t* VariantID_t::GetMainFile() const +IRDB_SDK::File_t* VariantID_t::getMainFile() const { for( auto it=files.begin(); @@ -425,7 +427,7 @@ File_t* VariantID_t::GetMainFile() const ++it ) { - if ((*it)->GetURL().find("a.ncexe") != string::npos) + if ((*it)->getURL().find("a.ncexe") != string::npos) return *it; } /* we should have found the main file somewhere. */ @@ -443,32 +445,32 @@ void VariantID_t::ReadFilesFromDB() " file_info.scoop_table_name, file_info.ehpgm_table_name, file_info.ehcss_table_name, file_info.file_id, file_info.url, file_info.hash," " file_info.arch, file_info.type, file_info.elfoid, file_info.doip_id " " from file_info,variant_dependency " - " where variant_dependency.variant_id = '" + to_string(GetBaseID()) + "' AND " + " where variant_dependency.variant_id = '" + to_string(getBaseID()) + "' AND " " file_info.file_id = variant_dependency.file_id ; "; - dbintr->IssueQuery(q); + dbintr->issueQuery(q); - while(!dbintr->IsDone()) + while(!dbintr->isDone()) { // file_info.file_id, file_info.url, file_info.hash, file_info.arch, file_info.type, file_info.doip_id - db_id_t file_id=atoi(dbintr->GetResultColumn("file_id").c_str()); - db_id_t orig_fid=atoi(dbintr->GetResultColumn("orig_file_id").c_str()); - std::string url=dbintr->GetResultColumn("url"); - std::string hash=dbintr->GetResultColumn("hash"); - std::string type=dbintr->GetResultColumn("type"); - int oid=atoi(dbintr->GetResultColumn("elfoid").c_str()); - db_id_t doipid=atoi(dbintr->GetResultColumn("doip_id").c_str()); - std::string atn=(BaseObj_t::dbintr->GetResultColumn("address_table_name")); - std::string ftn=(BaseObj_t::dbintr->GetResultColumn("function_table_name")); - std::string itn=(BaseObj_t::dbintr->GetResultColumn("instruction_table_name")); - std::string dtn=(BaseObj_t::dbintr->GetResultColumn("scoop_table_name")); - std::string ehp=(BaseObj_t::dbintr->GetResultColumn("ehpgm_table_name")); - std::string css=(BaseObj_t::dbintr->GetResultColumn("ehcss_table_name")); - std::string icfs=(BaseObj_t::dbintr->GetResultColumn("icfs_table_name")); - std::string icfs_map=(BaseObj_t::dbintr->GetResultColumn("icfs_map_table_name")); - std::string rtn=(BaseObj_t::dbintr->GetResultColumn("relocs_table_name")); - std::string typ=(BaseObj_t::dbintr->GetResultColumn("types_table_name")); + db_id_t file_id=atoi(dbintr->getResultColumn("file_id").c_str()); + db_id_t orig_fid=atoi(dbintr->getResultColumn("orig_file_id").c_str()); + std::string url=dbintr->getResultColumn("url"); + std::string hash=dbintr->getResultColumn("hash"); + std::string type=dbintr->getResultColumn("type"); + int oid=atoi(dbintr->getResultColumn("elfoid").c_str()); + db_id_t doipid=atoi(dbintr->getResultColumn("doip_id").c_str()); + std::string atn=(BaseObj_t::dbintr->getResultColumn("address_table_name")); + std::string ftn=(BaseObj_t::dbintr->getResultColumn("function_table_name")); + std::string itn=(BaseObj_t::dbintr->getResultColumn("instruction_table_name")); + std::string dtn=(BaseObj_t::dbintr->getResultColumn("scoop_table_name")); + std::string ehp=(BaseObj_t::dbintr->getResultColumn("ehpgm_table_name")); + std::string css=(BaseObj_t::dbintr->getResultColumn("ehcss_table_name")); + std::string icfs=(BaseObj_t::dbintr->getResultColumn("icfs_table_name")); + std::string icfs_map=(BaseObj_t::dbintr->getResultColumn("icfs_map_table_name")); + std::string rtn=(BaseObj_t::dbintr->getResultColumn("relocs_table_name")); + std::string typ=(BaseObj_t::dbintr->getResultColumn("types_table_name")); File_t *newfile=new File_t(file_id,orig_fid,url,hash,type,oid,atn,ftn,itn,icfs,icfs_map,rtn,typ,dtn,ehp,css,doipid); @@ -478,6 +480,26 @@ void VariantID_t::ReadFilesFromDB() files.insert(newfile); - dbintr->MoveToNextRow(); + dbintr->moveToNextRow(); } } + + +namespace IRDB_SDK +{ + +unique_ptr<VariantID_t> VariantID_t::factory(const DatabaseID_t& id) +{ + return unique_ptr<VariantID_t>(new libIRDB::VariantID_t(id)); +} + +unique_ptr<FileIR_t> FileIR_t::factory(VariantID_t *p_progid, File_t* p_fid) +{ + const auto progid=dynamic_cast<libIRDB::VariantID_t*>(p_progid); + const auto fid=dynamic_cast<libIRDB::File_t*>(p_fid); + return unique_ptr<FileIR_t>(new libIRDB::FileIR_t(*progid,fid)); +} + + +} + diff --git a/libIRDB/src/syscall/Makefile.in b/libIRDB/src/syscall/Makefile.in deleted file mode 100644 index c66e55627..000000000 --- a/libIRDB/src/syscall/Makefile.in +++ /dev/null @@ -1,29 +0,0 @@ - -LIB=../../lib/libIRDB-syscall.a - -OBJS=syscall.o - -CXX=@CXX@ -EXTRA_CXXFLAGS=-fPIC -g -c -I. -I../../include -I../../../beaengine/include @EXTRA_CXXFLAGS@ - -all: $(OBJS) - --include $(OBJS:.o=.d) - -clean: - rm -f $(OBJS) *.d - -.cpp.o: - ar rc $(LIB) $@ - -%.o: %.cpp - $(CXX) -c $(EXTRA_CXXFLAGS) $*.cpp - $(AR) -r $(LIB) $*.o - @# - @# build dependencies -- http://scottmcpeak.com/autodepend/autodepend.html - @# - $(CXX) -MM $(EXTRA_CXXFLAGS) $*.cpp > $*.d - @cp -f $*.d $*.d.tmp - @sed -e 's/.*://' -e 's/\\$$//' < $*.d.tmp | fmt -1 | sed -e 's/^ *//' -e 's/$$/:/' >> $*.d - @rm -f $*.d.tmp - diff --git a/libIRDB/src/syscall/SConscript b/libIRDB/src/syscall/SConscript index 2a5acdb1c..c768a3995 100644 --- a/libIRDB/src/syscall/SConscript +++ b/libIRDB/src/syscall/SConscript @@ -10,6 +10,7 @@ files= ''' syscall.cpp ''' cpppath=''' + $IRDB_SDK/include/ $SECURITY_TRANSFORMS_HOME/include/ $SECURITY_TRANSFORMS_HOME/libIRDB/include/ ''' diff --git a/libIRDB/src/syscall/syscall.cpp b/libIRDB/src/syscall/syscall.cpp index 42a6745e8..9ed6f134c 100644 --- a/libIRDB/src/syscall/syscall.cpp +++ b/libIRDB/src/syscall/syscall.cpp @@ -18,17 +18,16 @@ * */ -//#include <libIRDB-core.hpp> -//#include <libIRDB-util.hpp> -#include <stdlib.h> +#include <libIRDB-core.hpp> #include <libIRDB-syscall.hpp> +#include <stdlib.h> using namespace std; using namespace libIRDB; -SyscallNumber_t Syscalls_t::FindSystemCallNumber(Instruction_t* insn, const libIRDB::InstructionPredecessors_t& preds) +SyscallNumber_t Syscalls_t::FindSystemCallNumber(IRDB_SDK::Instruction_t* insn, const libIRDB::InstructionPredecessors_t& preds) { - Instruction_t *pred_insn=NULL; + IRDB_SDK::Instruction_t *pred_insn=NULL; for( const InstructionSet_t *cs_preds=&preds[insn]; cs_preds->size()==1; @@ -36,7 +35,6 @@ SyscallNumber_t Syscalls_t::FindSystemCallNumber(Instruction_t* insn, const libI ) { pred_insn=*(cs_preds->begin()); - // cout<<"Pred is "<<pred_insn->getDisassembly()<<endl; string disass=pred_insn->getDisassembly(); @@ -62,28 +60,28 @@ SyscallNumber_t Syscalls_t::FindSystemCallNumber(Instruction_t* insn, const libI } -bool Syscalls_t::FindSystemCalls(const FileIR_t *firp2) +bool Syscalls_t::FindSystemCalls(const IRDB_SDK::FileIR_t *firp2) { - FileIR_t* firp=(FileIR_t*)firp2; // discard const qualifer, but we aren't changing anything. + auto firp=const_cast<IRDB_SDK::FileIR_t*>(firp2); // discard const qualifer, but we aren't changing anything. assert(firp); libIRDB::InstructionPredecessors_t preds; preds.AddFile(firp); bool found_one=false; - for(InstructionSet_t::iterator it=firp->GetInstructions().begin(); - it!=firp->GetInstructions().end(); + for(auto it=firp->getInstructions().begin(); + it!=firp->getInstructions().end(); ++it ) { - Instruction_t* insn=*it; - if(insn->IsSyscall()) + auto insn=*it; + if(insn->getDisassembly()=="int 0x80") { SyscallNumber_t num=FindSystemCallNumber(insn, preds); syscalls.insert(SyscallSite_t(insn,num)); found_one=true; if(getenv("PRINTSYSCALLSFOUND")) - cout<<"Found system call "<< insn->GetBaseID()<< ":'"<< insn->getDisassembly() << "' with eax value "<< (size_t)num<<endl; + cout<<"Found system call "<< insn->getBaseID()<< ":'"<< insn->getDisassembly() << "' with eax value "<< (size_t)num<<endl; } } return found_one; diff --git a/libIRDB/src/util/IBT_Provenance.cpp b/libIRDB/src/util/IBT_Provenance.cpp index 9956da0bd..e01d5fd34 100644 --- a/libIRDB/src/util/IBT_Provenance.cpp +++ b/libIRDB/src/util/IBT_Provenance.cpp @@ -11,24 +11,25 @@ using namespace std; Provenance_t IBTProvenance_t::empty; -void IBTProvenance_t::AddFile(const FileIR_t* firp) +void IBTProvenance_t::AddFile(const IRDB_SDK::FileIR_t* firp) { - using ICFSProvMap_t = std::map<const ICFS_t*, Provenance_t>; + using ICFSProvMap_t = std::map<const IRDB_SDK::ICFS_t*, Provenance_t>; auto icfs_prov_map = ICFSProvMap_t(); // collect before info for each icfs into icfs_prov_map - for(auto insn : firp->GetInstructions()) + for(auto insn : firp->getInstructions()) { - const auto &ibTargets=insn->GetIBTargets(); + const auto &ibTargets=insn->getIBTargets(); if(!ibTargets) continue; auto this_prov=Provenance_t(); - const auto IndBranchAsm=DecodedInstruction_t(insn); - const auto isIndJmp = IndBranchAsm.isUnconditionalBranch() && !IndBranchAsm.getOperand(0).isConstant(); - const auto isIndCall = IndBranchAsm.isCall() && !IndBranchAsm.getOperand(0).isConstant(); + const auto p_IndBranchAsm=DecodedInstruction_t::factory(insn); + const auto &IndBranchAsm=*p_IndBranchAsm; + const auto isIndJmp = IndBranchAsm.isUnconditionalBranch() && !IndBranchAsm.getOperand(0)->isConstant(); + const auto isIndCall = IndBranchAsm.isCall() && !IndBranchAsm.getOperand(0)->isConstant(); const auto isRet = IndBranchAsm.isReturn(); if(isIndJmp) @@ -52,7 +53,7 @@ void IBTProvenance_t::AddFile(const FileIR_t* firp) } // deploy info for each target of the icfs - for(const auto &icfs : firp->GetAllICFS()) + for(const auto &icfs : firp->getAllICFS()) { assert(icfs); for(const auto &insn : *icfs) diff --git a/libIRDB/src/util/SConscript b/libIRDB/src/util/SConscript index 2e773c30e..48715cc08 100644 --- a/libIRDB/src/util/SConscript +++ b/libIRDB/src/util/SConscript @@ -12,6 +12,7 @@ files= ''' params.cpp ''' cpppath=''' + $IRDB_SDK/include/ $SECURITY_TRANSFORMS_HOME/include/ $SECURITY_TRANSFORMS_HOME/libIRDB/include/ ''' diff --git a/libIRDB/src/util/insn_preds.cpp b/libIRDB/src/util/insn_preds.cpp index d50a923a4..dc88e5c24 100644 --- a/libIRDB/src/util/insn_preds.cpp +++ b/libIRDB/src/util/insn_preds.cpp @@ -29,39 +29,39 @@ using namespace std; -void InstructionPredecessors_t::AddPreds(const Instruction_t* before, const InstructionSet_t& afterset) +void InstructionPredecessors_t::AddPreds(const IRDB_SDK::Instruction_t* before, const InstructionSet_t& afterset) { - for(InstructionSet_t::const_iterator it=afterset.begin(); it!=afterset.end(); ++it) + for(auto it=afterset.begin(); it!=afterset.end(); ++it) { - pred_map[*it].insert((libIRDB::Instruction_t*)before); + pred_map[*it].insert(const_cast<IRDB_SDK::Instruction_t*>(before)); } } -void InstructionPredecessors_t::AddPred(const Instruction_t* before, const Instruction_t* after) +void InstructionPredecessors_t::AddPred(const IRDB_SDK::Instruction_t* before, const IRDB_SDK::Instruction_t* after) { assert(before); if(!after) return; if(getenv("DUMP_PRED_CREATE")) - cout<<"Found "<<after->GetBaseID()<<":"<<after->getDisassembly() << " follows "<< before->GetBaseID()<<":"<<before->getDisassembly()<<endl; - pred_map[after].insert((Instruction_t*)before); + cout<<"Found "<<after->getBaseID()<<":"<<after->getDisassembly() << " follows "<< before->getBaseID()<<":"<<before->getDisassembly()<<endl; + pred_map[after].insert(const_cast<IRDB_SDK::Instruction_t*>(before)); } -void InstructionPredecessors_t::AddFile(const FileIR_t* firp2) +void InstructionPredecessors_t::AddFile(const IRDB_SDK::FileIR_t* firp2) { - FileIR_t* firp=(FileIR_t*)firp2; // discarding const qualifier because we know we won't change the set - for(InstructionSet_t::const_iterator it=firp->GetInstructions().begin(); - it!=firp->GetInstructions().end(); + auto firp=const_cast<IRDB_SDK::FileIR_t*>(firp2); // discarding const qualifier because we know we won't change the set + for(auto it=firp->getInstructions().begin(); + it!=firp->getInstructions().end(); ++it) { - Instruction_t* insn=*it; - AddPred(insn, insn->GetTarget()); - AddPred(insn, insn->GetFallthrough()); + auto insn=*it; + AddPred(insn, insn->getTarget()); + AddPred(insn, insn->getFallthrough()); // if we have a complete list, then explicitly add them. - if(insn->GetIBTargets() && insn->GetIBTargets()->IsComplete()) - AddPreds(insn, *insn->GetIBTargets()); + if(insn->getIBTargets() && insn->getIBTargets()->isComplete()) + AddPreds(insn, *insn->getIBTargets()); } } diff --git a/libIRDB/src/util/params.cpp b/libIRDB/src/util/params.cpp index 2d3448949..3f1cf1573 100644 --- a/libIRDB/src/util/params.cpp +++ b/libIRDB/src/util/params.cpp @@ -27,45 +27,32 @@ using namespace libIRDB; using namespace std; // Does instruction potentially write to a parameter to a call? -bool libIRDB::IsParameterWrite(const FileIR_t *firp, Instruction_t* insn, string& output_dst) +bool libIRDB::IsParameterWrite(const IRDB_SDK::FileIR_t *firp, IRDB_SDK::Instruction_t* insn, string& output_dst) { -// auto d=DISASM({0}); -// Disassemble(insn,d); - const auto d=DecodedInstruction_t(insn); + const auto p_d=DecodedInstruction_t::factory(insn); + const auto &d=*p_d; -// if(d.Argument1.AccessMode!=WRITE) if(!d.hasOperand(0)) return false; - if(!d.getOperand(0).isWritten()) + if(!d.getOperand(0)->isWritten()) return false; /* 64 bit machines use regs to pass parameters */ - if(firp->GetArchitectureBitWidth()==64) + if(firp->getArchitectureBitWidth()==64) { // if it's a register -// if((d.Argument1.ArgType®ISTER_TYPE)==REGISTER_TYPE) - if(d.getOperand(0).isGeneralPurposeRegister()) + if(d.getOperand(0)->isGeneralPurposeRegister()) { -// int regno=(d.Argument1.ArgType)&0xFFFF; - int regno=d.getOperand(0).getRegNumber(); + int regno=d.getOperand(0)->getRegNumber(); switch(regno) { -/* - case REG7: // rdi - case REG6: // rsi - case REG2: // rdx - case REG1: // rcx - case REG8: // r8 - case REG9: // r9 -*/ case 1: // rcx? case 2: // rdx? case 6: // rsi? case 7: // rdi? case 8: // r8? case 9: // r9? -// output_dst=d.Argument1.ArgMnemonic; - output_dst=d.getOperand(0).getString(); + output_dst=d.getOperand(0)->getString(); return true; // other regsiters == no. @@ -79,36 +66,31 @@ bool libIRDB::IsParameterWrite(const FileIR_t *firp, Instruction_t* insn, string // not a register or not 64-bit. check for [esp+k] // check for memory type -// if((d.Argument1.ArgType&MEMORY_TYPE)!=MEMORY_TYPE) - if(!d.getOperand(0).isMemory()) + if(!d.getOperand(0)->isMemory()) return false; // check that base reg is esp. -// if(d.Argument1.Memory.BaseRegister != REG4) - if(!d.getOperand(0).hasBaseRegister()) + if(!d.getOperand(0)->hasBaseRegister()) return false; - if(d.getOperand(0).getBaseRegister() != 4) + if(d.getOperand(0)->getBaseRegister() != 4) return false; // check that there's no index reg -// if(d.Argument1.Memory.IndexRegister != 0) - if(d.getOperand(0).hasIndexRegister()) + if(d.getOperand(0)->hasIndexRegister()) return false; // get k out of [esp + k ] -// unsigned int k=d.Argument1.Memory.Displacement; - if (!d.getOperand(0).hasMemoryDisplacement()) + if (!d.getOperand(0)->hasMemoryDisplacement()) return false; - const auto k=d.getOperand(0).getMemoryDisplacement(); + const auto k=d.getOperand(0)->getMemoryDisplacement(); // check that we know the frame layout. - if(insn->GetFunction() == NULL) + if(insn->getFunction() == NULL) return false; - if(k < insn->GetFunction()->GetOutArgsRegionSize()) + if(k < insn->getFunction()->getOutArgsRegionSize()) { -// output_dst=string("[")+d.Argument1.ArgMnemonic+string("]"); - output_dst=string("[")+d.getOperand(0).getString()+string("]"); + output_dst=string("[")+d.getOperand(0)->getString()+string("]"); return true; } @@ -121,35 +103,33 @@ bool libIRDB::IsParameterWrite(const FileIR_t *firp, Instruction_t* insn, string // (1) call instruction // (2) call converted to push/jmp pair // -static Instruction_t* IsOrWasCall(const FileIR_t *firp, Instruction_t* insn) +static IRDB_SDK::Instruction_t* IsOrWasCall(const IRDB_SDK::FileIR_t *firp, IRDB_SDK::Instruction_t* insn) { if (firp == NULL || insn == NULL) return NULL; -// auto d=DISASM({0}); -// Disassemble(insn,d); - const auto d=DecodedInstruction_t(insn); + const auto p_d=DecodedInstruction_t::factory(insn); + const auto &d=*p_d; -// if(d.Instruction.Mnemonic == string("call ")) if(d.isCall()) { - return insn->GetTarget(); + return insn->getTarget(); } else { // look for "push64" or "fix_call_fallthrough" reloc - auto it = std::find_if(insn->GetRelocations().begin(),insn->GetRelocations().end(),[&](const Relocation_t* reloc) + auto it = std::find_if(insn->getRelocations().begin(),insn->getRelocations().end(),[&](const IRDB_SDK::Relocation_t* reloc) { - return (reloc && ((reloc->GetType() == string("push64")) || reloc->GetType() == string("fix_call_fallthrough"))); + return (reloc && ((reloc->getType() == string("push64")) || reloc->getType() == string("fix_call_fallthrough"))); }); // find actual target - if (it != insn->GetRelocations().end()) + if (it != insn->getRelocations().end()) { - if (insn->GetTarget()) - return insn->GetTarget(); - else if (insn->GetFallthrough()) - return insn->GetFallthrough()->GetTarget(); + if (insn->getTarget()) + return insn->getTarget(); + else if (insn->getFallthrough()) + return insn->getFallthrough()->getTarget(); } } @@ -157,7 +137,7 @@ static Instruction_t* IsOrWasCall(const FileIR_t *firp, Instruction_t* insn) } // Does a call follow the instruction? -bool libIRDB::CallFollows(const FileIR_t *firp, Instruction_t* insn, const string& reg_arg_str, const std::string &fn_pattern) +bool libIRDB::CallFollows(const IRDB_SDK::FileIR_t *firp, IRDB_SDK::Instruction_t* insn, const string& reg_arg_str, const std::string &fn_pattern) { const std::set<std::string> param_regs = {"rdi", "rsi", "rdx", "rcx", "r8", "r9"}; const bool original_is_param_register = param_regs.find(reg_arg_str) != param_regs.end(); @@ -165,11 +145,10 @@ bool libIRDB::CallFollows(const FileIR_t *firp, Instruction_t* insn, const strin std::set<std::string> live_params; live_params.insert(reg_arg_str); - for(Instruction_t* ptr=insn->GetFallthrough(); ptr!=NULL; ptr=ptr->GetFallthrough()) + for(auto ptr=insn->getFallthrough(); ptr!=NULL; ptr=ptr->getFallthrough()) { -// auto d=DISASM({0}); -// Disassemble(ptr,d); - const auto d=DecodedInstruction_t(ptr); + const auto p_d=DecodedInstruction_t::factory(ptr); + const auto &d=*p_d; const auto tgt = IsOrWasCall(firp, ptr); if (tgt) @@ -185,10 +164,10 @@ bool libIRDB::CallFollows(const FileIR_t *firp, Instruction_t* insn, const strin // look for specific function // check the target has a function - if(tgt->GetFunction()==NULL) + if(tgt->getFunction()==NULL) return false; - const auto fname = tgt->GetFunction()->GetName(); + const auto fname = tgt->getFunction()->getName(); // std::cout << "CallFollows(): yes, parameter to call: function name: " << fname << endl; return fname.find(fn_pattern)!=string::npos; } @@ -196,7 +175,6 @@ bool libIRDB::CallFollows(const FileIR_t *firp, Instruction_t* insn, const strin // found reference to argstring, original code would just stop the search // need more sophisticated heuristic -// if(string(d.CompleteInstr).find(reg_arg_str)!= string::npos) if(d.getDisassembly().find(reg_arg_str)!= string::npos) { if (original_is_param_register) @@ -213,7 +191,7 @@ bool libIRDB::CallFollows(const FileIR_t *firp, Instruction_t* insn, const strin else { // if (std::string(d.Argument2.ArgMnemonic) == reg_arg_str) { - if (d.hasOperand(1) && d.getOperand(1).getString() == reg_arg_str) { + if (d.hasOperand(1) && d.getOperand(1)->getString() == reg_arg_str) { // std::cout << "CallFollows(): " << ptr->getDisassembly() << ": copy of original detected: add to live list: " << arg << std::endl; live_params.insert(arg); } @@ -240,11 +218,8 @@ bool libIRDB::CallFollows(const FileIR_t *firp, Instruction_t* insn, const strin return false; } -bool libIRDB::FlowsIntoCall(const FileIR_t *firp, Instruction_t* insn) +bool libIRDB::FlowsIntoCall(const IRDB_SDK::FileIR_t *firp, IRDB_SDK::Instruction_t* insn) { - //auto d=DISASM({0}); - //Disassemble(insn,d); - string param_write; if (!libIRDB::IsParameterWrite(firp, insn, param_write)) return false; @@ -252,29 +227,21 @@ bool libIRDB::FlowsIntoCall(const FileIR_t *firp, Instruction_t* insn) return CallFollows(firp, insn, param_write); } -bool libIRDB::LeaFlowsIntoCall(const FileIR_t *firp, Instruction_t* insn) +bool libIRDB::LeaFlowsIntoCall(const IRDB_SDK::FileIR_t *firp, IRDB_SDK::Instruction_t* insn) { -// auto d=DISASM({0}); -// Disassemble(insn,d); - const auto d=DecodedInstruction_t(insn); + const auto d=DecodedInstruction_t::factory(insn); -// if(string(d.Instruction.Mnemonic)!="lea ") -// return false; - if (d.getMnemonic()!="lea") + if (d->getMnemonic()!="lea") return false; return FlowsIntoCall(firp, insn); } -bool libIRDB::LeaFlowsIntoPrintf(const FileIR_t *firp, Instruction_t* insn) +bool libIRDB::LeaFlowsIntoPrintf(const IRDB_SDK::FileIR_t *firp, IRDB_SDK::Instruction_t* insn) { -// auto d=DISASM({0}); -// Disassemble(insn,d); - const auto d=DecodedInstruction_t(insn); + const auto d=DecodedInstruction_t::factory(insn); -// if(string(d.Instruction.Mnemonic)!="lea ") -// return false; - if (d.getMnemonic()!="lea") + if (d->getMnemonic()!="lea") return false; // std::cout << "LeaFlowsIntoCall(): investigating " << insn->getDisassembly() << endl; diff --git a/libtransform/include/Rewrite_Utility.hpp b/libtransform/include/Rewrite_Utility.hpp index 04f000067..7a9f1f90a 100644 --- a/libtransform/include/Rewrite_Utility.hpp +++ b/libtransform/include/Rewrite_Utility.hpp @@ -18,12 +18,12 @@ * */ -#include <libIRDB-core.hpp> +#include <irdb-core> -using namespace libIRDB; -using namespace std; namespace IRDBUtility { +using namespace IRDB_SDK; +using namespace std; //The "first" instruction will have its contents replaced and a duplicate of "first" will be in the follow of first. //This duplicate is returned since the user already has a pointer to first. @@ -50,7 +50,7 @@ Instruction_t* copyInstruction(FileIR_t* virp, Instruction_t* instr); //copy src to destination void copyInstruction(Instruction_t* src, Instruction_t* dest); -Instruction_t* allocateNewInstruction(FileIR_t* virp, db_id_t p_fileID,Function_t* func); +Instruction_t* allocateNewInstruction(FileIR_t* virp, DatabaseID_t p_fileID,Function_t* func); Instruction_t* allocateNewInstruction(FileIR_t* virp, Instruction_t *template_instr); void setInstructionAssembly(FileIR_t* virp,Instruction_t *p_instr, string p_assembly, Instruction_t *p_fallThrough, Instruction_t *p_target); diff --git a/libtransform/include/transform.hpp b/libtransform/include/transform.hpp index 775acf9c9..325fa40d6 100644 --- a/libtransform/include/transform.hpp +++ b/libtransform/include/transform.hpp @@ -25,21 +25,26 @@ #include <set> #include <map> -#include <libIRDB-core.hpp> +#include <irdb-core> #include "MEDS_InstructionCheckAnnotation.hpp" #include "VirtualOffset.hpp" -using namespace std; -using namespace libIRDB; -using namespace MEDS_Annotation; - #define MAX_ASSEMBLY_SIZE 2048 +namespace libIRDB +{ + class FileIR_t; +} namespace libTransform { +using namespace std; +using namespace IRDB_SDK; +using namespace MEDS_Annotation; -class Transform { + +class Transform +{ public: Transform(VariantID_t *, FileIR_t *, set<std::string> *p_filteredFunctions); @@ -85,18 +90,14 @@ class Transform { void addMulRegisterConstant(Instruction_t *p_instr, RegisterName p_regTgt, int p_constantValue, Instruction_t *p_fallThrough); void addMovRegisters(Instruction_t *p_instr, RegisterName p_regTgt, RegisterName p_regSrc, Instruction_t *p_fallThrough); - Instruction_t* allocateNewInstruction(db_id_t p_fileID=BaseObj_t::NOT_IN_DATABASE, Function_t* p_func=NULL); + Instruction_t* allocateNewInstruction(DatabaseID_t p_fileID=BaseObj_t::NOT_IN_DATABASE, Function_t* p_func=NULL); - virtual_offset_t getAvailableAddress(); + VirtualOffset_t getAvailableAddress(); VariantID_t* getVariantID() { return m_variantID; } - FileIR_t* getFileIR() { return m_fileIR; } + FileIR_t* getFileIR(); // { return dynamic_cast<FileIR_t*>(m_fileIR); } set<std::string>* getFilteredFunctions() { return m_filteredFunctions; } - // bool isMultiplyInstruction(libIRDB::Instruction_t*); - //bool isMovInstruction(libIRDB::Instruction_t*); - //bool isAddSubNonEspInstruction(libIRDB::Instruction_t*); - //RegisterName getTargetRegister(libIRDB::Instruction_t*, int argNo = 1); Instruction_t* addNewMaxSaturation(Instruction_t *p_prev, RegisterName p_reg, const MEDS_InstructionCheckAnnotation p_annotation); void addMinSaturation(Instruction_t *p_instruction, RegisterName p_reg, const MEDS_InstructionCheckAnnotation& p_annotation, Instruction_t *p_fallthrough); void addMaxSaturation(Instruction_t *p_instruction, RegisterName p_reg, const MEDS_InstructionCheckAnnotation& p_annotation, Instruction_t *p_fallthrough); @@ -114,10 +115,9 @@ class Transform { void addTestRegister32(Instruction_t *p_instr, RegisterName, Instruction_t *p_fallThrough); void addTestRegisterMask32(Instruction_t *p_instr, RegisterName, unsigned p_mask, Instruction_t *p_fallThrough); void addCmpRegisterMask32(Instruction_t *p_instr, RegisterName, unsigned p_mask, Instruction_t *p_fallThrough); - //bool hasTargetRegister(libIRDB::Instruction_t*, int argNo = 1); VariantID_t *m_variantID; - FileIR_t *m_fileIR; + libIRDB::FileIR_t *m_fileIR; set<std::string> *m_filteredFunctions; std::map<std::string, Instruction_t*> m_handlerMap; }; diff --git a/libtransform/src/Rewrite_Utility.cpp b/libtransform/src/Rewrite_Utility.cpp index 6df133421..9d434ad11 100644 --- a/libtransform/src/Rewrite_Utility.cpp +++ b/libtransform/src/Rewrite_Utility.cpp @@ -20,34 +20,34 @@ #include "Rewrite_Utility.hpp" +#include <libIRDB-core.hpp> + // Copied from PnTransform // @todo: create a utility library with the one interface using namespace std; -using namespace libIRDB; - -using namespace IRDBUtility; - -namespace IRDBUtility { -map<Function_t*, set<Instruction_t*> > inserted_instr; //used to undo inserted instructions -map<Function_t*, set<AddressID_t*> > inserted_addr; //used to undo inserted addresses +namespace IRDBUtility +{ -void setExitCode(FileIR_t* virp, Instruction_t* exit_code); +void setExitCode(FileIR_t* virp, IRDB_SDK::Instruction_t* exit_code); -void setInstructionDataBits(FileIR_t* virp, Instruction_t *p_instr, string p_dataBits, Instruction_t *p_fallThrough, Instruction_t *p_target) +void setInstructionsDetails(FileIR_t* virp, IRDB_SDK::Instruction_t *p_instr, string p_dataBits, IRDB_SDK::Instruction_t *p_fallThrough, IRDB_SDK::Instruction_t *p_target) { if (p_instr == NULL) return; - p_instr->SetDataBits(p_dataBits); - p_instr->SetComment(p_instr->getDisassembly()); - p_instr->SetFallthrough(p_fallThrough); - p_instr->SetTarget(p_target); + p_instr->setDataBits(p_dataBits); + p_instr->setComment(p_instr->getDisassembly()); + p_instr->setFallthrough(p_fallThrough); + p_instr->setTarget(p_target); - virp->GetAddresses().insert(p_instr->GetAddress()); - virp->GetInstructions().insert(p_instr); + auto real_virp=dynamic_cast<libIRDB::FileIR_t*>(virp); + assert(real_virp); + + real_virp->GetAddresses().insert(p_instr->getAddress()); + real_virp->GetInstructions().insert(p_instr); } @@ -56,126 +56,130 @@ void setInstructionDataBits(FileIR_t* virp, Instruction_t *p_instr, string p_dat //This duplicate is returned since the user already has a pointer to first. //To insert before an instruction is the same as modifying the original instruction, and inserting after it //a copy of the original instruction -Instruction_t* insertAssemblyBefore(FileIR_t* virp, Instruction_t* first, string assembly, Instruction_t *target) +IRDB_SDK::Instruction_t* insertAssemblyBefore(IRDB_SDK::FileIR_t* virp, IRDB_SDK::Instruction_t* first, string assembly, IRDB_SDK::Instruction_t *target) { - Instruction_t* next = copyInstruction(virp,first); + IRDB_SDK::Instruction_t* next = copyInstruction(virp,first); //In case the fallthrough is null, generate spri has to have a //place to jump, which is determined by the original address. //This code is not placed in copyInstruction since this is only needed //when inserting before - next->SetOriginalAddressID(first->GetOriginalAddressID()); + next->setOriginalAddressID(first->getOriginalAddressID()); //"Null" out the original address (it should be as if the instruction was not in the database). - first->SetOriginalAddressID(BaseObj_t::NOT_IN_DATABASE); - first->GetRelocations().clear(); - first->SetIBTargets(NULL); + first->setOriginalAddressID(BaseObj_t::NOT_IN_DATABASE); + auto real_first=dynamic_cast<libIRDB::Instruction_t*>(first); + assert(real_first); + real_first->GetRelocations().clear(); + first->setIBTargets(NULL); //Note that the instruction just inserted should have the same exception handling //info as the instructions immediately around it. //Thus the exception handling information (EhCallSite and EhProgram) are kept the //same from the copy of first (unlike with relocations and IBT's). - virp->ChangeRegistryKey(first,next); + virp->changeRegistryKey(first,next); setInstructionAssembly(virp,first,assembly,next,target); return next; } -Instruction_t* insertAssemblyBefore(FileIR_t* virp, Instruction_t* first, string assembly) +IRDB_SDK::Instruction_t* insertAssemblyBefore(FileIR_t* virp, IRDB_SDK::Instruction_t* first, string assembly) { return insertAssemblyBefore(virp,first,assembly,NULL); } -Instruction_t* insertDataBitsBefore(FileIR_t* virp, Instruction_t* first, string dataBits) +IRDB_SDK::Instruction_t* insertDataBitsBefore(FileIR_t* virp, IRDB_SDK::Instruction_t* first, string dataBits) { return insertDataBitsBefore(virp,first,dataBits,NULL); } -Instruction_t* insertDataBitsBefore(FileIR_t* virp, Instruction_t* first, string dataBits, Instruction_t *target) +IRDB_SDK::Instruction_t* insertDataBitsBefore(FileIR_t* virp, IRDB_SDK::Instruction_t* first, string dataBits, IRDB_SDK::Instruction_t *target) { - Instruction_t* next = copyInstruction(virp,first); + IRDB_SDK::Instruction_t* next = copyInstruction(virp,first); //In case the fallthrough is null, generate spri has to have a //place to jump, which is determined by the original address. //This code is not placed in copyInstruction since this is only needed //when inserting before - next->SetOriginalAddressID(first->GetOriginalAddressID()); + next->setOriginalAddressID(first->getOriginalAddressID()); //"Null" out the original address (it should be as if the instruction was not in the database). - first->SetOriginalAddressID(BaseObj_t::NOT_IN_DATABASE); - first->GetRelocations().clear(); - first->SetIBTargets(NULL); + first->setOriginalAddressID(BaseObj_t::NOT_IN_DATABASE); + auto real_first=dynamic_cast<libIRDB::Instruction_t*>(first); + assert(real_first); + real_first->GetRelocations().clear(); + first->setIBTargets(NULL); //Note that the instruction just inserted should have the same exception handling //info as the instructions immediately around it. //Thus the exception handling information (EhCallSite and EhProgram) are kept the //same from the copy of first (unlike with relocations and IBT's). - virp->ChangeRegistryKey(first,next); - setInstructionDataBits(virp,first,dataBits,next,target); + virp->changeRegistryKey(first,next); + setInstructionsDetails(virp,first,dataBits,next,target); return next; } -Instruction_t* insertAssemblyAfter(FileIR_t* virp, Instruction_t* first, string assembly, Instruction_t *target) +IRDB_SDK::Instruction_t* insertAssemblyAfter(IRDB_SDK::FileIR_t* virp, IRDB_SDK::Instruction_t* first, string assembly, IRDB_SDK::Instruction_t *target) { - Instruction_t *new_instr = allocateNewInstruction(virp,first); - setInstructionAssembly(virp,new_instr,assembly,first->GetFallthrough(), target); - first->SetFallthrough(new_instr); + IRDB_SDK::Instruction_t *new_instr = allocateNewInstruction(virp,first); + setInstructionAssembly(virp,new_instr,assembly,first->getFallthrough(), target); + first->setFallthrough(new_instr); return new_instr; } -Instruction_t* insertAssemblyAfter(FileIR_t* virp, Instruction_t* first, string assembly) +IRDB_SDK::Instruction_t* insertAssemblyAfter(IRDB_SDK::FileIR_t* virp, IRDB_SDK::Instruction_t* first, string assembly) { return insertAssemblyAfter(virp,first,assembly,NULL); } -Instruction_t* insertDataBitsAfter(FileIR_t* virp, Instruction_t* first, string dataBits, Instruction_t *target) +IRDB_SDK::Instruction_t* insertDataBitsAfter(IRDB_SDK::FileIR_t* virp, IRDB_SDK::Instruction_t* first, string dataBits, IRDB_SDK::Instruction_t *target) { - Instruction_t *new_instr = allocateNewInstruction(virp,first); - setInstructionDataBits(virp,new_instr,dataBits,first->GetFallthrough(), target); - first->SetFallthrough(new_instr); + IRDB_SDK::Instruction_t *new_instr = allocateNewInstruction(virp,first); + setInstructionsDetails(virp,new_instr,dataBits,first->getFallthrough(), target); + first->setFallthrough(new_instr); return new_instr; } -Instruction_t* insertDataBitsAfter(FileIR_t* virp, Instruction_t* first, string dataBits) +IRDB_SDK::Instruction_t* insertDataBitsAfter(IRDB_SDK::FileIR_t* virp, IRDB_SDK::Instruction_t* first, string dataBits) { return insertDataBitsAfter(virp,first,dataBits,NULL); } -Instruction_t* addNewDatabits(FileIR_t* firp, Instruction_t *p_instr, string p_bits) +IRDB_SDK::Instruction_t* addNewDatabits(IRDB_SDK::FileIR_t* firp, IRDB_SDK::Instruction_t *p_instr, string p_bits) { - Instruction_t* newinstr; + IRDB_SDK::Instruction_t* newinstr; if (p_instr) - newinstr = allocateNewInstruction(firp,p_instr->GetAddress()->GetFileID(), p_instr->GetFunction()); + newinstr = allocateNewInstruction(firp,p_instr->getAddress()->getFileID(), p_instr->getFunction()); else - newinstr = allocateNewInstruction(firp,firp->GetFile()->GetFileID(), NULL); + newinstr = allocateNewInstruction(firp,firp->getFile()->getFileID(), NULL); - newinstr->SetDataBits(p_bits); + newinstr->setDataBits(p_bits); if (p_instr) { - newinstr->SetFallthrough(p_instr->GetFallthrough()); - p_instr->SetFallthrough(newinstr); + newinstr->setFallthrough(p_instr->getFallthrough()); + p_instr->setFallthrough(newinstr); } return newinstr; } -Instruction_t* addNewAssembly(FileIR_t* firp, Instruction_t *p_instr, string p_asm) +IRDB_SDK::Instruction_t* addNewAssembly(FileIR_t* firp, IRDB_SDK::Instruction_t *p_instr, string p_asm) { - Instruction_t* newinstr; + IRDB_SDK::Instruction_t* newinstr; if (p_instr) - newinstr = allocateNewInstruction(firp,p_instr->GetAddress()->GetFileID(), p_instr->GetFunction()); + newinstr = allocateNewInstruction(firp,p_instr->getAddress()->getFileID(), p_instr->getFunction()); else - newinstr = allocateNewInstruction(firp,firp->GetFile()->GetFileID(), NULL); + newinstr = allocateNewInstruction(firp,firp->getFile()->getFileID(), NULL); - firp->RegisterAssembly(newinstr, p_asm); + firp->registerAssembly(newinstr, p_asm); if (p_instr) { - newinstr->SetFallthrough(p_instr->GetFallthrough()); - p_instr->SetFallthrough(newinstr); + newinstr->setFallthrough(p_instr->getFallthrough()); + p_instr->setFallthrough(newinstr); } return newinstr; @@ -187,77 +191,86 @@ Instruction_t* addNewAssembly(FileIR_t* firp, Instruction_t *p_instr, string p_a //Does not insert into any variant -Instruction_t* copyInstruction(Instruction_t* instr) +IRDB_SDK::Instruction_t* copyInstruction(IRDB_SDK::Instruction_t* instr) { - Instruction_t* cpy = new Instruction_t(); + IRDB_SDK::Instruction_t* cpy = new libIRDB::Instruction_t(); copyInstruction(instr,cpy); return cpy; } -Instruction_t* copyInstruction(FileIR_t* virp, Instruction_t* instr) +IRDB_SDK::Instruction_t* copyInstruction(IRDB_SDK::FileIR_t* virp, IRDB_SDK::Instruction_t* instr) { - Instruction_t* cpy = allocateNewInstruction(virp,instr); + IRDB_SDK::Instruction_t* cpy = allocateNewInstruction(virp,instr); copyInstruction(instr,cpy); return cpy; } -void copyInstruction(Instruction_t* src, Instruction_t* dest) +void copyInstruction(IRDB_SDK::Instruction_t* src, IRDB_SDK::Instruction_t* dest) { - dest->SetDataBits(src->GetDataBits()); - dest->SetComment(src->GetComment()); - dest->SetCallback(src->GetCallback()); - dest->SetFallthrough(src->GetFallthrough()); - dest->SetTarget(src->GetTarget()); - dest->SetIBTargets(src->GetIBTargets()); - dest->GetRelocations()=src->GetRelocations(); - dest->SetEhProgram(src->GetEhProgram()); - dest->SetEhCallSite(src->GetEhCallSite()); + auto real_dest=dynamic_cast<libIRDB::Instruction_t*>(dest); + dest->setDataBits(src->getDataBits()); + dest->setComment(src->getComment()); + dest->setCallback(src->getCallback()); + dest->setFallthrough(src->getFallthrough()); + dest->setTarget(src->getTarget()); + dest->setIBTargets(src->getIBTargets()); + real_dest->GetRelocations()=src->getRelocations(); + dest->setEhProgram(src->getEhProgram()); + dest->setEhCallSite(src->getEhCallSite()); } -Instruction_t* allocateNewInstruction(FileIR_t* virp, db_id_t p_fileID,Function_t* func) +IRDB_SDK::Instruction_t* allocateNewInstruction(IRDB_SDK::FileIR_t* virp, IRDB_SDK::DatabaseID_t p_fileID,IRDB_SDK::Function_t* func) { - Instruction_t *instr = new Instruction_t(); - AddressID_t *a =new AddressID_t(); + auto instr = new libIRDB::Instruction_t(); + auto a = new libIRDB::AddressID_t(); - a->SetFileID(p_fileID); + a->setFileID(p_fileID); - instr->SetFunction(func); - instr->SetAddress(a); + instr->setFunction(func); + instr->setAddress(a); if(func) - func->GetInstructions().insert(instr); - - virp->GetInstructions().insert(instr); - virp->GetAddresses().insert(a); - - inserted_instr[func].insert(instr); - inserted_addr[func].insert(a); + { + auto real_func=dynamic_cast<libIRDB::Function_t*>(func); + assert(func); + real_func->GetInstructions().insert(instr); + } + + auto real_virp=dynamic_cast<libIRDB::FileIR_t*>(virp); + assert(real_virp); + real_virp->GetInstructions().insert(instr); + real_virp->GetAddresses().insert(a); + +// inserted_instr[func].insert(instr); +// inserted_addr[func].insert(a); return instr; } -Instruction_t* allocateNewInstruction(FileIR_t* virp, Instruction_t *template_instr) +IRDB_SDK::Instruction_t* allocateNewInstruction(IRDB_SDK::FileIR_t* virp, IRDB_SDK::Instruction_t *template_instr) { - Function_t *func = template_instr->GetFunction(); - db_id_t fileID = template_instr->GetAddress()->GetFileID(); + Function_t *func = template_instr->getFunction(); + DatabaseID_t fileID = template_instr->getAddress()->getFileID(); return allocateNewInstruction(virp, fileID, func); } -void setInstructionAssembly(FileIR_t* virp,Instruction_t *p_instr, string p_assembly, Instruction_t *p_fallThrough, Instruction_t *p_target) +void setInstructionAssembly(IRDB_SDK::FileIR_t* virp,IRDB_SDK::Instruction_t *p_instr, string p_assembly, IRDB_SDK::Instruction_t *p_fallThrough, IRDB_SDK::Instruction_t *p_target) { if (p_instr == NULL) return; ///TODO: what if bad assembly? - virp->RegisterAssembly(p_instr,p_assembly); - p_instr->SetComment(p_assembly); - p_instr->SetFallthrough(p_fallThrough); - p_instr->SetTarget(p_target); - - virp->GetAddresses().insert(p_instr->GetAddress()); - virp->GetInstructions().insert(p_instr); + virp->registerAssembly(p_instr,p_assembly); + p_instr->setComment(p_assembly); + p_instr->setFallthrough(p_fallThrough); + p_instr->setTarget(p_target); + + auto real_virp=dynamic_cast<libIRDB::FileIR_t*>(virp); + assert(real_virp); + real_virp->GetAddresses().insert(p_instr->getAddress()); + real_virp->GetInstructions().insert(p_instr); } diff --git a/libtransform/src/SConscript b/libtransform/src/SConscript index d075920eb..8b64934eb 100644 --- a/libtransform/src/SConscript +++ b/libtransform/src/SConscript @@ -10,6 +10,7 @@ myenv.Replace(SECURITY_TRANSFORMS_HOME=os.environ['SECURITY_TRANSFORMS_HOME']) files="Rewrite_Utility.cpp transform.cpp" cpppath=''' + $IRDB_SDK/include $SECURITY_TRANSFORMS_HOME/include $SECURITY_TRANSFORMS_HOME/libIRDB/include $SECURITY_TRANSFORMS_HOME/libtransform/include diff --git a/libtransform/src/integertransform32.cpp b/libtransform/src/integertransform32.cpp index 84630171a..3f63ef755 100644 --- a/libtransform/src/integertransform32.cpp +++ b/libtransform/src/integertransform32.cpp @@ -106,10 +106,10 @@ int IntegerTransform32::execute() { Instruction_t* insn=*it; - if (insn && insn->GetAddress()) + if (insn && insn->getAddress()) { int policy = POLICY_DEFAULT; // use Strata default settings - virtual_offset_t irdb_vo = insn->GetAddress()->GetVirtualOffset(); + virtual_offset_t irdb_vo = insn->getAddress()->GetVirtualOffset(); if (irdb_vo == 0) continue; VirtualOffset vo(irdb_vo); @@ -183,7 +183,7 @@ int IntegerTransform32::execute() continue; } - if (!insn->GetFallthrough()) + if (!insn->getFallthrough()) { logMessage(__func__, "Warning: no fall through for instruction -- skipping"); continue; @@ -268,7 +268,7 @@ void IntegerTransform32::addSignednessCheck(Instruction_t *p_instruction, const return; } - db_id_t fileID = p_instruction->GetAddress()->GetFileID(); + DatabaseID_t fileID = p_instruction->getAddress()->getFileID(); Function_t* func = p_instruction->GetFunction(); Instruction_t* pushf_i = allocateNewInstruction(fileID, func); @@ -279,8 +279,8 @@ void IntegerTransform32::addSignednessCheck(Instruction_t *p_instruction, const addPushf(pushf_i, test_i); Instruction_t* originalInstrumentInstr = carefullyInsertBefore(p_instruction, pushf_i); - pushf_i->SetFallthrough(test_i); - pushf_i->SetComment("-- in signedness check"); + pushf_i->setFallthrough(test_i); + pushf_i->setComment("-- in signedness check"); addTestRegister(test_i, p_annotation.getRegister(), jns_i); addJns(jns_i, nop_i, popf_i); addNop(nop_i, popf_i); @@ -300,9 +300,9 @@ void IntegerTransform32::addSignednessCheck(Instruction_t *p_instruction, const if (p_policy == POLICY_CONTINUE_SATURATING_ARITHMETIC) { // implement saturating arithmetic on register, i.e.: mov <reg>, value - Instruction_t* saturate_i = allocateNewInstruction(p_instruction->GetAddress()->GetFileID(), p_instruction->GetFunction()); + Instruction_t* saturate_i = allocateNewInstruction(p_instruction->getAddress()->getFileID(), p_instruction->GetFunction()); - addCallbackHandler(detector, originalInstrumentInstr, nop_i, saturate_i, p_policy, p_instruction->GetAddress()); + addCallbackHandler(detector, originalInstrumentInstr, nop_i, saturate_i, p_policy, p_instruction->getAddress()); if (p_annotation.isSigned()) addMaxSaturation(saturate_i, p_annotation.getRegister(), p_annotation, popf_i); else @@ -310,7 +310,7 @@ void IntegerTransform32::addSignednessCheck(Instruction_t *p_instruction, const } else { - addCallbackHandler(detector, originalInstrumentInstr, nop_i, popf_i, p_policy, p_instruction->GetAddress()); + addCallbackHandler(detector, originalInstrumentInstr, nop_i, popf_i, p_policy, p_instruction->getAddress()); } addPopf(popf_i, originalInstrumentInstr); @@ -499,7 +499,7 @@ void IntegerTransform32::addOverflowCheckNoFlag_RegPlusReg(Instruction_t *p_inst // fallthrough-->originalNext // - db_id_t fileID = p_instruction->GetAddress()->GetFileID(); + DatabaseID_t fileID = p_instruction->getAddress()->getFileID(); Function_t* func = p_instruction->GetFunction(); Instruction_t* pushr1_i = allocateNewInstruction(fileID, func); @@ -521,18 +521,18 @@ void IntegerTransform32::addOverflowCheckNoFlag_RegPlusReg(Instruction_t *p_inst addRR_annot.setUnknownSign(); string msg = "Originally: " + p_instruction->getDisassembly(); - Instruction_t* originalNextInstr = p_instruction->GetFallthrough(); - AddressID_t *originalAddress = p_instruction->GetAddress(); + Instruction_t* originalNextInstr = p_instruction->getFallthrough(); + AddressID_t *originalAddress = p_instruction->getAddress(); addPushRegister(pushr1_i, p_reg1, pushf_i); Instruction_t* originalInstrumentInstr = carefullyInsertBefore(p_instruction, pushr1_i); - pushr1_i->SetFallthrough(pushf_i); - pushr1_i->SetComment("-- carefullyInsertBefore NoFlagRegPlusReg"); + pushr1_i->setFallthrough(pushf_i); + pushr1_i->setComment("-- carefullyInsertBefore NoFlagRegPlusReg"); addPushf(pushf_i, addRR_i); addAddRegisters(addRR_i, p_reg1, p_reg2, popf_i); - addRR_i->SetComment(msg); + addRR_i->setComment(msg); addPopf(popf_i, popr1_i); addPopRegister(popr1_i, p_reg1, originalInstrumentInstr); @@ -564,7 +564,7 @@ void IntegerTransform32::addOverflowCheckNoFlag_RegPlusReg(Instruction_t *p_inst Instruction_t* popR1sat_i = allocateNewInstruction(fileID, func); Instruction_t* saturate_i = allocateNewInstruction(fileID, func); - addRR_i->SetFallthrough(j_i); + addRR_i->setFallthrough(j_i); if (p_annotation.isSigned()) { @@ -649,7 +649,7 @@ void IntegerTransform32::addOverflowCheckNoFlag_RegPlusConstant(Instruction_t *p // Note: if r3 == r1, code still works (though inefficiently) // - db_id_t fileID = p_instruction->GetAddress()->GetFileID(); + DatabaseID_t fileID = p_instruction->getAddress()->getFileID(); Function_t* func = p_instruction->GetFunction(); Instruction_t* pushR3_i = allocateNewInstruction(fileID, func); @@ -671,14 +671,14 @@ void IntegerTransform32::addOverflowCheckNoFlag_RegPlusConstant(Instruction_t *p addR3Constant_annot.setUnknownSign(); string msg = "Originally: " + p_instruction->getDisassembly(); - Instruction_t* originalNextInstr = p_instruction->GetFallthrough(); + Instruction_t* originalNextInstr = p_instruction->getFallthrough(); - AddressID_t *originalAddress = p_instruction->GetAddress(); + AddressID_t *originalAddress = p_instruction->getAddress(); addPushRegister(pushR3_i, p_reg3, pushf_i); Instruction_t* originalInstrumentInstr = carefullyInsertBefore(p_instruction, pushR3_i); - pushR3_i->SetComment("in lea -- RegPlusConstant"); - pushR3_i->SetFallthrough(pushf_i); + pushR3_i->setComment("in lea -- RegPlusConstant"); + pushR3_i->setFallthrough(pushf_i); addPushf(pushf_i, movR3R1_i); addMovRegisters(movR3R1_i, p_reg3, p_reg1, addR3Constant_i); @@ -686,7 +686,7 @@ void IntegerTransform32::addOverflowCheckNoFlag_RegPlusConstant(Instruction_t *p addPopf(popf_i, popR3_i); addPopRegister(popR3_i, p_reg3, originalInstrumentInstr); - addR3Constant_i->SetComment(msg); + addR3Constant_i->setComment(msg); if (p_policy == POLICY_CONTINUE_SATURATING_ARITHMETIC) { // (jno|jnc <restore>) ; SIGNED|UNSIGNED @@ -709,7 +709,7 @@ void IntegerTransform32::addOverflowCheckNoFlag_RegPlusConstant(Instruction_t *p Instruction_t* popR3sat_i = allocateNewInstruction(fileID, func); Instruction_t* saturate_i = allocateNewInstruction(fileID, func); - addR3Constant_i->SetFallthrough(j_i); + addR3Constant_i->setFallthrough(j_i); if (p_annotation.isSigned()) { @@ -770,7 +770,7 @@ void IntegerTransform32::addOverflowCheckNoFlag_RegTimesConstant(Instruction_t * // // Note: if r3 == r1, code still works (though inefficiently) // - db_id_t fileID = p_instruction->GetAddress()->GetFileID(); + DatabaseID_t fileID = p_instruction->getAddress()->getFileID(); Function_t* func = p_instruction->GetFunction(); Instruction_t* pushR3_i = allocateNewInstruction(fileID, func); @@ -792,14 +792,14 @@ void IntegerTransform32::addOverflowCheckNoFlag_RegTimesConstant(Instruction_t * mulR3Constant_annot.setUnknownSign(); string msg = "Originally: " + p_instruction->getDisassembly(); - Instruction_t* originalNextInstr = p_instruction->GetFallthrough(); + Instruction_t* originalNextInstr = p_instruction->getFallthrough(); - AddressID_t *originalAddress = p_instruction->GetAddress(); + AddressID_t *originalAddress = p_instruction->getAddress(); addPushRegister(pushR3_i, p_reg3, pushf_i); Instruction_t* originalInstrumentInstr = carefullyInsertBefore(p_instruction, pushR3_i); - pushR3_i->SetFallthrough(pushf_i); - pushR3_i->SetComment("in lea -- Reg * Constant"); + pushR3_i->setFallthrough(pushf_i); + pushR3_i->setComment("in lea -- Reg * Constant"); addPushf(pushf_i, movR3R1_i); addMovRegisters(movR3R1_i, p_reg3, p_reg1, mulR3Constant_i); @@ -807,7 +807,7 @@ void IntegerTransform32::addOverflowCheckNoFlag_RegTimesConstant(Instruction_t * addPopf(popf_i, popR3_i); addPopRegister(popR3_i, p_reg3, originalInstrumentInstr); - mulR3Constant_i->SetComment(msg); + mulR3Constant_i->setComment(msg); if (p_policy == POLICY_CONTINUE_SATURATING_ARITHMETIC) { @@ -824,7 +824,7 @@ void IntegerTransform32::addOverflowCheckNoFlag_RegTimesConstant(Instruction_t * Instruction_t* popR3sat_i = allocateNewInstruction(fileID, func); Instruction_t* saturate_i = allocateNewInstruction(fileID, func); - mulR3Constant_i->SetFallthrough(jo_i); + mulR3Constant_i->setFallthrough(jo_i); addOverflowCheckForLea(mulR3Constant_i, mulR3Constant_annot, p_policy, originalAddress); addJo(jo_i, popf_i, popfsat_i); @@ -843,7 +843,7 @@ void IntegerTransform32::addOverflowCheckNoFlag_RegTimesConstant(Instruction_t * void IntegerTransform32::handleFISTTruncation(Instruction_t *p_instruction){ cerr << "IntegerTransform32::handleFISTTruncation(): instr: " << p_instruction->getDisassembly() << " address: " - << p_instruction->GetAddress() << endl; + << p_instruction->getAddress() << endl; int len=0; //We skip the qword case. @@ -870,7 +870,7 @@ void IntegerTransform32::handleFISTTruncation(Instruction_t *p_instruction){ void IntegerTransform32::addFistpTruncationCheck(Instruction_t *p_instruction, int len){ if(len!=32 && len!=16) return; - db_id_t fileID = p_instruction->GetAddress()->GetFileID(); + DatabaseID_t fileID = p_instruction->getAddress()->getFileID(); Function_t* func = p_instruction->GetFunction(); string dataBits; @@ -945,7 +945,7 @@ void IntegerTransform32::addFistpTruncationCheck(Instruction_t *p_instruction, i addPusha(pusha_i, pushf_i);//pusha Instruction_t* originalInstrumentInstr = carefullyInsertBefore(p_instruction, pusha_i); - pusha_i->SetFallthrough(pushf_i); + pusha_i->setFallthrough(pushf_i); addPushf(pushf_i, sub_esp_0x70);//pushf @@ -956,55 +956,55 @@ void IntegerTransform32::addFistpTruncationCheck(Instruction_t *p_instruction, i dataBits[3] = 0x00; dataBits[4] = 0x00; dataBits[5] = 0x00; - sub_esp_0x70->SetFallthrough(fst_esp); - sub_esp_0x70->SetDataBits(dataBits); - sub_esp_0x70->SetComment(sub_esp_0x70->getDisassembly()); + sub_esp_0x70->setFallthrough(fst_esp); + sub_esp_0x70->setDataBits(dataBits); + sub_esp_0x70->setComment(sub_esp_0x70->getDisassembly()); addInstruction(sub_esp_0x70, dataBits, fst_esp, NULL); dataBits.resize(3);//fst [esp] dataBits[0] = 0xd9; dataBits[1] = 0x14; dataBits[2] = 0x24; - fst_esp->SetFallthrough(fsave_esp_4); - fst_esp->SetDataBits(dataBits); - fst_esp->SetComment(fst_esp->getDisassembly()); + fst_esp->setFallthrough(fsave_esp_4); + fst_esp->setDataBits(dataBits); + fst_esp->setComment(fst_esp->getDisassembly()); addInstruction(fst_esp, dataBits, fsave_esp_4, NULL); dataBits.resize(1);//fsave [esp+4] dataBits[0] = 0x9b; - fsave_esp_4->SetFallthrough(pushretaddress); - fsave_esp_4->SetDataBits(dataBits); - fsave_esp_4->SetComment(fsave_wait->getDisassembly()); + fsave_esp_4->setFallthrough(pushretaddress); + fsave_esp_4->setDataBits(dataBits); + fsave_esp_4->setComment(fsave_wait->getDisassembly()); addInstruction(fsave_wait, dataBits, fsave_esp_4, NULL); dataBits.resize(4); dataBits[0] = 0xdd; dataBits[1] = 0x74; dataBits[2] = 0x24; dataBits[3] = 0x04; - fsave_esp_4->SetFallthrough(pushretaddress); - fsave_esp_4->SetDataBits(dataBits); - fsave_esp_4->SetComment(fsave_esp_4->getDisassembly()); + fsave_esp_4->setFallthrough(pushretaddress); + fsave_esp_4->setDataBits(dataBits); + fsave_esp_4->setComment(fsave_esp_4->getDisassembly()); addInstruction(fsave_esp_4, dataBits, pushretaddress, NULL); virtual_offset_t AfterTheCheckerReturn = getAvailableAddress(); - nop->GetAddress()->SetVirtualOffset(AfterTheCheckerReturn); - nop->GetAddress()->SetFileID(BaseObj_t::NOT_IN_DATABASE); + nop->getAddress()->SetVirtualOffset(AfterTheCheckerReturn); + nop->getAddress()->SetFileID(BaseObj_t::NOT_IN_DATABASE); dataBits.resize(5);//push return_address dataBits[0] = 0x68; virtual_offset_t *tmp; tmp = (virtual_offset_t *) &dataBits[1]; *tmp = AfterTheCheckerReturn; - pushretaddress->SetDataBits(dataBits); - pushretaddress->SetComment(pushretaddress->getDisassembly()); - pushretaddress->SetFallthrough(nop); + pushretaddress->setDataBits(dataBits); + pushretaddress->setComment(pushretaddress->getDisassembly()); + pushretaddress->setFallthrough(nop); dataBits.resize(1);//nop dataBits[0] = 0x90; - nop->SetDataBits(dataBits); - nop->SetComment(nop->getDisassembly() + " -- with callback to floating number check") ; - nop->SetFallthrough(frstor_esp_4); - nop->SetIndirectBranchTargetAddress(nop->GetAddress()); + nop->setDataBits(dataBits); + nop->setComment(nop->getDisassembly() + " -- with callback to floating number check") ; + nop->setFallthrough(frstor_esp_4); + nop->SetIndirectBranchTargetAddress(nop->getAddress()); if(len==32) nop->SetCallback(string("FloatingRangeCheck32")); else @@ -1015,14 +1015,14 @@ void IntegerTransform32::addFistpTruncationCheck(Instruction_t *p_instruction, i dataBits[1] = 0x64; dataBits[2] = 0x24; dataBits[3] = 0x04; - frstor_esp_4->SetDataBits(dataBits); - frstor_esp_4->SetFallthrough(test_eax_0); - frstor_esp_4->SetComment(frstor_esp_4->getDisassembly()); + frstor_esp_4->setDataBits(dataBits); + frstor_esp_4->setFallthrough(test_eax_0); + frstor_esp_4->setComment(frstor_esp_4->getDisassembly()); dataBits.resize(2);//test eax, eax dataBits[0] = 0x85; dataBits[1] = 0xC0; - test_eax_0->SetDataBits(dataBits); - test_eax_0->SetFallthrough(jz_eax_0); + test_eax_0->setDataBits(dataBits); + test_eax_0->setFallthrough(jz_eax_0); addInstruction(test_eax_0, dataBits, jz_eax_0, NULL); addJz(jz_eax_0, test_eax_1, add_esp_0x70_label0); @@ -1037,9 +1037,9 @@ void IntegerTransform32::addFistpTruncationCheck(Instruction_t *p_instruction, i dataBits[3] = 0x00; dataBits[4] = 0x00; dataBits[5] = 0x00; - add_esp_0x70_label0->SetFallthrough(popf_label0); - add_esp_0x70_label0->SetDataBits(dataBits); - add_esp_0x70_label0->SetComment(add_esp_0x70_label0->getDisassembly()); + add_esp_0x70_label0->setFallthrough(popf_label0); + add_esp_0x70_label0->setDataBits(dataBits); + add_esp_0x70_label0->setComment(add_esp_0x70_label0->getDisassembly()); addInstruction(add_esp_0x70_label0, dataBits, popf_label0, NULL); addPopf(popf_label0, popa_label0); @@ -1048,7 +1048,7 @@ void IntegerTransform32::addFistpTruncationCheck(Instruction_t *p_instruction, i dataBits.resize(2); dataBits[0] = 0xeb; - jmpOriginalInst->SetComment("Jump to original Inst"); + jmpOriginalInst->setComment("Jump to original Inst"); addInstruction(jmpOriginalInst,dataBits,NULL, originalInstrumentInstr); //label 1: @@ -1059,9 +1059,9 @@ void IntegerTransform32::addFistpTruncationCheck(Instruction_t *p_instruction, i dataBits[2] = 0x00; dataBits[3] = 0x00; dataBits[4] = 0x00; - test_eax_1->SetDataBits(dataBits); - test_eax_1->SetComment(test_eax_1->getDisassembly()) ; - test_eax_1->SetFallthrough(jz_eax_1); + test_eax_1->setDataBits(dataBits); + test_eax_1->setComment(test_eax_1->getDisassembly()) ; + test_eax_1->setFallthrough(jz_eax_1); addInstruction(test_eax_1, dataBits, jz_eax_1, NULL); addJz(jz_eax_1, add_esp_0x70_label1, add_esp_0x70_label2); @@ -1073,9 +1073,9 @@ void IntegerTransform32::addFistpTruncationCheck(Instruction_t *p_instruction, i dataBits[3] = 0x00; dataBits[4] = 0x00; dataBits[5] = 0x00; - add_esp_0x70_label1->SetFallthrough(popf_label1); - add_esp_0x70_label1->SetDataBits(dataBits); - add_esp_0x70_label1->SetComment(add_esp_0x70_label1->getDisassembly()); + add_esp_0x70_label1->setFallthrough(popf_label1); + add_esp_0x70_label1->setDataBits(dataBits); + add_esp_0x70_label1->setComment(add_esp_0x70_label1->getDisassembly()); addInstruction(add_esp_0x70_label1, dataBits, popf_label1, NULL); addPopf(popf_label1, popa_label1); @@ -1088,20 +1088,20 @@ void IntegerTransform32::addFistpTruncationCheck(Instruction_t *p_instruction, i string instrStr= originalInstrumentInstr->getDisassembly(); string addExpr = instrStr.substr(instrStr.find(" ")+1); mov0x7FFFFFFF->Assemble("mov "+ addExpr + ", 0x7FFFFFFF"); - mov0x7FFFFFFF->SetComment(mov0x7FFFFFFF->getDisassembly()); + mov0x7FFFFFFF->setComment(mov0x7FFFFFFF->getDisassembly()); addInstruction(mov0x7FFFFFFF, mov0x7FFFFFFF->GetDataBits(), fstpST0, NULL); - popa_label1->SetComment("just before " + mov0x7FFFFFFF->getDisassembly()); + popa_label1->setComment("just before " + mov0x7FFFFFFF->getDisassembly()); dataBits.resize(2);//fstp st(0) dataBits[0] = 0xDD; dataBits[1] = 0xD8; - fstpST0->SetDataBits(dataBits); - fstpST0->SetFallthrough(jmpOriginalInstNext); + fstpST0->setDataBits(dataBits); + fstpST0->setFallthrough(jmpOriginalInstNext); addInstruction(fstpST0, dataBits, jmpOriginalInstNext, NULL); dataBits.resize(2); dataBits[0] = 0xeb; - addInstruction(jmpOriginalInstNext,dataBits,NULL, originalInstrumentInstr->GetFallthrough()); + addInstruction(jmpOriginalInstNext,dataBits,NULL, originalInstrumentInstr->getFallthrough()); } else{ Instruction_t* mov0x7FFF = allocateNewInstruction(fileID, func); @@ -1112,22 +1112,22 @@ void IntegerTransform32::addFistpTruncationCheck(Instruction_t *p_instruction, i string instrStr= originalInstrumentInstr->getDisassembly(); string addExpr = instrStr.substr(instrStr.find(" ")+1); mov0x7FFF->Assemble("mov "+ addExpr + ", 0x7FFF"); - mov0x7FFF->SetComment(mov0x7FFF->getDisassembly()); + mov0x7FFF->setComment(mov0x7FFF->getDisassembly()); - //mov0x7FFF->SetFallthrough(fstpST0); + //mov0x7FFF->setFallthrough(fstpST0); addInstruction(mov0x7FFF, mov0x7FFF->GetDataBits(), fstpST0, NULL); dataBits.resize(2);//fstp st(0) dataBits[0] = 0xDD; dataBits[1] = 0xD8; - fstpST0->SetDataBits(dataBits); - fstpST0->SetFallthrough(jmpOriginalInstNext); + fstpST0->setDataBits(dataBits); + fstpST0->setFallthrough(jmpOriginalInstNext); addInstruction(fstpST0, dataBits, jmpOriginalInstNext, NULL); dataBits.resize(2); dataBits[0] = 0xeb; - addInstruction(jmpOriginalInstNext,dataBits,NULL, originalInstrumentInstr->GetFallthrough()); + addInstruction(jmpOriginalInstNext,dataBits,NULL, originalInstrumentInstr->getFallthrough()); } dataBits.resize(6);//add esp,0x70 @@ -1137,9 +1137,9 @@ void IntegerTransform32::addFistpTruncationCheck(Instruction_t *p_instruction, i dataBits[3] = 0x00; dataBits[4] = 0x00; dataBits[5] = 0x00; - add_esp_0x70_label2->SetFallthrough(popf_label2); - add_esp_0x70_label2->SetDataBits(dataBits); - add_esp_0x70_label2->SetComment(add_esp_0x70_label2->getDisassembly()); + add_esp_0x70_label2->setFallthrough(popf_label2); + add_esp_0x70_label2->setDataBits(dataBits); + add_esp_0x70_label2->setComment(add_esp_0x70_label2->getDisassembly()); addInstruction(add_esp_0x70_label2, dataBits, popf_label2, NULL); addPopf(popf_label2, popa_label2); @@ -1152,8 +1152,8 @@ void IntegerTransform32::addFistpTruncationCheck(Instruction_t *p_instruction, i string instrStr= originalInstrumentInstr->getDisassembly(); string addExpr = instrStr.substr(instrStr.find(" ")+1); mov0x80000000->Assemble("mov "+ addExpr + ", 0x80000001"); - mov0x80000000->SetComment(mov0x80000000->getDisassembly()); - mov0x80000000->SetFallthrough(fstpST0); + mov0x80000000->setComment(mov0x80000000->getDisassembly()); + mov0x80000000->setFallthrough(fstpST0); addInstruction(mov0x80000000, mov0x80000000->GetDataBits(), fstpST0, NULL); dataBits.resize(2);//fstp st(0) @@ -1164,7 +1164,7 @@ void IntegerTransform32::addFistpTruncationCheck(Instruction_t *p_instruction, i dataBits.resize(2); dataBits[0] = 0xeb; - addInstruction(jmpOriginalInstNext,dataBits,NULL, originalInstrumentInstr->GetFallthrough()); + addInstruction(jmpOriginalInstNext,dataBits,NULL, originalInstrumentInstr->getFallthrough()); } else{ Instruction_t* mov0x8000 = allocateNewInstruction(fileID, func); @@ -1175,7 +1175,7 @@ void IntegerTransform32::addFistpTruncationCheck(Instruction_t *p_instruction, i string instrStr= originalInstrumentInstr->getDisassembly(); string addExpr = instrStr.substr(instrStr.find(" ")+1); mov0x8000->Assemble("mov "+ addExpr + ", 0x8001"); - mov0x8000->SetComment(mov0x8000->getDisassembly()); + mov0x8000->setComment(mov0x8000->getDisassembly()); addInstruction(mov0x8000, mov0x8000->GetDataBits(), fstpST0, NULL); @@ -1186,7 +1186,7 @@ void IntegerTransform32::addFistpTruncationCheck(Instruction_t *p_instruction, i addInstruction(fstpST0, dataBits, jmpOriginalInstNext, NULL); dataBits.resize(2); dataBits[0] = 0xeb; - addInstruction(jmpOriginalInstNext,dataBits,NULL, originalInstrumentInstr->GetFallthrough()); + addInstruction(jmpOriginalInstNext,dataBits,NULL, originalInstrumentInstr->getFallthrough()); } m_numFP++; @@ -1195,7 +1195,7 @@ void IntegerTransform32::addFistpTruncationCheck(Instruction_t *p_instruction, i void IntegerTransform32::addFistTruncationCheck(Instruction_t *p_instruction, int len){ if(len!=32 && len!=16) return; - db_id_t fileID = p_instruction->GetAddress()->GetFileID(); + DatabaseID_t fileID = p_instruction->getAddress()->getFileID(); Function_t* func = p_instruction->GetFunction(); string dataBits; @@ -1268,7 +1268,7 @@ void IntegerTransform32::addFistTruncationCheck(Instruction_t *p_instruction, in addPusha(pusha_i, pushf_i);//pusha Instruction_t* originalInstrumentInstr = carefullyInsertBefore(p_instruction, pusha_i); - pusha_i->SetFallthrough(pushf_i); + pusha_i->setFallthrough(pushf_i); addPushf(pushf_i, sub_esp_0x70);//pushf @@ -1279,55 +1279,55 @@ void IntegerTransform32::addFistTruncationCheck(Instruction_t *p_instruction, in dataBits[3] = 0x00; dataBits[4] = 0x00; dataBits[5] = 0x00; - sub_esp_0x70->SetFallthrough(fst_esp); - sub_esp_0x70->SetDataBits(dataBits); - sub_esp_0x70->SetComment(sub_esp_0x70->getDisassembly()); + sub_esp_0x70->setFallthrough(fst_esp); + sub_esp_0x70->setDataBits(dataBits); + sub_esp_0x70->setComment(sub_esp_0x70->getDisassembly()); addInstruction(sub_esp_0x70, dataBits, fst_esp, NULL); dataBits.resize(3);//fst [esp] dataBits[0] = 0xd9; dataBits[1] = 0x14; dataBits[2] = 0x24; - fst_esp->SetFallthrough(fsave_esp_4); - fst_esp->SetDataBits(dataBits); - fst_esp->SetComment(fst_esp->getDisassembly()); + fst_esp->setFallthrough(fsave_esp_4); + fst_esp->setDataBits(dataBits); + fst_esp->setComment(fst_esp->getDisassembly()); addInstruction(fst_esp, dataBits, fsave_esp_4, NULL); dataBits.resize(1);//fsave [esp+4] dataBits[0] = 0x9b; - fsave_esp_4->SetFallthrough(pushretaddress); - fsave_esp_4->SetDataBits(dataBits); - fsave_esp_4->SetComment(fsave_wait->getDisassembly()); + fsave_esp_4->setFallthrough(pushretaddress); + fsave_esp_4->setDataBits(dataBits); + fsave_esp_4->setComment(fsave_wait->getDisassembly()); addInstruction(fsave_wait, dataBits, fsave_esp_4, NULL); dataBits.resize(4); dataBits[0] = 0xdd; dataBits[1] = 0x74; dataBits[2] = 0x24; dataBits[3] = 0x04; - fsave_esp_4->SetFallthrough(pushretaddress); - fsave_esp_4->SetDataBits(dataBits); - fsave_esp_4->SetComment(fsave_esp_4->getDisassembly()); + fsave_esp_4->setFallthrough(pushretaddress); + fsave_esp_4->setDataBits(dataBits); + fsave_esp_4->setComment(fsave_esp_4->getDisassembly()); addInstruction(fsave_esp_4, dataBits, pushretaddress, NULL); virtual_offset_t AfterTheCheckerReturn = getAvailableAddress(); - nop->GetAddress()->SetVirtualOffset(AfterTheCheckerReturn); - nop->GetAddress()->SetFileID(BaseObj_t::NOT_IN_DATABASE); + nop->getAddress()->SetVirtualOffset(AfterTheCheckerReturn); + nop->getAddress()->SetFileID(BaseObj_t::NOT_IN_DATABASE); dataBits.resize(5);//push return_address dataBits[0] = 0x68; virtual_offset_t *tmp; tmp = (virtual_offset_t *) &dataBits[1]; *tmp = AfterTheCheckerReturn; - pushretaddress->SetDataBits(dataBits); - pushretaddress->SetComment(pushretaddress->getDisassembly()); - pushretaddress->SetFallthrough(nop); + pushretaddress->setDataBits(dataBits); + pushretaddress->setComment(pushretaddress->getDisassembly()); + pushretaddress->setFallthrough(nop); dataBits.resize(1);//nop dataBits[0] = 0x90; - nop->SetDataBits(dataBits); - nop->SetComment(nop->getDisassembly() + " -- with callback to floating number check") ; - nop->SetFallthrough(frstor_esp_4); - nop->SetIndirectBranchTargetAddress(nop->GetAddress()); + nop->setDataBits(dataBits); + nop->setComment(nop->getDisassembly() + " -- with callback to floating number check") ; + nop->setFallthrough(frstor_esp_4); + nop->SetIndirectBranchTargetAddress(nop->getAddress()); if(len==32) nop->SetCallback(string("FloatingRangeCheck32")); else @@ -1338,14 +1338,14 @@ void IntegerTransform32::addFistTruncationCheck(Instruction_t *p_instruction, in dataBits[1] = 0x64; dataBits[2] = 0x24; dataBits[3] = 0x04; - frstor_esp_4->SetDataBits(dataBits); - frstor_esp_4->SetFallthrough(test_eax_0); - frstor_esp_4->SetComment(frstor_esp_4->getDisassembly()); + frstor_esp_4->setDataBits(dataBits); + frstor_esp_4->setFallthrough(test_eax_0); + frstor_esp_4->setComment(frstor_esp_4->getDisassembly()); dataBits.resize(2);//test eax, eax dataBits[0] = 0x85; dataBits[1] = 0xC0; - test_eax_0->SetDataBits(dataBits); - test_eax_0->SetFallthrough(jz_eax_0); + test_eax_0->setDataBits(dataBits); + test_eax_0->setFallthrough(jz_eax_0); addInstruction(test_eax_0, dataBits, jz_eax_0, NULL); addJz(jz_eax_0, test_eax_1, add_esp_0x70_label0); @@ -1360,9 +1360,9 @@ void IntegerTransform32::addFistTruncationCheck(Instruction_t *p_instruction, in dataBits[3] = 0x00; dataBits[4] = 0x00; dataBits[5] = 0x00; - add_esp_0x70_label0->SetFallthrough(popf_label0); - add_esp_0x70_label0->SetDataBits(dataBits); - add_esp_0x70_label0->SetComment(add_esp_0x70_label0->getDisassembly()); + add_esp_0x70_label0->setFallthrough(popf_label0); + add_esp_0x70_label0->setDataBits(dataBits); + add_esp_0x70_label0->setComment(add_esp_0x70_label0->getDisassembly()); addInstruction(add_esp_0x70_label0, dataBits, popf_label0, NULL); addPopf(popf_label0, popa_label0); @@ -1371,7 +1371,7 @@ void IntegerTransform32::addFistTruncationCheck(Instruction_t *p_instruction, in dataBits.resize(2); dataBits[0] = 0xeb; - jmpOriginalInst->SetComment("Jump to original Inst"); + jmpOriginalInst->setComment("Jump to original Inst"); addInstruction(jmpOriginalInst,dataBits,NULL, originalInstrumentInstr); //label 1: @@ -1382,9 +1382,9 @@ void IntegerTransform32::addFistTruncationCheck(Instruction_t *p_instruction, in dataBits[2] = 0x00; dataBits[3] = 0x00; dataBits[4] = 0x00; - test_eax_1->SetDataBits(dataBits); - test_eax_1->SetComment(test_eax_1->getDisassembly()) ; - test_eax_1->SetFallthrough(jz_eax_1); + test_eax_1->setDataBits(dataBits); + test_eax_1->setComment(test_eax_1->getDisassembly()) ; + test_eax_1->setFallthrough(jz_eax_1); addInstruction(test_eax_1, dataBits, jz_eax_1, NULL); addJz(jz_eax_1, add_esp_0x70_label1, add_esp_0x70_label2); @@ -1396,9 +1396,9 @@ void IntegerTransform32::addFistTruncationCheck(Instruction_t *p_instruction, in dataBits[3] = 0x00; dataBits[4] = 0x00; dataBits[5] = 0x00; - add_esp_0x70_label1->SetFallthrough(popf_label1); - add_esp_0x70_label1->SetDataBits(dataBits); - add_esp_0x70_label1->SetComment(add_esp_0x70_label1->getDisassembly()); + add_esp_0x70_label1->setFallthrough(popf_label1); + add_esp_0x70_label1->setDataBits(dataBits); + add_esp_0x70_label1->setComment(add_esp_0x70_label1->getDisassembly()); addInstruction(add_esp_0x70_label1, dataBits, popf_label1, NULL); addPopf(popf_label1, popa_label1); @@ -1411,20 +1411,20 @@ void IntegerTransform32::addFistTruncationCheck(Instruction_t *p_instruction, in string instrStr= originalInstrumentInstr->getDisassembly(); string addExpr = instrStr.substr(instrStr.find(" ")+1); mov0x7FFFFFFF->Assemble("mov "+ addExpr + ", 0x7FFFFFFF"); - mov0x7FFFFFFF->SetComment(mov0x7FFFFFFF->getDisassembly()); + mov0x7FFFFFFF->setComment(mov0x7FFFFFFF->getDisassembly()); addInstruction(mov0x7FFFFFFF, mov0x7FFFFFFF->GetDataBits(), jmpOriginalInstNext, NULL); - popa_label1->SetComment("just before " + mov0x7FFFFFFF->getDisassembly()); + popa_label1->setComment("just before " + mov0x7FFFFFFF->getDisassembly()); //dataBits.resize(2);//fstp st(0) //dataBits[0] = 0xDD; //dataBits[1] = 0xD8; - //fstpST0->SetDataBits(dataBits); - //fstpST0->SetFallthrough(jmpOriginalInstNext); + //fstpST0->setDataBits(dataBits); + //fstpST0->setFallthrough(jmpOriginalInstNext); //addInstruction(fstpST0, dataBits, jmpOriginalInstNext, NULL); dataBits.resize(2); dataBits[0] = 0xeb; - addInstruction(jmpOriginalInstNext,dataBits,NULL, originalInstrumentInstr->GetFallthrough()); + addInstruction(jmpOriginalInstNext,dataBits,NULL, originalInstrumentInstr->getFallthrough()); } else{ Instruction_t* mov0x7FFF = allocateNewInstruction(fileID, func); @@ -1435,22 +1435,22 @@ void IntegerTransform32::addFistTruncationCheck(Instruction_t *p_instruction, in string instrStr= originalInstrumentInstr->getDisassembly(); string addExpr = instrStr.substr(instrStr.find(" ")+1); mov0x7FFF->Assemble("mov "+ addExpr + ", 0x7FFF"); - mov0x7FFF->SetComment(mov0x7FFF->getDisassembly()); + mov0x7FFF->setComment(mov0x7FFF->getDisassembly()); - //mov0x7FFF->SetFallthrough(fstpST0); + //mov0x7FFF->setFallthrough(fstpST0); addInstruction(mov0x7FFF, mov0x7FFF->GetDataBits(), jmpOriginalInstNext, NULL); //dataBits.resize(2);//fstp st(0) //dataBits[0] = 0xDD; //dataBits[1] = 0xD8; - //fstpST0->SetDataBits(dataBits); - //fstpST0->SetFallthrough(jmpOriginalInstNext); + //fstpST0->setDataBits(dataBits); + //fstpST0->setFallthrough(jmpOriginalInstNext); //addInstruction(fstpST0, dataBits, jmpOriginalInstNext, NULL); dataBits.resize(2); dataBits[0] = 0xeb; - addInstruction(jmpOriginalInstNext,dataBits,NULL, originalInstrumentInstr->GetFallthrough()); + addInstruction(jmpOriginalInstNext,dataBits,NULL, originalInstrumentInstr->getFallthrough()); } dataBits.resize(6);//add esp,0x70 @@ -1460,9 +1460,9 @@ void IntegerTransform32::addFistTruncationCheck(Instruction_t *p_instruction, in dataBits[3] = 0x00; dataBits[4] = 0x00; dataBits[5] = 0x00; - add_esp_0x70_label2->SetFallthrough(popf_label2); - add_esp_0x70_label2->SetDataBits(dataBits); - add_esp_0x70_label2->SetComment(add_esp_0x70_label2->getDisassembly()); + add_esp_0x70_label2->setFallthrough(popf_label2); + add_esp_0x70_label2->setDataBits(dataBits); + add_esp_0x70_label2->setComment(add_esp_0x70_label2->getDisassembly()); addInstruction(add_esp_0x70_label2, dataBits, popf_label2, NULL); addPopf(popf_label2, popa_label2); @@ -1475,8 +1475,8 @@ void IntegerTransform32::addFistTruncationCheck(Instruction_t *p_instruction, in string instrStr= originalInstrumentInstr->getDisassembly(); string addExpr = instrStr.substr(instrStr.find(" ")+1); mov0x80000000->Assemble("mov "+ addExpr + ", 0x80000001"); - mov0x80000000->SetComment(mov0x80000000->getDisassembly()); - //mov0x80000000->SetFallthrough(fstpST0); + mov0x80000000->setComment(mov0x80000000->getDisassembly()); + //mov0x80000000->setFallthrough(fstpST0); addInstruction(mov0x80000000, mov0x80000000->GetDataBits(), jmpOriginalInstNext, NULL); //dataBits.resize(2);//fstp st(0) @@ -1487,7 +1487,7 @@ void IntegerTransform32::addFistTruncationCheck(Instruction_t *p_instruction, in dataBits.resize(2); dataBits[0] = 0xeb; - addInstruction(jmpOriginalInstNext,dataBits,NULL, originalInstrumentInstr->GetFallthrough()); + addInstruction(jmpOriginalInstNext,dataBits,NULL, originalInstrumentInstr->getFallthrough()); } else{ Instruction_t* mov0x8000 = allocateNewInstruction(fileID, func); @@ -1498,7 +1498,7 @@ void IntegerTransform32::addFistTruncationCheck(Instruction_t *p_instruction, in string instrStr= originalInstrumentInstr->getDisassembly(); string addExpr = instrStr.substr(instrStr.find(" ")+1); mov0x8000->Assemble("mov "+ addExpr + ", 0x8001"); - mov0x8000->SetComment(mov0x8000->getDisassembly()); + mov0x8000->setComment(mov0x8000->getDisassembly()); addInstruction(mov0x8000, mov0x8000->GetDataBits(), jmpOriginalInstNext, NULL); @@ -1509,7 +1509,7 @@ void IntegerTransform32::addFistTruncationCheck(Instruction_t *p_instruction, in //addInstruction(fstpST0, dataBits, jmpOriginalInstNext, NULL); dataBits.resize(2); dataBits[0] = 0xeb; - addInstruction(jmpOriginalInstNext,dataBits,NULL, originalInstrumentInstr->GetFallthrough()); + addInstruction(jmpOriginalInstNext,dataBits,NULL, originalInstrumentInstr->getFallthrough()); } m_numFP++; @@ -1542,16 +1542,16 @@ void IntegerTransform32::handleInfiniteLoop(Instruction_t *p_instruction, const logMessage(__func__, "handling infinite loop"); - db_id_t fileID = p_instruction->GetAddress()->GetFileID(); + DatabaseID_t fileID = p_instruction->getAddress()->getFileID(); Function_t* func = p_instruction->GetFunction(); - AddressID_t *originalAddress = p_instruction->GetAddress(); + AddressID_t *originalAddress = p_instruction->getAddress(); Instruction_t* nop_i = allocateNewInstruction(fileID, func); addNop(nop_i, p_instruction); Instruction_t* originalInstrumentInstr = carefullyInsertBefore(p_instruction, nop_i); - addCallbackHandler(string(INFINITE_LOOP_DETECTOR), originalInstrumentInstr, nop_i, nop_i->GetFallthrough(), p_policy, originalAddress); + addCallbackHandler(string(INFINITE_LOOP_DETECTOR), originalInstrumentInstr, nop_i, nop_i->getFallthrough(), p_policy, originalAddress); } // @@ -1573,7 +1573,7 @@ void IntegerTransform32::handleInfiniteLoop(Instruction_t *p_instruction, const // p_addressOriginalInstruction is set when we call method from lea instrumentation void IntegerTransform32::addOverflowCheck(Instruction_t *p_instruction, const MEDS_InstructionCheckAnnotation& p_annotation, int p_policy) { - assert(getFileIR() && p_instruction && p_instruction->GetFallthrough()); + assert(getFileIR() && p_instruction && p_instruction->getFallthrough()); RegisterName targetReg = getTargetRegister(p_instruction); if (targetReg == rn_UNKNOWN) @@ -1586,7 +1586,7 @@ void IntegerTransform32::addOverflowCheck(Instruction_t *p_instruction, const ME return; } -cerr << __func__ << ": instr: " << p_instruction->getDisassembly() << " address: " << std::hex << p_instruction->GetAddress() << " annotation: " << p_annotation.toString() << " policy: " << p_policy << endl; +cerr << __func__ << ": instr: " << p_instruction->getDisassembly() << " address: " << std::hex << p_instruction->getAddress() << " annotation: " << p_annotation.toString() << " policy: " << p_policy << endl; string detector(INTEGER_OVERFLOW_DETECTOR); string dataBits; @@ -1595,14 +1595,14 @@ cerr << __func__ << ": instr: " << p_instruction->getDisassembly() << " address // update to cleaner style Function_t* origFunction = p_instruction->GetFunction(); AddressID_t *jncond_a =new AddressID_t; - jncond_a->SetFileID(p_instruction->GetAddress()->GetFileID()); + jncond_a->SetFileID(p_instruction->getAddress()->getFileID()); Instruction_t* jncond_i = new Instruction_t; jncond_i->SetFunction(origFunction); jncond_i->SetAddress(jncond_a); // set fallthrough for the original instruction - Instruction_t* nextOrig_i = p_instruction->GetFallthrough(); - p_instruction->SetFallthrough(jncond_i); + Instruction_t* nextOrig_i = p_instruction->getFallthrough(); + p_instruction->setFallthrough(jncond_i); // jncond dataBits.resize(2); @@ -1645,23 +1645,23 @@ cerr << __func__ << ": instr: " << p_instruction->getDisassembly() << " address cerr << "integertransform: SIGNED OVERFLOW: " << detector << endl; } - jncond_i->SetDataBits(dataBits); - jncond_i->SetComment(jncond_i->getDisassembly()); - jncond_i->SetTarget(nextOrig_i); + jncond_i->setDataBits(dataBits); + jncond_i->setComment(jncond_i->getDisassembly()); + jncond_i->setTarget(nextOrig_i); - p_instruction->SetFallthrough(jncond_i); + p_instruction->setFallthrough(jncond_i); if (p_policy == POLICY_CONTINUE_SATURATING_ARITHMETIC) { // implement saturating arithmetic, e.g.: // mov <reg>, value - Instruction_t* saturate_i = allocateNewInstruction(p_instruction->GetAddress()->GetFileID(), p_instruction->GetFunction()); + Instruction_t* saturate_i = allocateNewInstruction(p_instruction->getAddress()->getFileID(), p_instruction->GetFunction()); if (p_annotation.flowsIntoCriticalSink() && p_annotation.getBitWidth() == 32) { logMessage(__func__, "OVERFLOW UNSIGNED 32: CRITICAL SINK: saturate by masking"); - db_id_t fileID = p_instruction->GetAddress()->GetFileID(); + DatabaseID_t fileID = p_instruction->getAddress()->getFileID(); Function_t* func = p_instruction->GetFunction(); Instruction_t* pushf_i = allocateNewInstruction(fileID, func); Instruction_t* popf_i = allocateNewInstruction(fileID, func); @@ -1681,7 +1681,7 @@ cerr << __func__ << ": instr: " << p_instruction->getDisassembly() << " address addCallbackHandler(detector, p_instruction, jncond_i, nextOrig_i, p_policy); } - getFileIR()->GetAddresses().insert(jncond_a); + getFileIR()->getAddresses().insert(jncond_a); getFileIR()->GetInstructions().insert(jncond_i); if (p_annotation.isUnderflow()) @@ -1712,12 +1712,12 @@ void IntegerTransform32::addUnderflowCheck(Instruction_t *p_instruction, const M RegisterName targetReg = getTargetRegister(p_instruction); if (targetReg == rn_UNKNOWN) { - cerr << "IntegerTransform32::addUnderflowCheck(): instr: " << p_instruction->getDisassembly() << " address: " << p_instruction->GetAddress() << " annotation: " << p_annotation.toString() << "-- SKIP b/c no target registers" << endl; + cerr << "IntegerTransform32::addUnderflowCheck(): instr: " << p_instruction->getDisassembly() << " address: " << p_instruction->getAddress() << " annotation: " << p_annotation.toString() << "-- SKIP b/c no target registers" << endl; m_numUnderflowsSkipped++; return; } - cerr << "IntegerTransform32::addUnderflowCheck(): instr: " << p_instruction->getDisassembly() << " address: " << p_instruction->GetAddress() << " annotation: " << p_annotation.toString() << endl; + cerr << "IntegerTransform32::addUnderflowCheck(): instr: " << p_instruction->getDisassembly() << " address: " << p_instruction->getAddress() << " annotation: " << p_annotation.toString() << endl; string detector(INTEGER_OVERFLOW_DETECTOR); string dataBits; @@ -1726,14 +1726,14 @@ void IntegerTransform32::addUnderflowCheck(Instruction_t *p_instruction, const M // update to cleaner style Function_t* origFunction = p_instruction->GetFunction(); AddressID_t *jncond_a =new AddressID_t; - jncond_a->SetFileID(p_instruction->GetAddress()->GetFileID()); + jncond_a->SetFileID(p_instruction->getAddress()->getFileID()); Instruction_t* jncond_i = new Instruction_t; jncond_i->SetFunction(origFunction); jncond_i->SetAddress(jncond_a); // set fallthrough for the original instruction - Instruction_t* nextOrig_i = p_instruction->GetFallthrough(); - p_instruction->SetFallthrough(jncond_i); + Instruction_t* nextOrig_i = p_instruction->getFallthrough(); + p_instruction->setFallthrough(jncond_i); // jncond dataBits.resize(2); @@ -1778,17 +1778,17 @@ void IntegerTransform32::addUnderflowCheck(Instruction_t *p_instruction, const M cerr << "integertransform: UNDERFLOW UNKONWN: assume signed for now: " << detector << endl; } - jncond_i->SetDataBits(dataBits); - jncond_i->SetComment(jncond_i->getDisassembly()); - jncond_i->SetTarget(nextOrig_i); + jncond_i->setDataBits(dataBits); + jncond_i->setComment(jncond_i->getDisassembly()); + jncond_i->setTarget(nextOrig_i); - p_instruction->SetFallthrough(jncond_i); + p_instruction->setFallthrough(jncond_i); if (p_policy == POLICY_CONTINUE_SATURATING_ARITHMETIC) { // implement saturating arithmetic, e.g.: // mov <reg>, value - Instruction_t* saturate_i = allocateNewInstruction(p_instruction->GetAddress()->GetFileID(), p_instruction->GetFunction()); + Instruction_t* saturate_i = allocateNewInstruction(p_instruction->getAddress()->getFileID(), p_instruction->GetFunction()); addCallbackHandler(detector, p_instruction, jncond_i, saturate_i, p_policy); addMinSaturation(saturate_i, targetReg, p_annotation, nextOrig_i); @@ -1798,7 +1798,7 @@ void IntegerTransform32::addUnderflowCheck(Instruction_t *p_instruction, const M addCallbackHandler(detector, p_instruction, jncond_i, nextOrig_i, p_policy); } - getFileIR()->GetAddresses().insert(jncond_a); + getFileIR()->getAddresses().insert(jncond_a); getFileIR()->GetInstructions().insert(jncond_i); m_numUnderflows++; @@ -1822,7 +1822,7 @@ void IntegerTransform32::addTruncationCheck(Instruction_t *p_instruction, const assert(getFileIR() && p_instruction); assert(p_annotation.getTruncationFromWidth() == 32 && p_annotation.getTruncationToWidth() == 8 || p_annotation.getTruncationToWidth() == 16); - cerr << __func__ << ": instr: " << p_instruction->getDisassembly() << " address: " << p_instruction->GetAddress() << " annotation: " << p_annotation.toString() << " policy: " << p_policy << endl; + cerr << __func__ << ": instr: " << p_instruction->getDisassembly() << " address: " << p_instruction->getAddress() << " annotation: " << p_annotation.toString() << " policy: " << p_policy << endl; string detector; @@ -1866,9 +1866,9 @@ void IntegerTransform32::addTruncationCheck(Instruction_t *p_instruction, const // mov [ebp+var_4], al ; <originalInstruction> // - db_id_t fileID = p_instruction->GetAddress()->GetFileID(); + DatabaseID_t fileID = p_instruction->getAddress()->getFileID(); Function_t* func = p_instruction->GetFunction(); - AddressID_t *saveAddress = p_instruction->GetAddress(); + AddressID_t *saveAddress = p_instruction->getAddress(); Instruction_t* pushf_i = allocateNewInstruction(fileID, func); Instruction_t* test_i = allocateNewInstruction(fileID, func); @@ -1883,9 +1883,9 @@ void IntegerTransform32::addTruncationCheck(Instruction_t *p_instruction, const addPushf(pushf_i, test_i); Instruction_t* originalInstrumentInstr = carefullyInsertBefore(p_instruction, pushf_i); - pushf_i->SetFallthrough(test_i); - pushf_i->SetComment("-- in truncation"); - originalInstrumentInstr->SetComment("-- in truncation (was original)"); + pushf_i->setFallthrough(test_i); + pushf_i->setComment("-- in truncation"); + originalInstrumentInstr->setComment("-- in truncation (was original)"); unsigned mask = 0; unsigned mask2 = 0; @@ -1925,12 +1925,12 @@ void IntegerTransform32::addTruncationCheck(Instruction_t *p_instruction, const if (p_policy == POLICY_CONTINUE_SATURATING_ARITHMETIC) { addNop(nop_i, saturate_i); - nop_i->SetComment("UNSIGNED TRUNC: fallthrough: saturating arithmetic instruction"); + nop_i->setComment("UNSIGNED TRUNC: fallthrough: saturating arithmetic instruction"); addCallbackHandler(detector, originalInstrumentInstr, nop_i, saturate_i, p_policy, saveAddress); } else { addNop(nop_i, popf_i); - nop_i->SetComment(string("UNSIGNED TRUNC: fallthrough: popf")); + nop_i->setComment(string("UNSIGNED TRUNC: fallthrough: popf")); addCallbackHandler(detector, originalInstrumentInstr, nop_i, popf_i, p_policy, saveAddress); } } @@ -1968,19 +1968,19 @@ void IntegerTransform32::addTruncationCheck(Instruction_t *p_instruction, const Instruction_t* s_jae_i = allocateNewInstruction(fileID, func); addJz(jz_i, s_cmp_i, popf_i); // target = popf_i, fall-through = s_cmp_i - jz_i->SetComment(string("jz - SIGNED or UNKNOWNSIGN TRUNC")); + jz_i->setComment(string("jz - SIGNED or UNKNOWNSIGN TRUNC")); addCmpRegisterMask(s_cmp_i, p_annotation.getRegister(), mask2, s_jae_i); addJae(s_jae_i, nop_i, popf_i); // target = popf_i, fall-through = nop_i - s_jae_i->SetComment(string("jae - SIGNED or UNKNOWNSIGN TRUNC")); + s_jae_i->setComment(string("jae - SIGNED or UNKNOWNSIGN TRUNC")); if (p_policy == POLICY_CONTINUE_SATURATING_ARITHMETIC) { addNop(nop_i, saturate_i); - nop_i->SetComment("SIGNED or UNKNOWNSIGN TRUNC: fallthrough: saturating arithmetic instruction"); + nop_i->setComment("SIGNED or UNKNOWNSIGN TRUNC: fallthrough: saturating arithmetic instruction"); addCallbackHandler(detector, originalInstrumentInstr, nop_i, saturate_i, p_policy, saveAddress); } else { addNop(nop_i, popf_i); - nop_i->SetComment(string("SIGNED or UNKNOWNSIGN TRUNC: fallthrough: popf")); + nop_i->setComment(string("SIGNED or UNKNOWNSIGN TRUNC: fallthrough: popf")); addCallbackHandler(detector, originalInstrumentInstr, nop_i, popf_i, p_policy, saveAddress); } } // end of SIGNED and UNKNOWNSIGN case @@ -1994,7 +1994,7 @@ void IntegerTransform32::addSaturation(Instruction_t *p_instruction, RegisterNam { assert(getFileIR() && p_instruction); - p_instruction->SetFallthrough(p_fallthrough); + p_instruction->setFallthrough(p_fallthrough); addMovRegisterUnsignedConstant(p_instruction, p_reg, p_value, p_fallthrough); } @@ -2003,7 +2003,7 @@ void IntegerTransform32::addZeroSaturation(Instruction_t *p_instruction, Registe { assert(getFileIR() && p_instruction); - p_instruction->SetFallthrough(p_fallthrough); + p_instruction->setFallthrough(p_fallthrough); addMovRegisterUnsignedConstant(p_instruction, p_reg, 0, p_fallthrough); } @@ -2018,7 +2018,7 @@ void IntegerTransform32::addZeroSaturation(Instruction_t *p_instruction, Registe // void IntegerTransform32::addOverflowCheckUnknownSign(Instruction_t *p_instruction, const MEDS_InstructionCheckAnnotation& p_annotation, int p_policy) { - assert(getFileIR() && p_instruction && p_instruction->GetFallthrough()); + assert(getFileIR() && p_instruction && p_instruction->getFallthrough()); RegisterName targetReg = getTargetRegister(p_instruction); if (targetReg == rn_UNKNOWN) @@ -2028,7 +2028,7 @@ void IntegerTransform32::addOverflowCheckUnknownSign(Instruction_t *p_instructio return; } -cerr << __func__ << ": instr: " << p_instruction->getDisassembly() << " address: " << std::hex << p_instruction->GetAddress() << " annotation: " << p_annotation.toString() << " policy: " << p_policy << endl; +cerr << __func__ << ": instr: " << p_instruction->getDisassembly() << " address: " << std::hex << p_instruction->getAddress() << " annotation: " << p_annotation.toString() << " policy: " << p_policy << endl; // set detector/handler string detector(OVERFLOW_UNKNOWN_SIGN_DETECTOR); @@ -2043,26 +2043,26 @@ cerr << __func__ << ": instr: " << p_instruction->getDisassembly() << " address: } // for now assume we're dealing with add/sub 32 bit - db_id_t fileID = p_instruction->GetAddress()->GetFileID(); + DatabaseID_t fileID = p_instruction->getAddress()->getFileID(); Function_t* func = p_instruction->GetFunction(); - Instruction_t* jno_i = allocateNewInstruction(p_instruction->GetAddress()->GetFileID(), p_instruction->GetFunction()); - Instruction_t* jnc_i = allocateNewInstruction(p_instruction->GetAddress()->GetFileID(), p_instruction->GetFunction()); - Instruction_t* nop_i = allocateNewInstruction(p_instruction->GetAddress()->GetFileID(), p_instruction->GetFunction()); + Instruction_t* jno_i = allocateNewInstruction(p_instruction->getAddress()->getFileID(), p_instruction->GetFunction()); + Instruction_t* jnc_i = allocateNewInstruction(p_instruction->getAddress()->getFileID(), p_instruction->GetFunction()); + Instruction_t* nop_i = allocateNewInstruction(p_instruction->getAddress()->getFileID(), p_instruction->GetFunction()); // save fallthrough from original instruction - Instruction_t* nextOrig_i = p_instruction->GetFallthrough(); + Instruction_t* nextOrig_i = p_instruction->getFallthrough(); // instrument for both jno and jnc // redundant for imul, but that's ok, optimize later - p_instruction->SetFallthrough(jno_i); + p_instruction->setFallthrough(jno_i); addJno(jno_i, jnc_i, nextOrig_i); addJnc(jnc_i, nop_i, nextOrig_i); addNop(nop_i, nextOrig_i); if (p_policy == POLICY_CONTINUE_SATURATING_ARITHMETIC) { - Instruction_t* saturate_i = allocateNewInstruction(p_instruction->GetAddress()->GetFileID(), p_instruction->GetFunction()); + Instruction_t* saturate_i = allocateNewInstruction(p_instruction->getAddress()->getFileID(), p_instruction->GetFunction()); addCallbackHandler(detector, p_instruction, nop_i, saturate_i, p_policy); addMaxSaturation(saturate_i, targetReg, p_annotation, nextOrig_i); } @@ -2094,7 +2094,7 @@ cerr << __func__ << ": instr: " << p_instruction->getDisassembly() << " address: // p_addressOriginalInstruction is set when we call method from lea instrumentation void IntegerTransform32::addOverflowCheckForLea(Instruction_t *p_instruction, const MEDS_InstructionCheckAnnotation& p_annotation, int p_policy, AddressID_t *p_addressOriginalInstruction) { - assert(getFileIR() && p_instruction && p_instruction->GetFallthrough()); + assert(getFileIR() && p_instruction && p_instruction->getFallthrough()); cerr << __func__ << ": comment: " << p_instruction->GetComment() << " annotation: " << p_annotation.toString() << " policy: " << p_policy << endl; @@ -2102,11 +2102,11 @@ cerr << __func__ << ": comment: " << p_instruction->GetComment() << " annotation string detector(INTEGER_OVERFLOW_DETECTOR); // this will be either jno or jnc - Instruction_t* jncond_i = allocateNewInstruction(p_instruction->GetAddress()->GetFileID(), p_instruction->GetFunction()); + Instruction_t* jncond_i = allocateNewInstruction(p_instruction->getAddress()->getFileID(), p_instruction->GetFunction()); // set fallthrough for the original instruction - Instruction_t* nextOrig_i = p_instruction->GetFallthrough(); - p_instruction->SetFallthrough(jncond_i); + Instruction_t* nextOrig_i = p_instruction->getFallthrough(); + p_instruction->setFallthrough(jncond_i); // jncond int isMultiply = isMultiplyInstruction(p_instruction); @@ -2152,7 +2152,7 @@ cerr << __func__ << ": comment: " << p_instruction->GetComment() << " annotation else if (p_annotation.getBitWidth() == 8) detector = string(ADDSUB_OVERFLOW_DETECTOR_UNKNOWN_8); - jnc_i = allocateNewInstruction(p_instruction->GetAddress()->GetFileID(), p_instruction->GetFunction()); + jnc_i = allocateNewInstruction(p_instruction->getAddress()->getFileID(), p_instruction->GetFunction()); addJno(jncond_i, jnc_i, nextOrig_i); addJnc(jnc_i, NULL, nextOrig_i); // fallthrough will be set by the callback handler diff --git a/libtransform/src/integertransform64.cpp b/libtransform/src/integertransform64.cpp index 6cf561f28..06315471f 100644 --- a/libtransform/src/integertransform64.cpp +++ b/libtransform/src/integertransform64.cpp @@ -102,7 +102,7 @@ int IntegerTransform64::execute() { Instruction_t* insn=*it; - if (insn && insn->GetAddress()) + if (insn && insn->getAddress()) { int policy = POLICY_DEFAULT; @@ -119,7 +119,7 @@ int IntegerTransform64::execute() policy = POLICY_CONTINUE; } - virtual_offset_t irdb_vo = insn->GetAddress()->GetVirtualOffset(); + virtual_offset_t irdb_vo = insn->getAddress()->GetVirtualOffset(); if (irdb_vo == 0) continue; VirtualOffset vo(irdb_vo); @@ -154,7 +154,7 @@ int IntegerTransform64::execute() continue; } - if (!insn->GetFallthrough()) + if (!insn->getFallthrough()) { logMessage(__func__, "Warning: no fall through for instruction -- skipping"); continue; @@ -314,7 +314,7 @@ bool IntegerTransform64::addOverflowUnderflowCheck(Instruction_t *p_instruction, { char tmpbuf[1024]; - assert(getFileIR() && p_instruction && p_instruction->GetFallthrough()); + assert(getFileIR() && p_instruction && p_instruction->getFallthrough()); RegisterName targetReg = getTargetRegister(p_instruction); if (targetReg == rn_UNKNOWN) { @@ -332,18 +332,18 @@ bool IntegerTransform64::addOverflowUnderflowCheck(Instruction_t *p_instruction, return false; } - Instruction_t* jncond_i = allocateNewInstruction(p_instruction->GetAddress()->GetFileID(), p_instruction->GetFunction()); - Instruction_t* nop_i = allocateNewInstruction(p_instruction->GetAddress()->GetFileID(), p_instruction->GetFunction()); + Instruction_t* jncond_i = allocateNewInstruction(p_instruction->getAddress()->getFileID(), p_instruction->GetFunction()); + Instruction_t* nop_i = allocateNewInstruction(p_instruction->getAddress()->getFileID(), p_instruction->GetFunction()); Instruction_t* policy_i; - Instruction_t* next_i = p_instruction->GetFallthrough(); - p_instruction->SetFallthrough(jncond_i); + Instruction_t* next_i = p_instruction->getFallthrough(); + p_instruction->setFallthrough(jncond_i); setAssembly(nop_i, "nop"); if (p_policy == POLICY_CONTINUE_SATURATING_ARITHMETIC) { - policy_i = allocateNewInstruction(p_instruction->GetAddress()->GetFileID(), p_instruction->GetFunction()); + policy_i = allocateNewInstruction(p_instruction->getAddress()->getFileID(), p_instruction->GetFunction()); } else { @@ -360,7 +360,7 @@ bool IntegerTransform64::addOverflowUnderflowCheck(Instruction_t *p_instruction, } else { // unknown sign - Instruction_t* jnc_i = allocateNewInstruction(p_instruction->GetAddress()->GetFileID(), p_instruction->GetFunction()); + Instruction_t* jnc_i = allocateNewInstruction(p_instruction->getAddress()->getFileID(), p_instruction->GetFunction()); addJno(jncond_i, jnc_i, next_i); addJnc(jnc_i, policy_i, next_i); } @@ -381,8 +381,8 @@ bool IntegerTransform64::addOverflowUnderflowCheck(Instruction_t *p_instruction, std::string detector = p_annotation.isOverflow() ? OVERFLOW64_DETECTOR : UNDERFLOW64_DETECTOR; Instruction_t* cb = addCallbackHandlerSequence(p_instruction, next_i, detector, p_policy); - nop_i->SetFallthrough(cb); - cb->SetComment("underflow callback/instrumentation"); + nop_i->setFallthrough(cb); + cb->setComment("underflow callback/instrumentation"); return true; } @@ -490,7 +490,7 @@ Instruction_t* IntegerTransform64::addCallbackHandlerSequence(Instruction_t *p_o char tmpbuf[1024]; Instruction_t* lea = addNewAssembly("lea rsp, [rsp-128]"); // red zone - lea->SetComment("callback: " + p_detector); + lea->setComment("callback: " + p_detector); // must save flags as strata will perturb them Instruction_t* saveFlags = addNewAssembly(lea, "pushf"); @@ -499,21 +499,21 @@ Instruction_t* IntegerTransform64::addCallbackHandlerSequence(Instruction_t *p_o // pass in p_policy sprintf(tmpbuf,"push 0x%08x", p_policy); Instruction_t* instr = addNewAssembly(saveFlags, tmpbuf); - sprintf(tmpbuf,"push 0x%08x", p_orig->GetAddress()->GetVirtualOffset()); + sprintf(tmpbuf,"push 0x%08x", p_orig->getAddress()->GetVirtualOffset()); instr = addNewAssembly(instr, tmpbuf); - Instruction_t* call = allocateNewInstruction(p_orig->GetAddress()->GetFileID(), p_orig->GetFunction()); - instr->SetFallthrough(call); + Instruction_t* call = allocateNewInstruction(p_orig->getAddress()->getFileID(), p_orig->GetFunction()); + instr->setFallthrough(call); setAssembly(call, "call 0"); addCallbackHandler64(call, p_detector, 2); // 2 args for now - assert(call->GetTarget()); + assert(call->getTarget()); instr = addNewAssembly(call, "lea rsp, [rsp+16]"); instr = addNewAssembly(instr, "popf"); instr = addNewAssembly(instr, "lea rsp, [rsp+128]"); - instr->SetFallthrough(p_fallthrough); + instr->setFallthrough(p_fallthrough); return lea; } @@ -553,16 +553,16 @@ Instruction_t* IntegerTransform64::addCallbackHandlerSequence(Instruction_t *p_o // void IntegerTransform64::addOverflowCheckNoFlag_RegPlusReg(Instruction_t *p_instruction, const MEDS_InstructionCheckAnnotation& p_annotation, const RegisterName& p_reg1, const RegisterName& p_reg2, const RegisterName& p_reg3, int p_policy) { - assert(p_instruction && p_instruction->GetFallthrough()); + assert(p_instruction && p_instruction->getFallthrough()); cerr << __func__ << ": r3 <-- r1+r2: r1: " << Register::toString(p_reg1) << " r2: " << Register::toString(p_reg2) << " target register: " << Register::toString(p_reg3) << " annotation: " << p_annotation.toString() << endl; - Instruction_t *origFallthrough = p_instruction->GetFallthrough(); + Instruction_t *origFallthrough = p_instruction->getFallthrough(); Instruction_t *instr, *first, *saturation_policy; Instruction_t *restore = addNewAssembly("popf"); saturation_policy = addNewAssembly("nop"); - saturation_policy->SetComment("lea overflow instrumentation(reg+reg): policy code sequence"); + saturation_policy->setComment("lea overflow instrumentation(reg+reg): policy code sequence"); // Original code sequence: // lea r3, [r1+r2] @@ -579,11 +579,11 @@ void IntegerTransform64::addOverflowCheckNoFlag_RegPlusReg(Instruction_t *p_inst // fallthrough--><policy> // // first = addNewAssembly("push " + Register::toString(p_reg1)); -// first->SetComment("lea overflow instrumentation(reg+reg): start"); +// first->setComment("lea overflow instrumentation(reg+reg): start"); // Instruction_t* originalInstrumentInstr = carefullyInsertBefore(p_instruction, first); Instruction_t* originalInstrumentInstr = IRDBUtility::insertAssemblyBefore(getFileIR(), p_instruction, "lea rsp, [rsp-128]" , NULL); - p_instruction->SetComment("lea overflow instrumentation(reg+reg): start"); + p_instruction->setComment("lea overflow instrumentation(reg+reg): start"); instr = addNewAssembly(p_instruction, std::string("push ") + Register::toString(p_reg1)); instr = addNewAssembly(instr, "pushf"); @@ -591,23 +591,23 @@ void IntegerTransform64::addOverflowCheckNoFlag_RegPlusReg(Instruction_t *p_inst if (p_annotation.isSigned()) { instr = addNewAssembly(instr, "jno 0x22"); - instr->SetFallthrough(saturation_policy); - instr->SetTarget(restore); - instr->SetComment("signed: lea: reg+reg"); + instr->setFallthrough(saturation_policy); + instr->setTarget(restore); + instr->setComment("signed: lea: reg+reg"); } else if (p_annotation.isUnsigned()) { instr = addNewAssembly(instr, "jnc 0x22"); - instr->SetFallthrough(saturation_policy); - instr->SetTarget(restore); + instr->setFallthrough(saturation_policy); + instr->setTarget(restore); } else { Instruction_t *instr2 = addNewAssembly(instr, "jno 0x22"); // this generates bogus assembly code, why? - instr2->SetTarget(restore); + instr2->setTarget(restore); instr = addNewAssembly(instr2, "jnc 0x22"); - instr->SetFallthrough(saturation_policy); - instr->SetTarget(restore); + instr->setFallthrough(saturation_policy); + instr->setTarget(restore); } // <policy> @@ -623,18 +623,18 @@ void IntegerTransform64::addOverflowCheckNoFlag_RegPlusReg(Instruction_t *p_inst // Instruction_t *popf = addNewAssembly("popf"); Instruction_t *callback = addCallbackHandlerSequence(p_instruction, popf, OVERFLOW64_DETECTOR, p_policy); - saturation_policy->SetFallthrough(callback); + saturation_policy->setFallthrough(callback); instr = addNewAssembly(popf, "pop " + Register::toString(p_reg1)); if (p_policy == POLICY_CONTINUE_SATURATING_ARITHMETIC) { instr = addNewMaxSaturation(instr, p_reg3, p_annotation); instr = addNewAssembly(instr, "lea rsp, [rsp+128]"); - instr->SetFallthrough(origFallthrough); + instr->setFallthrough(origFallthrough); } else { instr = addNewAssembly(instr, "lea rsp, [rsp+128]"); - instr->SetFallthrough(originalInstrumentInstr); + instr->setFallthrough(originalInstrumentInstr); } // <restore> @@ -644,10 +644,10 @@ void IntegerTransform64::addOverflowCheckNoFlag_RegPlusReg(Instruction_t *p_inst // <orig>: lea r3, [r1+r2] ; original instruction // <originalNext> ; original next instruction // - restore->SetComment("lea overflow instrumentation(reg+reg): restore"); + restore->setComment("lea overflow instrumentation(reg+reg): restore"); instr = addNewAssembly(restore, "pop " + Register::toString(p_reg1)); instr = addNewAssembly(instr, "lea rsp, [rsp+128]"); - instr->SetFallthrough(originalInstrumentInstr); + instr->setFallthrough(originalInstrumentInstr); } // Example annotation to handle @@ -685,15 +685,15 @@ void IntegerTransform64::addOverflowCheckNoFlag_RegPlusReg(Instruction_t *p_inst // void IntegerTransform64::addOverflowCheckNoFlag_RegTimesReg(Instruction_t *p_instruction, const MEDS_InstructionCheckAnnotation& p_annotation, const RegisterName& p_reg1, const RegisterName& p_reg2, const RegisterName& p_reg3, int p_policy) { - assert(p_instruction && p_instruction->GetFallthrough()); + assert(p_instruction && p_instruction->getFallthrough()); cerr << __func__ << ": r3 <-- r1*r2: r1: " << Register::toString(p_reg1) << " r2: " << Register::toString(p_reg2) << " target register: " << Register::toString(p_reg3) << " annotation: " << p_annotation.toString() << endl; - Instruction_t *origFallthrough = p_instruction->GetFallthrough(); + Instruction_t *origFallthrough = p_instruction->getFallthrough(); Instruction_t *instr, *first, *saturation_policy; Instruction_t *restore = addNewAssembly("popf"); saturation_policy = addNewAssembly("nop"); - saturation_policy->SetComment("lea overflow instrumentation(reg*reg): policy code sequence"); + saturation_policy->setComment("lea overflow instrumentation(reg*reg): policy code sequence"); // Original code sequence: @@ -709,14 +709,14 @@ void IntegerTransform64::addOverflowCheckNoFlag_RegTimesReg(Instruction_t *p_ins // fallthrough--><policy> // Instruction_t* originalInstrumentInstr = IRDBUtility::insertAssemblyBefore(getFileIR(), p_instruction, "lea rsp, [rsp-128]" , NULL); - p_instruction->SetComment("lea overflow instrumentation(reg*reg): start"); + p_instruction->setComment("lea overflow instrumentation(reg*reg): start"); instr = addNewAssembly(p_instruction, std::string("push ") + Register::toString(p_reg1)); instr = addNewAssembly(instr, "pushf"); instr = addNewAssembly(instr, "imul " + Register::toString(p_reg1) + "," + Register::toString(p_reg2)); instr = addNewAssembly(instr, "jno 0x22"); - instr->SetFallthrough(saturation_policy); - instr->SetTarget(restore); + instr->setFallthrough(saturation_policy); + instr->setTarget(restore); // <policy> // nop ; @@ -731,18 +731,18 @@ void IntegerTransform64::addOverflowCheckNoFlag_RegTimesReg(Instruction_t *p_ins // Instruction_t *popf = addNewAssembly("popf"); Instruction_t *callback = addCallbackHandlerSequence(p_instruction, popf, OVERFLOW64_DETECTOR, p_policy); - saturation_policy->SetFallthrough(callback); + saturation_policy->setFallthrough(callback); instr = addNewAssembly(popf, "pop " + Register::toString(p_reg1)); if (p_policy == POLICY_CONTINUE_SATURATING_ARITHMETIC) { instr = addNewMaxSaturation(instr, p_reg3, p_annotation); instr = addNewAssembly(instr, "lea rsp, [rsp+128]"); - instr->SetFallthrough(origFallthrough); + instr->setFallthrough(origFallthrough); } else { instr = addNewAssembly(instr, "lea rsp, [rsp+128]"); - instr->SetFallthrough(originalInstrumentInstr); + instr->setFallthrough(originalInstrumentInstr); } // <restore> @@ -752,10 +752,10 @@ void IntegerTransform64::addOverflowCheckNoFlag_RegTimesReg(Instruction_t *p_ins // <orig>: lea r3, [r1*r2] ; original instruction // <originalNext> ; original next instruction // - restore->SetComment("lea overflow instrumentation(reg*reg): restore"); + restore->setComment("lea overflow instrumentation(reg*reg): restore"); instr = addNewAssembly(restore, "pop " + Register::toString(p_reg1)); instr = addNewAssembly(instr, "lea rsp, [rsp+128]"); - instr->SetFallthrough(originalInstrumentInstr); + instr->setFallthrough(originalInstrumentInstr); } // Example annotation to handle @@ -793,7 +793,7 @@ void IntegerTransform64::addOverflowCheckNoFlag_RegTimesReg(Instruction_t *p_ins // void IntegerTransform64::addOverflowCheckNoFlag_RegPlusConstant(Instruction_t *p_instruction, const MEDS_InstructionCheckAnnotation& p_annotation, const RegisterName& p_reg1, const int p_constant, const RegisterName& p_reg3, int p_policy) { - assert(p_instruction && p_instruction->GetFallthrough()); + assert(p_instruction && p_instruction->getFallthrough()); if (p_annotation.isUnsigned() && (p_constant < 0)) { logMessage(__func__, "lea reg+neg constant pattern: skip this annotation type (prone to false positives)"); @@ -803,11 +803,11 @@ void IntegerTransform64::addOverflowCheckNoFlag_RegPlusConstant(Instruction_t *p cerr << __func__ << ": r3 <-- r1+k: r1: " << Register::toString(p_reg1) << " k: " << p_constant << " target register: " << Register::toString(p_reg3) << " annotation: " << p_annotation.toString() << endl; - Instruction_t *origFallthrough = p_instruction->GetFallthrough(); + Instruction_t *origFallthrough = p_instruction->getFallthrough(); Instruction_t *instr, *first, *saturation_policy; Instruction_t *restore = addNewAssembly("popf"); saturation_policy = addNewAssembly("nop"); - saturation_policy->SetComment("lea overflow instrumentation(reg+k): policy code sequence"); + saturation_policy->setComment("lea overflow instrumentation(reg+k): policy code sequence"); // Original code sequence: // lea r3, [r1+k] @@ -826,18 +826,18 @@ void IntegerTransform64::addOverflowCheckNoFlag_RegPlusConstant(Instruction_t *p // /* first = addNewAssembly("push " + Register::toString(p_reg1)); - first->SetComment("lea overflow instrumentation(reg+k): start"); + first->setComment("lea overflow instrumentation(reg+k): start"); Instruction_t* originalInstrumentInstr = carefullyInsertBefore(p_instruction, first); instr = addNewAssembly(first, "pushf"); */ Instruction_t* originalInstrumentInstr = IRDBUtility::insertAssemblyBefore(getFileIR(), p_instruction, "lea rsp, [rsp-128]" , NULL); - p_instruction->SetComment("lea overflow instrumentation(reg+k): start"); + p_instruction->setComment("lea overflow instrumentation(reg+k): start"); instr = addNewAssembly(p_instruction, std::string("push ") + Register::toString(p_reg1)); instr = addNewAssembly(instr, "pushf"); //------------------- // make sure we set the fallthrough post careful insertion -// first->SetFallthrough(instr); +// first->setFallthrough(instr); std::ostringstream s; if (p_constant >= 0) { @@ -852,22 +852,22 @@ void IntegerTransform64::addOverflowCheckNoFlag_RegPlusConstant(Instruction_t *p if (p_annotation.isSigned()) { instr = addNewAssembly(instr, "jno 0x22"); - instr->SetFallthrough(saturation_policy); - instr->SetTarget(restore); + instr->setFallthrough(saturation_policy); + instr->setTarget(restore); } else if (p_annotation.isUnsigned()) { instr = addNewAssembly(instr, "jnc 0x22"); - instr->SetFallthrough(saturation_policy); - instr->SetTarget(restore); + instr->setFallthrough(saturation_policy); + instr->setTarget(restore); } else { Instruction_t *instr2 = addNewAssembly(instr, "jno 0x22"); - instr2->SetTarget(restore); + instr2->setTarget(restore); instr = addNewAssembly(instr2, "jnc 0x22"); - instr->SetFallthrough(saturation_policy); - instr->SetTarget(restore); + instr->setFallthrough(saturation_policy); + instr->setTarget(restore); } // <policy> @@ -883,18 +883,18 @@ void IntegerTransform64::addOverflowCheckNoFlag_RegPlusConstant(Instruction_t *p // Instruction_t *popf = addNewAssembly("popf"); Instruction_t *callback = addCallbackHandlerSequence(p_instruction, popf, OVERFLOW64_DETECTOR, p_policy); - saturation_policy->SetFallthrough(callback); + saturation_policy->setFallthrough(callback); instr = addNewAssembly(popf, "pop " + Register::toString(p_reg1)); if (p_policy == POLICY_CONTINUE_SATURATING_ARITHMETIC) { instr = addNewMaxSaturation(instr, p_reg3, p_annotation); instr = addNewAssembly(instr, "lea rsp, [rsp+128]"); - instr->SetFallthrough(origFallthrough); + instr->setFallthrough(origFallthrough); } else { instr = addNewAssembly(instr, "lea rsp, [rsp+128]"); - instr->SetFallthrough(originalInstrumentInstr); + instr->setFallthrough(originalInstrumentInstr); } // <restore> @@ -904,11 +904,11 @@ void IntegerTransform64::addOverflowCheckNoFlag_RegPlusConstant(Instruction_t *p // <orig>: lea r3, [r1+k] ; original instruction // <originalNext> ; original next instruction // - restore->SetComment("lea overflow instrumentation(reg+k): restore"); + restore->setComment("lea overflow instrumentation(reg+k): restore"); instr = addNewAssembly(restore, "pop " + Register::toString(p_reg1)); instr = addNewAssembly(instr, "lea rsp, [rsp+128]"); - instr->SetFallthrough(originalInstrumentInstr); - originalInstrumentInstr->SetFallthrough(origFallthrough); + instr->setFallthrough(originalInstrumentInstr); + originalInstrumentInstr->setFallthrough(origFallthrough); } @@ -945,15 +945,15 @@ void IntegerTransform64::addOverflowCheckNoFlag_RegPlusConstant(Instruction_t *p // void IntegerTransform64::addOverflowCheckNoFlag_RegTimesConstant(Instruction_t *p_instruction, const MEDS_InstructionCheckAnnotation& p_annotation, const RegisterName& p_reg1, const int p_constant, const RegisterName& p_reg3, int p_policy) { - assert(p_instruction && p_instruction->GetFallthrough()); + assert(p_instruction && p_instruction->getFallthrough()); cerr << __func__ << ": r3 <-- r1*k: r1: " << Register::toString(p_reg1) << " k: " << p_constant << " target register: " << Register::toString(p_reg3) << " annotation: " << p_annotation.toString() << endl; - Instruction_t *origFallthrough = p_instruction->GetFallthrough(); + Instruction_t *origFallthrough = p_instruction->getFallthrough(); Instruction_t *instr, *first, *saturation_policy; Instruction_t *restore = addNewAssembly("popf"); saturation_policy = addNewAssembly("nop"); - saturation_policy->SetComment("lea overflow instrumentation(reg*k): policy code sequence"); + saturation_policy->setComment("lea overflow instrumentation(reg*k): policy code sequence"); // Original code sequence: // lea r3, [r1*k] @@ -969,25 +969,25 @@ void IntegerTransform64::addOverflowCheckNoFlag_RegTimesConstant(Instruction_t * // /* first = addNewAssembly("push " + Register::toString(p_reg1)); - first->SetComment("lea overflow instrumentation(reg*k): start"); + first->setComment("lea overflow instrumentation(reg*k): start"); Instruction_t* originalInstrumentInstr = carefullyInsertBefore(p_instruction, first); instr = addNewAssembly(first, "pushf"); */ Instruction_t* originalInstrumentInstr = IRDBUtility::insertAssemblyBefore(getFileIR(), p_instruction, "lea rsp, [rsp-128]" , NULL); - p_instruction->SetComment("lea overflow instrumentation(reg*k): start"); + p_instruction->setComment("lea overflow instrumentation(reg*k): start"); instr = addNewAssembly(p_instruction, std::string("push ") + Register::toString(p_reg1)); instr = addNewAssembly(instr, "pushf"); /*--------------*/ // make sure we set the fallthrough post careful insertion -// first->SetFallthrough(instr); +// first->setFallthrough(instr); std::ostringstream s; s << "imul " << Register::toString(p_reg1) << "," << p_constant; instr = addNewAssembly(instr, s.str()); instr = addNewAssembly(instr, "jno 0x22"); - instr->SetFallthrough(saturation_policy); - instr->SetTarget(restore); + instr->setFallthrough(saturation_policy); + instr->setTarget(restore); // <policy> // nop ; @@ -1002,18 +1002,18 @@ void IntegerTransform64::addOverflowCheckNoFlag_RegTimesConstant(Instruction_t * // Instruction_t *popf = addNewAssembly("popf"); Instruction_t *callback = addCallbackHandlerSequence(p_instruction, popf, OVERFLOW64_DETECTOR, p_policy); - saturation_policy->SetFallthrough(callback); + saturation_policy->setFallthrough(callback); instr = addNewAssembly(popf, "pop " + Register::toString(p_reg1)); if (p_policy == POLICY_CONTINUE_SATURATING_ARITHMETIC) { instr = addNewMaxSaturation(instr, p_reg3, p_annotation); instr = addNewAssembly(instr, "lea rsp, [rsp+128]"); - instr->SetFallthrough(origFallthrough); + instr->setFallthrough(origFallthrough); } else { instr = addNewAssembly(instr, "lea rsp, [rsp+128]"); - instr->SetFallthrough(originalInstrumentInstr); + instr->setFallthrough(originalInstrumentInstr); } // <restore> @@ -1023,11 +1023,11 @@ void IntegerTransform64::addOverflowCheckNoFlag_RegTimesConstant(Instruction_t * // <orig>: lea r3, [r1*k] ; original instruction // <originalNext> ; original next instruction // - restore->SetComment("lea overflow instrumentation(reg*reg): restore"); + restore->setComment("lea overflow instrumentation(reg*reg): restore"); instr = addNewAssembly(restore, "pop " + Register::toString(p_reg1)); instr = addNewAssembly(instr, "lea rsp, [rsp+128]"); - instr->SetFallthrough(originalInstrumentInstr); - originalInstrumentInstr->SetFallthrough(origFallthrough); + instr->setFallthrough(originalInstrumentInstr); + originalInstrumentInstr->setFallthrough(origFallthrough); } // @@ -1045,7 +1045,7 @@ void IntegerTransform64::addOverflowCheckNoFlag_RegTimesConstant(Instruction_t * bool IntegerTransform64::addTruncationCheck32(Instruction_t *p_instruction, const MEDS_InstructionCheckAnnotation& p_annotation, int p_policy) { - assert(p_instruction && p_instruction->GetFallthrough() && + assert(p_instruction && p_instruction->getFallthrough() && p_annotation.getTruncationFromWidth() == 32 && (p_annotation.getTruncationToWidth() == 16 || p_annotation.getTruncationToWidth() == 8) && isMovInstruction(p_instruction)); @@ -1094,7 +1094,7 @@ bool IntegerTransform64::addTruncationCheck32(Instruction_t *p_instruction, cons unsigned mask = 0, mask2 = 0; string saturationValue = "0x0"; - p_instruction->SetComment("monitor for truncation32"); + p_instruction->setComment("monitor for truncation32"); if (p_annotation.getTruncationToWidth() == 16) { @@ -1161,14 +1161,14 @@ bool IntegerTransform64::addTruncationCheck32(Instruction_t *p_instruction, cons // char buf[MAX_ASSEMBLY_SIZE]; - Instruction_t *origFallthrough = p_instruction->GetFallthrough(); + Instruction_t *origFallthrough = p_instruction->getFallthrough(); Instruction_t *instr, *save, *test; Instruction_t *restore = addNewAssembly("popf"); - restore->SetComment("trunc: restore flags"); + restore->setComment("trunc: restore flags"); /* save = addNewAssembly("pushf"); - save->SetComment("start truncation sequence"); + save->setComment("start truncation sequence"); */ if (p_annotation.isSigned()) @@ -1188,16 +1188,16 @@ bool IntegerTransform64::addTruncationCheck32(Instruction_t *p_instruction, cons /*--------------*/ // Instruction_t* originalInstrumentInstr = IRDBUtility::insertAssemblyBefore(getFileIR(), p_instruction, std::string("pushf"), NULL); Instruction_t* originalInstrumentInstr = IRDBUtility::insertAssemblyBefore(getFileIR(), p_instruction, "lea rsp, [rsp-128]" , NULL); - p_instruction->SetComment("start truncation sequence"); + p_instruction->setComment("start truncation sequence"); instr = addNewAssembly(p_instruction, "pushf"); test = addNewAssembly(instr, buf); /*--------------*/ - // p_instruction->SetFallthrough(test); + // p_instruction->setFallthrough(test); -// save->SetFallthrough(test); +// save->setFallthrough(test); instr = addNewAssembly(restore, "lea rsp, [rsp+128]"); - instr->SetFallthrough(originalInstrumentInstr); + instr->setFallthrough(originalInstrumentInstr); if (p_annotation.isUnsigned()) { @@ -1205,8 +1205,8 @@ bool IntegerTransform64::addTruncationCheck32(Instruction_t *p_instruction, cons Instruction_t *nop = addNewAssembly("nop"); instr = addNewAssembly(test, "jz 0x22"); // bogus jump target for now - instr->SetTarget(restore); - instr->SetFallthrough(nop); + instr->setTarget(restore); + instr->setFallthrough(nop); Instruction_t *callback; @@ -1214,16 +1214,16 @@ bool IntegerTransform64::addTruncationCheck32(Instruction_t *p_instruction, cons { string saturationInstruction = "mov " + p_annotation.getTarget2() + ", " + saturationValue; Instruction_t *saturation = addNewAssembly(saturationInstruction); - saturation->SetComment("trunc/unsigned/saturate"); + saturation->setComment("trunc/unsigned/saturate"); callback = addCallbackHandlerSequence(p_instruction, saturation, detector, p_policy); - nop->SetFallthrough(callback); - saturation->SetFallthrough(restore); + nop->setFallthrough(callback); + saturation->setFallthrough(restore); } else { callback = addCallbackHandlerSequence(p_instruction, restore, detector, p_policy); - nop->SetFallthrough(callback); + nop->setFallthrough(callback); } } else @@ -1253,15 +1253,15 @@ bool IntegerTransform64::addTruncationCheck32(Instruction_t *p_instruction, cons Instruction_t *nop = addNewAssembly("nop"); instr = addNewAssembly(test, "jz 0x22"); // bogus jump target for now - instr->SetTarget(restore); + instr->setTarget(restore); std::ostringstream s; s << "cmp " << Register::toString(p_annotation.getRegister()) << ", 0x" << hex << mask2 << dec; instr = addNewAssembly(instr, s.str()); instr = addNewAssembly(instr, "jae 0x22"); - instr->SetTarget(restore); - instr->SetFallthrough(nop); + instr->setTarget(restore); + instr->setFallthrough(nop); Instruction_t *callback; @@ -1270,18 +1270,18 @@ bool IntegerTransform64::addTruncationCheck32(Instruction_t *p_instruction, cons string saturationInstruction = "mov " + p_annotation.getTarget2() + ", " + saturationValue; Instruction_t *saturation = addNewAssembly(saturationInstruction); if (p_annotation.isSigned()) - saturation->SetComment("trunc/signed/saturate"); + saturation->setComment("trunc/signed/saturate"); else - saturation->SetComment("trunc/unknown/saturate"); + saturation->setComment("trunc/unknown/saturate"); callback = addCallbackHandlerSequence(p_instruction, saturation, detector, p_policy); - nop->SetFallthrough(callback); - saturation->SetFallthrough(restore); + nop->setFallthrough(callback); + saturation->setFallthrough(restore); } else { callback = addCallbackHandlerSequence(p_instruction, restore, detector, p_policy); - nop->SetFallthrough(callback); + nop->setFallthrough(callback); } } @@ -1328,7 +1328,7 @@ string IntegerTransform64::buildSaturationAssembly(Instruction_t *p_instruction, bool IntegerTransform64::addTruncationCheck64(Instruction_t *p_instruction, const MEDS_InstructionCheckAnnotation& p_annotation, int p_policy) { - assert(p_instruction && p_instruction->GetFallthrough() && + assert(p_instruction && p_instruction->getFallthrough() && p_annotation.getTruncationFromWidth() == 64 && (p_annotation.getTruncationToWidth() == 32 || p_annotation.getTruncationToWidth() == 16 || p_annotation.getTruncationToWidth() == 8) && isMovInstruction(p_instruction)); @@ -1398,7 +1398,7 @@ bool IntegerTransform64::addTruncationCheck64(Instruction_t *p_instruction, cons long long unsigned mask = 0, mask2 = 0; string saturationValue = "0x0"; - p_instruction->SetComment("monitor for truncation64"); + p_instruction->setComment("monitor for truncation64"); if (p_annotation.getTruncationToWidth() == 32) { @@ -1493,15 +1493,15 @@ bool IntegerTransform64::addTruncationCheck64(Instruction_t *p_instruction, cons // char buf[MAX_ASSEMBLY_SIZE]; - Instruction_t *origFallthrough = p_instruction->GetFallthrough(); + Instruction_t *origFallthrough = p_instruction->getFallthrough(); Instruction_t *instr, *save, *test, *pushf; Instruction_t *restore = addNewAssembly("popf"); - restore->SetComment("trunc: restore flags"); + restore->setComment("trunc: restore flags"); Instruction_t *restoreReg = addNewAssembly("pop " + Register::toString(borrowReg)); /* save = addNewAssembly("push " + Register::toString(borrowReg)); - save->SetComment("start truncation sequence"); + save->setComment("start truncation sequence"); pushf = addNewAssembly(save, "pushf"); @@ -1524,7 +1524,7 @@ bool IntegerTransform64::addTruncationCheck64(Instruction_t *p_instruction, cons // Instruction_t* originalInstrumentInstr = IRDBUtility::insertAssemblyBefore(getFileIR(), p_instruction, std::string("push ") + Register::toString(borrowReg), NULL); // Instruction_t* lea = addNewAssembly("lea rsp, [rsp-128]"); // red zone Instruction_t* originalInstrumentInstr = IRDBUtility::insertAssemblyBefore(getFileIR(), p_instruction, "lea rsp, [rsp-128]" , NULL); - p_instruction->SetComment("start truncation sequence"); + p_instruction->setComment("start truncation sequence"); instr = addNewAssembly(p_instruction, std::string("push ") + Register::toString(borrowReg)); instr = addNewAssembly(instr, "pushf"); if (p_annotation.isSigned()) @@ -1540,11 +1540,11 @@ bool IntegerTransform64::addTruncationCheck64(Instruction_t *p_instruction, cons // test eax, <reg> ; (for 8 bit) /*--------------*/ -// save->SetFallthrough(pushf); +// save->setFallthrough(pushf); - restore->SetFallthrough(restoreReg); + restore->setFallthrough(restoreReg); instr = addNewAssembly(restoreReg, "lea rsp, [rsp+128]"); - instr->SetFallthrough(originalInstrumentInstr); + instr->setFallthrough(originalInstrumentInstr); if (p_annotation.isUnsigned()) { @@ -1552,8 +1552,8 @@ bool IntegerTransform64::addTruncationCheck64(Instruction_t *p_instruction, cons Instruction_t *nop = addNewAssembly("nop"); instr = addNewAssembly(test, "jz 0x22"); // bogus jump target for now - instr->SetTarget(restore); - instr->SetFallthrough(nop); + instr->setTarget(restore); + instr->setFallthrough(nop); Instruction_t *callback; @@ -1561,16 +1561,16 @@ bool IntegerTransform64::addTruncationCheck64(Instruction_t *p_instruction, cons { string saturationInstruction = "mov " + p_annotation.getTarget2() + ", " + saturationValue; Instruction_t *saturation = addNewAssembly(saturationInstruction); - saturation->SetComment("trunc/unsigned/saturate"); + saturation->setComment("trunc/unsigned/saturate"); callback = addCallbackHandlerSequence(p_instruction, saturation, detector, p_policy); - nop->SetFallthrough(callback); - saturation->SetFallthrough(restore); + nop->setFallthrough(callback); + saturation->setFallthrough(restore); } else { callback = addCallbackHandlerSequence(p_instruction, restore, detector, p_policy); - nop->SetFallthrough(callback); + nop->setFallthrough(callback); } } else @@ -1603,7 +1603,7 @@ bool IntegerTransform64::addTruncationCheck64(Instruction_t *p_instruction, cons Instruction_t *nop = addNewAssembly("nop"); instr = addNewAssembly(test, "jz 0x22"); // bogus jump target for now - instr->SetTarget(restore); + instr->setTarget(restore); std::ostringstream s; s << "mov " << Register::toString(borrowReg) << ", 0x" << hex << mask2 << dec; @@ -1614,8 +1614,8 @@ bool IntegerTransform64::addTruncationCheck64(Instruction_t *p_instruction, cons instr = addNewAssembly(instr, s2.str()); instr = addNewAssembly(instr, "jae 0x22"); - instr->SetTarget(restore); - instr->SetFallthrough(nop); + instr->setTarget(restore); + instr->setFallthrough(nop); Instruction_t *callback; @@ -1624,18 +1624,18 @@ bool IntegerTransform64::addTruncationCheck64(Instruction_t *p_instruction, cons string saturationInstruction = "mov " + p_annotation.getTarget2() + ", " + saturationValue; Instruction_t *saturation = addNewAssembly(saturationInstruction); if (p_annotation.isSigned()) - saturation->SetComment("trunc/signed/saturate"); + saturation->setComment("trunc/signed/saturate"); else - saturation->SetComment("trunc/unknown/saturate"); + saturation->setComment("trunc/unknown/saturate"); callback = addCallbackHandlerSequence(p_instruction, saturation, detector, p_policy); - nop->SetFallthrough(callback); - saturation->SetFallthrough(restore); + nop->setFallthrough(callback); + saturation->setFallthrough(restore); } else { callback = addCallbackHandlerSequence(p_instruction, restore, detector, p_policy); - nop->SetFallthrough(callback); + nop->setFallthrough(callback); } } @@ -1658,7 +1658,7 @@ bool IntegerTransform64::addSignednessCheck(Instruction_t *p_instruction, const return false; string detector = p_annotation.isSigned() ? SIGNEDNESS64_DETECTOR_SIGNED : SIGNEDNESS64_DETECTOR_UNSIGNED; - Instruction_t *origFallthrough = p_instruction->GetFallthrough(); + Instruction_t *origFallthrough = p_instruction->getFallthrough(); Instruction_t* originalInstrumentInstr = IRDBUtility::insertAssemblyBefore(getFileIR(), p_instruction, std::string("lea rsp, [rsp-128]"), NULL); Instruction_t *save = addNewAssembly(p_instruction, "pushf"); @@ -1666,15 +1666,15 @@ bool IntegerTransform64::addSignednessCheck(Instruction_t *p_instruction, const std::ostringstream s; s << "test " << Register::toString(p_annotation.getRegister()) << "," << Register::toString(p_annotation.getRegister()); Instruction_t *test = addNewAssembly(save, s.str()); - originalInstrumentInstr->SetFallthrough(origFallthrough); + originalInstrumentInstr->setFallthrough(origFallthrough); Instruction_t *jns = addNewAssembly(test, "jns 0x22"); Instruction_t *nop = addNewAssembly(jns, "nop"); Instruction_t *restore = addNewAssembly("popf"); Instruction_t *learestore = addNewAssembly(restore, "lea rsp, [rsp+128]"); - learestore->SetFallthrough(originalInstrumentInstr); + learestore->setFallthrough(originalInstrumentInstr); - jns->SetTarget(restore); + jns->setTarget(restore); Instruction_t *callback = NULL; @@ -1684,18 +1684,18 @@ bool IntegerTransform64::addSignednessCheck(Instruction_t *p_instruction, const Instruction_t *saturation = addNewMaxSaturation(nop, p_annotation.getRegister(), p_annotation); if (p_annotation.isSigned()) - saturation->SetComment("signedness/signed/saturate"); + saturation->setComment("signedness/signed/saturate"); else - saturation->SetComment("signedness/unsigned/saturate"); + saturation->setComment("signedness/unsigned/saturate"); callback = addCallbackHandlerSequence(p_instruction, saturation, detector, p_policy); - nop->SetFallthrough(callback); - saturation->SetFallthrough(restore); + nop->setFallthrough(callback); + saturation->setFallthrough(restore); } else { callback = addCallbackHandlerSequence(p_instruction, restore, detector, p_policy); - nop->SetFallthrough(callback); + nop->setFallthrough(callback); } return true; diff --git a/libtransform/src/pointercheck64.cpp b/libtransform/src/pointercheck64.cpp index 7f11e1f61..3c4ba7d64 100644 --- a/libtransform/src/pointercheck64.cpp +++ b/libtransform/src/pointercheck64.cpp @@ -31,7 +31,7 @@ Instruction_t* PointerCheck64::addCallbackHandlerSequence(Instruction_t *p_orig, Instruction_t* exit_sequence = addNewAssembly("mov rax, 60"); Instruction_t* i = addNewAssembly(exit_sequence, "mov rdi, 25"); i = addNewAssembly(i, "syscall"); - i->SetFallthrough(p_fallthrough); + i->setFallthrough(p_fallthrough); return exit_sequence; } else @@ -70,11 +70,11 @@ int PointerCheck64::execute() { Instruction_t* insn=*it; - if (insn && insn->GetAddress()) + if (insn && insn->getAddress()) { int policy = POLICY_EXIT; - virtual_offset_t irdb_vo = insn->GetAddress()->GetVirtualOffset(); + virtual_offset_t irdb_vo = insn->getAddress()->GetVirtualOffset(); if (irdb_vo == 0) continue; VirtualOffset vo(irdb_vo); @@ -108,7 +108,7 @@ int PointerCheck64::execute() continue; } - if (!insn->GetFallthrough()) + if (!insn->getFallthrough()) { logMessage(__func__, "Warning: no fall through for instruction -- skipping"); continue; diff --git a/libtransform/src/transform.cpp b/libtransform/src/transform.cpp index de3277b8c..24021eec0 100644 --- a/libtransform/src/transform.cpp +++ b/libtransform/src/transform.cpp @@ -20,10 +20,12 @@ #include "transform.hpp" #include "Rewrite_Utility.hpp" +#include <libIRDB-core.hpp> #define OPTIMIZE_ASSEMBLY -using namespace libTransform; +using namespace IRDB_SDK; using namespace MEDS_Annotation; +using namespace libTransform; // 20130415 Anh added support for additional registers for various utility functions // 20130415 Anh added assert() statements for unhandled registers @@ -31,7 +33,8 @@ using namespace MEDS_Annotation; Transform::Transform(VariantID_t *p_variantID, FileIR_t *p_fileIR, set<std::string> *p_filteredFunctions) { m_variantID = p_variantID; // Current variant ID - m_fileIR = p_fileIR; // File IR (off the database) for variant + m_fileIR = dynamic_cast<libIRDB::FileIR_t*>(p_fileIR); // File IR (off the database) for variant + assert(m_fileIR); m_filteredFunctions = p_filteredFunctions; // Blacklisted funtions } @@ -39,12 +42,11 @@ void Transform::addInstruction(Instruction_t *p_instr, string p_dataBits, Instru { if (p_instr == NULL) return; - p_instr->SetDataBits(p_dataBits); - p_instr->SetComment(p_instr->getDisassembly()); - p_instr->SetFallthrough(p_fallThrough); - p_instr->SetTarget(p_target); - - m_fileIR->GetAddresses().insert(p_instr->GetAddress()); + p_instr->setDataBits(p_dataBits); + p_instr->setComment(p_instr->getDisassembly()); + p_instr->setFallthrough(p_fallThrough); + p_instr->setTarget(p_target); + m_fileIR->GetAddresses().insert(p_instr->getAddress()); m_fileIR->GetInstructions().insert(p_instr); } @@ -65,29 +67,29 @@ Instruction_t* Transform::carefullyInsertBefore(Instruction_t* &p_instrumented, //a copy of the original instruction #ifdef BENSWAY - Instruction_t* i2 = IRDBUtility::insertAssemblyBefore(m_fileIR, p_instrumented, m_fileIR->LookupAssembly(p_newInstr), p_newInstr->GetTarget()); -cerr << "carefullyInsertBefore (Ben's Way): @: 0x" << std::hex << p_instrumented->GetAddress() << std::dec << " old instruction: " << p_instrumented->getDisassembly() << " new instruction: " << m_fileIR->LookupAssembly(p_newInstr) << endl; + Instruction_t* i2 = IRDBUtility::insertAssemblyBefore(m_fileIR, p_instrumented, m_fileIR->lookupAssembly(p_newInstr), p_newInstr->getTarget()); +cerr << "carefullyInsertBefore (Ben's Way): @: 0x" << std::hex << p_instrumented->getAddress() << std::dec << " old instruction: " << p_instrumented->getDisassembly() << " new instruction: " << m_fileIR->lookupAssembly(p_newInstr) << endl; return i2; #else - db_id_t fileID = p_instrumented->GetAddress()->GetFileID(); - Function_t* func = p_instrumented->GetFunction(); + DatabaseID_t fileID = p_instrumented->getAddress()->getFileID(); + Function_t* func = p_instrumented->getFunction(); - assert(p_instrumented && p_newInstr && p_instrumented->GetAddress()); + assert(p_instrumented && p_newInstr && p_instrumented->getAddress()); // why is old instrunction blank? -cerr << "(1) carefullyInsertBefore: @: 0x" << std::hex << p_instrumented->GetAddress() << std::dec << " old instruction: " << p_instrumented->getDisassembly() << " new instruction: " << m_fileIR->LookupAssembly(p_newInstr) << endl; +cerr << "(1) carefullyInsertBefore: @: 0x" << std::hex << p_instrumented->getAddress() << std::dec << " old instruction: " << p_instrumented->getDisassembly() << " new instruction: " << m_fileIR->lookupAssembly(p_newInstr) << endl; // duplicate old instrumented instruction Instruction_t* dupInstr = allocateNewInstruction(fileID, func); - dupInstr->SetDataBits(p_instrumented->GetDataBits()); - dupInstr->SetComment(p_instrumented->GetComment()); - dupInstr->SetCallback(p_instrumented->GetCallback()); - dupInstr->SetFallthrough(p_instrumented->GetFallthrough()); - dupInstr->SetTarget(p_instrumented->GetTarget()); - dupInstr->SetOriginalAddressID(p_instrumented->GetOriginalAddressID()); + dupInstr->setDataBits(p_instrumented->GetDataBits()); + dupInstr->setComment(p_instrumented->getComment()); + dupInstr->setCallback(p_instrumented->getCallback()); + dupInstr->setFallthrough(p_instrumented->getFallthrough()); + dupInstr->setTarget(p_instrumented->getTarget()); + dupInstr->setOriginalAddressID(p_instrumented->getOriginalAddressID()); AddressID_t *saveIBTA = p_instrumented->GetIndirectBranchTargetAddress(); - dupInstr->SetIndirectBranchTargetAddress(NULL); + dupInstr->setIndirectBranchTargetAddress(NULL); // // pre: p_instrument --> "mov edx, 1" @@ -97,26 +99,26 @@ cerr << "(1) carefullyInsertBefore: @: 0x" << std::hex << p_instrumented->GetAdd // // this function is equivalent to: // m_fileIR->UnregisterAssembly(p_instrumented); - // m_fileIR->RegisterAssembly(dupInstr, newAssemblyCode); + // m_fileIR->registerAssembly(dupInstr, newAssemblyCode); // m_fileIR->ChangeRegistryKey(p_instrumented, dupInstr); if (p_newInstr->GetDataBits().size() == 0) - m_fileIR->RegisterAssembly(p_instrumented, m_fileIR->LookupAssembly(p_newInstr)); + m_fileIR->registerAssembly(p_instrumented, m_fileIR->lookupAssembly(p_newInstr)); else - p_instrumented->SetDataBits(p_newInstr->GetDataBits()); + p_instrumented->setDataBits(p_newInstr->GetDataBits()); - p_instrumented->SetComment(p_newInstr->GetComment()); - p_instrumented->SetCallback(p_newInstr->GetCallback()); - p_instrumented->SetFallthrough(dupInstr); + p_instrumented->setComment(p_newInstr->getComment()); + p_instrumented->setCallback(p_newInstr->getCallback()); + p_instrumented->setFallthrough(dupInstr); - p_instrumented->SetOriginalAddressID(BaseObj_t::NOT_IN_DATABASE); - p_instrumented->SetIndirectBranchTargetAddress(saveIBTA); + p_instrumented->setOriginalAddressID(BaseObj_t::NOT_IN_DATABASE); + p_instrumented->setIndirectBranchTargetAddress(saveIBTA); p_instrumented->GetRelocations().clear(); p_newInstr = p_instrumented; -cerr << "(2) carefullyInsertBefore: @: 0x" << std::hex << p_instrumented->GetAddress() << std::dec << " old instruction: " << dupInstr->getDisassembly() << " new instruction: " << m_fileIR->LookupAssembly(p_newInstr) << endl; +cerr << "(2) carefullyInsertBefore: @: 0x" << std::hex << p_instrumented->getAddress() << std::dec << " old instruction: " << dupInstr->getDisassembly() << " new instruction: " << m_fileIR->lookupAssembly(p_newInstr) << endl; return dupInstr; #endif } @@ -336,26 +338,26 @@ void Transform::addNop(Instruction_t *p_nop_i, Instruction_t *p_fallThrough) string dataBits; dataBits.resize(1); dataBits[0] = 0x90; - p_nop_i->SetComment(string("NOP")); + p_nop_i->setComment(string("NOP")); addInstruction(p_nop_i, dataBits, p_fallThrough, NULL); } -Instruction_t* Transform::allocateNewInstruction(db_id_t p_fileID, Function_t* p_func) +Instruction_t* Transform::allocateNewInstruction(DatabaseID_t p_fileID, Function_t* p_func) { - Instruction_t *instr = new Instruction_t(); - AddressID_t *a = new AddressID_t(); + Instruction_t *instr = new libIRDB::Instruction_t(); + AddressID_t *a = new libIRDB::AddressID_t(); - a->SetFileID(p_fileID); + a->setFileID(p_fileID); - instr->SetFunction(p_func); - instr->SetAddress(a); + instr->setFunction(p_func); + instr->setAddress(a); m_fileIR->GetInstructions().insert(instr); m_fileIR->GetAddresses().insert(a); return instr; } -virtual_offset_t Transform::getAvailableAddress() +VirtualOffset_t Transform::getAvailableAddress() { /* // traverse all instructions @@ -364,7 +366,7 @@ virtual_offset_t Transform::getAvailableAddress() // @todo: lookup instruction size so that we don't waste any space // for some reason the max available address is incorrect! was ist los? - virtual_offset_t availableAddressOffset = 0; + VirtualOffset_t availableAddressOffset = 0; for( set<Instruction_t*>::const_iterator it=p_virp->GetInstructions().begin(); it!=p_virp->GetInstructions().end(); @@ -374,8 +376,8 @@ virtual_offset_t Transform::getAvailableAddress() Instruction_t* insn=*it; if (!insn) continue; - AddressID_t* addr = insn->GetAddress(); - virtual_offset_t offset = addr->GetVirtualOffset(); + AddressID_t* addr = insn->getAddress(); + VirtualOffset_t offset = addr->setVirtualOffset(); if (offset > availableAddressOffset) { @@ -392,12 +394,13 @@ virtual_offset_t Transform::getAvailableAddress() void Transform::addCallbackHandler(string p_detector, Instruction_t *p_instrumentedInstruction, Instruction_t *p_instruction, Instruction_t *p_fallThrough, int p_policy, AddressID_t *p_addressOriginalInstruction) { + assert(getFileIR() && p_instruction && p_fallThrough); string dataBits; - db_id_t fileID = p_instruction->GetAddress()->GetFileID(); - Function_t* func = p_instruction->GetFunction(); + DatabaseID_t fileID = p_instruction->getAddress()->getFileID(); + Function_t* func = p_instruction->getFunction(); // create and register new instructions (and addresses) Instruction_t* pushf_i = allocateNewInstruction(fileID, func); @@ -411,12 +414,12 @@ void Transform::addCallbackHandler(string p_detector, Instruction_t *p_instrumen Instruction_t* popf_i = allocateNewInstruction(fileID, func); // pin the poparg instruction - virtual_offset_t postDetectorReturn = getAvailableAddress(); - poparg_i->GetAddress()->SetVirtualOffset(postDetectorReturn); + VirtualOffset_t postDetectorReturn = getAvailableAddress(); + poparg_i->getAddress()->setVirtualOffset(postDetectorReturn); // link callback handler sequence to instrumented instruction - p_instruction->SetFallthrough(pushf_i); - p_instruction->SetComment(p_instruction->GetComment() + " -- start of callback handler sequence"); + p_instruction->setFallthrough(pushf_i); + p_instruction->setComment(p_instruction->getComment() + " -- start of callback handler sequence"); // pushf addPushf(pushf_i, pusha_i); @@ -433,49 +436,49 @@ void Transform::addCallbackHandler(string p_detector, Instruction_t *p_instrumen dataBits[0] = 0x68; int *tmpi = (int *) &dataBits[1]; *tmpi = p_policy; - pushPolicy_i->SetDataBits(dataBits); - pushPolicy_i->SetComment(pushPolicy_i->getDisassembly() + string(" - policy spec")); - pushPolicy_i->SetFallthrough(pusharg_i); + pushPolicy_i->setDataBits(dataBits); + pushPolicy_i->setComment(pushPolicy_i->getDisassembly() + string(" - policy spec")); + pushPolicy_i->setFallthrough(pusharg_i); // push (PC of instrumented instruction) dataBits.resize(5); dataBits[0] = 0x68; - virtual_offset_t *tmp = (virtual_offset_t *) &dataBits[1]; + VirtualOffset_t *tmp = (VirtualOffset_t *) &dataBits[1]; if (p_addressOriginalInstruction) - *tmp = p_addressOriginalInstruction->GetVirtualOffset(); + *tmp = p_addressOriginalInstruction->getVirtualOffset(); else - *tmp = p_instrumentedInstruction->GetAddress()->GetVirtualOffset(); - pusharg_i->SetDataBits(dataBits); - pusharg_i->SetComment(pusharg_i->getDisassembly()); - pusharg_i->SetFallthrough(pushret_i); + *tmp = p_instrumentedInstruction->getAddress()->getVirtualOffset(); + pusharg_i->setDataBits(dataBits); + pusharg_i->setComment(pusharg_i->getDisassembly()); + pusharg_i->setFallthrough(pushret_i); // pushret dataBits.resize(5); dataBits[0] = 0x68; - tmp = (virtual_offset_t *) &dataBits[1]; + tmp = (VirtualOffset_t *) &dataBits[1]; *tmp = postDetectorReturn; - pushret_i->SetDataBits(dataBits); - pushret_i->SetComment(pushret_i->getDisassembly()); - pushret_i->SetFallthrough(poparg_i); + pushret_i->setDataBits(dataBits); + pushret_i->setComment(pushret_i->getDisassembly()); + pushret_i->setFallthrough(poparg_i); // poparg dataBits.resize(1); dataBits[0] = 0x58; - poparg_i->SetDataBits(dataBits); - poparg_i->SetComment(poparg_i->getDisassembly() + " -- with callback to " + p_detector + " orig: " + p_instruction->GetComment()) ; - poparg_i->SetFallthrough(popPolicy_i); - poparg_i->SetCallback(p_detector); - AddressID_t *poparg_i_indTarg =new AddressID_t(); + poparg_i->setDataBits(dataBits); + poparg_i->setComment(poparg_i->getDisassembly() + " -- with callback to " + p_detector + " orig: " + p_instruction->getComment()) ; + poparg_i->setFallthrough(popPolicy_i); + poparg_i->setCallback(p_detector); + auto poparg_i_indTarg =new libIRDB::AddressID_t(); m_fileIR->GetAddresses().insert(poparg_i_indTarg); - poparg_i_indTarg->SetVirtualOffset(poparg_i->GetAddress()->GetVirtualOffset()); - poparg_i_indTarg->SetFileID(BaseObj_t::NOT_IN_DATABASE); - poparg_i->SetIndirectBranchTargetAddress(poparg_i_indTarg); + poparg_i_indTarg->setVirtualOffset(poparg_i->getAddress()->getVirtualOffset()); + poparg_i_indTarg->setFileID(BaseObj_t::NOT_IN_DATABASE); + poparg_i->setIndirectBranchTargetAddress(poparg_i_indTarg); // popPolicy dataBits.resize(1); dataBits[0] = 0x58; - popPolicy_i->SetDataBits(dataBits); - popPolicy_i->SetFallthrough(popa_i); + popPolicy_i->setDataBits(dataBits); + popPolicy_i->setFallthrough(popa_i); // popa addPopa(popa_i, popf_i); @@ -532,7 +535,7 @@ bool Transform::isMultiplyInstruction(Instruction_t *p_instruction) if (!p_instruction) return false; - std::string assembly = m_fileIR->LookupAssembly(p_instruction); + std::string assembly = m_fileIR->lookupAssembly(p_instruction); if (assembly.length() > 0) { return my_strcasestr(assembly.c_str(), "MUL") != NULL; @@ -554,7 +557,7 @@ bool Transform::isMovInstruction(Instruction_t *p_instruction) if (!p_instruction) return false; - std::string assembly = m_fileIR->LookupAssembly(p_instruction); + std::string assembly = m_fileIR->lookupAssembly(p_instruction); if (assembly.length() > 0) { return my_strcasestr(assembly.c_str(), "MOV") != NULL; @@ -1094,9 +1097,9 @@ void Transform::addAddRegisters(Instruction_t *p_instr, RegisterName p_regTgt, R // too many combinations, just use the assembler string assembly = "add " + Register::toString(p_regTgt) + ", " + Register::toString(p_regSrc); #ifdef OPTIMIZE_ASSEMBLY - m_fileIR->RegisterAssembly(p_instr, assembly); + m_fileIR->registerAssembly(p_instr, assembly); #else - if (!p_instr->Assemble(assembly)) + if (!p_instr->assemble(assembly)) { cerr << "addAddRegisters(): error in assembling instruction: " << assembly << endl; assert(0); @@ -1104,7 +1107,7 @@ void Transform::addAddRegisters(Instruction_t *p_instr, RegisterName p_regTgt, R } #endif - p_instr->SetFallthrough(p_fallThrough); + p_instr->setFallthrough(p_fallThrough); } // add r1, constant @@ -1115,9 +1118,9 @@ void Transform::addAddRegisterConstant(Instruction_t *p_instr, RegisterName p_re sprintf(buf, "add %s, %d", Register::toString(p_reg).c_str(), p_constantValue); string assembly(buf); #ifdef OPTIMIZE_ASSEMBLY - m_fileIR->RegisterAssembly(p_instr, assembly); + m_fileIR->registerAssembly(p_instr, assembly); #else - if (!p_instr->Assemble(assembly)) + if (!p_instr->assemble(assembly)) { cerr << "Transform::addAddConstant(): error in assembling instruction: " << assembly << endl; assert(0); @@ -1126,7 +1129,7 @@ void Transform::addAddRegisterConstant(Instruction_t *p_instr, RegisterName p_re #endif // cerr << "Transform::addAddConstant(): " << p_instr->getDisassembly() << endl; - p_instr->SetFallthrough(p_fallThrough); + p_instr->setFallthrough(p_fallThrough); } // imul r1, constant @@ -1137,7 +1140,7 @@ void Transform::addMulRegisterConstant(Instruction_t *p_instr, RegisterName p_re sprintf(buf, "imul %s, %d", Register::toString(p_reg).c_str(), p_constantValue); string assembly(buf); #ifdef OPTIMIZE_ASSEMBLY - m_fileIR->RegisterAssembly(p_instr, assembly); + m_fileIR->registerAssembly(p_instr, assembly); #else if (!p_instr->Assemble(assembly)) { @@ -1148,7 +1151,7 @@ void Transform::addMulRegisterConstant(Instruction_t *p_instr, RegisterName p_re #endif // cerr << "Transform::addMulRegisterConstant(): " << p_instr->getDisassembly() << endl; - p_instr->SetFallthrough(p_fallThrough); + p_instr->setFallthrough(p_fallThrough); } @@ -1158,7 +1161,7 @@ void Transform::addMovRegisters(Instruction_t *p_instr, RegisterName p_regTgt, R // too many combinations, just use the assembler string assembly = "mov " + Register::toString(p_regTgt) + ", " + Register::toString(p_regSrc); #ifdef OPTIMIZE_ASSEMBLY - m_fileIR->RegisterAssembly(p_instr, assembly); + m_fileIR->registerAssembly(p_instr, assembly); #else if (!p_instr->Assemble(assembly)) { @@ -1167,40 +1170,40 @@ void Transform::addMovRegisters(Instruction_t *p_instr, RegisterName p_regTgt, R return; } #endif - p_instr->SetFallthrough(p_fallThrough); + p_instr->setFallthrough(p_fallThrough); // cerr << "addMovRegisters(): " << p_instr->getDisassembly() << endl; } void Transform::addMovRegisterSignedConstant(Instruction_t *p_instr, RegisterName p_regTgt, long int p_constant, Instruction_t *p_fallThrough) { - p_instr->SetFallthrough(p_fallThrough); + p_instr->setFallthrough(p_fallThrough); char buf[128]; sprintf(buf,"mov %s, %ld", Register::toString(p_regTgt).c_str(), p_constant); string assembly(buf); - m_fileIR->RegisterAssembly(p_instr, assembly); + m_fileIR->registerAssembly(p_instr, assembly); - p_instr->SetComment("Saturating arithmetic"); + p_instr->setComment("Saturating arithmetic"); } void Transform::addMovRegisterUnsignedConstant(Instruction_t *p_instr, RegisterName p_regTgt, unsigned long int p_constant, Instruction_t *p_fallThrough) { - p_instr->SetFallthrough(p_fallThrough); + p_instr->setFallthrough(p_fallThrough); char buf[128]; sprintf(buf,"mov %s, %lu", Register::toString(p_regTgt).c_str(), p_constant); string assembly(buf); - m_fileIR->RegisterAssembly(p_instr, assembly); + m_fileIR->registerAssembly(p_instr, assembly); - p_instr->SetComment("Saturating arithmetic"); + p_instr->setComment("Saturating arithmetic"); } void Transform::addAndRegister32Mask(Instruction_t *p_instr, RegisterName p_regTgt, unsigned int p_mask, Instruction_t *p_fallThrough) { - p_instr->SetFallthrough(p_fallThrough); + p_instr->setFallthrough(p_fallThrough); char buf[128]; sprintf(buf,"and %s, 0x%08X", Register::toString(p_regTgt).c_str(), p_mask); @@ -1208,7 +1211,7 @@ void Transform::addAndRegister32Mask(Instruction_t *p_instr, RegisterName p_regT string assembly(buf); cerr << "addAndRegisterMask(): assembling instruction: " << assembly << endl; #ifdef OPTIMIZE_ASSEMBLY - m_fileIR->RegisterAssembly(p_instr, assembly); + m_fileIR->registerAssembly(p_instr, assembly); #else if (!p_instr->Assemble(assembly)) { @@ -1218,7 +1221,7 @@ void Transform::addAndRegister32Mask(Instruction_t *p_instr, RegisterName p_regT } #endif - p_instr->SetComment("Saturating arithmetic by masking"); + p_instr->setComment("Saturating arithmetic by masking"); } //----------------------------------------------------- @@ -1229,33 +1232,33 @@ void Transform::addAndRegister32Mask(Instruction_t *p_instr, RegisterName p_regT void Transform::addHlt(Instruction_t *p_instr, Instruction_t *p_fallThrough) { string assembly("hlt"); - m_fileIR->RegisterAssembly(p_instr, assembly); - p_instr->SetFallthrough(p_fallThrough); + m_fileIR->registerAssembly(p_instr, assembly); + p_instr->setFallthrough(p_fallThrough); } // jno - jump not overflow void Transform::addJno(Instruction_t *p_instr, Instruction_t *p_fallThrough, Instruction_t *p_target) { string assembly("jno 0x22"); - m_fileIR->RegisterAssembly(p_instr, assembly); - p_instr->SetFallthrough(p_fallThrough); - p_instr->SetTarget(p_target); + m_fileIR->registerAssembly(p_instr, assembly); + p_instr->setFallthrough(p_fallThrough); + p_instr->setTarget(p_target); } // jnc - jump not carry void Transform::addJnc(Instruction_t *p_instr, Instruction_t *p_fallThrough, Instruction_t *p_target) { string assembly("jnc 0x22"); - m_fileIR->RegisterAssembly(p_instr, assembly); - p_instr->SetFallthrough(p_fallThrough); - p_instr->SetTarget(p_target); + m_fileIR->registerAssembly(p_instr, assembly); + p_instr->setFallthrough(p_fallThrough); + p_instr->setTarget(p_target); } Instruction_t* Transform::addNewMaxSaturation(Instruction_t *p_prev, RegisterName p_reg, const MEDS_InstructionCheckAnnotation p_annotation) { - Instruction_t *mov = allocateNewInstruction(p_prev->GetAddress()->GetFileID(), p_prev->GetFunction()); + Instruction_t *mov = allocateNewInstruction(p_prev->getAddress()->getFileID(), p_prev->getFunction()); if (p_prev) - p_prev->SetFallthrough(mov); + p_prev->setFallthrough(mov); addMaxSaturation(mov, p_reg, p_annotation, NULL); return mov; } @@ -1265,7 +1268,7 @@ void Transform::addMaxSaturation(Instruction_t *p_instruction, RegisterName p_re #if 0 assert(getFileIR() && p_instruction); - p_instruction->SetFallthrough(p_fallthrough); + p_instruction->setFallthrough(p_fallthrough); if (p_annotation.isUnsigned()) { @@ -1323,7 +1326,7 @@ void Transform::addMinSaturation(Instruction_t *p_instruction, RegisterName p_re #if 0 assert(getFileIR() && p_instruction); - p_instruction->SetFallthrough(p_fallthrough); + p_instruction->setFallthrough(p_fallthrough); if (p_annotation.isUnsigned()) { @@ -1361,7 +1364,7 @@ void Transform::addMinSaturation(Instruction_t *p_instruction, RegisterName p_re void Transform::setAssembly(Instruction_t *p_instr, string p_asm) { - m_fileIR->RegisterAssembly(p_instr, p_asm); + m_fileIR->registerAssembly(p_instr, p_asm); } // @@ -1382,20 +1385,20 @@ Instruction_t* Transform::addNewAssembly(Instruction_t *p_instr, string p_asm) { Instruction_t* newinstr; if (p_instr) - newinstr = allocateNewInstruction(p_instr->GetAddress()->GetFileID(), p_instr->GetFunction()); + newinstr = allocateNewInstruction(p_instr->getAddress()->getFileID(), p_instr->getFunction()); else - newinstr = allocateNewInstruction(m_fileIR->GetFile()->GetFileID(), NULL); + newinstr = allocateNewInstruction(m_fileIR->getFile()->getFileID(), NULL); - m_fileIR->RegisterAssembly(newinstr, p_asm); + m_fileIR->registerAssembly(newinstr, p_asm); if (p_instr) { - newinstr->SetFallthrough(p_instr->GetFallthrough()); - p_instr->SetFallthrough(newinstr); + newinstr->setFallthrough(p_instr->getFallthrough()); + p_instr->setFallthrough(newinstr); } else { - newinstr->SetFallthrough(NULL); + newinstr->setFallthrough(NULL); } return newinstr; @@ -1419,7 +1422,7 @@ void Transform::addCallbackHandler64(Instruction_t *p_orig, string p_callbackHan } if (p_orig) - p_orig->SetTarget(m_handlerMap[p_callbackHandler]); + p_orig->setTarget(m_handlerMap[p_callbackHandler]); } // x86-64 @@ -1480,8 +1483,8 @@ Instruction_t* Transform::registerCallbackHandler64(string p_callbackHandler, in // pin the instruction that follows the callback handler Instruction_t* postCallback = allocateNewInstruction(); - virtual_offset_t postCallbackReturn = getAvailableAddress(); - postCallback->GetAddress()->SetVirtualOffset(postCallbackReturn); + VirtualOffset_t postCallbackReturn = getAvailableAddress(); + postCallback->getAddress()->setVirtualOffset(postCallbackReturn); // push the address to return to once the callback handler is invoked sprintf(tmpbuf,"mov rax, 0x%x", (uint32_t)postCallbackReturn); @@ -1491,17 +1494,17 @@ Instruction_t* Transform::registerCallbackHandler64(string p_callbackHandler, in // use a nop instruction for the actual callback instr = addNewAssembly(instr, "nop"); - instr->SetComment(" -- callback: " + p_callbackHandler); - instr->SetCallback(p_callbackHandler); - instr->SetFallthrough(postCallback); + instr->setComment(" -- callback: " + p_callbackHandler); + instr->setCallback(p_callbackHandler); + instr->setFallthrough(postCallback); // need to make sure the post callback address is pinned // (so that ILR and other transforms do not relocate it) - AddressID_t *indTarg = new AddressID_t(); + AddressID_t *indTarg = new libIRDB::AddressID_t(); m_fileIR->GetAddresses().insert(indTarg); - indTarg->SetVirtualOffset(postCallback->GetAddress()->GetVirtualOffset()); - indTarg->SetFileID(BaseObj_t::NOT_IN_DATABASE); // SPRI global namespace - postCallback->SetIndirectBranchTargetAddress(indTarg); + indTarg->setVirtualOffset(postCallback->getAddress()->getVirtualOffset()); + indTarg->setFileID(BaseObj_t::NOT_IN_DATABASE); // SPRI global namespace + postCallback->setIndirectBranchTargetAddress(indTarg); // restore registers setAssembly(postCallback, "popf"); @@ -1545,3 +1548,6 @@ void libTransform::convertToLowercase(string &str) str[i] = tolower(str[i]); } } + +FileIR_t* Transform::getFileIR() { return dynamic_cast<FileIR_t*>(m_fileIR); } + diff --git a/meds2pdb/SConscript b/meds2pdb/SConscript index f2bc7d3c1..646957c92 100644 --- a/meds2pdb/SConscript +++ b/meds2pdb/SConscript @@ -7,8 +7,8 @@ myenv=env.Clone() myenv.Replace(SECURITY_TRANSFORMS_HOME=os.environ['SECURITY_TRANSFORMS_HOME']) cpppath=''' + $IRDB_SDK/include $SECURITY_TRANSFORMS_HOME/include - $SECURITY_TRANSFORMS_HOME/xform $SECURITY_TRANSFORMS_HOME/libEXEIO/include $SECURITY_TRANSFORMS_HOME/libIRDB/include $SECURITY_TRANSFORMS_HOME/libMEDSannotation/include diff --git a/meds2pdb/aspri.h b/meds2pdb/aspri.h index 54a974552..0da73ac38 100644 --- a/meds2pdb/aspri.h +++ b/meds2pdb/aspri.h @@ -34,7 +34,7 @@ typedef struct aspri_address aspri_address_t; struct aspri_address { char *library_name; - libIRDB::virtual_offset_t offset; + VirtualOffset_t offset; bool isCurrentPC; }; diff --git a/meds2pdb/constant_hash.cpp b/meds2pdb/constant_hash.cpp index 048158196..368ccbeb3 100644 --- a/meds2pdb/constant_hash.cpp +++ b/meds2pdb/constant_hash.cpp @@ -48,7 +48,7 @@ long constants_key_compare(void* key1, void* key2) } -constant_hash_value_t * add_constant_ref(libIRDB::virtual_offset_t pc,int the_const, constant_hash_field_t the_field, constant_hash_type_t the_type) +constant_hash_value_t * add_constant_ref(VirtualOffset_t pc,int the_const, constant_hash_field_t the_field, constant_hash_type_t the_type) { constant_hash_key_t *chk=(constant_hash_key_t*)spri_allocate_type(sizeof(constant_hash_key_t )); constant_hash_value_t *chv=(constant_hash_value_t*)spri_allocate_type(sizeof(constant_hash_value_t )); @@ -64,7 +64,7 @@ constant_hash_value_t * add_constant_ref(libIRDB::virtual_offset_t pc,int the_co } -constant_hash_value_t * get_constant_ref(libIRDB::virtual_offset_t pc, int the_const, constant_hash_field_t the_field) +constant_hash_value_t * get_constant_ref(VirtualOffset_t pc, int the_const, constant_hash_field_t the_field) { constant_hash_key_t chk={pc, the_const, the_field}; constant_hash_value_t *chv=(constant_hash_value_t*)Hashtable_get(constants_hash, &chk); diff --git a/meds2pdb/constant_hash.h b/meds2pdb/constant_hash.h index 422496b0e..215926528 100644 --- a/meds2pdb/constant_hash.h +++ b/meds2pdb/constant_hash.h @@ -33,7 +33,7 @@ typedef enum constant_hash_field constant_hash_field_t; extern Hashtable *constants_hash; struct constant_hash_key { - libIRDB::virtual_offset_t pc; + VirtualOffset_t pc; int the_const; constant_hash_field_t field; }; @@ -49,9 +49,9 @@ long constants_compute_hash(void* key1); long constants_key_compare(void* key1, void* key2); -constant_hash_value_t * add_constant_ref(libIRDB::virtual_offset_t pc,int the_const, constant_hash_field_t the_field, constant_hash_type_t the_type); +constant_hash_value_t * add_constant_ref(VirtualOffset_t pc,int the_const, constant_hash_field_t the_field, constant_hash_type_t the_type); -constant_hash_value_t * get_constant_ref(libIRDB::virtual_offset_t pc, int the_const, constant_hash_field_t the_field); +constant_hash_value_t * get_constant_ref(VirtualOffset_t pc, int the_const, constant_hash_field_t the_field); const char* constant_hash_type_to_string(constant_hash_type_t type); diff --git a/meds2pdb/elfreader.cpp b/meds2pdb/elfreader.cpp index 18f682709..924dbdb04 100644 --- a/meds2pdb/elfreader.cpp +++ b/meds2pdb/elfreader.cpp @@ -21,11 +21,12 @@ #include <iostream> #include <string.h> #include <stdio.h> -#include <libIRDB-core.hpp> +#include <irdb-core> #include "elfreader.h" +#include <libIRDB-core.hpp> using namespace std; -//using namespace ELFIO; +using namespace IRDB_SDK; using namespace EXEIO; ElfReader::ElfReader(char *p_elfFile) @@ -79,7 +80,7 @@ ElfReader::~ElfReader() /* * Read <p_numBytes> from ELF file for location <p_pc> */ -string ElfReader::read(libIRDB::virtual_offset_t p_pc, unsigned p_numBytes) const +string ElfReader::read(VirtualOffset_t p_pc, unsigned p_numBytes) const { for ( int i = 0; i < m_reader->sections.size(); ++i ) { @@ -102,7 +103,7 @@ string ElfReader::read(libIRDB::virtual_offset_t p_pc, unsigned p_numBytes) cons * No bounds checking is done on <p_buf> * Return false if address not in valid sections */ -bool ElfReader::read(libIRDB::virtual_offset_t p_pc, unsigned p_numBytes, char* p_buf) const +bool ElfReader::read(VirtualOffset_t p_pc, unsigned p_numBytes, char* p_buf) const { for ( int i = 0; i < m_reader->sections.size(); ++i ) { @@ -123,7 +124,7 @@ bool ElfReader::read(libIRDB::virtual_offset_t p_pc, unsigned p_numBytes, char* /* * Return buffer for instruction off the ELF file */ -const char* ElfReader::getInstructionBuffer(libIRDB::virtual_offset_t p_pc) const +const char* ElfReader::getInstructionBuffer(VirtualOffset_t p_pc) const { for ( int i = 0; i < m_reader->sections.size(); ++i ) { @@ -140,3 +141,17 @@ const char* ElfReader::getInstructionBuffer(libIRDB::virtual_offset_t p_pc) cons return NULL; } +void ElfReader::SetArchitecture() +{ + const auto width = + (isElf32() || isPe32()) ? 32 : + (isElf64() || isPe64()) ? 64 : + throw std::invalid_argument("Unknown architecture."); + const auto mt = m_reader->getMachineType() == EXEIO::mtI386 ? IRDB_SDK::admtI386 : + m_reader->getMachineType() == EXEIO::mtX86_64 ? IRDB_SDK::admtX86_64 : + m_reader->getMachineType() == EXEIO::mtAarch64 ? IRDB_SDK::admtAarch64 : + throw std::invalid_argument("Unknown architecture."); + + libIRDB::FileIR_t::setArchitecture(width,mt); +} + diff --git a/meds2pdb/elfreader.h b/meds2pdb/elfreader.h index 3eed1be6d..87b4ac4a7 100644 --- a/meds2pdb/elfreader.h +++ b/meds2pdb/elfreader.h @@ -3,10 +3,10 @@ #include <vector> #include "exeio.h" -#include <libIRDB-core.hpp> +#include <irdb-core> #include <assert.h> #include <exception> -#include <libIRDB-core.hpp> +#include <irdb-core> // doing this is very bad. @@ -20,27 +20,15 @@ class ElfReader ElfReader(char *); virtual ~ElfReader(); - std::string read(libIRDB::virtual_offset_t p_pc, unsigned p_numBytes) const ; - bool read(libIRDB::virtual_offset_t p_pc, unsigned p_numBytes, char* p_buf) const ; - const char* getInstructionBuffer(libIRDB::virtual_offset_t p_pc) const ; + std::string read(IRDB_SDK::VirtualOffset_t p_pc, unsigned p_numBytes) const ; + bool read(IRDB_SDK::VirtualOffset_t p_pc, unsigned p_numBytes, char* p_buf) const ; + const char* getInstructionBuffer(IRDB_SDK::VirtualOffset_t p_pc) const ; bool isElf32() const { assert(m_reader); return m_reader->get_class()==EXEIO::ELF32; } bool isElf64() const { assert(m_reader); return m_reader->get_class()==EXEIO::ELF64; } bool isPe32() const { assert(m_reader); return m_reader->get_class()==EXEIO::PE32; } bool isPe64() const { assert(m_reader); return m_reader->get_class()==EXEIO::PE64; } - void SetArchitecture() - { - const auto width = - (isElf32() || isPe32()) ? 32 : - (isElf64() || isPe64()) ? 64 : - throw std::invalid_argument("Unknown architecture."); - const auto mt = m_reader->getMachineType() == EXEIO::mtI386 ? libIRDB::admtI386 : - m_reader->getMachineType() == EXEIO::mtX86_64 ? libIRDB::admtX86_64 : - m_reader->getMachineType() == EXEIO::mtAarch64 ? libIRDB::admtAarch64 : - throw std::invalid_argument("Unknown architecture."); - - libIRDB::FileIR_t::SetArchitecture(width,mt); - } + void SetArchitecture() ; private: EXEIO::exeio* m_reader; diff --git a/meds2pdb/framerestore_hash.cpp b/meds2pdb/framerestore_hash.cpp index adf972ab8..d7c2d400f 100644 --- a/meds2pdb/framerestore_hash.cpp +++ b/meds2pdb/framerestore_hash.cpp @@ -45,7 +45,7 @@ long framerestores_key_compare(void* key1, void* key2) /* * frame_restore_set_return_address - set the offset of the return address for this frame */ -void frame_restore_set_return_address(libIRDB::virtual_offset_t pc, int offset) +void frame_restore_set_return_address(VirtualOffset_t pc, int offset) { instrmap_hash_value_t *imhv=(instrmap_hash_value_t*)Hashtable_get(instrmaps_hash,&pc); @@ -75,7 +75,7 @@ void frame_restore_set_return_address(libIRDB::virtual_offset_t pc, int offset) /* * frame_restore_hash_add_reg_restore - add info to the frame restore hash about the type and offset of saved registers */ -void frame_restore_hash_add_reg_restore(libIRDB::virtual_offset_t addr, int reg_num, int reg_offset, int reg_type) +void frame_restore_hash_add_reg_restore(VirtualOffset_t addr, int reg_num, int reg_offset, int reg_type) { framerestore_hash_value_t *frhv=(framerestore_hash_value_t*) Hashtable_get(framerestores_hash,&addr); @@ -104,7 +104,7 @@ void frame_restore_hash_add_reg_restore(libIRDB::virtual_offset_t addr, int reg_ } -void frame_restore_hash_set_safe_bit(libIRDB::virtual_offset_t addr, int is_safe) +void frame_restore_hash_set_safe_bit(VirtualOffset_t addr, int is_safe) { framerestore_hash_value_t *frhv=(framerestore_hash_value_t*)Hashtable_get(framerestores_hash,&addr); @@ -126,7 +126,7 @@ void frame_restore_hash_set_safe_bit(libIRDB::virtual_offset_t addr, int is_safe frhv->static_analyzer_believes_safe=is_safe; } -int is_safe_function(libIRDB::virtual_offset_t pc) +int is_safe_function(VirtualOffset_t pc) { instrmap_hash_value_t *imhv=(instrmap_hash_value_t*)Hashtable_get(instrmaps_hash,&pc); diff --git a/meds2pdb/framerestore_hash.h b/meds2pdb/framerestore_hash.h index 72edda0e6..df466ba83 100644 --- a/meds2pdb/framerestore_hash.h +++ b/meds2pdb/framerestore_hash.h @@ -50,12 +50,12 @@ long framerestores_compute_hash(void* key1); long framerestores_key_compare(void* key1, void* key2); -void frame_restore_hash_add_reg_restore(libIRDB::virtual_offset_t addr, int reg_num, int reg_offset, int reg_type); +void frame_restore_hash_add_reg_restore(VirtualOffset_t addr, int reg_num, int reg_offset, int reg_type); -void frame_restore_hash_set_safe_bit(libIRDB::virtual_offset_t addr, int is_safe); +void frame_restore_hash_set_safe_bit(VirtualOffset_t addr, int is_safe); -void frame_restore_hash_set_frame_size(libIRDB::virtual_offset_t addr, int is_safe); -void frame_restore_set_return_address(libIRDB::virtual_offset_t pc, int offset); +void frame_restore_hash_set_frame_size(VirtualOffset_t addr, int is_safe); +void frame_restore_set_return_address(VirtualOffset_t pc, int offset); #endif diff --git a/meds2pdb/function_descriptor.cpp b/meds2pdb/function_descriptor.cpp index 6177d0945..e81dd459c 100644 --- a/meds2pdb/function_descriptor.cpp +++ b/meds2pdb/function_descriptor.cpp @@ -22,6 +22,7 @@ #include <cstdio> #include "function_descriptor.h" +using namespace IRDB_SDK; void wahoo::Function::_init() { @@ -40,13 +41,13 @@ wahoo::Function::Function() _init(); } -wahoo::Function::Function(libIRDB::virtual_offset_t p_start) +wahoo::Function::Function(VirtualOffset_t p_start) { _init(); setAddress(p_start); } -wahoo::Function::Function(string p_name, libIRDB::virtual_offset_t p_start, int p_size) +wahoo::Function::Function(string p_name, VirtualOffset_t p_start, int p_size) { _init(); setName(p_name); @@ -63,7 +64,7 @@ bool wahoo::Function::operator == (const Function &other) return (other.m_name == this->m_name && other.m_address == this->m_address); } -bool wahoo::Function::operator == (const libIRDB::virtual_offset_t p_addr) +bool wahoo::Function::operator == (const VirtualOffset_t p_addr) { return (this->m_address == p_addr); } @@ -73,7 +74,7 @@ bool wahoo::Function::operator != (const Function &other) return (other.m_name != this->m_name || other.m_address != this->m_address); } -bool wahoo::Function::operator != (const libIRDB::virtual_offset_t p_addr) +bool wahoo::Function::operator != (const VirtualOffset_t p_addr) { return (this->m_address != p_addr); } diff --git a/meds2pdb/function_descriptor.h b/meds2pdb/function_descriptor.h index 51ce72bd8..502c175e6 100644 --- a/meds2pdb/function_descriptor.h +++ b/meds2pdb/function_descriptor.h @@ -2,8 +2,8 @@ #include <vector> #include <string> -#include <libIRDB-core.hpp> -#include <libIRDB-core.hpp> +#include <irdb-core> +#include <irdb-core> #include "instruction_descriptor.h" //class wahoo::Instruction; @@ -16,14 +16,14 @@ class Function { public: Function(); - Function(libIRDB::virtual_offset_t); - Function(string, libIRDB::virtual_offset_t, int); + Function(IRDB_SDK::VirtualOffset_t); + Function(string, IRDB_SDK::VirtualOffset_t, int); ~Function(); string getName() const { return m_name; } void setName(const string p_name) { m_name = p_name; } - libIRDB::virtual_offset_t getAddress() const { return m_address; } - void setAddress(const libIRDB::virtual_offset_t p_address) { m_address = p_address; } + IRDB_SDK::VirtualOffset_t getAddress() const { return m_address; } + void setAddress(const IRDB_SDK::VirtualOffset_t p_address) { m_address = p_address; } int getSize() const { return m_size; } void setSize(const int p_size) { m_size = p_size; } int getFrameSize() const { return m_frameSize; } @@ -33,9 +33,9 @@ class Function bool operator == (const Function &); - bool operator == (const libIRDB::virtual_offset_t); + bool operator == (const IRDB_SDK::VirtualOffset_t); bool operator != (const Function &); - bool operator != (const libIRDB::virtual_offset_t); + bool operator != (const IRDB_SDK::VirtualOffset_t); bool isSafe() const { return m_isSafe; } void setSafe() { m_isSafe = true; } @@ -68,7 +68,7 @@ class Function int m_functionID; string m_name; - libIRDB::virtual_offset_t m_address; + IRDB_SDK::VirtualOffset_t m_address; int m_size; int m_frameSize; bool m_isSafe; diff --git a/meds2pdb/instruction_descriptor.cpp b/meds2pdb/instruction_descriptor.cpp index c761d75b0..d01255f91 100644 --- a/meds2pdb/instruction_descriptor.cpp +++ b/meds2pdb/instruction_descriptor.cpp @@ -21,6 +21,8 @@ #include "instruction_descriptor.h" #include "function_descriptor.h" +using namespace IRDB_SDK; + wahoo::Instruction::Instruction() { m_address = 0; @@ -36,7 +38,7 @@ wahoo::Instruction::Instruction() m_data = NULL; } -wahoo::Instruction::Instruction(libIRDB::virtual_offset_t p_address, int p_size, Function* p_func) +wahoo::Instruction::Instruction(VirtualOffset_t p_address, int p_size, Function* p_func) { m_address = p_address; m_size = p_size; diff --git a/meds2pdb/instruction_descriptor.h b/meds2pdb/instruction_descriptor.h index 5fdf972a4..2cb5bfd2e 100644 --- a/meds2pdb/instruction_descriptor.h +++ b/meds2pdb/instruction_descriptor.h @@ -3,9 +3,9 @@ #include <string> #include <set> -#include <libIRDB-core.hpp> +#include <irdb-core> -#include <libIRDB-core.hpp> +#include <irdb-core> using namespace std; @@ -18,7 +18,7 @@ class Function; class Instruction { public: Instruction(); - Instruction(libIRDB::virtual_offset_t, int p_size = -1, Function* = NULL); + Instruction(IRDB_SDK::VirtualOffset_t, int p_size = -1, Function* = NULL); ~Instruction(); void setSize(int p_size) { m_size = p_size; } @@ -29,7 +29,7 @@ class Instruction { void markStackRef(); void markVarStackRef(); - libIRDB::virtual_offset_t getAddress() const { return m_address; } + IRDB_SDK::VirtualOffset_t getAddress() const { return m_address; } int getSize() const { return m_size; } Function* getFunction() const { return m_function; } string getAsm() const { return m_asm; } @@ -48,7 +48,7 @@ class Instruction { bool isVisited() const { return m_isVisited; } private: - libIRDB::virtual_offset_t m_address; + IRDB_SDK::VirtualOffset_t m_address; int m_size; Function* m_function; string m_asm; diff --git a/meds2pdb/instrument.h b/meds2pdb/instrument.h index 753a3b370..80f85f760 100644 --- a/meds2pdb/instrument.h +++ b/meds2pdb/instrument.h @@ -31,8 +31,8 @@ /* no needed for SPRI -void add_smp_instrumentation(strata_fragment_t *frag, libIRDB::virtual_offset_t PC, insn_t *insn); -void add_smp_postinstrumentation(strata_fragment_t *frag, libIRDB::virtual_offset_t PC, insn_t *insn); +void add_smp_instrumentation(strata_fragment_t *frag, VirtualOffset_t PC, insn_t *insn); +void add_smp_postinstrumentation(strata_fragment_t *frag, VirtualOffset_t PC, insn_t *insn); */ @@ -58,7 +58,7 @@ struct reg_values /* no needed for SPRI -libIRDB::virtual_offset_t targ_watched_called_instrument(libIRDB::virtual_offset_t next_PC, watch *w, strata_fragment_t *frag); +VirtualOffset_t targ_watched_called_instrument(VirtualOffset_t next_PC, watch *w, strata_fragment_t *frag); */ diff --git a/meds2pdb/meds2pdb.cpp b/meds2pdb/meds2pdb.cpp index 56980d468..67539ea7b 100644 --- a/meds2pdb/meds2pdb.cpp +++ b/meds2pdb/meds2pdb.cpp @@ -29,11 +29,11 @@ #include <stdlib.h> #include "MEDS_AnnotationParser.hpp" #include "MEDS_FuncPrototypeAnnotation.hpp" -#include "libIRDB-core.hpp" +#include <irdb-core> using namespace std; using namespace pqxx; -using namespace libIRDB; +using namespace IRDB_SDK; using namespace MEDS_Annotation; #include <sstream> @@ -58,7 +58,7 @@ inline std::string my_to_string (const T& t) int next_address_id=0; -map<libIRDB::virtual_offset_t,int> address_to_instructionid_map; +map<VirtualOffset_t,int> address_to_instructionid_map; map<wahoo::Instruction*,int> instruction_to_addressid_map; // extract the file id from the md5 hash and the program name @@ -104,7 +104,7 @@ void insert_instructions(int fileID, const vector<wahoo::Instruction*> &instruct char buf[128]; wahoo::Instruction *instruction = instructions[i]; - libIRDB::virtual_offset_t addr = instruction->getAddress(); + auto addr = instruction->getAddress(); // assign an instruction id address_to_instructionid_map[addr]=next_address_id++; @@ -204,7 +204,6 @@ void insert_functions(int fileID, const vector<wahoo::Function*> &functions ) if (j >= functions.size()) break; wahoo::Function *f = functions[j]; string functionName = f->getName(); - //libIRDB::virtual_offset_t functionAddress = f->getAddress(); int functionFrameSize = f->getFrameSize(); int function_id = j; @@ -249,7 +248,7 @@ void update_functions(int fileID, const vector<wahoo::Function*> &functions ) if (j >= functions.size()) break; wahoo::Function *f = functions[j]; string functionName = f->getName(); - libIRDB::virtual_offset_t functionAddress = f->getAddress(); + auto functionAddress = f->getAddress(); //int functionSize = f->getSize(); int function_id = f->getFunctionID(); //int outArgsRegionSize = f->getOutArgsRegionSize(); @@ -347,7 +346,7 @@ void update_function_prototype(const vector<wahoo::Function*> &functions, char* if (j >= functions.size()) break; wahoo::Function *f = functions[j]; int function_id = f->getFunctionID(); - libIRDB::virtual_offset_t functionAddress = f->getAddress(); + auto functionAddress = f->getAddress(); VirtualOffset vo(functionAddress); //MEDS_FuncPrototypeAnnotation* fn_prototype_annot = NULL; @@ -385,33 +384,33 @@ void update_function_prototype(const vector<wahoo::Function*> &functions, char* // (3) define new function type (combo (1) + (2)) int aggregate_type_id = getNewTypeId(); int func_type_id = getNewTypeId(); - int basic_type_id = T_UNKNOWN; + int basic_type_id = IRDB_SDK::itUnknown; for (auto i = 0U; i < args->size(); ++i) { if ((*args)[i].isNumericType()) - basic_type_id = T_NUMERIC; + basic_type_id = itNumeric; else if ((*args)[i].isPointerType()) - basic_type_id = T_POINTER; + basic_type_id = itPointer; q += "INSERT into " + typesTable + " (type_id, type, name, ref_type_id, pos) VALUES ("; q += txn.quote(my_to_string(aggregate_type_id)) + ","; - q += txn.quote(my_to_string(T_AGGREGATE)) + ","; + q += txn.quote(my_to_string(itAggregate)) + ","; q += txn.quote(string(f->getName()) + "_arg") + ","; q += txn.quote(my_to_string(basic_type_id)) + ","; q += txn.quote(my_to_string(i)) + ");"; } - int return_type_id = T_UNKNOWN; + int return_type_id = itUnknown; if (returnArg) { if (returnArg->isNumericType()) - return_type_id = T_NUMERIC; + return_type_id = itNumeric; else if (returnArg->isPointerType()) - return_type_id = T_POINTER; + return_type_id = itPointer; else - return_type_id = T_UNKNOWN; + return_type_id = itUnknown; } // new function type id (ok to have duplicate prototypes) @@ -421,7 +420,7 @@ void update_function_prototype(const vector<wahoo::Function*> &functions, char* q += "INSERT into " + typesTable + " (type_id, type, name, ref_type_id, ref_type_id2) VALUES ("; q += txn.quote(my_to_string(func_type_id)) + ","; - q += txn.quote(my_to_string(T_FUNC)) + ","; + q += txn.quote(my_to_string(itFunc)) + ","; q += txn.quote(string(f->getName()) + "_func") + ","; q += txn.quote(my_to_string(return_type_id)) + ","; q += txn.quote(my_to_string(aggregate_type_id)) + ");"; diff --git a/meds2pdb/meds_all.h b/meds2pdb/meds_all.h index a06390efc..f551ac1dc 100644 --- a/meds2pdb/meds_all.h +++ b/meds2pdb/meds_all.h @@ -29,7 +29,9 @@ #include <string.h> #include <assert.h> -#include <libIRDB-core.hpp> +#include <irdb-core> + +using namespace IRDB_SDK; #include "strata_defines.h" diff --git a/meds2pdb/null_transform.cpp b/meds2pdb/null_transform.cpp index 37ca87aec..c675d20ce 100644 --- a/meds2pdb/null_transform.cpp +++ b/meds2pdb/null_transform.cpp @@ -20,7 +20,7 @@ #include <iostream> -#include <libIRDB-core.hpp> +#include <irdb-core> // #include "elfio/elfio.hpp" @@ -49,9 +49,9 @@ using namespace wahoo; void NullTransform::rewrite() { // only transform instructions contained in well-defined functions - for (map<libIRDB::virtual_offset_t, wahoo::Function*>::iterator it = m_functions.begin(); it != m_functions.end(); ++it) + for (map<VirtualOffset_t, wahoo::Function*>::iterator it = m_functions.begin(); it != m_functions.end(); ++it) { - libIRDB::virtual_offset_t addr = it->first; + VirtualOffset_t addr = it->first; wahoo::Function* f = it->second; if (!f) { diff --git a/meds2pdb/read_annot_file.cpp b/meds2pdb/read_annot_file.cpp index 1385f05b1..10508f237 100644 --- a/meds2pdb/read_annot_file.cpp +++ b/meds2pdb/read_annot_file.cpp @@ -46,7 +46,7 @@ void ignore_result(const T& v) { (void)v; } void read_annot_file(char fn[]) { FILE* fin=nullptr; - libIRDB::virtual_offset_t addr=0; + VirtualOffset_t addr=0; union { int size, type;} size_type_u; char type[200]; char scope[200]; @@ -281,7 +281,7 @@ void read_annot_file(char fn[]) #endif else if (strcmp(scope, "BELONGTO") == 0) { - libIRDB::virtual_offset_t func_addr; + VirtualOffset_t func_addr; unsigned int tmp=0; ignore_result(fscanf(fin, "%x", &tmp)); func_addr=tmp; diff --git a/meds2pdb/rewriter.cpp b/meds2pdb/rewriter.cpp index a1f3b1ea8..f95a60ec4 100644 --- a/meds2pdb/rewriter.cpp +++ b/meds2pdb/rewriter.cpp @@ -23,11 +23,11 @@ #include <string> #include <set> #include <stdlib.h> -#include <libIRDB-core.hpp> +#include <irdb-core> #include "meds_all.h" -#include <libIRDB-core.hpp> +#include <irdb-core> //#include "elfio/elfio.hpp" @@ -35,7 +35,7 @@ using namespace std; -using namespace libIRDB; +using namespace IRDB_SDK; template <class T> void ignore_result(T /* res */) { } @@ -54,7 +54,7 @@ Rewriter::~Rewriter() { } -wahoo::Function* Rewriter::ensureFunctionExists(const libIRDB::virtual_offset_t p_addr) +wahoo::Function* Rewriter::ensureFunctionExists(const VirtualOffset_t p_addr) { if (m_functions.count(p_addr) > 0) return m_functions[p_addr]; @@ -65,7 +65,7 @@ wahoo::Function* Rewriter::ensureFunctionExists(const libIRDB::virtual_offset_t return fn; } -wahoo::Instruction* Rewriter::ensureInstructionExists(const libIRDB::virtual_offset_t p_addr) +wahoo::Instruction* Rewriter::ensureInstructionExists(const VirtualOffset_t p_addr) { if (m_instructions.count(p_addr) > 0) return m_instructions[p_addr]; @@ -82,7 +82,7 @@ wahoo::Instruction* Rewriter::ensureInstructionExists(const libIRDB::virtual_off void Rewriter::readAnnotationFile(char p_filename[]) { FILE* fin=NULL; - libIRDB::virtual_offset_t addr = 0, prevStackDeallocPC = 0; + VirtualOffset_t addr = 0, prevStackDeallocPC = 0; union { int size, type;} size_type_u; char type[200]; char scope[200]; @@ -323,7 +323,7 @@ void Rewriter::readAnnotationFile(char p_filename[]) } else if (strcmp(scope, "BELONGTO") == 0) { - libIRDB::virtual_offset_t func_addr; + VirtualOffset_t func_addr; ignore_result(fscanf(fin, "%p", (void**)&func_addr)); instrmap_hash_key_t* key = (instrmap_hash_key_t*)spri_allocate_type(sizeof(instrmap_hash_key_t)); instrmap_hash_value_t* val = (instrmap_hash_value_t*)spri_allocate_type(sizeof(instrmap_hash_value_t)); @@ -641,14 +641,14 @@ void Rewriter::readElfFile(char p_filename[]) sprintf(buf, "%s -d --prefix-addresses %s | grep \"^[0-9]\"", objdump, p_filename); printf("Running objdump, like so: %s\n", buf); FILE* pin=popen(buf, "r"); - libIRDB::virtual_offset_t addr; + VirtualOffset_t addr; assert(pin); void* tmp=NULL; ignore_result(fscanf(pin, "%p", &tmp)); - addr=(libIRDB::virtual_offset_t)tmp; + addr=(VirtualOffset_t)tmp; ignore_result(fgets(buf,sizeof(buf),pin)); do { @@ -658,7 +658,7 @@ void Rewriter::readElfFile(char p_filename[]) m_instructions[addr]=new wahoo::Instruction(addr,-1,NULL); } ignore_result(fscanf(pin,"%p", &tmp)); - addr=(libIRDB::virtual_offset_t)tmp; + addr=(VirtualOffset_t)tmp; ignore_result(fgets(buf,sizeof(buf),pin)); } while(!feof(pin)); @@ -693,7 +693,8 @@ void Rewriter::disassemble() wahoo::Instruction *instr = instructions[j]; const auto instr_data=(void*)(getElfReader()->getInstructionBuffer(instr->getAddress())); - const auto disasm=DecodedInstruction_t(instr->getAddress(), instr_data, 16); + const auto p_disasm=DecodedInstruction_t::factory(instr->getAddress(), instr_data, 16); + const auto &disasm=*p_disasm; /* maybe this isn't in a section so getInstructionBuffer returns 0 */ @@ -718,7 +719,7 @@ void Rewriter::disassemble() } } -void Rewriter::addSimpleRewriteRule(wahoo::Function* p_func, char *p_origInstr, int p_origSize, libIRDB::virtual_offset_t p_origAddress, char *p_newInstr) +void Rewriter::addSimpleRewriteRule(wahoo::Function* p_func, char *p_origInstr, int p_origSize, VirtualOffset_t p_origAddress, char *p_newInstr) { char buf[1024]; char aspri[2048]; @@ -753,7 +754,7 @@ void Rewriter::commitFn2SPRI(wahoo::Function *p_func, FILE *p_fp) vector<wahoo::Function*> Rewriter::getCandidateFunctions() { vector<wahoo::Function*> candidates; - for (map<libIRDB::virtual_offset_t, wahoo::Function*>::iterator it = m_functions.begin(); it != m_functions.end(); ++it) + for (map<VirtualOffset_t, wahoo::Function*>::iterator it = m_functions.begin(); it != m_functions.end(); ++it) { wahoo::Function* f = it->second; @@ -769,7 +770,7 @@ vector<wahoo::Function*> Rewriter::getCandidateFunctions() vector<wahoo::Function*> Rewriter::getNonCandidateFunctions() { vector<wahoo::Function*> nonCandidates; - for (map<libIRDB::virtual_offset_t, wahoo::Function*>::iterator it = m_functions.begin(); it != m_functions.end(); ++it) + for (map<VirtualOffset_t, wahoo::Function*>::iterator it = m_functions.begin(); it != m_functions.end(); ++it) { wahoo::Function* f = it->second; @@ -786,7 +787,7 @@ vector<wahoo::Function*> Rewriter::getAllFunctions() { vector<wahoo::Function*> allFunctions; - for (map<libIRDB::virtual_offset_t, wahoo::Function*>::iterator it = m_functions.begin(); it != m_functions.end(); ++it) + for (map<VirtualOffset_t, wahoo::Function*>::iterator it = m_functions.begin(); it != m_functions.end(); ++it) { wahoo::Function* f = it->second; @@ -802,7 +803,7 @@ vector<wahoo::Instruction*> Rewriter::getAllInstructions() { vector<wahoo::Instruction*> allInstructions; - for (map<libIRDB::virtual_offset_t, wahoo::Instruction*>::iterator it = m_instructions.begin(); it != m_instructions.end(); ++it) + for (map<VirtualOffset_t, wahoo::Instruction*>::iterator it = m_instructions.begin(); it != m_instructions.end(); ++it) { wahoo::Instruction* instr = it->second; @@ -827,7 +828,7 @@ map<wahoo::Function*, double> Rewriter::getFunctionCoverage(char *p_instructionF return coverage; } - set<libIRDB::virtual_offset_t> visitedInstructions; + set<VirtualOffset_t> visitedInstructions; infile.seekg(0,ios::end); size_t size = infile.tellg(); @@ -844,7 +845,7 @@ map<wahoo::Function*, double> Rewriter::getFunctionCoverage(char *p_instructionF infile>>hex>>address; - visitedInstructions.insert((libIRDB::virtual_offset_t) address); + visitedInstructions.insert((VirtualOffset_t) address); } vector<wahoo::Instruction*> allInstructions = getAllInstructions(); diff --git a/meds2pdb/rewriter.h b/meds2pdb/rewriter.h index 1b2a40a23..9614dbced 100644 --- a/meds2pdb/rewriter.h +++ b/meds2pdb/rewriter.h @@ -1,6 +1,6 @@ #include <map> #include <set> -#include <libIRDB-core.hpp> +#include <irdb-core> // #include "elfio/elfio.hpp" //#include "elfio/elfio_dump.hpp" @@ -35,18 +35,18 @@ class Rewriter void disassemble(); // one instruction modification - void addSimpleRewriteRule(wahoo::Function* p_func, char *p_origInstr, int p_origSize, libIRDB::virtual_offset_t p_origAddress, char *p_newInstr); + void addSimpleRewriteRule(wahoo::Function* p_func, char *p_origInstr, int p_origSize, IRDB_SDK::VirtualOffset_t p_origAddress, char *p_newInstr); // commit function to AsmSPRI file void commitFn2SPRI(wahoo::Function* p_func, FILE *p_file); protected: - map<libIRDB::virtual_offset_t, wahoo::Function*> m_functions; - map<libIRDB::virtual_offset_t, wahoo::Instruction*> m_instructions; + map<IRDB_SDK::VirtualOffset_t, wahoo::Function*> m_functions; + map<IRDB_SDK::VirtualOffset_t, wahoo::Instruction*> m_instructions; private: - wahoo::Function* ensureFunctionExists(const libIRDB::virtual_offset_t); - wahoo::Instruction* ensureInstructionExists(const libIRDB::virtual_offset_t); + wahoo::Function* ensureFunctionExists(const IRDB_SDK::VirtualOffset_t); + wahoo::Instruction* ensureInstructionExists(const IRDB_SDK::VirtualOffset_t); private: ElfReader* m_elfReader; diff --git a/meds2pdb/stackref_hash.cpp b/meds2pdb/stackref_hash.cpp index b6ee871f1..baba24981 100644 --- a/meds2pdb/stackref_hash.cpp +++ b/meds2pdb/stackref_hash.cpp @@ -47,7 +47,7 @@ long stackrefs_key_compare(void* key1, void* key2) /* add something to the stackrefs_hash hashtable */ -stackref_hash_value_t *add_stack_ref(libIRDB::virtual_offset_t pc,int size, int offset) +stackref_hash_value_t *add_stack_ref(VirtualOffset_t pc,int size, int offset) { stackref_hash_key_t *sshk=(stackref_hash_key_t*)spri_allocate_type(sizeof(stackref_hash_key_t )); stackref_hash_value_t *sshv=(stackref_hash_value_t*)spri_allocate_type(sizeof(stackref_hash_value_t )); @@ -64,7 +64,7 @@ stackref_hash_value_t *add_stack_ref(libIRDB::virtual_offset_t pc,int size, int return sshv; } -stackref_hash_value_t *add_stack_ref_field(stackref_hash_value_t* parent, libIRDB::virtual_offset_t pc, int size, int offset) +stackref_hash_value_t *add_stack_ref_field(stackref_hash_value_t* parent, VirtualOffset_t pc, int size, int offset) { stackref_hash_key_t *sshk=(stackref_hash_key_t*)spri_allocate_type(sizeof(stackref_hash_key_t )); stackref_hash_value_t *sshv=(stackref_hash_value_t*)spri_allocate_type(sizeof(stackref_hash_value_t )); diff --git a/meds2pdb/stackref_hash.h b/meds2pdb/stackref_hash.h index e409a9249..b5f526aa3 100644 --- a/meds2pdb/stackref_hash.h +++ b/meds2pdb/stackref_hash.h @@ -35,7 +35,7 @@ extern Hashtable *stackrefs_hash; typedef struct stackref_hash_key stackref_hash_key_t; struct stackref_hash_key { - libIRDB::virtual_offset_t pc; + VirtualOffset_t pc; }; typedef struct stackref_hash_value stackref_hash_value_t; @@ -52,8 +52,8 @@ long stackrefs_compute_hash(void* key1); long stackrefs_key_compare(void* key1, void* key2); -stackref_hash_value_t *add_stack_ref(libIRDB::virtual_offset_t pc,int size, int offset); -stackref_hash_value_t *add_stack_ref_field(stackref_hash_value_t *parent, libIRDB::virtual_offset_t pc,int size, int offset); +stackref_hash_value_t *add_stack_ref(VirtualOffset_t pc,int size, int offset); +stackref_hash_value_t *add_stack_ref_field(stackref_hash_value_t *parent, VirtualOffset_t pc,int size, int offset); #endif diff --git a/thanos/SConscript b/thanos/SConscript index 32e69a3b7..3d5b5bfd0 100644 --- a/thanos/SConscript +++ b/thanos/SConscript @@ -7,11 +7,8 @@ myenv=env.Clone() myenv.Replace(SECURITY_TRANSFORMS_HOME=os.environ['SECURITY_TRANSFORMS_HOME']) cpppath=''' - $SECURITY_TRANSFORMS_HOME/include + $IRDB_SDK/include $SECURITY_TRANSFORMS_HOME/libIRDB/include - $SECURITY_TRANSFORMS_HOME/libMEDSannotation/include - $SECURITY_TRANSFORMS_HOME/libtransform/include - $SECURITY_TRANSFORMS_HOME/libEXEIO/include ''' @@ -22,7 +19,7 @@ myenv.Append(CXXFLAGS = " -std=c++11 -Wall ") pgm="thanos.exe" LIBPATH="$SECURITY_TRANSFORMS_HOME/lib" -LIBS=Split( env.subst('$BASE_IRDB_LIBS')+ " IRDB-cfg IRDB-util IRDB-core transform MEDSannotation pqxx pq dl") +LIBS=Split( env.subst('$BASE_IRDB_LIBS')+ " IRDB-core transform pqxx dl") myenv=myenv.Clone(CPPPATH=Split(cpppath)) pgm=myenv.Program(pgm, files, LIBPATH=LIBPATH, LIBS=LIBS) install=myenv.Install("$SECURITY_TRANSFORMS_HOME/plugins_install", pgm) diff --git a/thanos/thanos.cpp b/thanos/thanos.cpp index a5523b239..e336c3307 100644 --- a/thanos/thanos.cpp +++ b/thanos/thanos.cpp @@ -1,3 +1,4 @@ +#include <irdb-core> #include <libIRDB-core.hpp> #include <dlfcn.h> #include <vector> @@ -14,8 +15,7 @@ using namespace std; -using namespace libIRDB; -using namespace Transform_SDK; +using namespace IRDB_SDK; #define ALLOF(a) begin(a),end(a) @@ -67,7 +67,7 @@ class ThanosPlugin_t static const unique_ptr<IRDBObjects_t> shared_objects; }; // initialize private static data member -const unique_ptr<IRDBObjects_t> ThanosPlugin_t::shared_objects(new IRDBObjects_t()); +const unique_ptr<IRDBObjects_t> ThanosPlugin_t::shared_objects(new libIRDB::IRDBObjects_t()); using PluginList_t = vector<unique_ptr<ThanosPlugin_t>>; PluginList_t getPlugins(const int argc, char const *const argv[]); @@ -240,11 +240,11 @@ int ThanosPlugin_t::runPlugin() return -1; } - const void *const sym = dlsym(dlhdl, "GetTransformStep"); + const void *const sym = dlsym(dlhdl, "getTransformStep"); if(sym == NULL) { const auto err=dlerror(); - *thanos_log<<"Cannot find GetTransformStep in "<<step_name<<": "<<err<<endl; + *thanos_log<<"Cannot find getTransformStep in "<<step_name<<": "<<err<<endl; return -1; } @@ -351,7 +351,7 @@ int ThanosPlugin_t::executeStep(TransformStep_t& the_step, const bool are_debugg else { // commit changes (in case this step fails) and reset interface - pqxx_interface->Commit(); + pqxx_interface->commit(); pqxx_interface = shared_objects->resetDBInterface(); } } @@ -392,7 +392,7 @@ int ThanosPlugin_t::executeStep(TransformStep_t& the_step, const bool are_debugg else if(are_debugging) { // commit changes (in case next step fails) and reset interface - pqxx_interface->Commit(); + pqxx_interface->commit(); pqxx_interface = shared_objects->resetDBInterface(); } } @@ -407,7 +407,7 @@ int ThanosPlugin_t::executeStep(TransformStep_t& the_step, const bool are_debugg else { // commit changes (in case next step fails) and reset interface - pqxx_interface->Commit(); + pqxx_interface->commit(); pqxx_interface = shared_objects->resetDBInterface(); } } @@ -427,7 +427,7 @@ int ThanosPlugin_t::saveChanges() else { // commit changes and reset interface - pqxx_interface->Commit(); + pqxx_interface->commit(); pqxx_interface = shared_objects->resetDBInterface(); return 0; } diff --git a/tools/SConscript b/tools/SConscript index 285442475..bfaf22cb6 100644 --- a/tools/SConscript +++ b/tools/SConscript @@ -5,15 +5,15 @@ Import('env') tools=[] dirs=''' + selective_cfi + ''' + +nobuild_dirs=''' cover fix_rets safefr - selective_cfi spasm hook_start - ''' - -nobuild_dirs=''' cookbook simple_cdi ret_shadow_stack diff --git a/tools/selective_cfi/SConscript b/tools/selective_cfi/SConscript index a338045a0..78cc1e98e 100644 --- a/tools/selective_cfi/SConscript +++ b/tools/selective_cfi/SConscript @@ -7,6 +7,7 @@ myenv=env.Clone() myenv.Replace(SECURITY_TRANSFORMS_HOME=os.environ['SECURITY_TRANSFORMS_HOME']) cpppath=''' + $IRDB_SDK/include $SECURITY_TRANSFORMS_HOME/include $SECURITY_TRANSFORMS_HOME/libIRDB/include $SECURITY_TRANSFORMS_HOME/libMEDSannotation/include diff --git a/tools/selective_cfi/color_map.cpp b/tools/selective_cfi/color_map.cpp index 9a050f4bd..587ea2035 100644 --- a/tools/selective_cfi/color_map.cpp +++ b/tools/selective_cfi/color_map.cpp @@ -2,7 +2,7 @@ #include "color_map.hpp" using namespace std; -using namespace libIRDB; +using namespace IRDB_SDK; bool ColoredInstructionNonces_t::create() @@ -10,7 +10,7 @@ bool ColoredInstructionNonces_t::create() UniqueICFSSet_t unique_icfs; assert(firp); - const ICFSSet_t& all_icfs=firp->GetAllICFS(); + const ICFSSet_t& all_icfs=firp->getAllICFS(); for(ICFSSet_t::iterator it=all_icfs.begin(); it!=all_icfs.end(); ++it) { ICFS_t* p=*it; @@ -19,9 +19,10 @@ bool ColoredInstructionNonces_t::create() } ColoredSlotValue_t v; - for(UniqueICFSSet_t::iterator it=unique_icfs.begin(); it!=unique_icfs.end(); ++it) + for(auto the_icfs : unique_icfs) { - const ICFS_t& the_icfs=*it; + // const ICFS_t& the_icfs=*it; + // const auto the_icfs=*it; for(auto slot_no=0U; /* loop until break */ ; slot_no++) { @@ -39,9 +40,8 @@ bool ColoredInstructionNonces_t::create() } // check if any of the targets for this branch already have a slot filled. - for(ICFS_t::iterator it2=the_icfs.begin(); it2!=the_icfs.end(); ++it2) + for(auto target : the_icfs) { - Instruction_t* target=*it2; if(color_assignments[target][slot_no].IsValid()) goto next_slot; } @@ -56,7 +56,7 @@ bool ColoredInstructionNonces_t::create() Instruction_t* target=*it2; color_assignments[target][slot_no]=v; cout<<"Setting slot[-"<<hex<<v.GetPosition()<<"]=color["<<hex<<v.GetNonceValue()<<dec<<"]" - << " for "<<hex<<target->GetBaseID()<<":"<<target->getDisassembly() + << " for "<<hex<<target->getBaseID()<<":"<<target->getDisassembly() << endl; } @@ -74,16 +74,15 @@ bool ColoredInstructionNonces_t::create() #if 1 /* debug code */ UniqueICFSSet_t used_icfs; - for(InstructionSet_t::iterator it=firp->GetInstructions().begin(); it!=firp->GetInstructions().end(); ++it) + for(auto insn : firp->getInstructions()) { - Instruction_t* insn=*it; - if(insn->GetIBTargets()) + if(insn->getIBTargets()) { v=GetColorOfIB(insn); cout<<"IB assigned " <<"slot[-"<<v.GetPosition()<<"]=color["<<hex<<v.GetNonceValue()<<dec<<"]" - << " for "<<insn->GetBaseID()<<":"<<insn->getDisassembly() << endl; + << " for "<<insn->getBaseID()<<":"<<insn->getDisassembly() << endl; - used_icfs.insert(*insn->GetIBTargets()); + used_icfs.insert(*insn->getIBTargets()); } } diff --git a/tools/selective_cfi/color_map.hpp b/tools/selective_cfi/color_map.hpp index 2ffb0992d..2f78675d3 100644 --- a/tools/selective_cfi/color_map.hpp +++ b/tools/selective_cfi/color_map.hpp @@ -21,7 +21,7 @@ #ifndef color_map_hpp #define color_map_hpp -#include <libIRDB-core.hpp> +#include <irdb-core> #include <stdint.h> @@ -73,16 +73,16 @@ typedef std::map<int,ColoredSlotValue_t> ColoredSlotValues_t; class ColoredInstructionNonces_t { public: - ColoredInstructionNonces_t(libIRDB::FileIR_t *the_firp) + ColoredInstructionNonces_t(IRDB_SDK::FileIR_t *the_firp) : firp(the_firp), slot_size(1), slot_values(255) { } - ColoredInstructionNonces_t(libIRDB::FileIR_t *the_firp, int the_slot_size) + ColoredInstructionNonces_t(IRDB_SDK::FileIR_t *the_firp, int the_slot_size) : firp(the_firp), slot_size(the_slot_size), slot_values(MaxNonceValForSlotSize(the_slot_size)) { } - ColoredSlotValues_t GetColorsOfIBT (libIRDB::Instruction_t* i) + ColoredSlotValues_t GetColorsOfIBT (IRDB_SDK::Instruction_t* i) { return color_assignments[i]; } - ColoredSlotValue_t GetColorOfIB (libIRDB::Instruction_t* i) - { assert(i->GetIBTargets()); return slot_assignments[*i->GetIBTargets()]; } + ColoredSlotValue_t GetColorOfIB (IRDB_SDK::Instruction_t* i) + { assert(i->getIBTargets()); return slot_assignments[*i->getIBTargets()]; } int NumberSlotsUsed() { return slots_used.size(); } @@ -94,7 +94,7 @@ class ColoredInstructionNonces_t bool create(); // the IR we're working on. - libIRDB::FileIR_t* firp; + IRDB_SDK::FileIR_t* firp; // used to describe how big a nonce slot is. for now, 1 byte. const int slot_size; @@ -106,11 +106,11 @@ class ColoredInstructionNonces_t // information for each IBT. // a map for each instruction, which contains a ColorSlotValue_t for each slot used. // instruction -> ( int-> slot_value ) - std::map<libIRDB::Instruction_t*, ColoredSlotValues_t> color_assignments; + std::map<IRDB_SDK::Instruction_t*, ColoredSlotValues_t> color_assignments; // information for each IB (as indexed by the IBs ICFS). // the slot that each IB uses. ICFS_t -> slot_value - std::map<libIRDB::ICFS_t, ColoredSlotValue_t> slot_assignments; + std::map<IRDB_SDK::InstructionSet_t, ColoredSlotValue_t> slot_assignments; NonceValueType_t MaxNonceValForSlotSize(int slot_size) { @@ -128,12 +128,12 @@ class ColoredInstructionNonces_t // a simple way to sort ICFS. class UniqueICFSSetSorter_t; -typedef std::set<libIRDB::ICFS_t, UniqueICFSSetSorter_t> UniqueICFSSet_t; +typedef std::set<IRDB_SDK::InstructionSet_t, UniqueICFSSetSorter_t> UniqueICFSSet_t; class UniqueICFSSetSorter_t { public: - bool operator() (const libIRDB::ICFS_t& a, const libIRDB::ICFS_t& b) const + bool operator() (const IRDB_SDK::InstructionSet_t& a, const IRDB_SDK::InstructionSet_t& b) const { if(a.size() == b.size()) return a<b; return a.size() < b.size() ; diff --git a/tools/selective_cfi/scfi_driver.cpp b/tools/selective_cfi/scfi_driver.cpp index 0bd71b6d0..2e5d79607 100644 --- a/tools/selective_cfi/scfi_driver.cpp +++ b/tools/selective_cfi/scfi_driver.cpp @@ -20,13 +20,13 @@ #include <stdlib.h> #include <fstream> -#include <libIRDB-core.hpp> +#include <irdb-core> #include <libgen.h> #include "scfi_instr.hpp" using namespace std; -using namespace libIRDB; +using namespace IRDB_SDK; #define BINARY_NAME "a.ncexe" @@ -206,59 +206,53 @@ int main(int argc, char **argv) string programName(argv[0]); int variantID = atoi(argv[1]); - VariantID_t *pidp=NULL; - /* setup the interface to the sql server */ - pqxxDB_t pqxx_interface; - BaseObj_t::SetInterface(&pqxx_interface); + auto pqxx_interface=pqxxDB_t::factory(); + BaseObj_t::setInterface(pqxx_interface.get()); - pidp=new VariantID_t(variantID); - assert(pidp->IsRegistered()==true); + auto pidp=VariantID_t::factory(variantID); + assert(pidp->isRegistered()==true); cout<<"selective_cfi.exe started\n"; bool one_success = false; bool seen_failures = false; - for(set<File_t*>::iterator it=pidp->GetFiles().begin(); - it!=pidp->GetFiles().end(); - ++it) + for(auto this_file : pidp->getFiles()) { - File_t* this_file = *it; - FileIR_t *firp = new FileIR_t(*pidp, this_file); + auto firp = FileIR_t::factory(pidp.get(), this_file); - cout<<"Transforming "<<this_file->GetURL()<<endl; + cout<<"Transforming "<<this_file->getURL()<<endl; assert(firp && pidp); try { - SCFI_Instrument scfii(firp, nonce_size, exe_nonce_size, do_coloring, do_color_exe_nonces, do_common_slow_path, do_jumps, do_calls, do_rets, do_safefn, do_multimodule, do_exe_nonce_for_call); + SCFI_Instrument scfii(firp.get(), nonce_size, exe_nonce_size, do_coloring, do_color_exe_nonces, do_common_slow_path, do_jumps, do_calls, do_rets, do_safefn, do_multimodule, do_exe_nonce_for_call); int success=scfii.execute(); if (success) { - cout<<"Writing changes for "<<this_file->GetURL()<<endl; + cout<<"Writing changes for "<<this_file->getURL()<<endl; one_success = true; - firp->WriteToDB(); - delete firp; + firp->writeToDB(); } else { seen_failures = true; - cout<<"Skipping (no changes) "<<this_file->GetURL()<<endl; + cout<<"Skipping (no changes) "<<this_file->getURL()<<endl; } } catch (DatabaseError_t pnide) { seen_failures = true; - cerr << programName << ": Unexpected database error: " << pnide << "file url: " << this_file->GetURL() << endl; + cerr << programName << ": Unexpected database error: " << pnide << "file url: " << this_file->getURL() << endl; } catch (...) { seen_failures = true; - cerr << programName << ": Unexpected error file url: " << this_file->GetURL() << endl; + cerr << programName << ": Unexpected error file url: " << this_file->getURL() << endl; } } // end file iterator @@ -266,7 +260,7 @@ int main(int argc, char **argv) if (one_success) { cout<<"Commiting changes...\n"; - pqxx_interface.Commit(); + pqxx_interface->commit(); } if(seen_failures) diff --git a/tools/selective_cfi/scfi_instr.cpp b/tools/selective_cfi/scfi_instr.cpp index 1d968ae4c..91cff3534 100644 --- a/tools/selective_cfi/scfi_instr.cpp +++ b/tools/selective_cfi/scfi_instr.cpp @@ -35,7 +35,7 @@ using namespace std; -using namespace libIRDB; +using namespace IRDB_SDK; using namespace IRDBUtility; string getRetDataBits() @@ -51,10 +51,10 @@ string getRetDataBits() Relocation_t* SCFI_Instrument::FindRelocation(Instruction_t* insn, string type) { RelocationSet_t::iterator rit; - for( rit=insn->GetRelocations().begin(); rit!=insn->GetRelocations().end(); ++rit) + for( rit=insn->getRelocations().begin(); rit!=insn->getRelocations().end(); ++rit) { Relocation_t& reloc=*(*rit); - if(reloc.GetType()==type) + if(reloc.getType()==type) { return &reloc; } @@ -64,22 +64,22 @@ Relocation_t* SCFI_Instrument::FindRelocation(Instruction_t* insn, string type) bool SCFI_Instrument::isSafeFunction(Instruction_t* insn) { - return (insn && insn->GetFunction() && insn->GetFunction()->IsSafe()); + return (insn && insn->getFunction() && insn->getFunction()->isSafe()); } bool SCFI_Instrument::isCallToSafeFunction(Instruction_t* insn) { - if (insn && insn->GetTarget() && insn->GetTarget()->GetFunction()) + if (insn && insn->getTarget() && insn->getTarget()->getFunction()) { if(getenv("SCFI_VERBOSE")!=NULL) { - if (insn->GetTarget()->GetFunction()->IsSafe()) + if (insn->getTarget()->getFunction()->isSafe()) { - cout << "Function " << insn->GetTarget()->GetFunction()->GetName() << " is deemed safe" << endl; + cout << "Function " << insn->getTarget()->getFunction()->getName() << " is deemed safe" << endl; } } - return insn->GetTarget()->GetFunction()->IsSafe(); + return insn->getTarget()->getFunction()->isSafe(); } return false; @@ -87,9 +87,12 @@ bool SCFI_Instrument::isCallToSafeFunction(Instruction_t* insn) Relocation_t* SCFI_Instrument::create_reloc(Instruction_t* insn) { - Relocation_t* reloc=new Relocation_t; - insn->GetRelocations().insert(reloc); - firp->GetRelocations().insert(reloc); + /* + * Relocation_t* reloc=new Relocation_t; + insn->getRelocations().insert(reloc); + firp->getRelocations().insert(reloc); + */ + auto reloc=firp->addNewRelocation(insn,0,"error-if-seen"); // will update offset and type in caller return reloc; } @@ -116,7 +119,7 @@ unsigned int SCFI_Instrument::GetExeNonceOffset(Instruction_t* insn) { if(exe_nonce_color_map) { - assert(insn->GetIBTargets()); + assert(insn->getIBTargets()); // We can't know the offset yet because this nonce may need to get // shoved into multiple exe nonces, so just return the position. cout << "EXE NONCE OFFSET IS: "<< exe_nonce_color_map->GetColorOfIB(insn).GetPosition() << endl; @@ -130,7 +133,7 @@ NonceValueType_t SCFI_Instrument::GetExeNonce(Instruction_t* insn) { if(exe_nonce_color_map) { - assert(insn->GetIBTargets()); + assert(insn->getIBTargets()); return exe_nonce_color_map->GetColorOfIB(insn).GetNonceValue(); } // Otherwise, all nonces are the same @@ -158,7 +161,7 @@ unsigned int SCFI_Instrument::GetNonceOffset(Instruction_t* insn) { if(color_map) { - assert(insn->GetIBTargets()); + assert(insn->getIBTargets()); return (color_map->GetColorOfIB(insn).GetPosition()+1) * GetNonceSize(insn); } return GetNonceSize(insn); @@ -170,7 +173,7 @@ NonceValueType_t SCFI_Instrument::GetNonce(Instruction_t* insn) /* for now, it's just f4 as the nonce */ if(color_map) { - assert(insn->GetIBTargets()); + assert(insn->getIBTargets()); return color_map->GetColorOfIB(insn).GetNonceValue(); } // Otherwise, all nonces are the same @@ -198,32 +201,28 @@ bool SCFI_Instrument::mark_targets() { int targets=0, ind_targets=0, exe_nonce_targets=0; // Make sure no unresolved instructions are in the insn set - firp->AssembleRegistry(); - firp->SetBaseIDS(); + firp->assembleRegistry(); + firp->setBaseIDS(); // create new preds (we've added instructions) - InstructionPredecessors_t newPreds; + libIRDB::InstructionPredecessors_t newPreds; newPreds.AddFile(firp); // Make sure the new insns added in this loop are not processed in this loop // (ok since none of the them should receive nonces) - auto insn_set = firp->GetInstructions(); - for(InstructionSet_t::iterator it=insn_set.begin(); - it!=insn_set.end(); - ++it) + auto insn_set = firp->getInstructions(); + for(auto insn : insn_set) { targets++; - Instruction_t* insn=*it; - if(insn->GetIndirectBranchTargetAddress()) + if(insn->getIndirectBranchTargetAddress()) { // make sure there are no fallthroughs to nonces. - for(InstructionSet_t::iterator pred_it=newPreds[insn].begin(); pred_it!=newPreds[insn].end(); ++pred_it) + for(auto the_pred : newPreds[insn]) { - Instruction_t* the_pred=*pred_it; - if(the_pred->GetFallthrough()==insn) + if(the_pred->getFallthrough()==insn) { Instruction_t* jmp=addNewAssembly(firp,NULL, "jmp 0x0"); - the_pred->SetFallthrough(jmp); - jmp->SetTarget(insn); + the_pred->setFallthrough(jmp); + jmp->setTarget(insn); } } @@ -249,9 +248,9 @@ bool SCFI_Instrument::mark_targets() type=string("cfi_nonce=(pos=") + to_string(position) + ",nv=" + to_string(noncevalue) + ",sz="+ to_string(size)+ ")"; Relocation_t* reloc=create_reloc(insn); - reloc->SetOffset(-position*size); - reloc->SetType(type); - cout<<"Created reloc='"+type+"' for "<<std::hex<<insn->GetBaseID()<<":"<<insn->getDisassembly()<<endl; + reloc->setOffset(-position*size); + reloc->setType(type); + cout<<"Created reloc='"+type+"' for "<<std::hex<<insn->getBaseID()<<":"<<insn->getDisassembly()<<endl; } } else @@ -259,26 +258,26 @@ bool SCFI_Instrument::mark_targets() type=string("cfi_nonce=(pos=") + to_string(-((int) GetNonceOffset(insn))) + ",nv=" + to_string(GetNonce(insn)) + ",sz="+ to_string(GetNonceSize(insn))+ ")"; Relocation_t* reloc=create_reloc(insn); - reloc->SetOffset(-((int) GetNonceOffset(insn))); - reloc->SetType(type); - cout<<"Created reloc='"+type+"' for "<<std::hex<<insn->GetBaseID()<<":"<<insn->getDisassembly()<<endl; + reloc->setOffset(-((int) GetNonceOffset(insn))); + reloc->setType(type); + cout<<"Created reloc='"+type+"' for "<<std::hex<<insn->getBaseID()<<":"<<insn->getDisassembly()<<endl; } } - if(do_exe_nonce_for_call && DecodedInstruction_t(insn).isCall()) + if(do_exe_nonce_for_call && DecodedInstruction_t::factory(insn)->isCall()) { ++exe_nonce_targets; if(do_color_exe_nonces) { // The colors we want are not on the call, but on its return target. - ColoredSlotValues_t v=exe_nonce_color_map->GetColorsOfIBT(insn->GetFallthrough()); + ColoredSlotValues_t v=exe_nonce_color_map->GetColorsOfIBT(insn->getFallthrough()); // The return target gets a regular nonce as well, so there may be an inserted jmp // in the way of the original IBT that has our colors. if(v.size() == 0) { - v=exe_nonce_color_map->GetColorsOfIBT(insn->GetFallthrough()->GetTarget()); + v=exe_nonce_color_map->GetColorsOfIBT(insn->getFallthrough()->getTarget()); } int nonceSz=GetExeNonceSize(insn); //Multiple sizes not yet supported @@ -345,9 +344,9 @@ void SCFI_Instrument::CreateExeNonceReloc(Instruction_t* insn, NonceValueType_t string type=string("cfi_exe_nonce=(pos=") + to_string(bytePos) + ",nv=" + to_string(nonceVal) + ",sz="+ to_string(nonceSz)+ ")"; Relocation_t* reloc=create_reloc(insn); - reloc->SetOffset(bytePos); - reloc->SetType(type); - cout<<"Created reloc='"+type+"' for "<<std::hex<<insn->GetBaseID()<<":"<<insn->getDisassembly()<<endl; + reloc->setOffset(bytePos); + reloc->setType(type); + cout<<"Created reloc='"+type+"' for "<<std::hex<<insn->getBaseID()<<":"<<insn->getDisassembly()<<endl; } @@ -448,19 +447,14 @@ void SCFI_Instrument::PlaceExeNonceReloc(Instruction_t* insn, NonceValueType_t n */ static string change_to_push(Instruction_t *insn) { - string newbits=insn->GetDataBits(); + string newbits=insn->getDataBits(); - //DISASM d; - //Disassemble(insn,d); - const auto d=DecodedInstruction_t(insn); + const auto dp=DecodedInstruction_t::factory(insn); + const auto &d=*dp; int opcode_offset=0; - - // FIXME: assumes REX is only prefix on jmp insn. - // does not assume rex exists. - //if(d.Prefix.REX.state == InUsePrefix) - opcode_offset=d.getPrefixCount(); + opcode_offset=d.getPrefixCount(); unsigned char modregrm = (newbits[1+opcode_offset]); modregrm &= 0xc7; @@ -472,51 +466,35 @@ static string change_to_push(Instruction_t *insn) } -void mov_reloc(Instruction_t* from, Instruction_t* to, string type ) +void SCFI_Instrument::mov_reloc(Instruction_t* from, Instruction_t* to, string type ) { - for( - /* start */ - RelocationSet_t::iterator it=from->GetRelocations().begin(); - - /* continue */ - it!=from->GetRelocations().end(); - - /* increment */ - /* empty */ - ) + // need to copy because moveReloc will destroy the iterator used for copying + auto copy_of_relocs=from->getRelocations(); + for(auto reloc : copy_of_relocs) { - Relocation_t* reloc=*it; - if(reloc->GetType()==type) + if(reloc->getType()==type) { - to->GetRelocations().insert(reloc); - + firp->moveRelocation(reloc,from,to); // odd standards-conforming way to delete object while iterating. - from->GetRelocations().erase(it++); - } - else - { - it++; + //to->getRelocations().insert(reloc); + //from->getRelocations().erase(it++); } } } -static void move_relocs(Instruction_t* from, Instruction_t* to) +void SCFI_Instrument::move_relocs(Instruction_t* from, Instruction_t* to) { - for(auto it=from->GetRelocations().begin(); it!=from->GetRelocations().end(); ) + auto copy_of_relocs=from->getRelocations(); + for(auto reloc : copy_of_relocs) { - auto current=it++; - Relocation_t* reloc=*current; - if(reloc->GetType()=="fix_call_fallthrough") + if(reloc->getType()!="fix_call_fallthrough") { - // don't move it. - } - else - { - to->GetRelocations().insert(reloc); - from->GetRelocations().erase(current); + firp->moveRelocation(reloc,from,to); + // to->getRelocations().insert(reloc); + // from->getRelocations().erase(current); } } } @@ -530,7 +508,7 @@ void SCFI_Instrument::AddJumpCFI(Instruction_t* insn) Instruction_t* after=insertDataBitsBefore(firp,insn,pushbits); move_relocs(after,insn); - after->SetDataBits(getRetDataBits()); + after->setDataBits(getRetDataBits()); cout <<insn->getDisassembly()<<" + ret' "<<endl ; // move any pc-rel relocation bits to the push, which will access memory now @@ -555,7 +533,7 @@ void SCFI_Instrument::AddJumpCFI(Instruction_t* insn) void SCFI_Instrument::AddCallCFIWithExeNonce(Instruction_t* insn) { string reg="ecx"; // 32-bit reg - if(firp->GetArchitectureBitWidth()==64) + if(firp->getArchitectureBitWidth()==64) reg="r11"; // 64-bit reg. Instruction_t* call=NULL, *stub=NULL; @@ -577,13 +555,13 @@ void SCFI_Instrument::AddCallCFIWithExeNonce(Instruction_t* insn) insertAssemblyAfter(firp,insn,string("pop ")+reg); // keep any relocs on the push instruction, as those may need updating. - insn->GetRelocations()=call->GetRelocations(); - call->GetRelocations().clear(); + insn->setRelocations(call->getRelocations()); + call->setRelocations({}); // Jump to non-exe nonce check code stub = addNewAssembly(firp, NULL, string("push ")+reg); Instruction_t* ret = insertDataBitsAfter(firp, stub, getRetDataBits()); - ret->SetIBTargets(call->GetIBTargets()); + ret->setIBTargets(call->getIBTargets()); if(do_exe_nonce_for_call) { @@ -598,13 +576,13 @@ void SCFI_Instrument::AddCallCFIWithExeNonce(Instruction_t* insn) } // convert the indirct call to a direct call to the stub. - string call_bits=call->GetDataBits(); + string call_bits=call->getDataBits(); call_bits.resize(5); call_bits[0]=0xe8; - call->SetTarget(stub); - call->SetDataBits(call_bits); - call->SetComment("Direct call to cfi stub"); - call->SetIBTargets(NULL); // lose info about branch targets. + call->setTarget(stub); + call->setDataBits(call_bits); + call->setComment("Direct call to cfi stub"); + call->setIBTargets(NULL); // lose info about branch targets. return; } @@ -620,7 +598,7 @@ Instruction_t* SCFI_Instrument::GetExeNonceSlowPath(Instruction_t* insn) { // Jump to non-exe nonce check code Instruction_t* ret = addNewDatabits(firp, NULL, getRetDataBits()); - ret->SetIBTargets(insn->GetIBTargets()); + ret->setIBTargets(insn->getIBTargets()); AddReturnCFI(ret); return ret; } @@ -641,7 +619,7 @@ void SCFI_Instrument::InsertExeNonceComparisons(Instruction_t* insn, noncePartSz = nonceSz; string reg="ecx"; // 32-bit reg - if(firp->GetArchitectureBitWidth()==64) + if(firp->getArchitectureBitWidth()==64) reg="r11"; // 64-bit reg. string decoration=""; @@ -677,7 +655,7 @@ void SCFI_Instrument::InsertExeNonceComparisons(Instruction_t* insn, tmp=insertAssemblyAfter(firp,tmp,string("cmp ")+decoration+ " ["+reg+"+"+to_string(theNoncePart.bytePos)+"], "+to_string(theNoncePart.val)); jne=tmp=insertAssemblyAfter(firp,tmp,"jne 0"); - jne->SetTarget(exeNonceSlowPath); + jne->setTarget(exeNonceSlowPath); } } @@ -689,26 +667,25 @@ void SCFI_Instrument::AddReturnCFIForExeNonce(Instruction_t* insn, ColoredSlotVa return; string reg="ecx"; // 32-bit reg - if(firp->GetArchitectureBitWidth()==64) + if(firp->getArchitectureBitWidth()==64) reg="r11"; // 64-bit reg. string rspreg="esp"; // 32-bit reg - if(firp->GetArchitectureBitWidth()==64) + if(firp->getArchitectureBitWidth()==64) rspreg="rsp"; // 64-bit reg. string worddec="dword"; // 32-bit reg - if(firp->GetArchitectureBitWidth()==64) + if(firp->getArchitectureBitWidth()==64) worddec="qword"; // 64-bit reg. - //DISASM d; - //Disassemble(insn,d); - const auto d=DecodedInstruction_t(insn); + const auto dp=DecodedInstruction_t::factory(insn); + const auto &d=*dp; - if(d.hasOperand(0)) // d.Argument1.ArgType!=NO_ARGUMENT) + if(d.hasOperand(0)) { - unsigned int sp_adjust=d.getImmediate() /*d.Instruction.Immediat*/-firp->GetArchitectureBitWidth()/8; - cout<<"Found relatively rare ret_with_pop insn: "<<d.getDisassembly() /*CompleteInstr*/<<endl; + unsigned int sp_adjust=d.getImmediate() -firp->getArchitectureBitWidth()/8; + cout<<"Found relatively rare ret_with_pop insn: "<<d.getDisassembly() <<endl; char buf[30]; sprintf(buf, "pop %s [%s+%d]", worddec.c_str(), rspreg.c_str(), sp_adjust); Instruction_t* newafter=insertAssemblyBefore(firp,insn,buf); @@ -722,7 +699,7 @@ void SCFI_Instrument::AddReturnCFIForExeNonce(Instruction_t* insn, ColoredSlotVa insn=newafter; //Needed b/c AddReturnCFI may be called on this ret insn //But also clean up and change ret_with_pop to ret (as it should be now) to be safe - setInstructionAssembly(firp,insn, string("ret"), insn->GetFallthrough(), insn->GetTarget()); + setInstructionAssembly(firp,insn, string("ret"), insn->getFallthrough(), insn->getTarget()); } //TODO: Handle uncommon slow path @@ -763,24 +740,22 @@ void SCFI_Instrument::AddReturnCFI(Instruction_t* insn, ColoredSlotValue_t *v) string reg="ecx"; // 32-bit reg - if(firp->GetArchitectureBitWidth()==64) + if(firp->getArchitectureBitWidth()==64) reg="r11"; // 64-bit reg. string rspreg="esp"; // 32-bit reg - if(firp->GetArchitectureBitWidth()==64) + if(firp->getArchitectureBitWidth()==64) rspreg="rsp"; // 64-bit reg. string worddec="dword"; // 32-bit reg - if(firp->GetArchitectureBitWidth()==64) + if(firp->getArchitectureBitWidth()==64) worddec="qword"; // 64-bit reg. - - //DISASM d; - //Disassemble(insn,d); - const auto d=DecodedInstruction_t(insn); + const auto dp=DecodedInstruction_t::factory(insn); + const auto &d=*dp; if(d.hasOperand(0)) // d.Argument1.ArgType!=NO_ARGUMENT) { - unsigned int sp_adjust=d.getImmediate() /* Instruction.Immediat*/-firp->GetArchitectureBitWidth()/8; + unsigned int sp_adjust=d.getImmediate() /* Instruction.Immediat*/-firp->getArchitectureBitWidth()/8; cout<<"Found relatively rare ret_with_pop insn: "<<d.getDisassembly()<<endl; char buf[30]; sprintf(buf, "pop %s [%s+%d]", worddec.c_str(), rspreg.c_str(), sp_adjust); @@ -794,7 +769,7 @@ void SCFI_Instrument::AddReturnCFI(Instruction_t* insn, ColoredSlotValue_t *v) // rewrite the "old" isntruction, as that's what insertAssemblyBefore returns insn=newafter; //Clean up and change ret_with_pop to ret (as it should be now) to be safe - setInstructionAssembly(firp,insn, string("ret"), insn->GetFallthrough(), insn->GetTarget()); + setInstructionAssembly(firp,insn, string("ret"), insn->getFallthrough(), insn->getTarget()); } int size=1; @@ -871,23 +846,23 @@ void SCFI_Instrument::AddReturnCFI(Instruction_t* insn, ColoredSlotValue_t *v) tmp=insertAssemblyAfter(firp,tmp,string("cmp ")+decoration+ " ["+reg+"-"+to_string(nonce_offset - 4)+"], "+to_string((uint32_t) (nonce >> 32))); // set the jne's target to itself, and create a reloc that zipr/strata will have to resolve. - jne->SetTarget(jne); // needed so spri/spasm/irdb don't freak out about missing target for new insn. + jne->setTarget(jne); // needed so spri/spasm/irdb don't freak out about missing target for new insn. Relocation_t* reloc=create_reloc(jne); - reloc->SetType(slow_cfi_path_reloc_string); - reloc->SetOffset(0); + reloc->setType(slow_cfi_path_reloc_string); + reloc->setOffset(0); cout<<"Setting slow path for: "<<slow_cfi_path_reloc_string<<endl; } jne=tmp=insertAssemblyAfter(firp,tmp,"jne 0"); // convert the ret instruction to a jmp ecx - cout<<"Converting "<<hex<<tmp->GetFallthrough()->GetBaseID()<<":"<<tmp->GetFallthrough()->getDisassembly()<<"to jmp+reg"<<endl; - setInstructionAssembly(firp,tmp->GetFallthrough(), string("jmp ")+reg, NULL,NULL); + cout<<"Converting "<<hex<<tmp->getFallthrough()->getBaseID()<<":"<<tmp->getFallthrough()->getDisassembly()<<"to jmp+reg"<<endl; + setInstructionAssembly(firp,tmp->getFallthrough(), string("jmp ")+reg, NULL,NULL); // set the jne's target to itself, and create a reloc that zipr/strata will have to resolve. - jne->SetTarget(jne); // needed so spri/spasm/irdb don't freak out about missing target for new insn. + jne->setTarget(jne); // needed so spri/spasm/irdb don't freak out about missing target for new insn. Relocation_t* reloc=create_reloc(jne); - reloc->SetType(slow_cfi_path_reloc_string); - reloc->SetOffset(0); + reloc->setType(slow_cfi_path_reloc_string); + reloc->setOffset(0); cout<<"Setting slow path for: "<<slow_cfi_path_reloc_string<<endl; return; @@ -914,13 +889,10 @@ static void display_histogram(std::ostream& out, std::string attr_label, std::ma bool SCFI_Instrument::is_plt_style_jmp(Instruction_t* insn) { - //DISASM d; - //Disassemble(insn,d); - const auto d=DecodedInstruction_t(insn); - if(d.getOperand(0).isMemory()) // (d.Argument1.ArgType&MEMORY_TYPE)==MEMORY_TYPE) + const auto d=DecodedInstruction_t::factory(insn); + if(d->getOperand(0)->isMemory()) { - //if(d.Argument1.Memory.BaseRegister == 0 && d.Argument1.Memory.IndexRegister == 0) - if(!d.getOperand(0).hasBaseRegister() && !d.getOperand(0).hasIndexRegister() ) + if(!d->getOperand(0)->hasBaseRegister() && !d->getOperand(0)->hasIndexRegister() ) return true; return false; } @@ -935,7 +907,7 @@ bool SCFI_Instrument::is_jmp_a_fixed_call(Instruction_t* insn) Instruction_t* pred=*(preds[insn].begin()); assert(pred); - if(pred->GetDataBits()[0]==0x68) + if(pred->getDataBits()[0]==0x68) return true; return false; } @@ -966,15 +938,9 @@ bool SCFI_Instrument::instrument_jumps() // for each instruction // But make sure the new insns added in this loop are not processed in this loop // (ok since none of the them should need to be protected) - auto insn_set = firp->GetInstructions(); - for(InstructionSet_t::iterator it=insn_set.begin(); - it!=insn_set.end(); - ++it) + auto insn_set = firp->getInstructions(); + for(auto insn : insn_set) { - Instruction_t* insn=*it; - //DISASM d; - //Disassemble(insn,d); - // we always have to protect the zestcfi dispatcher, that we just added. if(zestcfi_function_entry==insn) @@ -985,17 +951,18 @@ bool SCFI_Instrument::instrument_jumps() continue; } - if(insn->GetBaseID()==BaseObj_t::NOT_IN_DATABASE) + if(insn->getBaseID()==BaseObj_t::NOT_IN_DATABASE) continue; - const auto d=DecodedInstruction_t(insn); + const auto dp=DecodedInstruction_t::factory(insn); + const auto &d=*dp; - if (insn->GetFunction()) - cerr<<"Looking at: "<<insn->getDisassembly()<< " from func: " << insn->GetFunction()->GetName() << endl; + if (insn->getFunction()) + cerr<<"Looking at: "<<insn->getDisassembly()<< " from func: " << insn->getFunction()->getName() << endl; else cerr<<"Looking at: "<<insn->getDisassembly()<< " but no associated function" << endl; - if(d.isCall() /*string(d.Instruction.Mnemonic)==string("call ")*/ && (protect_safefn && !do_exe_nonce_for_call)) + if(d.isCall() && (protect_safefn && !do_exe_nonce_for_call)) { cerr<<"Fatal Error: Found call instruction!"<<endl; cerr<<"FIX_CALLS_FIX_ALL_CALLS=1 should be set in the environment, or"<<endl; @@ -1010,29 +977,25 @@ bool SCFI_Instrument::instrument_jumps() bool safefn = isSafeFunction(insn); if (safefn) { - if (insn->GetFunction()) - cerr << insn->GetFunction()->GetName() << " is safe" << endl; + if (insn->getFunction()) + cerr << insn->getFunction()->getName() << " is safe" << endl; } - //switch(d.Instruction.BranchType) - //{ - //case JmpType: if(d.isUnconditionalBranch()) { - //if((d.Argument1.ArgType&CONSTANT_TYPE)!=CONSTANT_TYPE) - if(!d.getOperand(0).isConstant()) + if(!d.getOperand(0)->isConstant()) { bool is_fixed_call=is_jmp_a_fixed_call(insn); bool is_plt_style=is_plt_style_jmp(insn); bool is_any_call_style = (is_fixed_call || is_plt_style); if(do_jumps && !is_any_call_style) { - if (insn->GetIBTargets() && insn->GetIBTargets()->IsComplete()) + if (insn->getIBTargets() && insn->getIBTargets()->isComplete()) { cfi_branch_jmp_complete++; - jmps[insn->GetIBTargets()->size()]++; + jmps[insn->getIBTargets()->size()]++; } cfi_checks++; @@ -1042,10 +1005,10 @@ bool SCFI_Instrument::instrument_jumps() } else if(do_calls && is_any_call_style) { - if (insn->GetIBTargets() && insn->GetIBTargets()->IsComplete()) + if (insn->getIBTargets() && insn->getIBTargets()->isComplete()) { cfi_branch_call_complete++; - calls[insn->GetIBTargets()->size()]++; + calls[insn->getIBTargets()->size()]++; } cfi_checks++; @@ -1064,7 +1027,6 @@ bool SCFI_Instrument::instrument_jumps() } } } - // case CallType: else if(d.isCall()) { @@ -1073,9 +1035,7 @@ bool SCFI_Instrument::instrument_jumps() // (1) --no-fix-safefn in fixcalls leaves call as call (instead of push/jmp) // (2) and here, we don't plop down a nonce // see (3) below where we don't instrument returns for safe functions - - // bool isDirectCall = (d.Argument1.ArgType&CONSTANT_TYPE)==CONSTANT_TYPE; - bool isDirectCall = d.getOperand(0).isConstant(); + bool isDirectCall = d.getOperand(0)->isConstant(); if (!protect_safefn) { @@ -1087,23 +1047,22 @@ bool SCFI_Instrument::instrument_jumps() } AddExecutableNonce(insn); // for all calls - if(!isDirectCall) // (d.Argument1.ArgType&CONSTANT_TYPE)!=CONSTANT_TYPE) + if(!isDirectCall) { // for indirect calls. AddCallCFIWithExeNonce(insn); } } - // case RetType: else if (d.isReturn()) { - if (insn->GetFunction()) - cerr << "found ret type protect_safefn: " << protect_safefn << " safefn: " << safefn << " function: " << insn->GetFunction()->GetName() << endl; + if (insn->getFunction()) + cerr << "found ret type protect_safefn: " << protect_safefn << " safefn: " << safefn << " function: " << insn->getFunction()->getName() << endl; else cerr << "found ret type protect_safefn: " << protect_safefn << " safefn: " << safefn << " no functions associated with instruction!! wtf???" << endl; - if (insn->GetIBTargets() && insn->GetIBTargets()->IsComplete()) + if (insn->getIBTargets() && insn->getIBTargets()->isComplete()) { cfi_branch_ret_complete++; - rets[insn->GetIBTargets()->size()]++; + rets[insn->getIBTargets()->size()]++; } // (3) and here, we don't instrument returns for safe function @@ -1123,10 +1082,9 @@ bool SCFI_Instrument::instrument_jumps() AddReturnCFI(insn); } } - else // default: + else { } - //} } cout<<"# ATTRIBUTE Selective_Control_Flow_Integrity::cfi_jmp_checks="<<std::dec<<cfi_branch_jmp_checks<<endl; @@ -1184,14 +1142,14 @@ static struct ScoopFinder : binary_function<const DataScoop_t*,const string,bool // declare a simple scoop finder function that finds scoops by name bool operator()(const DataScoop_t* scoop, const string& name) const { - return (scoop->GetName() == name); + return (scoop->getName() == name); }; } finder; static DataScoop_t* find_scoop(FileIR_t *firp,const string &name) { - auto it=find_if(firp->GetDataScoops().begin(), firp->GetDataScoops().end(), bind2nd(finder, name)) ; - if( it != firp->GetDataScoops().end() ) + auto it=find_if(firp->getDataScoops().begin(), firp->getDataScoops().end(), bind2nd(finder, name)) ; + if( it != firp->getDataScoops().end() ) return *it; return NULL; }; @@ -1199,12 +1157,12 @@ static DataScoop_t* find_scoop(FileIR_t *firp,const string &name) static unsigned int add_to_scoop(const string &str, DataScoop_t* scoop) { // assert that this scoop is unpinned. may need to enable --step move_globals --step-option move_globals:--elftables-only - assert(scoop->GetStart()->GetVirtualOffset()==0); + assert(scoop->getStart()->getVirtualOffset()==0); int len=str.length(); - scoop->SetContents(scoop->GetContents()+str); - virtual_offset_t oldend=scoop->GetEnd()->GetVirtualOffset(); + scoop->setContents(scoop->getContents()+str); + virtual_offset_t oldend=scoop->getEnd()->getVirtualOffset(); virtual_offset_t newend=oldend+len; - scoop->GetEnd()->SetVirtualOffset(newend); + scoop->getEnd()->setVirtualOffset(newend); return oldend+1; }; @@ -1212,73 +1170,73 @@ template<int ptrsize> static void insert_into_scoop_at(const string &str, DataScoop_t* scoop, FileIR_t* firp, const unsigned int at) { // assert that this scoop is unpinned. may need to enable --step move_globals --step-option move_globals:--cfi - assert(scoop->GetStart()->GetVirtualOffset()==0); + assert(scoop->getStart()->getVirtualOffset()==0); int len=str.length(); - string new_scoop_contents=scoop->GetContents(); + string new_scoop_contents=scoop->getContents(); new_scoop_contents.insert(at,str); - scoop->SetContents(new_scoop_contents); + scoop->setContents(new_scoop_contents); - virtual_offset_t oldend=scoop->GetEnd()->GetVirtualOffset(); + virtual_offset_t oldend=scoop->getEnd()->getVirtualOffset(); virtual_offset_t newend=oldend+len; - scoop->GetEnd()->SetVirtualOffset(newend); + scoop->getEnd()->setVirtualOffset(newend); // update each reloc to point to the new location. - for_each(scoop->GetRelocations().begin(), scoop->GetRelocations().end(), [str,at](Relocation_t* reloc) + for_each(scoop->getRelocations().begin(), scoop->getRelocations().end(), [str,at](Relocation_t* reloc) { - if((unsigned int)reloc->GetOffset()>=at) - reloc->SetOffset(reloc->GetOffset()+str.size()); + if((unsigned int)reloc->getOffset()>=at) + reloc->setOffset(reloc->getOffset()+str.size()); }); // check relocations for pointers to this object. // we'll update dataptr_to_scoop relocs, but nothing else // so assert if we find something else - for_each(firp->GetRelocations().begin(), firp->GetRelocations().end(), [scoop](Relocation_t* reloc) + for_each(firp->getRelocations().begin(), firp->getRelocations().end(), [scoop](Relocation_t* reloc) { - DataScoop_t* wrt=dynamic_cast<DataScoop_t*>(reloc->GetWRT()); - assert(wrt != scoop || reloc->GetType()=="dataptr_to_scoop"); + DataScoop_t* wrt=dynamic_cast<DataScoop_t*>(reloc->getWRT()); + assert(wrt != scoop || reloc->getType()=="dataptr_to_scoop"); }); // for each scoop - for_each(firp->GetDataScoops().begin(), firp->GetDataScoops().end(), [&str,scoop,firp,at](DataScoop_t* scoop_to_update) + for_each(firp->getDataScoops().begin(), firp->getDataScoops().end(), [&str,scoop,firp,at](DataScoop_t* scoop_to_update) { // for each relocation for that scoop - for_each(scoop_to_update->GetRelocations().begin(), scoop_to_update->GetRelocations().end(), [&str,scoop,firp,scoop_to_update,at](Relocation_t* reloc) + for_each(scoop_to_update->getRelocations().begin(), scoop_to_update->getRelocations().end(), [&str,scoop,firp,scoop_to_update,at](Relocation_t* reloc) { // if it's a reloc that's wrt scoop - DataScoop_t* wrt=dynamic_cast<DataScoop_t*>(reloc->GetWRT()); + DataScoop_t* wrt=dynamic_cast<DataScoop_t*>(reloc->getWRT()); if(wrt==scoop) { // then we need to update the scoop - if(reloc->GetType()=="dataptr_to_scoop") + if(reloc->getType()=="dataptr_to_scoop") { - string contents=scoop_to_update->GetContents(); + string contents=scoop_to_update->getContents(); // subtract the stringsize from the (implicitly stored) addend // taking pointer size into account. switch(ptrsize) { case 4: { - unsigned int val=*((unsigned int*)&contents.c_str()[reloc->GetOffset()]); + unsigned int val=*((unsigned int*)&contents.c_str()[reloc->getOffset()]); if(val>=at) val +=str.size(); - contents.replace(reloc->GetOffset(), ptrsize, (const char*)&val, ptrsize); + contents.replace(reloc->getOffset(), ptrsize, (const char*)&val, ptrsize); break; } case 8: { - unsigned long long val=*((long long*)&contents.c_str()[reloc->GetOffset()]); + unsigned long long val=*((long long*)&contents.c_str()[reloc->getOffset()]); if(val>=at) val +=str.size(); - contents.replace(reloc->GetOffset(), ptrsize, (const char*)&val, ptrsize); + contents.replace(reloc->getOffset(), ptrsize, (const char*)&val, ptrsize); break; } default: assert(0); } - scoop_to_update->SetContents(contents); + scoop_to_update->setContents(contents); } } @@ -1308,18 +1266,18 @@ template<typename T_Elf_Sym, typename T_Elf_Rela, typename T_Elf_Dyn, int reloc_ Instruction_t* SCFI_Instrument::find_runtime_resolve(DataScoop_t* gotplt_scoop) { // find any data_to_insn_ptr reloc for the gotplt scoop - auto it=find_if(gotplt_scoop->GetRelocations().begin(), gotplt_scoop->GetRelocations().end(), [](Relocation_t* reloc) + auto it=find_if(gotplt_scoop->getRelocations().begin(), gotplt_scoop->getRelocations().end(), [](Relocation_t* reloc) { - return reloc->GetType()=="data_to_insn_ptr"; + return reloc->getType()=="data_to_insn_ptr"; }); // there _should_ be one. - assert(it!=gotplt_scoop->GetRelocations().end()); + assert(it!=gotplt_scoop->getRelocations().end()); Relocation_t* reloc=*it; - Instruction_t* wrt=dynamic_cast<Instruction_t*>(reloc->GetWRT()); + Instruction_t* wrt=dynamic_cast<Instruction_t*>(reloc->getWRT()); assert(wrt); // should be a WRT assert(wrt->getDisassembly().find("push ") != string::npos); // should be push K insn - return wrt->GetFallthrough(); // jump to the jump, or not.. doesn't matter. zopt will fix + return wrt->getFallthrough(); // jump to the jump, or not.. doesn't matter. zopt will fix } template<typename T_Elf_Sym, typename T_Elf_Rela, typename T_Elf_Dyn, int reloc_type, int rela_shift, int ptrsize> @@ -1338,14 +1296,23 @@ void SCFI_Instrument::add_got_entry(const std::string& name) // create a new, unpinned, rw+relro scoop that's an empty pointer. - AddressID_t* start_addr=new AddressID_t(BaseObj_t::NOT_IN_DATABASE, firp->GetFile()->GetBaseID(), 0); - AddressID_t* end_addr=new AddressID_t(BaseObj_t::NOT_IN_DATABASE, firp->GetFile()->GetBaseID(), ptrsize-1); - DataScoop_t* external_func_addr_scoop=new DataScoop_t(BaseObj_t::NOT_IN_DATABASE, - name, start_addr,end_addr, NULL, 6, true, new_got_entry_str); - + /* + AddressID_t* start_addr=new AddressID_t(BaseObj_t::NOT_IN_DATABASE, firp->getFile()->getBaseID(), 0); firp->GetAddresses().insert(start_addr); + */ + auto start_addr=firp->addNewAddress(firp->getFile()->getBaseID(), 0); + /* + AddressID_t* end_addr=new AddressID_t(BaseObj_t::NOT_IN_DATABASE, firp->getFile()->getBaseID(), ptrsize-1); firp->GetAddresses().insert(end_addr); - firp->GetDataScoops().insert(external_func_addr_scoop); + */ + auto end_addr=firp->addNewAddress(firp->getFile()->getBaseID(), ptrsize-1); + + /* + DataScoop_t* external_func_addr_scoop=new DataScoop_t(BaseObj_t::NOT_IN_DATABASE, + name, start_addr,end_addr, NULL, 6, true, new_got_entry_str); + firp->getDataScoops().insert(external_func_addr_scoop); + */ + auto external_func_addr_scoop=firp->addNewDataScoop(name, start_addr,end_addr, NULL, 6, true, new_got_entry_str); // add string to string table auto dl_str_pos=add_to_scoop(name+'\0', dynstr_scoop); @@ -1360,9 +1327,9 @@ void SCFI_Instrument::add_got_entry(const std::string& name) // find the rela count. can't insert before that. int rela_count=0; - for(int i=0;i+sizeof(T_Elf_Dyn)<dynamic_scoop->GetSize(); i+=sizeof(T_Elf_Dyn)) + for(int i=0;i+sizeof(T_Elf_Dyn)<dynamic_scoop->getSize(); i+=sizeof(T_Elf_Dyn)) { - T_Elf_Dyn &dyn_entry=*(T_Elf_Dyn*)&dynamic_scoop->GetContents().c_str()[i]; + T_Elf_Dyn &dyn_entry=*(T_Elf_Dyn*)&dynamic_scoop->getContents().c_str()[i]; if(dyn_entry.d_tag==DT_RELACOUNT) // diff than rela size. { // add to the size @@ -1382,15 +1349,19 @@ void SCFI_Instrument::add_got_entry(const std::string& name) unsigned int at=rela_count*sizeof(T_Elf_Rela); insert_into_scoop_at<ptrsize>(dl_rel_str, relscoop, firp, at); - Relocation_t* dl_reloc=new Relocation_t(BaseObj_t::NOT_IN_DATABASE, at+((uintptr_t)&dl_rel.r_offset -(uintptr_t)&dl_rel), "dataptr_to_scoop", external_func_addr_scoop); - relscoop->GetRelocations().insert(dl_reloc); - firp->GetRelocations().insert(dl_reloc); - - for(int i=0;i+sizeof(T_Elf_Dyn)<dynamic_scoop->GetSize(); i+=sizeof(T_Elf_Dyn)) + /* + * Relocation_t* dl_reloc=new Relocation_t(BaseObj_t::NOT_IN_DATABASE, at+((uintptr_t)&dl_rel.r_offset -(uintptr_t)&dl_rel), "dataptr_to_scoop", external_func_addr_scoop); + relscoop->getRelocations().insert(dl_reloc); + firp->getRelocations().insert(dl_reloc); + */ + auto dl_reloc=firp->addNewRelocation(relscoop,at+((uintptr_t)&dl_rel.r_offset -(uintptr_t)&dl_rel), "dataptr_to_scoop", external_func_addr_scoop); + (void)dl_reloc; + + for(int i=0;i+sizeof(T_Elf_Dyn)<dynamic_scoop->getSize(); i+=sizeof(T_Elf_Dyn)) { // cast the index'd c_str to an Elf_Dyn pointer and deref it to assign to a // reference structure. That way editing the structure directly edits the string. - T_Elf_Dyn &dyn_entry=*(T_Elf_Dyn*)&dynamic_scoop->GetContents().c_str()[i]; + T_Elf_Dyn &dyn_entry=*(T_Elf_Dyn*)&dynamic_scoop->getContents().c_str()[i]; if(dyn_entry.d_tag==DT_RELASZ) // add to the size dyn_entry.d_un.d_val+=sizeof(T_Elf_Rela); @@ -1439,34 +1410,39 @@ bool SCFI_Instrument::add_got_entries() // add "function" for zestcfi" // for now, return that the target is allowed. the nonce plugin will have to have a slow path for this later. - assert(firp->GetArchitectureBitWidth()==64); // fixme for 32-bit, should jmp to ecx. + assert(firp->getArchitectureBitWidth()==64); // fixme for 32-bit, should jmp to ecx. zestcfi_function_entry=addNewAssembly(firp,NULL,"jmp r11"); // this jump can target any IBT in the module. - ICFS_t *newicfs=new ICFS_t; - for_each(firp->GetInstructions().begin(), firp->GetInstructions().end(), [&](Instruction_t* insn) + // ICFS_t *newicfs=new ICFS_t; + // firp->GetAllICFS().insert(newicfs); + auto newicfs=firp->addNewICFS(); + for_each(firp->getInstructions().begin(), firp->getInstructions().end(), [&](Instruction_t* insn) { - if(insn->GetIndirectBranchTargetAddress() != NULL ) + if(insn->getIndirectBranchTargetAddress() != NULL ) newicfs->insert(insn); }); - zestcfi_function_entry->SetIBTargets(newicfs); - firp->GetAllICFS().insert(newicfs); - firp->AssembleRegistry(); + zestcfi_function_entry->setIBTargets(newicfs); + firp->assembleRegistry(); // add a relocation so that the zest_cfi "function" gets pointed to by the symbol + /* Relocation_t* zestcfi_reloc=new Relocation_t(BaseObj_t::NOT_IN_DATABASE, zestcfi_pos+((uintptr_t)&zestcfi_sym.st_value - (uintptr_t)&zestcfi_sym), "data_to_insn_ptr", zestcfi_function_entry); - dynsym_scoop->GetRelocations().insert(zestcfi_reloc); - firp->GetRelocations().insert(zestcfi_reloc); + dynsym_scoop->getRelocations().insert(zestcfi_reloc); + firp->getRelocations().insert(zestcfi_reloc); + */ + auto zestcfi_reloc=firp->addNewRelocation(dynsym_scoop,zestcfi_pos+((uintptr_t)&zestcfi_sym.st_value - (uintptr_t)&zestcfi_sym), "data_to_insn_ptr", zestcfi_function_entry); + (void)zestcfi_reloc; // update strtabsz after got/etc entries are added. - for(int i=0;i+sizeof(T_Elf_Dyn)<dynamic_scoop->GetSize(); i+=sizeof(T_Elf_Dyn)) + for(int i=0;i+sizeof(T_Elf_Dyn)<dynamic_scoop->getSize(); i+=sizeof(T_Elf_Dyn)) { - T_Elf_Dyn &dyn_entry=*(T_Elf_Dyn*)&dynamic_scoop->GetContents().c_str()[i]; + T_Elf_Dyn &dyn_entry=*(T_Elf_Dyn*)&dynamic_scoop->getContents().c_str()[i]; if(dyn_entry.d_tag==DT_STRSZ) { - dyn_entry.d_un.d_val=dynstr_scoop->GetContents().size(); + dyn_entry.d_un.d_val=dynstr_scoop->getContents().size(); } } @@ -1527,9 +1503,9 @@ bool SCFI_Instrument::add_libdl_as_needed_support() while(1) { // assert we don't run off the end. - assert((index+1)*sizeof(T_Elf_Dyn) <= dynamic_scoop->GetContents().size()); + assert((index+1)*sizeof(T_Elf_Dyn) <= dynamic_scoop->getContents().size()); - T_Elf_Dyn* dyn_ptr=(T_Elf_Dyn*) & dynamic_scoop->GetContents().c_str()[index*sizeof(T_Elf_Dyn)]; + T_Elf_Dyn* dyn_ptr=(T_Elf_Dyn*) & dynamic_scoop->getContents().c_str()[index*sizeof(T_Elf_Dyn)]; if(memcmp(dyn_ptr,&null_dynamic_entry,sizeof(T_Elf_Dyn)) == 0 ) { @@ -1538,14 +1514,16 @@ bool SCFI_Instrument::add_libdl_as_needed_support() for(unsigned int i=0; i<sizeof(T_Elf_Dyn); i++) { // copy new_dynamic_entry ontop of null entry. - dynamic_scoop->GetContents()[index*sizeof(T_Elf_Dyn) + i ] = ((char*)&new_dynamic_entry)[i]; + auto str=dynamic_scoop->getContents(); + str[index*sizeof(T_Elf_Dyn) + i ] = ((char*)&new_dynamic_entry)[i]; + dynamic_scoop->setContents(str); } // check if there's room for the new null entry - if((index+2)*sizeof(T_Elf_Dyn) <= dynamic_scoop->GetContents().size()) + if((index+2)*sizeof(T_Elf_Dyn) <= dynamic_scoop->getContents().size()) { /* yes */ - T_Elf_Dyn* next_entry=(T_Elf_Dyn*)&dynamic_scoop->GetContents().c_str()[(index+1)*sizeof(T_Elf_Dyn)]; + T_Elf_Dyn* next_entry=(T_Elf_Dyn*)&dynamic_scoop->getContents().c_str()[(index+1)*sizeof(T_Elf_Dyn)]; // assert it's actually null assert(memcmp(next_entry,&null_dynamic_entry,sizeof(T_Elf_Dyn)) == 0 ); } @@ -1562,7 +1540,7 @@ bool SCFI_Instrument::add_libdl_as_needed_support() #if 0 cout<<".dynamic contents after scfi update:"<<hex<<endl; - const string &dynstr_contents=dynamic_scoop->GetContents(); + const string &dynstr_contents=dynamic_scoop->getContents(); for(unsigned int i=0;i<dynstr_contents.size(); i+=16) { cout<<*(long long*) &dynstr_contents.c_str()[i] <<" " @@ -1585,7 +1563,7 @@ bool SCFI_Instrument::execute() // do not move later. if(do_multimodule) { - if(firp->GetArchitectureBitWidth()==64) + if(firp->getArchitectureBitWidth()==64) success = success && add_dl_support<Elf64_Sym, Elf64_Rela, Elf64_Dyn, R_X86_64_GLOB_DAT, 32, 8>(); else success = success && add_dl_support<Elf32_Sym, Elf32_Rel, Elf32_Dyn, R_386_GLOB_DAT, 8, 4>(); diff --git a/tools/selective_cfi/scfi_instr.hpp b/tools/selective_cfi/scfi_instr.hpp index 93f3568fc..492656856 100644 --- a/tools/selective_cfi/scfi_instr.hpp +++ b/tools/selective_cfi/scfi_instr.hpp @@ -21,7 +21,7 @@ #ifndef scfi_instrument_hpp #define scfi_instrument_hpp -#include <libIRDB-core.hpp> +#include <irdb-core> #include <libIRDB-util.hpp> #include "color_map.hpp" #include <iostream> @@ -33,7 +33,7 @@ class SCFI_Instrument { public: - SCFI_Instrument(libIRDB::FileIR_t *the_firp, + SCFI_Instrument(IRDB_SDK::FileIR_t *the_firp, int p_nonce_size=1, int p_exe_nonce_size=4, bool p_do_coloring=true, @@ -90,7 +90,7 @@ class SCFI_Instrument bool add_got_entries(); template<typename T_Elf_Sym, typename T_Elf_Rela, typename T_Elf_Dyn, int reloc_type, int rela_shift, int ptrsize> - libIRDB::Instruction_t* find_runtime_resolve(libIRDB::DataScoop_t* gotplt_scoop); + IRDB_SDK::Instruction_t* find_runtime_resolve(IRDB_SDK::DataScoop_t* gotplt_scoop); template<typename T_Elf_Sym, typename T_Elf_Rela, typename T_Elf_Dyn, int reloc_type, int rela_shift, int ptrsize> void add_got_entry(const std::string& name); @@ -103,47 +103,47 @@ class SCFI_Instrument bool instrument_jumps(); // helper - libIRDB::Instruction_t* GetExeNonceSlowPath(libIRDB::Instruction_t* insn); - libIRDB::Relocation_t* create_reloc(libIRDB::Instruction_t* insn); - libIRDB::Relocation_t* FindRelocation(libIRDB::Instruction_t* insn, std::string type); - bool isSafeFunction(libIRDB::Instruction_t* insn); - bool isCallToSafeFunction(libIRDB::Instruction_t* insn); - bool is_jmp_a_fixed_call(libIRDB::Instruction_t* insn); - bool is_plt_style_jmp(libIRDB::Instruction_t* insn); + IRDB_SDK::Instruction_t* GetExeNonceSlowPath(IRDB_SDK::Instruction_t* insn); + IRDB_SDK::Relocation_t* create_reloc(IRDB_SDK::Instruction_t* insn); + IRDB_SDK::Relocation_t* FindRelocation(IRDB_SDK::Instruction_t* insn, std::string type); + bool isSafeFunction(IRDB_SDK::Instruction_t* insn); + bool isCallToSafeFunction(IRDB_SDK::Instruction_t* insn); + bool is_jmp_a_fixed_call(IRDB_SDK::Instruction_t* insn); + bool is_plt_style_jmp(IRDB_SDK::Instruction_t* insn); // add instrumentation - bool add_scfi_instrumentation(libIRDB::Instruction_t* insn); - bool needs_scfi_instrumentation(libIRDB::Instruction_t* insn); + bool add_scfi_instrumentation(IRDB_SDK::Instruction_t* insn); + bool needs_scfi_instrumentation(IRDB_SDK::Instruction_t* insn); // return instrumentation - void AddReturnCFI(libIRDB::Instruction_t* insn, ColoredSlotValue_t *v=NULL); - void AddReturnCFIForExeNonce(libIRDB::Instruction_t* insn, ColoredSlotValue_t *v=NULL); + void AddReturnCFI(IRDB_SDK::Instruction_t* insn, ColoredSlotValue_t *v=NULL); + void AddReturnCFIForExeNonce(IRDB_SDK::Instruction_t* insn, ColoredSlotValue_t *v=NULL); // jump instrumentation - void AddJumpCFI(libIRDB::Instruction_t* insn); + void AddJumpCFI(IRDB_SDK::Instruction_t* insn); // call instrumentation with executable nonce - void AddCallCFIWithExeNonce(libIRDB::Instruction_t* insn); + void AddCallCFIWithExeNonce(IRDB_SDK::Instruction_t* insn); // for all calls - void AddExecutableNonce(libIRDB::Instruction_t* insn); + void AddExecutableNonce(IRDB_SDK::Instruction_t* insn); // Nonce Manipulation. - NonceValueType_t GetNonce(libIRDB::Instruction_t* insn); - unsigned int GetNonceSize(libIRDB::Instruction_t* insn); - unsigned int GetNonceOffset(libIRDB::Instruction_t*); + NonceValueType_t GetNonce(IRDB_SDK::Instruction_t* insn); + unsigned int GetNonceSize(IRDB_SDK::Instruction_t* insn); + unsigned int GetNonceOffset(IRDB_SDK::Instruction_t*); - unsigned int GetExeNonceOffset(libIRDB::Instruction_t* insn); - NonceValueType_t GetExeNonce(libIRDB::Instruction_t* insn); - unsigned int GetExeNonceSize(libIRDB::Instruction_t* insn); + unsigned int GetExeNonceOffset(IRDB_SDK::Instruction_t* insn); + NonceValueType_t GetExeNonce(IRDB_SDK::Instruction_t* insn); + unsigned int GetExeNonceSize(IRDB_SDK::Instruction_t* insn); private: // data // predecessors of instructions. libIRDB::InstructionPredecessors_t preds; - libIRDB::FileIR_t* firp; + IRDB_SDK::FileIR_t* firp; const int nonce_size; const int exe_nonce_size; const bool do_coloring; @@ -157,8 +157,8 @@ class SCFI_Instrument const bool do_exe_nonce_for_call; std::unique_ptr<ColoredInstructionNonces_t> color_map; std::unique_ptr<ColoredInstructionNonces_t> exe_nonce_color_map; - const libIRDB::Instruction_t *ret_shared; - libIRDB::Instruction_t *zestcfi_function_entry; + const IRDB_SDK::Instruction_t *ret_shared; + IRDB_SDK::Instruction_t *zestcfi_function_entry; std::string ExecutableNonceValue; // Exe Nonce helpers @@ -188,10 +188,15 @@ class SCFI_Instrument */ std::vector<NoncePart_t> GetExeNonceFit(NonceValueType_t nonceVal, int nonceSz, int noncePos); int GetNonceBytePos(int nonceSz, int noncePos); - void CreateExeNonceReloc(libIRDB::Instruction_t* insn, NonceValueType_t nonceVal, int nonceSz, int bytePos); - void PlaceExeNonceReloc(libIRDB::Instruction_t* insn, NonceValueType_t nonceVal, int nonceSz, int noncePos); - void InsertExeNonceComparisons(libIRDB::Instruction_t* insn, NonceValueType_t nonceVal, int nonceSz, - int noncePos, libIRDB::Instruction_t* exeNonceSlowPath ); + void CreateExeNonceReloc(IRDB_SDK::Instruction_t* insn, NonceValueType_t nonceVal, int nonceSz, int bytePos); + void PlaceExeNonceReloc(IRDB_SDK::Instruction_t* insn, NonceValueType_t nonceVal, int nonceSz, int noncePos); + void InsertExeNonceComparisons(IRDB_SDK::Instruction_t* insn, NonceValueType_t nonceVal, int nonceSz, + int noncePos, IRDB_SDK::Instruction_t* exeNonceSlowPath ); + + + void mov_reloc(IRDB_SDK::Instruction_t* from, IRDB_SDK::Instruction_t* to, std::string type ); + void move_relocs(IRDB_SDK::Instruction_t* from, IRDB_SDK::Instruction_t* to); + }; #endif -- GitLab