Loops can have multiple back edges and cleaned up instrumentation removal
[dyninst.git] / dyninstAPI / src / BPatch_addressSpace.C
1 /*
2  * Copyright (c) 1996-2009 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" // int_function
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 "callbacks.h"
56
57 #include "BPatch_private.h"
58
59 #include "ast.h"
60
61 #include "BPatch_addressSpace.h"
62
63 #include "BPatch_instruction.h"
64
65 #include <sstream>
66
67 BPatch_addressSpace::BPatch_addressSpace() :
68    image(NULL)
69 {
70 }
71
72 BPatch_addressSpace::~BPatch_addressSpace()
73 {}
74
75
76 BPatch_function *BPatch_addressSpace::findOrCreateBPFunc(int_function* ifunc,
77                                                          BPatch_module *bpmod)
78 {
79    if (!bpmod)
80       bpmod = image->findOrCreateModule(ifunc->mod());
81    assert(bpmod);
82    if (bpmod->func_map.count(ifunc)) {
83       BPatch_function *bpf = bpmod->func_map[ifunc];
84       assert(bpf);
85       return bpf;
86    }
87
88    // Find the module that contains the function
89    if (bpmod == NULL && ifunc->mod() != NULL) {
90       bpmod = getImage()->findModule(ifunc->mod()->fileName().c_str());
91    }
92
93    // findModule has a tendency to make new function objects... so
94    // check the map again
95    if (bpmod->func_map.count(ifunc)) {
96       BPatch_function *bpf = bpmod->func_map[ifunc];
97       assert(bpf);
98       return bpf;
99    }
100
101    BPatch_function *ret = new BPatch_function(this, ifunc, bpmod);
102    assert( ret != NULL );
103    return ret;
104 }
105
106
107
108
109 BPatch_point *BPatch_addressSpace::findOrCreateBPPoint(BPatch_function *bpfunc,
110                               instPoint *ip, BPatch_procedureLocation pointType)
111 {
112    assert(ip);
113    
114    BPatch_module *mod = image->findOrCreateModule(ip->func()->mod());
115    assert(mod);
116    
117    if (mod->instp_map.count(ip)) 
118       return mod->instp_map[ip];
119
120    if (pointType == BPatch_locUnknownLocation)
121       return NULL;
122
123    AddressSpace *lladdrSpace = ip->func()->proc();
124    if (!bpfunc) 
125       bpfunc = findOrCreateBPFunc(ip->func(), mod);
126
127    BPatch_point *pt = new BPatch_point(this, bpfunc, ip, pointType, lladdrSpace);
128    mod->instp_map[ip] = pt;
129
130    return pt;
131 }
132
133 BPatch_variableExpr *BPatch_addressSpace::findOrCreateVariable(int_variable *v,
134                                                                BPatch_type *type)
135 {
136    BPatch_module *mod = image->findOrCreateModule(v->mod());
137    assert(mod);
138    if (mod->var_map.count(v))
139       return mod->var_map[v];
140
141    if (!type) {
142       SymtabAPI::Type *stype = v->ivar()->svar()->getType();
143       if (stype)
144          type = BPatch_type::findOrCreateType(stype);
145       else
146          type = BPatch::bpatch->type_Untyped;
147    }
148    
149    BPatch_variableExpr *var = BPatch_variableExpr::makeVariableExpr(this, v, type);
150    mod->var_map[v] = var;
151    return var;
152 }
153                                                                
154
155
156 BPatch_function *BPatch_addressSpace::createBPFuncCB(AddressSpace *a, int_function *f)
157 {
158    BPatch_addressSpace *aS = (BPatch_addressSpace *)a->up_ptr();
159    assert(aS);
160    return aS->findOrCreateBPFunc(f, NULL);
161 }
162
163 BPatch_point *BPatch_addressSpace::createBPPointCB(AddressSpace *a, 
164                                                    int_function *f, 
165                                                    instPoint *ip, int type)
166 {
167    BPatch_addressSpace *aS = (BPatch_addressSpace *)a->up_ptr();
168    assert(aS);
169
170    BPatch_module *bpmod = aS->getImageInt()->findOrCreateModule(f->mod());
171    assert(bpmod);
172
173    BPatch_function *func = aS->findOrCreateBPFunc(f, bpmod);
174    assert(func);
175    
176    return aS->findOrCreateBPPoint(func, ip, (BPatch_procedureLocation) type);
177 }
178
179
180
181 /***************************************************************************
182  * Bpatch_snippetHandle
183  ***************************************************************************/
184
185 /*
186  * BPatchSnippetHandle::BPatchSnippetHandle
187  *
188  * Constructor for BPatchSnippetHandle.  Delete the snippet instance(s)
189  * associated with the BPatchSnippetHandle.
190  */
191 BPatchSnippetHandle::BPatchSnippetHandle(BPatch_addressSpace * addSpace) :
192    addSpace_(addSpace)
193 {
194 }
195
196 /*
197  * BPatchSnippetHandle::~BPatchSnippetHandle
198  *
199  * Destructor for BPatchSnippetHandle.  Delete the snippet instance(s)
200  * associated with the BPatchSnippetHandle.
201  */
202 void BPatchSnippetHandle::BPatchSnippetHandle_dtor()
203 {
204    // don't delete inst instances since they are might have been copied
205 }
206
207 BPatch_addressSpace *BPatchSnippetHandle::getAddressSpaceInt()
208 {
209    return addSpace_;
210 }
211
212 BPatch_process *BPatchSnippetHandle::getProcessInt()
213 {
214    return dynamic_cast<BPatch_process *>(addSpace_);
215 }
216
217 BPatch_Vector<BPatch_thread *> &BPatchSnippetHandle::getCatchupThreadsInt()
218 {
219    return catchup_threads;
220 }
221
222
223 BPatch_image * BPatch_addressSpace::getImageInt()
224 {
225    return image;
226 }
227
228
229 /*
230  * BPatch_addressSpace::deleteSnippet
231  * 
232  * Deletes an instance of a snippet.
233  *
234  * handle       The handle returned by insertSnippet when the instance to
235  *              deleted was created.
236  */
237
238 bool BPatch_addressSpace::deleteSnippetInt(BPatchSnippetHandle *handle)
239 {   
240    if (getTerminated()) return true;
241
242    if (handle == NULL) {
243        bperr("Request to delete NULL snippet handle, returning false\n");
244        return false;
245    }
246
247    if (handle->addSpace_ == this) {  
248
249        // uninstrument and remove snippet handle from point datastructures
250        for (unsigned int i=0; i < handle->mtHandles_.size(); i++)
251        {
252            instPoint *iPoint = handle->mtHandles_[i]->instP();
253            handle->mtHandles_[i]->uninstrument();
254            BPatch_point *bPoint = findOrCreateBPPoint(NULL, iPoint);
255            assert(bPoint);
256            bPoint->deleteSnippet(handle);
257        }
258
259        delete handle;
260        return true;
261    } 
262    // Handle isn't to a snippet instance in this process
263    bperr("Error: wrong address space in deleteSnippet\n");
264    return false;
265 }
266
267 /*
268  * BPatch_addressSpace::replaceCode
269  *
270  * Replace a given instruction with a BPatch_snippet.
271  *
272  * point       Represents the instruction to be replaced
273  * snippet     The replacing snippet
274  */
275
276 bool BPatch_addressSpace::replaceCodeInt(BPatch_point *point,
277       BPatch_snippet *snippet) 
278 {
279    if (!getMutationsActive())
280       return false;
281
282    if (!point) {
283       return false;
284    }
285    if (getTerminated()) {
286       return true;
287    }
288
289    if (point->edge_) {
290       return false;
291    }
292
293
294    return point->point->replaceCode(snippet->ast_wrapper);
295 }
296
297
298
299 /*
300  * BPatch_addressSpace::replaceFunctionCall
301  *
302  * Replace a function call with a call to a different function.  Returns true
303  * upon success, false upon failure.
304  * 
305  * point        The call site that is to be changed.
306  * newFunc      The function that the call site will now call.
307  */
308 bool BPatch_addressSpace::replaceFunctionCallInt(BPatch_point &point,
309       BPatch_function &newFunc)
310 {
311    char name[1024];
312    newFunc.getName(name, 1024);
313
314    // Can't make changes to code when mutations are not active.
315    if (!getMutationsActive())
316       return false;
317
318    assert(point.point && newFunc.lowlevel_func());
319
320 #if defined(arch_x86) || defined(arch_x86_64)
321    bool old_recursion_flag = BPatch::bpatch->isTrampRecursive();
322    BPatch::bpatch->setTrampRecursive( true );
323
324    BPatch_funcJumpExpr fjmp(newFunc, true);
325    insertSnippet(fjmp, point, BPatch_lastSnippet);
326    
327    BPatch::bpatch->setTrampRecursive( old_recursion_flag );
328    return true;
329 #else
330    return point.getAS()->replaceFunctionCall(point.point, 
331                                              newFunc.lowlevel_func());
332 #endif
333 }
334
335 /*
336  * BPatch_addressSpace::removeFunctionCall
337  *
338  * Replace a function call with a NOOP.  Returns true upon success, false upon
339  * failure.
340  * 
341  * point        The call site that is to be NOOPed out.
342  */
343 bool BPatch_addressSpace::removeFunctionCallInt(BPatch_point &point)
344 {
345    // Can't make changes to code when mutations are not active.
346    if (!getMutationsActive())
347       return false;   
348
349    assert(point.point);
350
351    return point.getAS()->replaceFunctionCall(point.point, NULL);
352 }
353
354
355 /*
356  * BPatch_addressSpace::replaceFunction
357  *
358  * Replace all calls to function OLDFUNC with calls to NEWFUNC.
359  * Returns true upon success, false upon failure.
360  * 
361  * oldFunc      The function to replace
362  * newFunc      The replacement function
363  */
364 bool BPatch_addressSpace::replaceFunctionInt(BPatch_function &oldFunc,
365       BPatch_function &newFunc)
366 {
367   char oldname[1024];
368   char newname[1024];
369   oldFunc.getName(oldname, 1024);
370   newFunc.getName(newname, 1024);
371    assert(oldFunc.lowlevel_func() && newFunc.lowlevel_func());
372    if (!getMutationsActive())
373       return false;
374
375    // Self replacement is a nop
376    // We should just test direct equivalence here...
377    if (oldFunc.lowlevel_func() == newFunc.lowlevel_func()) {
378       return true;
379    }
380
381    BPatch_Vector<BPatch_point *> *pts = oldFunc.findPoint(BPatch_entry);
382
383    if (! pts || ! pts->size()) {
384       return false;
385    }
386
387    BPatch_funcJumpExpr fje(newFunc);
388 //#if defined(cap_instruction_replacement) && defined(arch_power)
389 #if 0
390    // Replace the first instruction with fje
391    for (unsigned i = 0; i < pts->size(); i++) {
392        BPatch_point *point = (*pts)[i];
393        point->getPoint()->replaceCode(fje.ast_wrapper);
394    }
395
396    return true;
397 #else
398
399    bool old_recursion_flag = BPatch::bpatch->isTrampRecursive();
400    BPatch::bpatch->setTrampRecursive( true );
401
402    // We replace functions by instrumenting the entry of OLDFUNC with
403    // a non-linking jump to NEWFUNC.  Calls to OLDFUNC do actually
404    // transfer to OLDFUNC, but then our jump shunts them to NEWFUNC.
405    // The non-linking jump ensures that when NEWFUNC returns, it
406    // returns directly to the caller of OLDFUNC.
407
408
409    BPatchSnippetHandle * result = insertSnippet(fje, *pts, BPatch_callBefore);
410
411    BPatch::bpatch->setTrampRecursive( old_recursion_flag );
412
413    return (NULL != result);
414 #endif
415 }
416
417
418 bool BPatch_addressSpace::getAddressRangesInt( const char * fileName, 
419       unsigned int lineNo, 
420       std::vector< std::pair< unsigned long, unsigned long > > & ranges ) 
421 {
422    unsigned int originalSize = ranges.size();
423    BPatch_Vector< BPatch_module * > * modules = image->getModules();
424
425    /* Iteratate over the modules, looking for addr in each. */
426    for ( unsigned int i = 0; i < modules->size(); i++ ) {
427       BPatch_module *m = (*modules)[i];
428       m->getAddressRanges(fileName, lineNo, ranges);
429    }
430
431    if ( ranges.size() != originalSize ) { return true; }
432
433    return false;
434 } /* end getAddressRangesInt() */
435
436 bool BPatch_addressSpace::getSourceLinesInt( unsigned long addr, 
437       BPatch_Vector< BPatch_statement > & lines ) 
438 {
439    return image->getSourceLinesInt(addr, lines);
440 } /* end getLineAndFile() */
441
442
443 /*
444  * BPatch_process::malloc
445  *
446  * Allocate memory in the thread's address space.
447  *
448  * n    The number of bytes to allocate.
449  *
450  * Returns:
451  *      A pointer to a BPatch_variableExpr representing the memory.
452  *
453  * If otherwise unspecified when binary rewriting, then the allocation
454  * happens in the original object.
455  */
456
457 BPatch_variableExpr *BPatch_addressSpace::mallocInt(int n)
458 {
459    std::vector<AddressSpace *> as;
460    assert(BPatch::bpatch != NULL);
461    getAS(as);
462    assert(as.size());
463    void *ptr = (void *) as[0]->inferiorMalloc(n, dataHeap);
464    if (!ptr) return NULL;
465    std::stringstream namestr;
466    namestr << "dyn_malloc_0x" << std::hex << ptr << "_" << n << "_bytes";
467    std::string name = namestr.str();
468    
469    BPatch_type *type = BPatch::bpatch->createScalar(name.c_str(), n);
470
471    return BPatch_variableExpr::makeVariableExpr(this, as[0], name, ptr,
472                                                 type);
473 }
474
475
476 /*
477  * BPatch_process::malloc
478  *
479  * Allocate memory in the thread's address space for a variable of the given
480  * type.
481  *
482  * type         The type of variable for which to allocate space.
483  *
484  * Returns:
485  *      A pointer to a BPatch_variableExpr representing the memory.
486  *
487  * XXX Should return NULL on failure, but the function which it calls,
488  *     inferiorMalloc, calls exit rather than returning an error, so this
489  *     is not currently possible.
490  */
491
492 BPatch_variableExpr *BPatch_addressSpace::mallocByType(const BPatch_type &type)
493 {
494    std::vector<AddressSpace *> as;
495    assert(BPatch::bpatch != NULL);
496    getAS(as);
497    assert(as.size());
498    BPatch_type &t = const_cast<BPatch_type &>(type);
499    void *mem = (void *) as[0]->inferiorMalloc(t.getSize(), dataHeap);
500    if (!mem) return NULL;
501    std::stringstream namestr;
502    namestr << "dyn_malloc_0x" << std::hex << mem << "_" << type.getName();
503    std::string name = namestr.str();
504    return BPatch_variableExpr::makeVariableExpr(this, as[0], name, mem, &t);
505 }
506
507
508 /*
509  * BPatch_process::free
510  *
511  * Free memory that was allocated with BPatch_process::malloc.
512  *
513  * ptr          A BPatch_variableExpr representing the memory to free.
514  */
515
516 bool BPatch_addressSpace::freeInt(BPatch_variableExpr &ptr)
517 {
518   if(ptr.intvar)
519   {
520     // kill the symbols
521     
522   }
523   
524    ptr.getAS()->inferiorFree((Address)ptr.getBaseAddr());
525    return true;
526 }
527
528 BPatch_variableExpr *BPatch_addressSpace::createVariableInt(std::string name,
529                                                             Dyninst::Address addr,
530                                                             BPatch_type *type) {
531     assert(BPatch::bpatch != NULL);
532     std::vector<AddressSpace *> as;
533     getAS(as);
534     assert(as.size());
535
536     return BPatch_variableExpr::makeVariableExpr(this, 
537                                                  as[0],
538                                                  name,
539                                                  (void *)addr, 
540                                                  type);
541 }
542
543
544 /*
545  * BPatch_addressSpace::findFunctionByAddr
546  *
547  * Returns the function that contains the specified address, or NULL if the
548  * address is not within a function.
549  *
550  * addr         The address to use for the lookup.
551  */
552
553 BPatch_function *BPatch_addressSpace::findFunctionByAddrInt(void *addr)
554 {
555    int_function *func;   
556    std::vector<AddressSpace *> as;
557
558    getAS(as);
559    assert(as.size());
560    codeRange *range = as[0]->findOrigByAddr((Address) addr);
561    if (!range)
562       return NULL;
563
564    func = range->is_function();
565
566    if (!func) {
567       // if it's a mapped_object that has yet to be analyzed, 
568       // trigger analysis and re-invoke this function
569       if ( range->is_mapped_object() && 
570           ! ((mapped_object*)range)->isAnalyzed() ) {
571          ((mapped_object*)range)->analyze();
572          return findFunctionByAddrInt(addr);
573       }
574       return NULL;
575    }
576
577    return findOrCreateBPFunc(func, NULL);
578 }
579
580
581 /*
582  * BPatch_addressSpace::insertSnippet
583  *
584  * Insert a code snippet at a given instrumentation point.  Upon success,
585  * returns a handle to the created instance of the snippet, which can be used
586  * to delete it.  Otherwise returns NULL.
587  *
588  * expr         The snippet to insert.
589  * point        The point at which to insert it.
590  */
591
592 BPatchSnippetHandle *BPatch_addressSpace::insertSnippetInt(const BPatch_snippet &expr, 
593       BPatch_point &point, 
594       BPatch_snippetOrder order)
595 {
596    BPatch_callWhen when;
597    if (point.getPointType() == BPatch_exit)
598       when = BPatch_callAfter;
599    else
600       when = BPatch_callBefore;
601
602    return insertSnippetWhen(expr, point, when, order);
603 }
604
605 /*
606  * BPatch_addressSpace::insertSnippet
607  *
608  * Insert a code snippet at a given instrumentation point.  Upon succes,
609  * returns a handle to the created instance of the snippet, which can be used
610  * to delete it.  Otherwise returns NULL.
611  *
612  * expr         The snippet to insert.
613  * point        The point at which to insert it.
614  */
615
616 // This handles conversion without requiring inst.h in a header file...
617 extern bool BPatchToInternalArgs(BPatch_point *point,
618       BPatch_callWhen when,
619       BPatch_snippetOrder order,
620       callWhen &ipWhen,
621       callOrder &ipOrder);
622
623
624 BPatchSnippetHandle *BPatch_addressSpace::insertSnippetWhen(const BPatch_snippet &expr,
625       BPatch_point &point,
626       BPatch_callWhen when,
627       BPatch_snippetOrder order)
628 {
629    BPatch_Vector<BPatch_point *> points;
630    points.push_back(&point);
631
632    return insertSnippetAtPointsWhen(expr,
633          points,
634          when,
635          order);
636 }
637
638
639 /*
640  * BPatch_addressSpace::insertSnippet
641  *
642  * Insert a code snippet at each of a list of instrumentation points.  Upon
643  * success, Returns a handle to the created instances of the snippet, which
644  * can be used to delete them (as a unit).  Otherwise returns NULL.
645  *
646  * expr         The snippet to insert.
647  * points       The list of points at which to insert it.
648  */
649
650 // A lot duplicated from the single-point version. This is unfortunate.
651 BPatchSnippetHandle *BPatch_addressSpace::insertSnippetAtPointsWhen(const BPatch_snippet &expr,
652       const BPatch_Vector<BPatch_point *> &points,
653       BPatch_callWhen when,
654       BPatch_snippetOrder order)
655 {
656
657    if (dyn_debug_inst) {
658       BPatch_function *f;
659       for (unsigned i=0; i<points.size(); i++) {
660          f = points[i]->getFunction();
661          const char *sname = f->func->prettyName().c_str();
662          inst_printf("[%s:%u] - %d. Insert instrumentation at function %s, "
663                "address %p, when %d, order %d\n",
664                FILE__, __LINE__, i,
665                sname, points[i]->getAddress(), (int) when, (int) order);
666
667       }
668    }
669
670    if (BPatch::bpatch->isTypeChecked()) {
671       if (expr.ast_wrapper->checkType() == BPatch::bpatch->type_Error) {
672          inst_printf("[%s:%u] - Type error inserting instrumentation\n",
673                FILE__, __LINE__);
674          expr.ast_wrapper->debugPrint();
675          return false;
676       }
677    }
678
679    if (!points.size()) {
680       inst_printf("%s[%d]:  request to insert snippet at zero points!\n", FILE__, __LINE__);
681       return false;
682    }
683
684
685    batchInsertionRecord *rec = new batchInsertionRecord;
686    rec->thread_ = NULL;
687    rec->snip = expr;
688    rec->trampRecursive_ = BPatch::bpatch->isTrampRecursive();
689
690    BPatchSnippetHandle *ret = new BPatchSnippetHandle(this);
691    rec->handle_ = ret;
692
693    for (unsigned i = 0; i < points.size(); i++) {
694       BPatch_point *point = points[i];
695
696       if (point->addSpace == NULL) {
697          fprintf(stderr, "Error: attempt to use point with no process info\n");
698          continue;
699       }
700
701       if (dynamic_cast<BPatch_addressSpace *>(point->addSpace) != this) {
702          fprintf(stderr, "Error: attempt to use point specific to a different process\n");
703          continue;
704       }        
705
706       callWhen ipWhen;
707       callOrder ipOrder;
708
709       if (!BPatchToInternalArgs(point, when, order, ipWhen, ipOrder)) {
710          inst_printf("[%s:%u] - BPatchToInternalArgs failed for point %d\n",
711                FILE__, __LINE__, i);
712          return NULL;
713       }
714
715       rec->points_.push_back(point);
716       rec->when_.push_back(ipWhen);
717       rec->order_ = ipOrder;
718
719       point->recordSnippet(when, order, ret);
720    }
721
722    assert(rec->points_.size() == rec->when_.size());
723
724    // Okey dokey... now see if we just tack it on, or insert now.
725    if (pendingInsertions) {
726       pendingInsertions->push_back(rec);
727    }
728    else {
729       BPatch_process *proc = dynamic_cast<BPatch_process *>(this);
730       assert(proc);
731       proc->beginInsertionSetInt();
732       pendingInsertions->push_back(rec);
733       // All the insertion work was moved here...
734       proc->finalizeInsertionSetInt(false);
735    }
736    return ret;
737 }
738
739
740 /*
741  * BPatch_addressSpace::insertSnippet
742  *
743  * Insert a code snippet at each of a list of instrumentation points.  Upon
744  * success, Returns a handle to the created instances of the snippet, which
745  * can be used to delete them (as a unit).  Otherwise returns NULL.
746  *
747  * expr         The snippet to insert.
748  * points       The list of points at which to insert it.
749  */
750
751 BPatchSnippetHandle *BPatch_addressSpace::insertSnippetAtPoints(
752       const BPatch_snippet &expr,
753       const BPatch_Vector<BPatch_point *> &points,
754       BPatch_snippetOrder order)
755 {
756    return insertSnippetAtPointsWhen(expr,
757          points,
758          BPatch_callUnset,
759          order);
760 }
761
762 #include "registerSpace.h"
763
764 #if defined(cap_registers)
765 bool BPatch_addressSpace::getRegistersInt(std::vector<BPatch_register> &regs) {
766    if (registers_.size()) {
767        regs = registers_;
768        return true;
769    }
770
771    std::vector<AddressSpace *> as;
772
773    getAS(as);
774    assert(as.size());
775           
776    registerSpace *rs = registerSpace::getRegisterSpace(as[0]);
777    
778    for (unsigned i = 0; i < rs->realRegs().size(); i++) {
779        // Let's do just GPRs for now
780        registerSlot *regslot = rs->realRegs()[i];
781        registers_.push_back(BPatch_register(regslot->name, regslot->number));
782    }
783    regs = registers_;
784    return true;
785 }
786 #else
787 bool BPatch_addressSpace::getRegistersInt(std::vector<BPatch_register> &) {
788     // Empty vector since we're not supporting register objects on
789     // these platforms (yet)
790    return false;
791 }
792 #endif
793
794 #if defined(cap_registers)
795 bool BPatch_addressSpace::createRegister_NPInt(std::string regName,
796                                                BPatch_register &reg) {
797     // Build the register list.
798     std::vector<BPatch_register> dontcare;
799     getRegisters(dontcare);
800
801     for (unsigned i = 0; i < registers_.size(); i++) {
802         if (registers_[i].name() == regName) {
803             reg = registers_[i];
804             return true;
805         }
806     }
807     return false;
808 }
809 #else
810 bool BPatch_addressSpace::createRegister_NPInt(std::string,
811                                                BPatch_register &) 
812 {
813    return false;
814 }
815 #endif
816
817 bool BPatch_addressSpace::loadLibraryInt(const char * /*libname*/, bool /*reload*/)
818 {
819         return false;
820 }
821
822 void BPatch_addressSpace::allowTrapsInt(bool allowtraps)
823 {
824    std::vector<AddressSpace *> as;
825    getAS(as);
826    
827    for (std::vector<AddressSpace *>::iterator i = as.begin(); i != as.end(); i++)
828    {
829       (*i)->setUseTraps(allowtraps);
830    }
831 }
832
833 BPatch_variableExpr *BPatch_addressSpace::createVariableInt(
834                         Dyninst::Address at_addr,
835                         BPatch_type *type, std::string var_name,
836                         BPatch_module *in_module)
837 {
838    BPatch_binaryEdit *binEdit = dynamic_cast<BPatch_binaryEdit *>(this);
839    if (binEdit && !in_module) {
840       //Address alone isn't unique when binary rewriting
841       return NULL;
842    }
843    if (!type) {
844       //Required for size information.  
845       return NULL;
846    }
847    AddressSpace *ll_addressSpace = NULL;
848    
849    std::vector<AddressSpace *> as;
850    getAS(as);
851    if (binEdit) {
852       std::vector<AddressSpace *>::iterator as_i;      
853       for (as_i = as.begin(); as_i != as.end(); as_i++)
854       {
855          BinaryEdit *b = dynamic_cast<BinaryEdit *>(*as_i);
856          assert(b);
857          if (in_module->mod->obj() == b->getMappedObject()) {
858             ll_addressSpace = *as_i;
859             break;
860          }
861       }
862    }
863    else {
864       assert(as.size() == 1);
865       ll_addressSpace = as[0];
866    }
867
868    if (!ll_addressSpace) {
869       //in_module doesn't belong to 'this'
870       return NULL;
871    }
872
873    if (!var_name.size()) {
874       std::stringstream namestream;
875       namestream << "dyninst_var_" << std::hex << at_addr;
876       var_name = namestream.str();
877    }
878    
879    return BPatch_variableExpr::makeVariableExpr(this, ll_addressSpace, var_name,
880                                                 (void *) at_addr, type);
881 }
882