CFG-modification, instrumentation & springboard corner cases, defensive mode
[dyninst.git] / dyninstAPI / src / BPatch_addressSpace.C
1 /*
2  * Copyright (c) 1996-2011 Barton P. Miller
3  *
4  * We provide the Paradyn Parallel Performance Tools (below
5  * described as "Paradyn") on an AS IS basis, and do not warrant its
6  * validity or performance.  We reserve the right to update, modify,
7  * or discontinue this software at any time.  We shall have no
8  * obligation to supply such updates or modifications or any other
9  * form of support to you.
10  *
11  * By your use of Paradyn, you understand and agree that we (or any
12  * other person or entity with proprietary rights in Paradyn) are
13  * under no obligation to provide either maintenance services,
14  * update services, notices of latent defects, or correction of
15  * defects for Paradyn.
16  *
17  * This library is free software; you can redistribute it and/or
18  * modify it under the terms of the GNU Lesser General Public
19  * License as published by the Free Software Foundation; either
20  * version 2.1 of the License, or (at your option) any later version.
21  *
22  * This library is distributed in the hope that it will be useful,
23  * but WITHOUT ANY WARRANTY; without even the implied warranty of
24  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
25  * Lesser General Public License for more details.
26  *
27  * You should have received a copy of the GNU Lesser General Public
28  * License along with this library; if not, write to the Free Software
29  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
30  */
31
32 #define BPATCH_FILE
33
34 #include "process.h"
35 #include "binaryEdit.h"
36 #include "EventHandler.h"
37 #include "mailbox.h"
38 #include "signalgenerator.h"
39 #include "inst.h"
40 #include "instP.h"
41 #include "instPoint.h"
42 #include "function.h" // func_instance
43 #include "codeRange.h"
44 #include "dyn_thread.h"
45 #include "miniTramp.h"
46 #include "addressSpace.h"
47
48 #include "mapped_module.h"
49
50 #include "BPatch_libInfo.h"
51 #include "BPatch_asyncEventHandler.h"
52 #include "BPatch.h"
53 #include "BPatch_thread.h"
54 #include "BPatch_function.h"
55 #include "BPatch_point.h"
56 #include "callbacks.h"
57
58 #include "BPatch_private.h"
59
60 #include "ast.h"
61
62 #include "BPatch_addressSpace.h"
63
64 #include "BPatch_instruction.h"
65
66 #include "mapped_object.h"
67
68 #include <sstream>
69 #include "Parsing.h"
70
71 #include "Command.h"
72 #include "Relocation/DynInstrumenter.h"
73
74 using Dyninst::PatchAPI::Patcher;
75 using Dyninst::PatchAPI::PatcherPtr;
76 using Dyninst::PatchAPI::DynInsertSnipCommand;
77 using Dyninst::PatchAPI::DynReplaceFuncCommand;
78 using Dyninst::PatchAPI::DynModifyCallCommand;
79 using Dyninst::PatchAPI::DynRemoveCallCommand;
80
81 BPatch_addressSpace::BPatch_addressSpace() :
82    image(NULL)
83 {
84 }
85
86 BPatch_addressSpace::~BPatch_addressSpace()
87 {}
88
89
90 BPatch_function *BPatch_addressSpace::findOrCreateBPFunc(func_instance* ifunc,
91                                                          BPatch_module *bpmod)
92 {
93    if (!bpmod)
94       bpmod = image->findOrCreateModule(ifunc->mod());
95    assert(bpmod);
96    if (bpmod->func_map.count(ifunc)) {
97       BPatch_function *bpf = bpmod->func_map[ifunc];
98       assert(bpf);
99       assert(bpf->func == ifunc);
100       return bpf;
101    }
102
103    // Find the module that contains the function
104    if (bpmod == NULL && ifunc->mod() != NULL) {
105       bpmod = getImage()->findModule(ifunc->mod()->fileName().c_str());
106    }
107
108    // findModule has a tendency to make new function objects... so
109    // check the map again
110    if (bpmod->func_map.count(ifunc)) {
111       BPatch_function *bpf = bpmod->func_map[ifunc];
112       assert(bpf);
113       assert(bpf->func == ifunc);
114       return bpf;
115    }
116
117    BPatch_function *ret = new BPatch_function(this, ifunc, bpmod);
118    assert( ret != NULL );
119    assert(ret->func == ifunc);
120    return ret;
121 }
122
123
124
125
126 BPatch_point *BPatch_addressSpace::findOrCreateBPPoint(BPatch_function *bpfunc,
127                                                        instPoint *ip,
128                                                        BPatch_procedureLocation pointType)
129 {
130    assert(ip);
131
132    BPatch_module *mod = image->findOrCreateModule(ip->func()->mod());
133    assert(mod);
134
135    if (mod->instp_map.count(ip))
136       return mod->instp_map[ip];
137
138    if (pointType == BPatch_locUnknownLocation) {
139       cerr << "Error: point type not specified!" << endl;
140       assert(0);
141       return NULL;
142    }
143
144    AddressSpace *lladdrSpace = ip->func()->proc();
145    if (!bpfunc)
146       bpfunc = findOrCreateBPFunc(ip->func(), mod);
147
148    assert(bpfunc->func == ip->func());
149    std::pair<instPoint *, instPoint *> pointsToUse = instPoint::getInstpointPair(ip);
150
151    BPatch_point *pt = new BPatch_point(this, bpfunc,
152                                        pointsToUse.first, pointsToUse.second,
153                                        pointType, lladdrSpace);
154    mod->instp_map[ip] = pt;
155
156    return pt;
157 }
158
159 BPatch_variableExpr *BPatch_addressSpace::findOrCreateVariable(int_variable *v,
160                                                                BPatch_type *type)
161 {
162    BPatch_module *mod = image->findOrCreateModule(v->mod());
163    assert(mod);
164    if (mod->var_map.count(v))
165       return mod->var_map[v];
166
167    if (!type) {
168       SymtabAPI::Type *stype = v->ivar()->svar()->getType();
169
170       if (stype){
171          type = BPatch_type::findOrCreateType(stype);
172       }else{
173          type = BPatch::bpatch->type_Untyped;
174       }
175    }
176
177    BPatch_variableExpr *var = BPatch_variableExpr::makeVariableExpr(this, v, type);
178    mod->var_map[v] = var;
179    return var;
180 }
181
182
183
184 BPatch_function *BPatch_addressSpace::createBPFuncCB(AddressSpace *a, func_instance *f)
185 {
186    BPatch_addressSpace *aS = (BPatch_addressSpace *)a->up_ptr();
187    assert(aS);
188    return aS->findOrCreateBPFunc(f, NULL);
189 }
190
191 BPatch_point *BPatch_addressSpace::createBPPointCB(AddressSpace *a,
192                                                    func_instance *f,
193                                                    instPoint *ip, int type)
194 {
195    BPatch_addressSpace *aS = (BPatch_addressSpace *)a->up_ptr();
196    assert(aS);
197
198    BPatch_module *bpmod = aS->getImageInt()->findOrCreateModule(f->mod());
199    assert(bpmod);
200
201    BPatch_function *func = aS->findOrCreateBPFunc(f, bpmod);
202    assert(func);
203
204    return aS->findOrCreateBPPoint(func, ip, (BPatch_procedureLocation) type);
205 }
206
207
208
209 /***************************************************************************
210  * Bpatch_snippetHandle
211  ***************************************************************************/
212
213 /*
214  * BPatchSnippetHandle::BPatchSnippetHandle
215  *
216  * Constructor for BPatchSnippetHandle.  Delete the snippet instance(s)
217  * associated with the BPatchSnippetHandle.
218  */
219 BPatchSnippetHandle::BPatchSnippetHandle(BPatch_addressSpace * addSpace) :
220    addSpace_(addSpace)
221 {
222 }
223
224 /*
225  * BPatchSnippetHandle::~BPatchSnippetHandle
226  *
227  * Destructor for BPatchSnippetHandle.  Delete the snippet instance(s)
228  * associated with the BPatchSnippetHandle.
229  */
230 void BPatchSnippetHandle::BPatchSnippetHandle_dtor()
231 {
232    // don't delete inst instances since they are might have been copied
233 }
234
235 BPatch_addressSpace *BPatchSnippetHandle::getAddressSpaceInt()
236 {
237    return addSpace_;
238 }
239
240 BPatch_process *BPatchSnippetHandle::getProcessInt()
241 {
242    return dynamic_cast<BPatch_process *>(addSpace_);
243 }
244
245 BPatch_Vector<BPatch_thread *> &BPatchSnippetHandle::getCatchupThreadsInt()
246 {
247    return catchup_threads;
248 }
249
250 BPatch_function * BPatchSnippetHandle::getFuncInt()
251 {
252     if (!mtHandles_.empty()) {
253         func_instance *func = mtHandles_.back()->instP()->func();
254         BPatch_function *bpfunc = addSpace_->findOrCreateBPFunc(func,NULL);
255         return bpfunc;
256     }
257     return NULL;
258 }
259
260
261 BPatch_image * BPatch_addressSpace::getImageInt()
262 {
263    return image;
264 }
265
266
267 /*
268  * BPatch_addressSpace::deleteSnippet
269  *
270  * Deletes an instance of a snippet.
271  *
272  * handle       The handle returned by insertSnippet when the instance to
273  *              deleted was created.
274  */
275
276 bool BPatch_addressSpace::deleteSnippetInt(BPatchSnippetHandle *handle)
277 {
278    if (getTerminated()) return true;
279
280    if (handle == NULL) {
281        bperr("Request to delete NULL snippet handle, returning false\n");
282        return false;
283    }
284
285    if (handle->addSpace_ != this) {
286      bperr("Error: wrong address space in deleteSnippet\n");
287      return false;
288    }
289
290    mal_printf("deleting snippet handle from func at %lx, point at %lx of type %d\n",
291               (Address)handle->getFunc()->getBaseAddr(), 
292               handle->mtHandles_.empty() ? 0 : handle->mtHandles_[0]->instP()->addr(),
293               handle->mtHandles_.empty() ? -1 : handle->mtHandles_[0]->instP()->type());
294
295    // if this is a process, check to see if the instrumentation is
296    // executing on the call stack
297    if ( handle->getProcess() && handle->mtHandles_.size() > 0 &&
298        BPatch_normalMode !=
299         handle->mtHandles_[0]->instP()->func()->obj()->hybridMode())
300    {
301        if (handle->mtHandles_.size() > 1) {
302            mal_printf("ERROR: Removing snippet that is installed in "
303                           "multiple miniTramps %s[%d]\n",FILE__,__LINE__);
304      }
305    }
306
307    // uninstrument and remove snippet handle from point datastructures
308    for (unsigned int i=0; i < handle->mtHandles_.size(); i++)
309      {
310        instPoint *iPoint = handle->mtHandles_[i]->instP();
311        handle->mtHandles_[i]->uninstrument();
312        BPatch_point *bPoint = findOrCreateBPPoint(NULL, iPoint,
313                                                   BPatch_point::convertInstPointType_t(iPoint->type()));
314        assert(bPoint);
315        bPoint->removeSnippet(handle);
316      }
317
318    handle->mtHandles_.clear();
319
320    if (pendingInsertions == NULL) {
321      // Trigger it now
322      bool tmp;
323      finalizeInsertionSet(false, &tmp);
324    }
325
326    //delete handle;
327    return true;
328 }
329
330 /*
331  * BPatch_addressSpace::replaceCode
332  *
333  * Replace a given instruction with a BPatch_snippet.
334  *
335  * point       Represents the instruction to be replaced
336  * snippet     The replacing snippet
337  */
338
339 bool BPatch_addressSpace::replaceCodeInt(BPatch_point * /*point*/,
340                                          BPatch_snippet * /*snippet*/)
341 {
342    // Need to reevaluate how this code works. I don't think it should be
343    // point-based, though.
344
345    assert(0);
346    return false;
347 }
348
349 /*
350  * BPatch_addressSpace::replaceFunctionCall
351  *
352  * Replace a function call with a call to a different function.  Returns true
353  * upon success, false upon failure.
354  *
355  * point        The call site that is to be changed.
356  * newFunc      The function that the call site will now call.
357  */
358 bool BPatch_addressSpace::replaceFunctionCallInt(BPatch_point &point,
359       BPatch_function &newFunc)
360 {
361    char name[1024];
362    newFunc.getName(name, 1024);
363
364    // Can't make changes to code when mutations are not active.
365    if (!getMutationsActive())
366       return false;
367
368    assert(point.point && newFunc.lowlevel_func());
369
370   /* PatchAPI stuffs */
371    AddressSpace* addr_space = point.getAS();
372    DynModifyCallCommand::Ptr rep_call = DynModifyCallCommand::create(addr_space,
373       point.point->block(), newFunc.lowlevel_func(), point.point->func());
374   addr_space->patcher()->add(rep_call);
375   /* End of PatchAPI */
376   /*
377    point.getAS()->modifyCall(point.point->block(),
378                              newFunc.lowlevel_func(),
379                              point.point->func());
380   */
381    if (pendingInsertions == NULL) {
382      // Trigger it now
383      bool tmp;
384      finalizeInsertionSet(false, &tmp);
385    }
386    return true;
387 }
388
389 /*
390  * BPatch_addressSpace::removeFunctionCall
391  *
392  * Replace a function call with a NOOP.  Returns true upon success, false upon
393  * failure.
394  *
395  * point        The call site that is to be NOOPed out.
396  */
397 bool BPatch_addressSpace::removeFunctionCallInt(BPatch_point &point)
398 {
399    // Can't make changes to code when mutations are not active.
400    if (!getMutationsActive())
401       return false;
402
403    assert(point.point);
404
405   /* PatchAPI stuffs */
406    AddressSpace* addr_space = point.getAS();
407    DynRemoveCallCommand::Ptr remove_call = DynRemoveCallCommand::create(addr_space,
408       point.point->block(), point.point->func());
409   addr_space->patcher()->add(remove_call);
410   /* End of PatchAPI */
411    // point.getAS()->removeCall(point.point->block(), point.point->func());
412
413    if (pendingInsertions == NULL) {
414      // Trigger it now
415      bool tmp;
416      finalizeInsertionSet(false, &tmp);
417    }
418
419    return true;
420 }
421
422
423 /*
424  * BPatch_addressSpace::replaceFunction
425  *
426  * Replace all calls to function OLDFUNC with calls to NEWFUNC.
427  * Returns true upon success, false upon failure.
428  *
429  * oldFunc      The function to replace
430  * newFunc      The replacement function
431  */
432 bool BPatch_addressSpace::replaceFunctionInt(BPatch_function &oldFunc,
433       BPatch_function &newFunc)
434 {
435   assert(oldFunc.lowlevel_func() && newFunc.lowlevel_func());
436   if (!getMutationsActive())
437     return false;
438
439   // Self replacement is a nop
440   // We should just test direct equivalence here...
441   if (oldFunc.lowlevel_func() == newFunc.lowlevel_func()) {
442     return true;
443   }
444
445   /* PatchAPI stuffs */
446   AddressSpace* addr_space = oldFunc.lowlevel_func()->proc();
447   DynReplaceFuncCommand::Ptr rep_func = DynReplaceFuncCommand::create(addr_space,
448      oldFunc.lowlevel_func(), newFunc.lowlevel_func());
449   addr_space->patcher()->add(rep_func);
450   /* End of PatchAPI */
451
452   //oldFunc.lowlevel_func()->proc()->replaceFunction(oldFunc.lowlevel_func(), newFunc.lowlevel_func());
453
454   if (pendingInsertions == NULL) {
455     // Trigger it now
456     bool tmp;
457     finalizeInsertionSet(false, &tmp);
458   }
459   return true;
460 }
461
462 bool BPatch_addressSpace::wrapFunctionInt(BPatch_function *original,
463                                           BPatch_function *wrapper,
464                                           Dyninst::SymtabAPI::Symbol *clone)
465 {
466    assert(original->lowlevel_func() && wrapper->lowlevel_func());
467    if (!getMutationsActive())
468       return false;
469
470    // Self replacement is a nop
471    // We should just test direct equivalence here...
472    if (original->lowlevel_func() == wrapper->lowlevel_func()) {
473       return true;
474    }
475
476    if (!original->lowlevel_func()->proc()->wrapFunction(original->lowlevel_func(), 
477                                                       wrapper->lowlevel_func(),
478                                                       clone))
479       return false;
480
481    if (pendingInsertions == NULL) {
482       // Trigger it now
483       bool tmp;
484       finalizeInsertionSet(false, &tmp);
485    }
486    return true;
487 }
488
489
490 bool BPatch_addressSpace::getAddressRangesInt( const char * fileName,
491       unsigned int lineNo,
492       std::vector< std::pair< unsigned long, unsigned long > > & ranges )
493 {
494    unsigned int originalSize = ranges.size();
495    BPatch_Vector< BPatch_module * > * modules = image->getModules();
496
497    /* Iteratate over the modules, looking for addr in each. */
498    for ( unsigned int i = 0; i < modules->size(); i++ ) {
499       BPatch_module *m = (*modules)[i];
500       m->getAddressRanges(fileName, lineNo, ranges);
501    }
502
503    if ( ranges.size() != originalSize ) { return true; }
504
505    return false;
506 } /* end getAddressRangesInt() */
507
508 bool BPatch_addressSpace::getSourceLinesInt( unsigned long addr,
509       BPatch_Vector< BPatch_statement > & lines )
510 {
511    return image->getSourceLinesInt(addr, lines);
512 } /* end getLineAndFile() */
513
514
515 /*
516  * BPatch_process::malloc
517  *
518  * Allocate memory in the thread's address space.
519  *
520  * n    The number of bytes to allocate.
521  *
522  * Returns:
523  *      A pointer to a BPatch_variableExpr representing the memory.
524  *
525  * If otherwise unspecified when binary rewriting, then the allocation
526  * happens in the original object.
527  */
528
529 BPatch_variableExpr *BPatch_addressSpace::mallocInt(int n, std::string name)
530 {
531    std::vector<AddressSpace *> as;
532    assert(BPatch::bpatch != NULL);
533    getAS(as);
534    assert(as.size());
535    void *ptr = (void *) as[0]->inferiorMalloc(n, dataHeap);
536    if (!ptr) return NULL;
537    if(name.empty()){
538       std::stringstream namestr;
539       namestr << "dyn_malloc_0x" << std::hex << ptr << "_" << n << "_bytes";
540       name = namestr.str();
541    }
542    BPatch_type *type = BPatch::bpatch->createScalar(name.c_str(), n);
543
544    return BPatch_variableExpr::makeVariableExpr(this, as[0], name, ptr,
545                                                 type);
546 }
547
548
549 /*
550  * BPatch_process::malloc
551  *
552  * Allocate memory in the thread's address space for a variable of the given
553  * type.
554  *
555  * type         The type of variable for which to allocate space.
556  *
557  * Returns:
558  *      A pointer to a BPatch_variableExpr representing the memory.
559  *
560  * XXX Should return NULL on failure, but the function which it calls,
561  *     inferiorMalloc, calls exit rather than returning an error, so this
562  *     is not currently possible.
563  */
564
565 BPatch_variableExpr *BPatch_addressSpace::mallocByType(const BPatch_type &type, std::string name)
566 {
567    std::vector<AddressSpace *> as;
568    assert(BPatch::bpatch != NULL);
569    getAS(as);
570    assert(as.size());
571    BPatch_type &t = const_cast<BPatch_type &>(type);
572    void *mem = (void *) as[0]->inferiorMalloc(t.getSize(), dataHeap);
573    if (!mem) return NULL;
574    if(name.empty()){
575       std::stringstream namestr;
576       namestr << "dyn_malloc_0x" << std::hex << mem << "_" << type.getName();
577       name = namestr.str();
578    }
579    BPatch_variableExpr *varExpr = BPatch_variableExpr::makeVariableExpr(this, as[0], name, mem, &t);
580    return varExpr;
581 }
582
583
584 /*
585  * BPatch_process::free
586  *
587  * Free memory that was allocated with BPatch_process::malloc.
588  *
589  * ptr          A BPatch_variableExpr representing the memory to free.
590  */
591
592 bool BPatch_addressSpace::freeInt(BPatch_variableExpr &ptr)
593 {
594   if(ptr.intvar)
595   {
596     // kill the symbols
597
598   }
599
600    ptr.getAS()->inferiorFree((Address)ptr.getBaseAddr());
601    return true;
602 }
603
604 BPatch_variableExpr *BPatch_addressSpace::createVariableInt(std::string name,
605                                                             Dyninst::Address addr,
606                                                             BPatch_type *type) {
607     assert(BPatch::bpatch != NULL);
608     std::vector<AddressSpace *> as;
609     getAS(as);
610     assert(as.size());
611
612 //dynC added feature
613     if(strstr(name.c_str(), "dynC") == name.c_str()){
614        void *mem = (void *) as[0]->inferiorMalloc(type->getSize(), dataHeap);
615        if (!mem) return NULL;
616        BPatch_variableExpr *varExpr = BPatch_variableExpr::makeVariableExpr(this, as[0], name, mem, type);
617        BPatch_module *mod = image->findOrCreateModule(varExpr->intvar->mod());
618        assert(mod);
619        mod->var_map[varExpr->intvar] = varExpr;
620        return varExpr;
621     }
622
623     BPatch_variableExpr *varExpr = BPatch_variableExpr::makeVariableExpr(this,
624                                                  as[0],
625                                                  name,
626                                                  (void *)addr,
627                                                  type);
628
629     return varExpr;
630 }
631
632 /*
633  * BPatch_addressSpace::findFunctionByAddr
634  *
635  * Returns the function that contains the specified address, or NULL if the
636  * address is not within a function.
637  *
638  * addr         The address to use for the lookup.
639  */
640 BPatch_function *BPatch_addressSpace::findFunctionByAddrInt(void *addr)
641 {
642    std::vector<AddressSpace *> as;
643
644    getAS(as);
645    assert(as.size());
646    std::set<func_instance *> funcs;
647    if (!as[0]->findFuncsByAddr((Address) addr, funcs)) {
648       // if it's a mapped_object that has yet to be analyzed,
649       // trigger analysis and re-invoke this function
650        mapped_object *obj = as[0]->findObject((Address) addr);
651        if (obj &&
652            !obj->isAnalyzed()) {
653          obj->analyze();
654          return findFunctionByAddrInt(addr);
655       }
656       return NULL;
657    }
658    if (funcs.empty()) return NULL;
659
660    if (funcs.size() > 1) {
661        bpwarn("Warning: deprecated function findFunctionByAddr found "
662               "multiple functions sharing address 0x%lx, picking one at "
663               "random.  Use findFunctionByEntry or findFunctionsByAddr\n",
664               addr);
665    }
666
667    return findOrCreateBPFunc((*(funcs.begin())), NULL);
668 }
669
670 /*
671  *  BPatch_addressSpace::findFunctionByEntry
672  *
673  *  Returns the function starting at the given address, or NULL if the
674  *  address is not within a function.
675  *
676  *  entry       The address to use for the lookup.
677  */
678 BPatch_function *BPatch_addressSpace::findFunctionByEntryInt(Address entry)
679 {
680     vector<BPatch_function*> funcs;
681     findFunctionsByAddr(entry, funcs);
682     vector<BPatch_function*>::iterator fit;
683     for (fit = funcs.begin(); fit != funcs.end(); fit++) {
684         if (entry == (Address)(*fit)->getBaseAddrInt()) {
685             return *fit;
686         }
687     }
688     return NULL;
689 }
690
691 bool BPatch_addressSpace::findFuncsByRange(Address startAddr,
692                                            Address endAddr,
693                                            std::set<BPatch_function*> &bpFuncs)
694 {
695     std::vector<AddressSpace *> as;
696     getAS(as);
697     assert(as.size());
698
699     // find the first code range in the region
700     mapped_object* mobj = as[0]->findObject(startAddr);
701     assert(mobj);
702     set<func_instance*> intFuncs;
703     mobj->findFuncsByRange(startAddr,endAddr,intFuncs);
704     set<func_instance*>::iterator fIter = intFuncs.begin();
705     for (; fIter != intFuncs.end(); fIter++) {
706         BPatch_function * bpfunc = findOrCreateBPFunc(*fIter,NULL);
707         bpFuncs.insert(bpfunc);
708     }
709     return 0 != bpFuncs.size();
710 }
711
712
713 /*
714  * BPatch_addressSpace::findFunctionsByAddr
715  *
716  * Returns the functions that contain the specified address, or NULL if the
717  * address is not within a function. (there could be multiple functions
718  * because of the possibility of shared code)
719  *
720  * addr         The address to use for the lookup.
721  * returns false if there were no functions that matched the address
722  */
723 bool BPatch_addressSpace::findFunctionsByAddrInt
724     (Address addr, std::vector<BPatch_function*> &funcs)
725 {
726     std::vector<AddressSpace *> as;
727     getAS(as);
728     assert(as.size());
729
730     // grab the funcs, return false if there aren't any
731     std::set<func_instance*> intfuncs;
732     if (!as[0]->findFuncsByAddr( addr, intfuncs )) {
733         return false;
734     }
735     // convert to BPatch_functions
736     for (std::set<func_instance*>::iterator fiter=intfuncs.begin();
737          fiter != intfuncs.end(); fiter++)
738     {
739         funcs.push_back(findOrCreateBPFunc(*fiter, NULL));
740     }
741     return 0 < funcs.size();
742 }
743
744
745 /*
746  * BPatch_addressSpace::findModuleByAddr
747  *
748  * Returns the module that contains the specified address, or NULL if the
749  * address is not within a module.  Does NOT trigger parsing
750  *
751  * addr         The address to use for the lookup.
752  */
753 BPatch_module *BPatch_addressSpace::findModuleByAddr(Address addr)
754 {
755    std::vector<AddressSpace *> as;
756    getAS(as);
757    assert(as.size());
758
759    mapped_object *obj = as[0]->findObject(addr);
760    if ( ! obj )
761        return NULL;
762
763    const pdvector<mapped_module*> mods = obj->getModules();
764    if (mods.size()) {
765        return getImage()->findOrCreateModule(mods[0]);
766    }
767    return NULL;
768 }
769
770
771 /*
772  * BPatch_addressSpace::insertSnippet
773  *
774  * Insert a code snippet at a given instrumentation point.  Upon success,
775  * returns a handle to the created instance of the snippet, which can be used
776  * to delete it.  Otherwise returns NULL.
777  *
778  * expr         The snippet to insert.
779  * point        The point at which to insert it.
780  */
781
782 BPatchSnippetHandle *BPatch_addressSpace::insertSnippetInt(const BPatch_snippet &expr,
783       BPatch_point &point,
784       BPatch_snippetOrder order)
785 {
786    BPatch_callWhen when;
787    if (point.getPointType() == BPatch_exit)
788       when = BPatch_callAfter;
789    else
790       when = BPatch_callBefore;
791
792    return insertSnippetWhen(expr, point, when, order);
793 }
794
795 /*
796  * BPatch_addressSpace::insertSnippet
797  *
798  * Insert a code snippet at a given instrumentation point.  Upon succes,
799  * returns a handle to the created instance of the snippet, which can be used
800  * to delete it.  Otherwise returns NULL.
801  *
802  * expr         The snippet to insert.
803  * point        The point at which to insert it.
804  */
805
806 // This handles conversion without requiring inst.h in a header file...
807 extern bool BPatchToInternalArgs(BPatch_point *point,
808       BPatch_callWhen when,
809       BPatch_snippetOrder order,
810       callWhen &ipWhen,
811       callOrder &ipOrder);
812
813
814 BPatchSnippetHandle *BPatch_addressSpace::insertSnippetWhen(const BPatch_snippet &expr,
815       BPatch_point &point,
816       BPatch_callWhen when,
817       BPatch_snippetOrder order)
818 {
819    BPatch_Vector<BPatch_point *> points;
820    points.push_back(&point);
821    return insertSnippetAtPointsWhen(expr,
822          points,
823          when,
824          order);
825 }
826
827 extern int dyn_debug_ast;
828
829 /*
830  * BPatch_addressSpace::insertSnippet
831  *
832  * Insert a code snippet at each of a list of instrumentation points.  Upon
833  * success, Returns a handle to the created instances of the snippet, which
834  * can be used to delete them (as a unit).  Otherwise returns NULL.
835  *
836  * expr         The snippet to insert.
837  * points       The list of points at which to insert it.
838  */
839
840 // A lot duplicated from the single-point version. This is unfortunate.
841 BPatchSnippetHandle *BPatch_addressSpace::insertSnippetAtPointsWhen(const BPatch_snippet &expr,
842                                                                     const BPatch_Vector<BPatch_point *> &points,
843                                                                     BPatch_callWhen when,
844                                                                     BPatch_snippetOrder order)
845 {
846   BPatchSnippetHandle *retHandle = new BPatchSnippetHandle(this);
847
848   if (dyn_debug_inst) {
849       BPatch_function *f;
850       for (unsigned i=0; i<points.size(); i++) {
851          f = points[i]->getFunction();
852          const char *sname = f->func->prettyName().c_str();
853          inst_printf("[%s:%u] - %d. Insert instrumentation at function %s, "
854                "address %p, when %d, order %d\n",
855                FILE__, __LINE__, i,
856                sname, points[i]->getAddress(), (int) when, (int) order);
857
858       }
859   }
860
861   if (BPatch::bpatch->isTypeChecked()) {
862       if (expr.ast_wrapper->checkType() == BPatch::bpatch->type_Error) {
863         fprintf(stderr, "[%s:%u] - Type error inserting instrumentation\n",
864                 FILE__, __LINE__);
865          expr.ast_wrapper->debugPrint();
866          return false;
867       }
868    }
869
870    if (!points.size()) {
871      fprintf(stderr, "%s[%d]:  request to insert snippet at zero points!\n", FILE__, __LINE__);
872       return false;
873    }
874
875    for (unsigned i = 0; i < points.size(); i++) {
876       BPatch_point *bppoint = points[i];
877
878       if (bppoint->addSpace == NULL) {
879          fprintf(stderr, "Error: attempt to use point with no process info\n");
880          continue;
881       }
882
883       if (dynamic_cast<BPatch_addressSpace *>(bppoint->addSpace) != this) {
884          fprintf(stderr, "Error: attempt to use point specific to a different process\n");
885          continue;
886       }
887
888       callWhen ipWhen;
889       callOrder ipOrder;
890
891       if (!BPatchToInternalArgs(bppoint, when, order, ipWhen, ipOrder)) {
892         fprintf(stderr, "[%s:%u] - BPatchToInternalArgs failed for point %d\n",
893                FILE__, __LINE__, i);
894          return retHandle;
895       }
896
897       /* PatchAPI stuffs */
898       instPoint* ipoint = bppoint->getPoint(when);
899       AddressSpace* ias = ipoint->proc();
900       PatcherPtr patcher = ias->patcher();
901       DynInsertSnipCommand::Ptr ins_snip = DynInsertSnipCommand::create(ipoint,
902               ipOrder, expr.ast_wrapper, BPatch::bpatch->isTrampRecursive());
903       miniTramp* mini = ins_snip->mini();
904       patcher->add(ins_snip);
905       /* End of PatchAPI stuffs */
906
907       if (mini) {
908         retHandle->mtHandles_.push_back(mini);
909         bppoint->recordSnippet(when, order, retHandle);
910       }
911    }
912    if (pendingInsertions == NULL) {
913      // There's no insertion set, instrument now
914      bool tmp;
915      finalizeInsertionSet(false, &tmp);
916    }   
917
918    return retHandle;
919 }
920
921
922 /*
923  * BPatch_addressSpace::insertSnippet
924  *
925  * Insert a code snippet at each of a list of instrumentation points.  Upon
926  * success, Returns a handle to the created instances of the snippet, which
927  * can be used to delete them (as a unit).  Otherwise returns NULL.
928  *
929  * expr         The snippet to insert.
930  * points       The list of points at which to insert it.
931  */
932
933 BPatchSnippetHandle *BPatch_addressSpace::insertSnippetAtPoints(
934       const BPatch_snippet &expr,
935       const BPatch_Vector<BPatch_point *> &points,
936       BPatch_snippetOrder order)
937 {
938    return insertSnippetAtPointsWhen(expr,
939          points,
940          BPatch_callUnset,
941          order);
942 }
943
944 /*
945  * BPatch_addressSpace::isStaticExecutable
946  *
947  * Returns true if the underlying image represents a statically-linked executable, false otherwise.
948  */
949 bool BPatch_addressSpace::isStaticExecutableInt() {
950    std::vector<AddressSpace *> as;
951    getAS(as);
952
953    if( !as.size() ) return false;
954
955    AddressSpace *aout = as[0];
956    return aout->getAOut()->isStaticExec();
957 }
958
959 #include "registerSpace.h"
960
961 #if defined(cap_registers)
962 bool BPatch_addressSpace::getRegistersInt(std::vector<BPatch_register> &regs) {
963    if (registers_.size()) {
964        regs = registers_;
965        return true;
966    }
967
968    std::vector<AddressSpace *> as;
969
970    getAS(as);
971    assert(as.size());
972
973    registerSpace *rs = registerSpace::getRegisterSpace(as[0]);
974
975    for (unsigned i = 0; i < rs->realRegs().size(); i++) {
976        // Let's do just GPRs for now
977        registerSlot *regslot = rs->realRegs()[i];
978        registers_.push_back(BPatch_register(regslot->name, regslot->number));
979    }
980    regs = registers_;
981    return true;
982 }
983 #else
984 bool BPatch_addressSpace::getRegistersInt(std::vector<BPatch_register> &) {
985     // Empty vector since we're not supporting register objects on
986     // these platforms (yet)
987    return false;
988 }
989 #endif
990
991 #if defined(cap_registers)
992 bool BPatch_addressSpace::createRegister_NPInt(std::string regName,
993                                                BPatch_register &reg) {
994     // Build the register list.
995     std::vector<BPatch_register> dontcare;
996     getRegisters(dontcare);
997
998     for (unsigned i = 0; i < registers_.size(); i++) {
999         if (registers_[i].name() == regName) {
1000             reg = registers_[i];
1001             return true;
1002         }
1003     }
1004     return false;
1005 }
1006 #else
1007 bool BPatch_addressSpace::createRegister_NPInt(std::string,
1008                                                BPatch_register &)
1009 {
1010    return false;
1011 }
1012 #endif
1013
1014 bool BPatch_addressSpace::loadLibraryInt(const char * /*libname*/, bool /*reload*/)
1015 {
1016         return false;
1017 }
1018
1019 void BPatch_addressSpace::allowTrapsInt(bool allowtraps)
1020 {
1021    std::vector<AddressSpace *> as;
1022    getAS(as);
1023
1024    for (std::vector<AddressSpace *>::iterator i = as.begin(); i != as.end(); i++)
1025    {
1026       (*i)->setUseTraps(allowtraps);
1027    }
1028 }
1029
1030 BPatch_variableExpr *BPatch_addressSpace::createVariableInt(
1031                         Dyninst::Address at_addr,
1032                         BPatch_type *type, std::string var_name,
1033                         BPatch_module *in_module)
1034 {
1035    BPatch_binaryEdit *binEdit = dynamic_cast<BPatch_binaryEdit *>(this);
1036    if (binEdit && !in_module) {
1037       //Address alone isn't unique when binary rewriting
1038       return NULL;
1039    }
1040    if (!type) {
1041       //Required for size information.
1042       return NULL;
1043    }
1044    AddressSpace *ll_addressSpace = NULL;
1045
1046    std::vector<AddressSpace *> as;
1047    getAS(as);
1048    if (binEdit) {
1049       std::vector<AddressSpace *>::iterator as_i;
1050       for (as_i = as.begin(); as_i != as.end(); as_i++)
1051       {
1052          BinaryEdit *b = dynamic_cast<BinaryEdit *>(*as_i);
1053          assert(b);
1054          if (in_module->mod->obj() == b->getMappedObject()) {
1055             ll_addressSpace = *as_i;
1056             break;
1057          }
1058       }
1059    }
1060    else {
1061       assert(as.size() == 1);
1062       ll_addressSpace = as[0];
1063    }
1064
1065    if (!ll_addressSpace) {
1066       //in_module doesn't belong to 'this'
1067       return NULL;
1068    }
1069
1070    if (!var_name.size()) {
1071       std::stringstream namestream;
1072       namestream << "dyninst_var_" << std::hex << at_addr;
1073       var_name = namestream.str();
1074    }
1075
1076    return BPatch_variableExpr::makeVariableExpr(this, ll_addressSpace, var_name,
1077                                                 (void *) at_addr, type);
1078 }
1079