|
| 1 | +#include "BPatch.h" |
| 2 | +#include "BPatch_function.h" |
| 3 | +#include "BPatch_object.h" |
| 4 | +#include "Symtab.h" |
| 5 | + |
| 6 | +#include <iostream> |
| 7 | +#include <string> |
| 8 | +#include <vector> |
| 9 | + |
| 10 | +namespace st = Dyninst::SymtabAPI; |
| 11 | + |
| 12 | +/* The instrumented binary should have these two functions defined: |
| 13 | + * |
| 14 | + * void* origMalloc(unsigned long size); |
| 15 | + * void* fastMalloc(unsigned long size); |
| 16 | + * |
| 17 | +*/ |
| 18 | + |
| 19 | +char const* orig_func = "origMalloc"; |
| 20 | +char const* replacement_func = "fastMalloc"; |
| 21 | + |
| 22 | +int main(int argc, char** argv) { |
| 23 | + if(argc != 2) { |
| 24 | + std::cerr << "Usage: " << argv[0] << " file\n"; |
| 25 | + return -1; |
| 26 | + } |
| 27 | + |
| 28 | + BPatch bpatch; |
| 29 | + BPatch_binaryEdit* appBin = bpatch.openBinary(argv[1]); |
| 30 | + |
| 31 | + if(!appBin) { |
| 32 | + std::cerr << "Unable to open '" << argv[1] << "'\n"; |
| 33 | + return -1; |
| 34 | + } |
| 35 | + |
| 36 | + BPatch_image* appImage = appBin->getImage(); |
| 37 | + |
| 38 | + auto find_func = [appImage](std::string const& name) -> BPatch_function* { |
| 39 | + std::vector<BPatch_function*> funcs; |
| 40 | + appImage->findFunction("", funcs); |
| 41 | + if(funcs.size() != 1) { |
| 42 | + std::cerr << "Unable to find '" << name << "'\n"; |
| 43 | + return nullptr; |
| 44 | + } |
| 45 | + return funcs[0]; |
| 46 | + }; |
| 47 | + |
| 48 | + BPatch_function* original_malloc = find_func(orig_func); |
| 49 | + if(!original_malloc) { |
| 50 | + return -1; |
| 51 | + } |
| 52 | + |
| 53 | + BPatch_function* fast_malloc = find_func(replacement_func); |
| 54 | + if(!fast_malloc) { |
| 55 | + return -1; |
| 56 | + } |
| 57 | + |
| 58 | + auto* symtab = st::convert(fast_malloc->getModule())->exec(); |
| 59 | + |
| 60 | + std::vector<st::Symbol*> syms; |
| 61 | + symtab->findSymbol(syms, orig_func, |
| 62 | + st::Symbol::ST_UNKNOWN, // Don’t specify type |
| 63 | + st::NameType::prettyName, // Look for demangled symbol name |
| 64 | + false, // Not regular expression |
| 65 | + false, // Don’t check case |
| 66 | + true); // Include undefined symbols |
| 67 | + |
| 68 | + if(syms.size() != 1) { |
| 69 | + std::cerr << "Unable to find symbol for '" << orig_func << "'\n"; |
| 70 | + return -1; |
| 71 | + } |
| 72 | + |
| 73 | + appBin->wrapFunction(original_malloc, fast_malloc, syms[0]); |
| 74 | +} |
0 commit comments