This commit enables arbitrary instrumentation points at the last instruction
[dyninst.git] / dyninstAPI / src / BPatch.C
1 /*
2  * Copyright (c) 1996 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  * This license is for research uses.  For such uses, there is no
12  * charge. We define "research use" to mean you may freely use it
13  * inside your organization for whatever purposes you see fit. But you
14  * may not re-distribute Paradyn or parts of Paradyn, in any form
15  * source or binary (including derivatives), electronic or otherwise,
16  * to any other organization or entity without our permission.
17  * 
18  * (for other uses, please contact us at paradyn@cs.wisc.edu)
19  * 
20  * All warranties, including without limitation, any warranty of
21  * merchantability or fitness for a particular purpose, are hereby
22  * excluded.
23  * 
24  * By your use of Paradyn, you understand and agree that we (or any
25  * other person or entity with proprietary rights in Paradyn) are
26  * under no obligation to provide either maintenance services,
27  * update services, notices of latent defects, or correction of
28  * defects for Paradyn.
29  * 
30  * Even if advised of the possibility of such damages, under no
31  * circumstances shall we (or any other person or entity with
32  * proprietary rights in the software licensed hereunder) be liable
33  * to you or any third party for direct, indirect, or consequential
34  * damages of any character regardless of type of action, including,
35  * without limitation, loss of profits, loss of use, loss of good
36  * will, or computer failure or malfunction.  You agree to indemnify
37  * us (and any other person or entity with proprietary rights in the
38  * software licensed hereunder) for any and all liability it may
39  * incur to third parties resulting from your use of Paradyn.
40  */
41
42 // $Id: BPatch.C,v 1.56 2003/03/13 17:00:14 jodom Exp $
43
44 #include <stdio.h>
45 #include <assert.h>
46 #include <signal.h>
47
48 #define BPATCH_FILE
49 #include "signalhandler.h"
50 #include "BPatch.h"
51 #include "BPatch_libInfo.h"
52 #include "process.h"
53 #include "BPatch_collections.h"
54 #include "common/h/timing.h"
55
56 #if defined(i386_unknown_nt4_0) || defined(mips_unknown_ce2_11) //ccw 20 july 2000 : 28 mar 2001
57 #include "nt_signal_emul.h"
58 #endif
59
60 extern bool dyninstAPI_init();
61
62 BPatch *BPatch::bpatch = NULL;
63
64 /*
65  * BPatch::BPatch
66  *
67  * Constructor for BPatch.  Performs one-time initialization needed by the
68  * library.
69  */
70 BPatch::BPatch()
71   : info(NULL),
72     errorHandler(NULL),
73     dynLibraryCallback(NULL),
74     typeCheckOn(true),
75     lastError(0),
76     debugParseOn(true),
77     baseTrampDeletionOn(false),
78     trampRecursiveOn(false),
79     forceRelocation_NP(false),
80     autoRelocation(true),
81     builtInTypes(NULL),
82     stdTypes(NULL),
83     type_Error(NULL),
84     type_Untyped(NULL)
85 {
86     extern bool init();
87
88     // Save a pointer to the one-and-only bpatch object.
89     if (bpatch == NULL){
90         bpatch = this;
91 #ifdef mips_unknown_ce2_11 //ccw 10 aug 2000 : 28 mar 2001
92         rDevice = new remoteDevice(); //ccw 8 aug 2000
93 #endif
94         }
95
96     /* XXX else
97      *  (indicate an error somehow)
98      */
99
100     // XXX dyninstAPI_init returns success/failure -- should pass on somehow
101     dyninstAPI_init();
102     initCyclesPerSecond();
103
104     /*
105      * Create the library private info object.
106      */
107     info = new BPatch_libInfo;
108
109     /*
110      * Create the "error" and "untyped" types.
111      */
112     type_Error   = new BPatch_type("<error>", true);
113     type_Untyped = new BPatch_type("<no type>", true);
114
115     /*
116      * Initialize hash table of standard types.
117      */
118     stdTypes = new BPatch_typeCollection;
119     stdTypes->addType(new BPatch_type("int",-1, BPatch_dataScalar, sizeof(int)));
120     stdTypes->addType(new BPatch_type("char *",-3, BPatch_dataScalar, sizeof(char*)));
121     BPatch_type *voidType = new BPatch_type("void",-11, BPatch_dataScalar, 0);
122     stdTypes->addType(voidType);
123     stdTypes->addType(new BPatch_type("void *",-4, BPatch_dataPointer, voidType));
124     stdTypes->addType(new BPatch_type("float",-12, BPatch_dataScalar, sizeof(float)));
125 #if !defined(i386_unknown_nt4_0)
126     stdTypes->addType(new BPatch_type("long long",-31, BPatch_dataScalar, sizeof(long long int)));
127 #endif
128
129     /*
130      * Initialize hash table of API types.
131      */
132     APITypes = new BPatch_typeCollection;
133
134     /*
135      *  Initialize hash table of Built-in types.
136      *  Negative type numbers defined in the gdb stab-docs
137      */
138      
139     builtInTypes = new BPatch_builtInTypeCollection;
140     
141     // NOTE: integral type  mean twos-complement
142     // -1  int, 32 bit signed integral type
143     // in stab document, size specified in bits, system size is in bytes
144     builtInTypes->addBuiltInType(new BPatch_type("int",-1, BPatch_dataBuilt_inType,
145                                                  4));
146     // -2  char, 8 bit type holding a character. GDB & dbx(AIX) treat as signed
147     builtInTypes->addBuiltInType(new BPatch_type("char",-2,
148                                                  BPatch_dataBuilt_inType, 1));
149     // -3  short, 16 bit signed integral type
150     builtInTypes->addBuiltInType(new BPatch_type("short",-3,
151                                                  BPatch_dataBuilt_inType, 2));
152     // -4  long, 32/64 bit signed integral type
153     builtInTypes->addBuiltInType(new BPatch_type("long",-4,
154                                                  BPatch_dataBuilt_inType, 
155                                                  sizeof(long)));
156     // -5  unsigned char, 8 bit unsigned integral type
157     builtInTypes->addBuiltInType(new BPatch_type("unsigned char",-5,
158                                                  BPatch_dataBuilt_inType, 1));
159     // -6  signed char, 8 bit signed integral type
160     builtInTypes->addBuiltInType(new BPatch_type("signed char",-6,
161                                                  BPatch_dataBuilt_inType, 1));
162     // -7  unsigned short, 16 bit unsigned integral type
163     builtInTypes->addBuiltInType(new BPatch_type("unsigned short",-7,
164                                                  BPatch_dataBuilt_inType, 2));
165     // -8  unsigned int, 32 bit unsigned integral type
166     builtInTypes->addBuiltInType(new BPatch_type("unsigned int",-8,
167                                                  BPatch_dataBuilt_inType, 4));
168     // -9  unsigned, 32 bit unsigned integral type
169     builtInTypes->addBuiltInType(new BPatch_type("unsigned",-9,
170                                                  BPatch_dataBuilt_inType,4));
171     // -10 unsigned long, 32 bit unsigned integral type
172     builtInTypes->addBuiltInType(new BPatch_type("unsigned long",-10,
173                                                  BPatch_dataBuilt_inType, 
174                                                  sizeof(unsigned long)));
175     // -11 void, type indicating the lack of a value
176     //  XXX-size may not be correct jdd 4/22/99
177     builtInTypes->addBuiltInType(new BPatch_type("void",-11,
178                                                  BPatch_dataBuilt_inType,
179                                                  0));
180     // -12 float, IEEE single precision
181     builtInTypes->addBuiltInType(new BPatch_type("float",-12,
182                                                  BPatch_dataBuilt_inType,
183                                                  sizeof(float)));
184     // -13 double, IEEE double precision
185     builtInTypes->addBuiltInType(new BPatch_type("double",-13,
186                                                  BPatch_dataBuilt_inType,
187                                                  sizeof(double)));
188     // -14 long double, IEEE double precision, size may increase in future
189     builtInTypes->addBuiltInType(new BPatch_type("long double",-14,
190                                                  BPatch_dataBuilt_inType,
191                                                  sizeof(long double)));
192     // -15 integer, 32 bit signed integral type
193     builtInTypes->addBuiltInType(new BPatch_type("integer",-15,
194                                                  BPatch_dataBuilt_inType, 4));
195     // -16 boolean, 32 bit type. GDB/GCC 0=False, 1=True, all other values
196     //     have unspecified meaning
197     builtInTypes->addBuiltInType(new BPatch_type("boolean",-16,
198                                                  BPatch_dataBuilt_inType, 4));
199     // -17 short real, IEEE single precision
200     //  XXX-size may not be correct jdd 4/22/99
201     builtInTypes->addBuiltInType(new BPatch_type("short real",-17,
202                                                  BPatch_dataBuilt_inType,
203                                                  sizeof(float)));
204     // -18 real, IEEE double precision XXX-size may not be correct jdd 4/22/99 
205     builtInTypes->addBuiltInType(new BPatch_type("real",-18,
206                                                  BPatch_dataBuilt_inType,
207                                                  sizeof(double)));
208     // -19 stringptr XXX- size of void * -- jdd 4/22/99
209     builtInTypes->addBuiltInType(new BPatch_type("stringptr",-19,
210                                                  BPatch_dataBuilt_inType,
211                                                  sizeof(void *)));
212     // -20 character, 8 bit unsigned character type
213     builtInTypes->addBuiltInType(new BPatch_type("character",-20,
214                                                  BPatch_dataBuilt_inType, 1));
215     // -21 logical*1, 8 bit type (Fortran, used for boolean or unsigned int)
216     builtInTypes->addBuiltInType(new BPatch_type("logical*1",-21,
217                                                  BPatch_dataBuilt_inType, 1));
218     // -22 logical*2, 16 bit type (Fortran, some for boolean or unsigned int)
219     builtInTypes->addBuiltInType(new BPatch_type("logical*2",-22,
220                                                  BPatch_dataBuilt_inType, 2));
221     // -23 logical*4, 32 bit type (Fortran, some for boolean or unsigned int)
222     builtInTypes->addBuiltInType(new BPatch_type("logical*4",-23,
223                                                  BPatch_dataBuilt_inType, 4));
224     // -24 logical, 32 bit type (Fortran, some for boolean or unsigned int)
225     builtInTypes->addBuiltInType(new BPatch_type("logical",-24,
226                                                  BPatch_dataBuilt_inType, 4));
227     // -25 complex, consists of 2 IEEE single-precision floating point values
228     builtInTypes->addBuiltInType(new BPatch_type("complex",-25,
229                                                  BPatch_dataBuilt_inType,
230                                                  (sizeof(float)*2)));
231     // -26 complex, consists of 2 IEEE double-precision floating point values
232     builtInTypes->addBuiltInType(new BPatch_type("complex",-26,
233                                                  BPatch_dataBuilt_inType,
234                                                  (sizeof(double)*2)));
235     // -27 integer*1, 8 bit signed integral type
236     builtInTypes->addBuiltInType(new BPatch_type("integer*1",-27,
237                                                  BPatch_dataBuilt_inType, 1));
238     // -28 integer*2, 16 bit signed integral type
239     builtInTypes->addBuiltInType(new BPatch_type("integer*2",-28,
240                                                  BPatch_dataBuilt_inType, 2));
241
242 /* Quick hack to make integer*4 compatible with int for Fortran
243    jnb 6/20/01 */
244
245     builtInTypes->addBuiltInType(new BPatch_type("int",-29,
246                                                  BPatch_built_inType, 4));
247 /*    // -29 integer*4, 32 bit signed integral type
248     builtInTypes->addBuiltInType(new BPatch_type("integer*4",-29,
249                                                  BPatch_built_inType, 4)); */
250
251     // -30 wchar, Wide character, 16 bits wide, unsigned (unknown format)
252     builtInTypes->addBuiltInType(new BPatch_type("wchar",-30,
253                                                  BPatch_dataBuilt_inType, 2));
254     // -31 long long, 64 bit signed integral type
255     builtInTypes->addBuiltInType(new BPatch_type("long long",-31,
256                                                  BPatch_dataBuilt_inType, 8));
257     // -32 unsigned long long, 64 bit unsigned integral type
258     builtInTypes->addBuiltInType(new BPatch_type("unsigned long long", -32,
259                                                  BPatch_dataBuilt_inType, 8));
260     // -33 logical*8, 64 bit unsigned integral type
261     builtInTypes->addBuiltInType(new BPatch_type("logical*8",-33,
262                                                  BPatch_dataBuilt_inType, 8));
263     // -34 integer*8, 64 bit signed integral type
264     builtInTypes->addBuiltInType(new BPatch_type("integer*8",-34,
265                                                  BPatch_dataBuilt_inType, 8));
266
267     // default callbacks are null
268     postForkCallback = NULL;
269     preForkCallback = NULL;
270     errorHandler = NULL;
271     dynLibraryCallback = NULL;
272     execCallback = NULL;
273     exitCallback = NULL;
274     oneTimeCodeCallback = NULL;
275
276 }
277
278
279 /*
280  * BPatch::~BPatch
281  *
282  * Destructor for BPatch.  Free allocated memory.
283  */
284 BPatch::~BPatch()
285 {
286     delete info;
287
288     delete type_Error;
289     delete type_Untyped;
290
291     delete stdTypes;
292
293     bpatch = NULL;
294 }
295
296
297 /*
298  * BPatch::registerErrorCallback
299  *
300  * Registers a function that is to be called by the library when an error
301  * occurs or when there is status to report.  Returns the address of the
302  * previously registered error callback function.
303  *
304  * function     The function to be called.
305  */
306 BPatchErrorCallback BPatch::registerErrorCallback(BPatchErrorCallback function)
307 {
308     BPatchErrorCallback ret;
309
310     ret = errorHandler;
311     errorHandler = function;
312
313     return ret;
314 }
315
316
317 /*
318  * BPatch::registerPostForkCallback
319  *
320  * Registers a function that is to be called by the library when a new
321  * process has been forked off by an mutatee process.
322  *
323  * function     The function to be called.
324  */
325 BPatchForkCallback BPatch::registerPostForkCallback(BPatchForkCallback func)
326 {
327
328 #if !defined(sparc_sun_solaris2_4) && \
329     !defined(i386_unknown_solaris2_5) && \
330     !defined(alpha_dec_osf4_0) && \
331     !defined(mips_sgi_irix6_4)
332
333   reportError(BPatchWarning, 0,
334               "postfork callbacks not implemented on this platform\n");
335   return NULL;
336 #else
337     BPatchForkCallback ret;
338
339     ret = postForkCallback;
340     postForkCallback = func;
341
342     return ret;
343 #endif
344 }
345
346 /*
347  * BPatch::registerPreForkCallback
348  *
349  * Registers a function that is to be called by the library when a process
350  * is about to fork a new process
351  *
352  * function     The function to be called.
353  */
354 BPatchForkCallback BPatch::registerPreForkCallback(BPatchForkCallback func)
355 {
356 #if !defined(sparc_sun_solaris2_4) && \
357     !defined(i386_unknown_solaris2_5) &&\
358     !defined(alpha_dec_osf4_0) && \
359     !defined(mips_sgi_irix6_4)
360     reportError(BPatchWarning, 0,
361         "prefork callbacks not implemented on this platform\n");
362     return NULL;
363 #else
364     BPatchForkCallback ret;
365
366     ret = preForkCallback;
367     preForkCallback = func;
368
369     return ret;
370 #endif
371 }
372
373 /*
374  * BPatch::registerExecCallback
375  *
376  * Registers a function that is to be called by the library when a 
377  * process has just completed an exec* call
378  *
379  * func The function to be called.
380  */
381 BPatchExecCallback BPatch::registerExecCallback(BPatchExecCallback func)
382 {
383
384 #if !defined(sparc_sun_solaris2_4) && \
385     !defined(i386_unknown_solaris2_5) &&\
386     !defined(alpha_dec_osf4_0) && \
387     !defined(mips_sgi_irix6_4)
388     reportError(BPatchWarning, 0,
389         "exec callbacks not implemented on this platform\n");
390     return NULL;
391 #else
392     BPatchExecCallback ret;
393
394     ret = execCallback;
395     execCallback = func;
396
397     return ret;
398 #endif
399 }
400
401 /*
402  * BPatch::registerExecCallback
403  *
404  * Registers a function that is to be called by the library when a 
405  * process has just called the exit system call
406  *
407  * func The function to be called.
408  */
409 BPatchExitCallback BPatch::registerExitCallback(BPatchExitCallback func)
410 {
411
412 #if !defined(sparc_sun_solaris2_4) && \
413     !defined(i386_unknown_solaris2_5) &&\
414     !defined(alpha_dec_osf4_0) && \
415     !defined(mips_sgi_irix6_4)
416     reportError(BPatchWarning, 0,
417         "exit callbacks not implemented on this platform\n");
418     return NULL;
419 #else
420     BPatchExitCallback ret;
421
422     ret = exitCallback;
423     exitCallback = func;
424     
425     return ret;
426 #endif
427 }
428
429 /*
430  * BPatch::registerOneTimeCodeCallback
431  *
432  * Registers a function that is to be called by the library when a 
433  * oneTimeCode (inferior RPC) is completed.
434  *
435  * func The function to be called.
436  */
437 BPatchOneTimeCodeCallback BPatch::registerOneTimeCodeCallback(BPatchOneTimeCodeCallback func)
438 {
439     BPatchOneTimeCodeCallback ret;
440
441     ret = oneTimeCodeCallback;
442     oneTimeCodeCallback = func;
443
444     return ret;
445 }
446
447 #ifdef IBM_BPATCH_COMPAT
448 BPatchExitCallback BPatch::registerExitCallback(BPatchThreadEventCallback func)
449 {
450
451     BPatchExitCallback ret;
452
453     ret = exitCallback;
454     exitCallback = (BPatchExitCallback) func;
455
456     return ret;
457
458 }
459 #endif
460
461 /*
462  * BPatch::registerDynLibraryCallback
463  *
464  * Registers a function that is to be called by the library when a dynamically
465  * loaded library is loaded or unloaded by a process under the API's control.
466  * Returns the address of the previously registered callback function.
467  *
468  * function     The function to be called.
469  */
470 BPatchDynLibraryCallback
471 BPatch::registerDynLibraryCallback(BPatchDynLibraryCallback function)
472 {
473     BPatchDynLibraryCallback ret;
474
475     ret = dynLibraryCallback;
476     dynLibraryCallback = function;
477
478     return ret;
479 }
480
481
482 /*
483  * BPatch::getEnglishErrorString
484  *
485  * Returns the descriptive error string for the passed error number.
486  *
487  * number       The number that identifies the error.
488  */
489 const char *BPatch::getEnglishErrorString(int /* number */)
490 {
491     return "%s";
492 }
493
494
495 /*
496  * BPatch::reportError
497  *
498  * Report an error using the callback mechanism.
499  *
500  * severity     The severity level of the error.
501  * number       Identifies the error.
502  * str          A string to pass as the first element of the list of strings
503  *              given to the callback function.
504  */
505 void BPatch::reportError(BPatchErrorLevel severity, int number, const char *str)
506 {
507     assert(bpatch != NULL);
508   
509     // don't log BPatchWarning or BPatchInfo messages as "errors"
510     if ((severity == BPatchFatal) || (severity == BPatchSerious))
511         bpatch->lastError = number;
512
513     if (bpatch->errorHandler != NULL) {
514         bpatch->errorHandler(severity, number, &str);
515     } else if ((severity == BPatchFatal) || (severity == BPatchSerious)){
516         fprintf(stdout, "DYNINST ERROR: %s\n", str);
517         fflush(stdout);
518     }
519 }
520
521
522 /*
523  * BPatch::formatErrorString
524  *
525  * Takes a format string with an error message (obtained from
526  * getEnglishErrorString) and an array of parameters that were passed to an
527  * error callback function, and creates a string with the parameters
528  * substituted into it.
529  *
530  * dst          The address into which the formatted string should be copied.
531  * size         If the formatted string is equal to or longer than this number
532  *              of characters, then it will be truncated to size-1 characters
533  *              and terminated with a nul ('\0').
534  * fmt          The format string (returned by a function such as
535  *              getEnglishErrorString).
536  * params       The array of parameters that were passed to an error callback
537  *              function.
538  */
539 void BPatch::formatErrorString(char *dst, int size,
540                                const char *fmt, const char **params)
541 {
542     int cur_param = 0;
543
544     while (size > 1 && *fmt) {
545         if (*fmt == '%') {
546             if (fmt[1] == '\0') {
547                 break;
548             } else if (fmt[1] == '%') {
549                 *dst++ = '%';
550                 size--;
551             } else if (fmt[1] == 's') {
552                 char *p = const_cast<char *>(params[cur_param++]);
553                 while (size > 1 && *p) {
554                     *dst++ = *p++;
555                     size--;
556                 }
557             } else {
558                 // Illegal specifier
559                 *dst++ = fmt[0];
560                 *dst++ = fmt[1];
561                 size -= 2;
562             }
563             fmt += 2;
564         } else {
565             *dst++ = *fmt++;
566             size--;
567         }
568     }
569     if (size > 0)
570         *dst = '\0';
571 }
572
573
574 /*
575  * BPatch::getThreadByPid
576  *
577  * Given a process ID, this function returns a pointer to the associated
578  * BPatch_thread object (or NULL if there is none).  Since a process may be
579  * registered provisionally with a thread object pointer of NULL, the boolean
580  * pointed to by the parameter "exists" is set to true if the pid exists in
581  * the table of processes, and false if it does not.
582  *
583  * pid          The pid to look up.
584  * exists       A pointer to a boolean to fill in with true if the pid exists
585  *              in the table and false if it does not.  NULL may be passed in
586  *              if this information is not required.
587  */
588 BPatch_thread *BPatch::getThreadByPid(int pid, bool *exists)
589 {
590     if (info->threadsByPid.defines(pid)) {
591         if (exists) *exists = true;
592         return info->threadsByPid[pid];
593     } else {
594         if (exists) *exists = false;
595         return NULL;
596     }
597 }
598
599
600 /*
601  * BPatch::getThreads
602  *
603  * Returns a vector of all threads that are currently defined.  Includes
604  * threads created directly using the library and those created with UNIX fork
605  * or Windows NT spawn system calls.  The caller is responsible for deleting
606  * the vector when it is no longer needed.
607  */
608 BPatch_Vector<BPatch_thread *> *BPatch::getThreads()
609 {
610     BPatch_Vector<BPatch_thread *> *result = new BPatch_Vector<BPatch_thread *>;
611
612     dictionary_hash_iter<int, BPatch_thread *> ti(info->threadsByPid);
613
614     int pid;
615     BPatch_thread *thread;
616
617     while (ti.next(pid, thread))
618         result->push_back(thread);
619
620     return result;
621 }
622
623
624 /*
625  * BPatch::registerProvisionalThread
626  *
627  * Register a new process that is not yet associated with a thread.
628  * (this function is called only by createProcess).
629  *
630  * pid          The pid of the process to register.
631  */
632 void BPatch::registerProvisionalThread(int pid)
633 {
634     assert(!info->threadsByPid.defines(pid));
635     info->threadsByPid[pid] = NULL;
636 }
637
638
639 /*
640  * BPatch::registerForkedThread
641  *
642  * Register a new process that is not yet associated with a thread.
643  * (this function is an upcall when a new process is created).
644  *
645  * parentPid            the pid of the parent process.
646  * childPid             The pid of the process to register.
647  * proc                 lower lever handle to process specific stuff
648  *
649  */
650 void BPatch::registerForkedThread(int parentPid, int childPid, process *proc)
651 {
652     assert(!info->threadsByPid.defines(childPid));
653
654     BPatch_thread *parent = info->threadsByPid[parentPid];
655
656     assert(parent);
657     info->threadsByPid[childPid] = new BPatch_thread(childPid, proc);
658
659     if (postForkCallback) {
660         postForkCallback(parent, info->threadsByPid[childPid]);
661     }
662 }
663
664 /*
665  * BPatch::registerForkingThread
666  *
667  * Perform whatever processing is necessary when a thread enters
668  * a fork system call. Previously the preForkCallback was made directly.
669  *
670  * forkingPid   pid of the forking process
671  * proc                 lower lever handle to process specific stuff
672  *
673  */
674 void BPatch::registerForkingThread(int forkingPid, process *proc)
675 {
676     BPatch_thread *forking = info->threadsByPid[forkingPid];
677     // Wouldn't this be the same as proc->thread?
678     assert(forking);
679     
680     if (preForkCallback) {
681         preForkCallback(forking, NULL);
682     }
683 }
684
685
686 /*
687  * BPatch::registerExec
688  *
689  * Register a process that has just done an exec call.
690  *
691  * thread       thread that has just performed the exec
692  *
693  */
694 void BPatch::registerExec(BPatch_thread *thread)
695 {
696     // build a new BPatch_image for this one
697     thread->image = new BPatch_image(thread->proc);
698
699     if (execCallback) {
700         execCallback(thread);
701     }
702 }
703
704
705 /*
706  * BPatch::registerExit
707  *
708  * Register a process that has just done an exit call.
709  *
710  * thread       thread that has just performed the exec
711  * code         the exit status code
712  *
713  */
714 void BPatch::registerExit(BPatch_thread *thread, int code)
715 {
716     if (exitCallback) {
717         exitCallback(thread, code);
718     }
719 }
720
721
722 /*
723  * BPatch::registerThread
724  *
725  * Register a new BPatch_thread object with the BPatch library (this function
726  * is called only by the constructor for BPatch_thread).
727  *
728  * thread       A pointer to the thread to register.
729  */
730 void BPatch::registerThread(BPatch_thread *thread)
731 {
732     assert(!info->threadsByPid.defines(thread->getPid()) ||
733             info->threadsByPid[thread->getPid()] == NULL);
734     info->threadsByPid[thread->getPid()] = thread;
735 }
736
737
738 /*
739  * BPatch::unRegisterThread
740  *
741  * Remove the BPatch_thread associated with a given pid from the list of
742  * threads being managed by the library.
743  *
744  * pid          The pid of the thread to be removed.
745  */
746 void BPatch::unRegisterThread(int pid)
747 {
748     assert(info->threadsByPid.defines(pid));
749     info->threadsByPid.undef(pid);      
750 }
751
752
753 /*
754  * BPatch::createProcess
755  *
756  * Create a process and return a BPatch_thread representing it.
757  * Returns NULL upon failure.
758  *
759  * path         The pathname of the executable for the new process.
760  * argv         A list of the arguments for the new process, terminated by a
761  *              NULL.
762  * envp         A list of values that make up the environment for the new
763  *              process, terminated by a NULL.  If envp is NULL, the new
764  *              new process will inherit the environemnt of the parent.
765  * stdin_fd     file descriptor to use for stdin for the application
766  * stdout_fd    file descriptor to use for stdout for the application
767  * stderr_fd    file descriptor to use for stderr for the application
768
769  */
770 BPatch_thread *BPatch::createProcess(const char *path, char *argv[], 
771         char *envp[], int stdin_fd, int stdout_fd, int stderr_fd)
772 {
773     clearError();
774
775     BPatch_thread *ret = 
776         new BPatch_thread(path, argv, envp, stdin_fd, stdout_fd, stderr_fd);
777
778     if (!ret->proc ||
779        (ret->proc->status() != stopped) ||
780        !ret->proc->isBootstrappedYet()) {
781         delete ret;
782         return NULL;
783     }
784     ret->proc->collectSaveWorldData = false;
785     //ccw 23 jan 2002 : this forces the user to call
786     //BPatch_thread::startSaveWorld() if they want to use the save the world
787     //functionality.
788     return ret;
789 }
790
791
792 /*
793  * BPatch::attachProcess
794  *
795  * Attach to a running process and return a BPatch_thread representing it.
796  * Returns NULL upon failure.
797  *
798  * path         The pathname of the executable for the process.
799  * pid          The id of the process to attach to.
800  */
801 BPatch_thread *BPatch::attachProcess(const char *path, int pid)
802 {
803     clearError();
804
805     BPatch_thread *ret = new BPatch_thread(path, pid);
806
807     if (!ret->proc ||
808        (ret->proc->status() != stopped) ||
809        !ret->proc->isBootstrappedYet()) {
810         // It would be considerate to (attempt to) leave the process running
811         // at this point (*before* deleting the BPatch_thread handle for it!),
812         // even though it might be in bad shape after the attempted attach.
813         char msg[256];
814         sprintf(msg,"attachProcess failed: process %d may now be killed!",pid);
815         reportError(BPatchWarning, 26, msg);
816         delete ret;
817         return NULL;
818     }
819     ret->proc->collectSaveWorldData = false;
820     //ccw 31 jan 2003 : this forces the user to call
821     //BPatch_thread::startSaveWorld() if they want to use the save the world
822     //functionality.
823
824     return ret;
825 }
826
827 /*
828  * BPatch::getThreadEvent
829  *
830  * Checks for changes in any child process, and optionally blocks until such a
831  * change has occurred.  Also performs housekeeping on behalf of Dyninst:
832  * - Launches pending oneTimeCode calls (aka inferior RPCs)
833  * - Updates the process object representing each process for which a
834  *   change is detected.
835  *
836  * The return value is true if a change was detected, otherwise it is false.
837  *
838  * block        Set this parameter to true to block waiting for a change,
839  *              set to false to poll and return immediately, whether or not a
840  *              change occurred.
841  */
842 bool BPatch::getThreadEvent(bool block)
843 {
844     launchDeferredOneTimeCode();
845
846     return getThreadEventOnly(block);
847 }
848
849 /*
850  * BPatch::getThreadEventOnly
851  *
852  * Like getThreadEvent (which actually calls this function), this function
853  * checks for changes in any child process, optionally blocking until such a
854  * change occurs.  It also updates the process objects with information about
855  * such changes.  Unlike getThreadEvent, it does not perform any additional
856  * housekeeping like launching deferred RPCs.
857  *
858  * Returns true if a change was detected, otherwise returns false.
859  *
860  * block        Set this parameter to true to block waiting for a change,
861  *              set to false to poll and return immediately, whether or not a
862  *              change occurred.
863  */
864 bool BPatch::getThreadEventOnly(bool block)
865 {
866    bool result = false;
867    procSignalWhy_t why;
868    procSignalWhat_t what;
869    procSignalInfo_t info;
870    process *proc;
871    
872    if ( (proc = decodeProcessEvent(-1, why, what, info, block)) != NULL) {
873        // There's been a change in a child process
874        result = true;
875        // Since we found something, we don't want to block anymore
876        block = false;
877        
878        bool exists;
879        BPatch_thread *thread = getThreadByPid(proc->getPid(), &exists);
880        if (thread == NULL) {
881            if (exists) {
882                if (didProcExit(why) || didProcExitOnSignal(why))
883                    unRegisterThread(proc->getPid());
884            } else {
885                fprintf(stderr, "Warning - wait returned status of an unknown process (%d)\n",
886                        proc->getPid());
887            }
888        }
889        if (thread != NULL) {
890            if (didProcReceiveSignal(why)) {
891                thread->lastSignal = what;
892                thread->setUnreportedStop(true);
893            }
894            else if (didProcExitOnSignal(why)) {
895                thread->lastSignal = what;
896                thread->setUnreportedTermination(true);
897            }
898            else if (didProcExit(why)) {
899                thread->proc->exitCode_ = what;
900                thread->exitCode = thread->proc->exitCode();
901                thread->lastSignal = 0; /* XXX Make into some constant */
902                thread->setUnreportedTermination(true);
903            }
904        }
905        
906        // Do standard handling
907        handleProcessEvent(proc, why, what, info);
908    }
909    return result;
910 }
911
912
913 /*
914  * havePendingEvent
915  *
916  * Returns true if any thread has stopped or terminated and that fact hasn't
917  * been reported to the user of the library.  Otherwise, returns false.
918  */
919 bool BPatch::havePendingEvent()
920 {
921 #if defined(i386_unknown_nt4_0) || defined(mips_unknown_ce2_11) //ccw 20 july 2001 : 28 mar 2001
922     // On NT, we need to poll for events as often as possible, so that we can
923     // handle traps.
924     if (getThreadEvent(false))
925         return true;
926 #endif
927
928     // For now, we'll do it by iterating over the threads and checking them,
929     // and we'll change it to something more efficient later on.
930     dictionary_hash_iter<int, BPatch_thread *> ti(info->threadsByPid);
931
932     int pid;
933     BPatch_thread *thread;
934
935     while (ti.next(pid, thread)) {
936         if (thread != NULL &&
937             (thread->pendingUnreportedStop() ||
938              thread->pendingUnreportedTermination())) {
939             return true;
940         }
941     }
942
943     return false;
944 }
945
946
947 /*
948  * pollForStatusChange
949  *
950  * Checks for unreported changes to the status of any child process, and
951  * returns true if any are detected.  Returns false otherwise.
952  *
953  * This function is declared as a friend of BPatch_thread so that it can use
954  * the BPatch_thread::getThreadEvent call to check for status changes.
955  */
956 bool BPatch::pollForStatusChange()
957 {
958     if (havePendingEvent())
959         return true;
960   
961     // No changes were previously detected, so check for new changes
962     return getThreadEvent(false);
963 }
964
965
966 /*
967  * waitForStatusChange
968  *
969  * Blocks waiting for a change to occur in the running status of a child
970  * process.  Returns true upon success, false upon failure.
971  *
972  * This function is declared as a friend of BPatch_thread so that it can use
973  * the BPatch_thread::getThreadEvent call to check for status changes.
974  */
975 bool BPatch::waitForStatusChange()
976 {
977     if (havePendingEvent())
978         return true;
979     
980     // No changes were previously detected, so wait for a new change
981     return getThreadEvent(true);
982 }
983
984 /*
985  * createEnum
986  *
987  * This function is a wrapper for the BPatch_type constructors for API/User
988  * created types.
989  *
990  * It returns a pointer to a BPatch_type that was added to the APITypes
991  * collection.
992  */
993 BPatch_type * BPatch::createEnum( const char * name, 
994                                   BPatch_Vector<char *> elementNames,
995                                   BPatch_Vector<int> elementIds)
996 {
997
998     if (elementNames.size() != elementIds.size()) {
999       return NULL;
1000     }
1001
1002     BPatch_type * newType = new BPatch_type( name, BPatch_dataEnumerated );
1003     if (!newType) return NULL;
1004     
1005     APITypes->addType(newType);
1006
1007     // ADD components to type
1008     for (unsigned int i=0; i < elementNames.size(); i++) {
1009         newType->addField(elementNames[i], BPatch_dataScalar, elementIds[i]);
1010     }
1011
1012     return(newType);
1013 }
1014
1015
1016 /*
1017  * createEnum
1018  *
1019  * This function is a wrapper for the BPatch_type constructors for API/User
1020  * created types.  The user has left element id specification to us
1021  *
1022  * It returns a pointer to a BPatch_type that was added to the APITypes
1023  * collection.
1024  */
1025 BPatch_type * BPatch::createEnum( const char * name, 
1026                                   BPatch_Vector<char *> elementNames)
1027 {
1028     BPatch_type * newType = new BPatch_type( name, BPatch_dataEnumerated );
1029
1030     if (!newType) return NULL;
1031     
1032     APITypes->addType(newType);
1033
1034     // ADD components to type
1035     for (unsigned int i=0; i < elementNames.size(); i++) {
1036         newType->addField(elementNames[i], BPatch_dataScalar, i);
1037     }
1038
1039     return(newType);
1040 }
1041
1042 /*
1043  * createStructs
1044  *
1045  * This function is a wrapper for the BPatch_type constructors for API/User
1046  * created types.
1047  *
1048  * It returns a pointer to a BPatch_type that was added to the APITypes
1049  * collection.
1050  */
1051
1052 BPatch_type * BPatch::createStruct( const char * name,
1053                                     BPatch_Vector<char *> fieldNames,
1054                                     BPatch_Vector<BPatch_type *> fieldTypes)
1055 {
1056     unsigned int i;
1057     int offset, size;
1058
1059     offset = size = 0;
1060     if (fieldNames.size() != fieldTypes.size()) {
1061       return NULL;
1062     }
1063
1064     //Compute the size of the struct
1065     for (i=0; i < fieldNames.size(); i++) {
1066         BPatch_type *type = fieldTypes[i];
1067         size = type->getSize();
1068         size += size;
1069     }
1070   
1071     BPatch_type *newType = new BPatch_type(name, BPatch_dataStructure, size);
1072     if (!newType) return NULL;
1073     
1074     APITypes->addType(newType);
1075
1076     // ADD components to type
1077     size = 0;
1078     for (i=0; i < fieldNames.size(); i++) {
1079         BPatch_type *type = fieldTypes[i];
1080         size = type->getSize();
1081         newType->addField(fieldNames[i], type->getDataClass(), type, offset, size);
1082   
1083         // Calculate next offset (in bits) into the struct
1084         offset += (size * 8);
1085     }
1086
1087     return(newType);
1088 }
1089
1090 /*
1091  * createUnions
1092  *
1093  * This function is a wrapper for the BPatch_type constructors for API/User
1094  * created types.
1095  *
1096  * It returns a pointer to a BPatch_type that was added to the APITypes
1097  * collection.
1098  */
1099
1100 BPatch_type * BPatch::createUnion( const char * name, 
1101                                    BPatch_Vector<char *> fieldNames,
1102                                    BPatch_Vector<BPatch_type *> fieldTypes)
1103 {
1104     unsigned int i;
1105     int offset, size, newsize;
1106     offset = size = newsize = 0;
1107
1108     if (fieldNames.size() != fieldTypes.size()) {
1109         return NULL;
1110     }
1111
1112     // Compute the size of the union
1113     for (i=0; i < fieldTypes.size(); i++) {
1114         BPatch_type *type = fieldTypes[i];
1115         newsize = type->getSize();
1116         if(size < newsize) size = newsize;
1117     }
1118   
1119     BPatch_type * newType = new BPatch_type(name, BPatch_dataUnion, size);
1120     if (!newType) return NULL;
1121
1122     APITypes->addType(newType);
1123
1124     // ADD components to type
1125     for (i=0; i < fieldNames.size(); i++) {
1126         BPatch_type *type = fieldTypes[i];
1127         size = type->getSize();
1128         newType->addField(fieldNames[i], type->getDataClass(), type, offset, size);
1129     }  
1130     return(newType);
1131 }
1132
1133
1134 /*
1135  * createArray for Arrays and SymTypeRanges
1136  *
1137  * This function is a wrapper for the BPatch_type constructors for API/User
1138  * created types.
1139  *
1140  * It returns a pointer to a BPatch_type that was added to the APITypes
1141  * collection.
1142  */
1143 BPatch_type * BPatch::createArray( const char * name, BPatch_type * ptr,
1144                                    unsigned int low, unsigned int hi)
1145 {
1146
1147     BPatch_type * newType;
1148
1149     if (!ptr) {
1150         return NULL;
1151     } else {
1152         newType = new BPatch_type(name, BPatch_dataArray , ptr, low, hi);
1153         if (!newType) return NULL;
1154     }
1155
1156     APITypes->addType(newType);
1157
1158     return newType;
1159 }
1160
1161 /*
1162  * createPointer for BPatch_pointers
1163  *
1164  * This function is a wrapper for the BPatch_type constructors for API/User
1165  * created types.
1166  *
1167  * It returns a pointer to a BPatch_type that was added to the APITypes
1168  * collection.
1169  */
1170 BPatch_type * BPatch::createPointer(const char * name, BPatch_type * ptr,
1171                                     int size)
1172 {
1173
1174     BPatch_type * newType = new BPatch_type(name, ptr, size);
1175     if(!newType) return NULL;
1176
1177     APITypes->addType(newType);
1178   
1179     return newType;
1180 }
1181
1182 /*
1183  * createScalar for scalars with a size and no range
1184  *
1185  * This function is a wrapper for the BPatch_type constructors for API/User
1186  * created types.
1187  *
1188  * It returns a pointer to a BPatch_type that was added to the APITypes
1189  * collection.
1190  */
1191
1192 BPatch_type * BPatch::createScalar( const char * name, int size)
1193 {
1194     BPatch_type * newType = new BPatch_type(name, BPatch_dataScalar, size);
1195     if (!newType) return NULL;
1196
1197     APITypes->addType(newType);
1198  
1199     return newType;
1200 }
1201
1202 /*
1203  * createType for typedefs
1204  *
1205  * This function is a wrapper for the BPatch_type constructors for API/User
1206  * created types.
1207  *
1208  * It returns a pointer to a BPatch_type that was added to the APITypes
1209  * collection.
1210  */
1211 BPatch_type * BPatch::createTypedef( const char * name, BPatch_type * ptr)
1212 {
1213     BPatch_type * newType = new BPatch_type(name, ptr);
1214
1215     if (!newType) return NULL;
1216
1217     APITypes->addType(newType);
1218   
1219     return newType;
1220 }
1221
1222 bool BPatch::waitUntilStopped(BPatch_thread *appThread){
1223         while (!appThread->isStopped() && !appThread->isTerminated())
1224                 this->waitForStatusChange();
1225
1226         if (!appThread->isStopped())
1227         {
1228                 cerr << "ERROR : process did not signal mutator via stop"
1229                      << endl;
1230                 return false;
1231         }
1232 #if defined(i386_unknown_nt4_0) || \
1233     defined(mips_unknown_ce2_11)
1234         else if((appThread->stopSignal() != EXCEPTION_BREAKPOINT) && 
1235                 (appThread->stopSignal() != -1))
1236         {
1237                 cerr << "ERROR : process stopped on signal different"
1238                      << " than SIGTRAP" << endl;
1239                 return false;
1240         }
1241 #else
1242         else if ((appThread->stopSignal() != SIGSTOP) &&
1243 #ifdef USE_IRIX_FIXES
1244                  (appThread->stopSignal() != SIGEMT) &&
1245 #endif /* USE_IRIX_FIXES */
1246                  (appThread->stopSignal() != SIGHUP)) {
1247                 cerr << "ERROR :  process stopped on signal "
1248                      << "different than SIGSTOP" << endl;
1249                 return false;
1250         }
1251 #endif
1252         return true;
1253 }
1254
1255 #ifdef IBM_BPATCH_COMPAT
1256
1257 /*
1258  * Register a function to call when an RPC (i.e. oneshot) is done.
1259  *
1260  * dyninst version is a callback that is defined for BPatch_thread
1261  *
1262  */
1263 BPatchThreadEventCallback BPatch::registerRPCTerminationCallback(BPatchThreadEventCallback func)
1264 {
1265     BPatchThreadEventCallback ret;
1266
1267     ret = RPCdoneCallback;
1268     RPCdoneCallback = func;
1269
1270     return ret;
1271 }
1272
1273 void setLogging_NP(BPatchLoggingCallback, int)
1274 {
1275     return;
1276 }
1277
1278 #endif
1279
1280 /*
1281  * BPatch::launchDeferredOneTimeCode
1282  *
1283  * Launch any deferred oneTimeCode calls (aka inferior RPCs) that might exist,
1284  * if it is now okay to do so.
1285  */
1286 void BPatch::launchDeferredOneTimeCode()
1287 {
1288     for (unsigned int p = 0; p < processVec.size(); p++) {
1289         process *proc = processVec[p];
1290
1291         if (proc == NULL)
1292             continue;
1293
1294         if (proc->status() == exited || proc->status() == neonatal)
1295             continue;
1296
1297         proc->launchRPCs(proc->status() == running);
1298     
1299     }
1300 }