Add BPatch_thread::oneTimeCodeAsync and other changes to support it.
[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.48 2002/09/19 01:21:37 buck Exp $
43
44 #include <stdio.h>
45 #include <assert.h>
46 #include <signal.h>
47
48 #define BPATCH_FILE
49 #include "BPatch.h"
50 #include "BPatch_libInfo.h"
51 #include "process.h"
52 #include "BPatch_collections.h"
53 #include "common/h/timing.h"
54
55 #if defined(i386_unknown_nt4_0) || defined(mips_unknown_ce2_11) //ccw 20 july 2000 : 28 mar 2001
56 #include "nt_signal_emul.h"
57 #endif
58
59 extern bool dyninstAPI_init();
60 extern int handleSigChild(int pid, int status);
61
62
63 BPatch *BPatch::bpatch = NULL;
64
65 /*
66  * BPatch::BPatch
67  *
68  * Constructor for BPatch.  Performs one-time initialization needed by the
69  * library.
70  */
71 BPatch::BPatch()
72   : info(NULL),
73     errorHandler(NULL),
74     dynLibraryCallback(NULL),
75     typeCheckOn(true),
76     lastError(0),
77     debugParseOn(true),
78     baseTrampDeletionOn(false),
79     trampRecursiveOn(false),
80     forceRelocation_NP(false),
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 #ifdef DETACH_ON_THE_FLY
277     // Register handler for notification from detached inferiors
278     extern void initDetachOnTheFly();
279     initDetachOnTheFly();
280 #endif
281 }
282
283
284 /*
285  * BPatch::~BPatch
286  *
287  * Destructor for BPatch.  Free allocated memory.
288  */
289 BPatch::~BPatch()
290 {
291     delete info;
292
293     delete type_Error;
294     delete type_Untyped;
295
296     delete stdTypes;
297
298     bpatch = NULL;
299 }
300
301
302 /*
303  * BPatch::registerErrorCallback
304  *
305  * Registers a function that is to be called by the library when an error
306  * occurs or when there is status to report.  Returns the address of the
307  * previously registered error callback function.
308  *
309  * function     The function to be called.
310  */
311 BPatchErrorCallback BPatch::registerErrorCallback(BPatchErrorCallback function)
312 {
313     BPatchErrorCallback ret;
314
315     ret = errorHandler;
316     errorHandler = function;
317
318     return ret;
319 }
320
321
322 /*
323  * BPatch::registerPostForkCallback
324  *
325  * Registers a function that is to be called by the library when a new
326  * process has been forked off by an mutatee process.
327  *
328  * function     The function to be called.
329  */
330 BPatchForkCallback BPatch::registerPostForkCallback(BPatchForkCallback func)
331 {
332
333 #if !defined(sparc_sun_solaris2_4) && \
334     !defined(i386_unknown_solaris2_5) && \
335     !defined(alpha_dec_osf4_0) && \
336     !defined(mips_sgi_irix6_4)
337
338   reportError(BPatchWarning, 0,
339               "postfork callbacks not implemented on this platform\n");
340   return NULL;
341 #else
342     BPatchForkCallback ret;
343
344     ret = postForkCallback;
345     postForkCallback = func;
346
347     return ret;
348 #endif
349 }
350
351 /*
352  * BPatch::registerPreForkCallback
353  *
354  * Registers a function that is to be called by the library when a process
355  * is about to fork a new process
356  *
357  * function     The function to be called.
358  */
359 BPatchForkCallback BPatch::registerPreForkCallback(BPatchForkCallback func)
360 {
361 #if !defined(sparc_sun_solaris2_4) && \
362     !defined(i386_unknown_solaris2_5) &&\
363     !defined(alpha_dec_osf4_0) && \
364     !defined(mips_sgi_irix6_4)
365     reportError(BPatchWarning, 0,
366         "prefork callbacks not implemented on this platform\n");
367     return NULL;
368 #else
369     BPatchForkCallback ret;
370
371     ret = preForkCallback;
372     preForkCallback = func;
373
374     return ret;
375 #endif
376 }
377
378 /*
379  * BPatch::registerExecCallback
380  *
381  * Registers a function that is to be called by the library when a 
382  * process has just completed an exec* call
383  *
384  * func The function to be called.
385  */
386 BPatchExecCallback BPatch::registerExecCallback(BPatchExecCallback func)
387 {
388
389 #if !defined(sparc_sun_solaris2_4) && \
390     !defined(i386_unknown_solaris2_5) &&\
391     !defined(alpha_dec_osf4_0) && \
392     !defined(mips_sgi_irix6_4)
393     reportError(BPatchWarning, 0,
394         "exec callbacks not implemented on this platform\n");
395     return NULL;
396 #else
397     BPatchExecCallback ret;
398
399     ret = execCallback;
400     execCallback = func;
401
402     return ret;
403 #endif
404 }
405
406 /*
407  * BPatch::registerExecCallback
408  *
409  * Registers a function that is to be called by the library when a 
410  * process has just called the exit system call
411  *
412  * func The function to be called.
413  */
414 BPatchExitCallback BPatch::registerExitCallback(BPatchExitCallback func)
415 {
416
417 #if !defined(sparc_sun_solaris2_4) && \
418     !defined(i386_unknown_solaris2_5) &&\
419     !defined(alpha_dec_osf4_0) && \
420     !defined(mips_sgi_irix6_4)
421     reportError(BPatchWarning, 0,
422         "exit callbacks not implemented on this platform\n");
423     return NULL;
424 #else
425     BPatchExitCallback ret;
426
427     ret = exitCallback;
428     exitCallback = func;
429
430     return ret;
431 #endif
432 }
433
434 /*
435  * BPatch::registerOneTimeCodeCallback
436  *
437  * Registers a function that is to be called by the library when a 
438  * oneTimeCode (inferior RPC) is completed.
439  *
440  * func The function to be called.
441  */
442 BPatchOneTimeCodeCallback BPatch::registerOneTimeCodeCallback(BPatchOneTimeCodeCallback func)
443 {
444     BPatchOneTimeCodeCallback ret;
445
446     ret = oneTimeCodeCallback;
447     oneTimeCodeCallback = func;
448
449     return ret;
450 }
451
452 #ifdef IBM_BPATCH_COMPAT
453 BPatchExitCallback BPatch::registerExitCallback(BPatchThreadEventCallback func)
454 {
455
456     BPatchExitCallback ret;
457
458     ret = exitCallback;
459     exitCallback = (BPatchExitCallback) func;
460
461     return ret;
462
463 }
464 #endif
465
466 /*
467  * BPatch::registerDynLibraryCallback
468  *
469  * Registers a function that is to be called by the library when a dynamically
470  * loaded library is loaded or unloaded by a process under the API's control.
471  * Returns the address of the previously registered callback function.
472  *
473  * function     The function to be called.
474  */
475 BPatchDynLibraryCallback
476 BPatch::registerDynLibraryCallback(BPatchDynLibraryCallback function)
477 {
478     BPatchDynLibraryCallback ret;
479
480     ret = dynLibraryCallback;
481     dynLibraryCallback = function;
482
483     return ret;
484 }
485
486
487 /*
488  * BPatch::getEnglishErrorString
489  *
490  * Returns the descriptive error string for the passed error number.
491  *
492  * number       The number that identifies the error.
493  */
494 const char *BPatch::getEnglishErrorString(int /* number */)
495 {
496     return "%s";
497 }
498
499
500 /*
501  * BPatch::reportError
502  *
503  * Report an error using the callback mechanism.
504  *
505  * severity     The severity level of the error.
506  * number       Identifies the error.
507  * str          A string to pass as the first element of the list of strings
508  *              given to the callback function.
509  */
510 void BPatch::reportError(BPatchErrorLevel severity, int number, const char *str)
511 {
512     assert(bpatch != NULL);
513   
514     // don't log BPatchWarning or BPatchInfo messages as "errors"
515     if ((severity == BPatchFatal) || (severity == BPatchSerious))
516         bpatch->lastError = number;
517
518     if (bpatch->errorHandler != NULL) {
519         bpatch->errorHandler(severity, number, &str);
520     } else if ((severity == BPatchFatal) || (severity == BPatchSerious)){
521         fprintf(stdout, "DYNINST ERROR: %s\n", str);
522         fflush(stdout);
523     }
524 }
525
526
527 /*
528  * BPatch::formatErrorString
529  *
530  * Takes a format string with an error message (obtained from
531  * getEnglishErrorString) and an array of parameters that were passed to an
532  * error callback function, and creates a string with the parameters
533  * substituted into it.
534  *
535  * dst          The address into which the formatted string should be copied.
536  * size         If the formatted string is equal to or longer than this number
537  *              of characters, then it will be truncated to size-1 characters
538  *              and terminated with a nul ('\0').
539  * fmt          The format string (returned by a function such as
540  *              getEnglishErrorString).
541  * params       The array of parameters that were passed to an error callback
542  *              function.
543  */
544 void BPatch::formatErrorString(char *dst, int size,
545                                const char *fmt, const char **params)
546 {
547     int cur_param = 0;
548
549     while (size > 1 && *fmt) {
550         if (*fmt == '%') {
551             if (fmt[1] == '\0') {
552                 break;
553             } else if (fmt[1] == '%') {
554                 *dst++ = '%';
555                 size--;
556             } else if (fmt[1] == 's') {
557                 char *p = const_cast<char *>(params[cur_param++]);
558                 while (size > 1 && *p) {
559                     *dst++ = *p++;
560                     size--;
561                 }
562             } else {
563                 // Illegal specifier
564                 *dst++ = fmt[0];
565                 *dst++ = fmt[1];
566                 size -= 2;
567             }
568             fmt += 2;
569         } else {
570             *dst++ = *fmt++;
571             size--;
572         }
573     }
574     if (size > 0)
575         *dst = '\0';
576 }
577
578
579 /*
580  * BPatch::getThreadByPid
581  *
582  * Given a process ID, this function returns a pointer to the associated
583  * BPatch_thread object (or NULL if there is none).  Since a process may be
584  * registered provisionally with a thread object pointer of NULL, the boolean
585  * pointed to by the parameter "exists" is set to true if the pid exists in
586  * the table of processes, and false if it does not.
587  *
588  * pid          The pid to look up.
589  * exists       A pointer to a boolean to fill in with true if the pid exists
590  *              in the table and false if it does not.  NULL may be passed in
591  *              if this information is not required.
592  */
593 BPatch_thread *BPatch::getThreadByPid(int pid, bool *exists)
594 {
595     if (info->threadsByPid.defines(pid)) {
596         if (exists) *exists = true;
597         return info->threadsByPid[pid];
598     } else {
599         if (exists) *exists = false;
600         return NULL;
601     }
602 }
603
604
605 /*
606  * BPatch::getThreads
607  *
608  * Returns a vector of all threads that are currently defined.  Includes
609  * threads created directly using the library and those created with UNIX fork
610  * or Windows NT spawn system calls.  The caller is responsible for deleting
611  * the vector when it is no longer needed.
612  */
613 BPatch_Vector<BPatch_thread *> *BPatch::getThreads()
614 {
615     BPatch_Vector<BPatch_thread *> *result = new BPatch_Vector<BPatch_thread *>;
616
617     dictionary_hash_iter<int, BPatch_thread *> ti(info->threadsByPid);
618
619     int pid;
620     BPatch_thread *thread;
621
622     while (ti.next(pid, thread))
623         result->push_back(thread);
624
625     return result;
626 }
627
628
629 /*
630  * BPatch::registerProvisionalThread
631  *
632  * Register a new process that is not yet associated with a thread.
633  * (this function is called only by createProcess).
634  *
635  * pid          The pid of the process to register.
636  */
637 void BPatch::registerProvisionalThread(int pid)
638 {
639     assert(!info->threadsByPid.defines(pid));
640     info->threadsByPid[pid] = NULL;
641 }
642
643
644 /*
645  * BPatch::registerForkedThread
646  *
647  * Register a new process that is not yet associated with a thread.
648  * (this function is an upcall when a new process is created).
649  *
650  * parentPid            the pid of the parent process.
651  * childPid             The pid of the process to register.
652  * proc                 lower lever handle to process specific stuff
653  *
654  */
655 void BPatch::registerForkedThread(int parentPid, int childPid, process *proc)
656 {
657     assert(!info->threadsByPid.defines(childPid));
658
659     BPatch_thread *parent = info->threadsByPid[parentPid];
660
661     assert(parent);
662     info->threadsByPid[childPid] = new BPatch_thread(childPid, proc);
663
664     if (postForkCallback) {
665         postForkCallback(parent, info->threadsByPid[childPid]);
666     }
667 }
668
669
670 /*
671  * BPatch::registerExec
672  *
673  * Register a process that has just done an exec call.
674  *
675  * thread       thread that has just performed the exec
676  *
677  */
678 void BPatch::registerExec(BPatch_thread *thread)
679 {
680     // build a new BPatch_image for this one
681     thread->image = new BPatch_image(thread->proc);
682
683     if (execCallback) {
684         execCallback(thread);
685     }
686 }
687
688
689 /*
690  * BPatch::registerExit
691  *
692  * Register a process that has just done an exit call.
693  *
694  * thread       thread that has just performed the exec
695  * code         the exit status code
696  *
697  */
698 void BPatch::registerExit(BPatch_thread *thread, int code)
699 {
700     if (exitCallback) {
701         exitCallback(thread, code);
702     }
703 }
704
705
706 /*
707  * BPatch::registerThread
708  *
709  * Register a new BPatch_thread object with the BPatch library (this function
710  * is called only by the constructor for BPatch_thread).
711  *
712  * thread       A pointer to the thread to register.
713  */
714 void BPatch::registerThread(BPatch_thread *thread)
715 {
716     assert(!info->threadsByPid.defines(thread->getPid()) ||
717             info->threadsByPid[thread->getPid()] == NULL);
718     info->threadsByPid[thread->getPid()] = thread;
719 }
720
721
722 /*
723  * BPatch::unRegisterThread
724  *
725  * Remove the BPatch_thread associated with a given pid from the list of
726  * threads being managed by the library.
727  *
728  * pid          The pid of the thread to be removed.
729  */
730 void BPatch::unRegisterThread(int pid)
731 {
732     assert(info->threadsByPid.defines(pid));
733     info->threadsByPid.undef(pid);      
734 }
735
736
737 /*
738  * BPatch::createProcess
739  *
740  * Create a process and return a BPatch_thread representing it.
741  * Returns NULL upon failure.
742  *
743  * path         The pathname of the executable for the new process.
744  * argv         A list of the arguments for the new process, terminated by a
745  *              NULL.
746  * envp         A list of values that make up the environment for the new
747  *              process, terminated by a NULL.  If envp is NULL, the new
748  *              new process will inherit the environemnt of the parent.
749  * stdin_fd     file descriptor to use for stdin for the application
750  * stdout_fd    file descriptor to use for stdout for the application
751  * stderr_fd    file descriptor to use for stderr for the application
752
753  */
754 BPatch_thread *BPatch::createProcess(char *path, char *argv[], 
755         char *envp[], int stdin_fd, int stdout_fd, int stderr_fd)
756 {
757     clearError();
758
759     BPatch_thread *ret = 
760         new BPatch_thread(path, argv, envp, stdin_fd, stdout_fd, stderr_fd);
761
762     if (!ret->proc ||
763        (ret->proc->status() != stopped) ||
764        !ret->proc->isBootstrappedYet()) {
765         delete ret;
766         return NULL;
767     }
768     ret->proc->collectSaveWorldData = false;
769     //ccw 23 jan 2002 : this forces the user to call
770     //BPatch_thread::startSaveWorld() if they want to use the save the world
771     //functionality.
772     return ret;
773 }
774
775
776 /*
777  * BPatch::attachProcess
778  *
779  * Attach to a running process and return a BPatch_thread representing it.
780  * Returns NULL upon failure.
781  *
782  * path         The pathname of the executable for the process.
783  * pid          The id of the process to attach to.
784  */
785 BPatch_thread *BPatch::attachProcess(char *path, int pid)
786 {
787     clearError();
788
789     BPatch_thread *ret = new BPatch_thread(path, pid);
790
791     if (!ret->proc ||
792        (ret->proc->status() != stopped) ||
793        !ret->proc->isBootstrappedYet()) {
794         // It would be considerate to (attempt to) leave the process running
795         // at this point (*before* deleting the BPatch_thread handle for it!),
796         // even though it might be in bad shape after the attempted attach.
797         char msg[256];
798         sprintf(msg,"attachProcess failed: process %d may now be killed!",pid);
799         reportError(BPatchWarning, 26, msg);
800         delete ret;
801         return NULL;
802     }
803
804     return ret;
805 }
806
807 /*
808  * BPatch::getThreadEvent
809  *
810  * Checks for changes in any child process, and optionally blocks until such a
811  * change has occurred.  Also performs housekeeping on behalf of Dyninst:
812  * - Launches pending oneTimeCode calls (aka inferior RPCs)
813  * - Updates the process object representing each process for which a
814  *   change is detected.
815  *
816  * The return value is true if a change was detected, otherwise it is false.
817  *
818  * block        Set this parameter to true to block waiting for a change,
819  *              set to false to poll and return immediately, whether or not a
820  *              change occurred.
821  */
822 bool BPatch::getThreadEvent(bool block)
823 {
824     launchDeferredOneTimeCode();
825
826     return getThreadEventOnly(block);
827 }
828
829 /*
830  * BPatch::getThreadEventOnly
831  *
832  * Like getThreadEvent (which actually calls this function), this function
833  * checks for changes in any child process, optionally blocking until such a
834  * change occurs.  It also updates the process objects with information about
835  * such changes.  Unlike getThreadEvent, it does not perform any additional
836  * housekeeping like launching deferred RPCs.
837  *
838  * Returns true if a change was detected, otherwise returns false.
839  *
840  * block        Set this parameter to true to block waiting for a change,
841  *              set to false to poll and return immediately, whether or not a
842  *              change occurred.
843  */
844 bool BPatch::getThreadEventOnly(bool block)
845 {
846     bool        result = false;
847     int         pid, status;
848
849     // while ((pid = process::waitProcs(&status, block)) > 0) {
850     if ((pid = process::waitProcs(&status, block)) > 0) {
851         // There's been a change in a child process
852         result = true;
853         // Since we found something, we don't want to block anymore
854         block = false;
855
856         bool exists;
857         BPatch_thread *thread = getThreadByPid(pid, &exists);
858         if (thread == NULL) {
859             if (exists) {
860                 if (WIFSIGNALED(status) || WIFEXITED(status))
861                     unRegisterThread(pid);
862             } else {
863                 fprintf(stderr, "Warning - wait returned status of an unknown process (%d)\n", pid);
864             }
865         }
866         if (thread != NULL) {
867             if (WIFSTOPPED(status)) {
868                 thread->lastSignal = WSTOPSIG(status);
869                 thread->setUnreportedStop(true);
870             } else if (WIFSIGNALED(status)) {
871                 thread->lastSignal = WTERMSIG(status);
872                 thread->setUnreportedTermination(true);
873             } else if (WIFEXITED(status)) {
874 #if !defined(i386_unknown_nt4_0) && !defined(mips_unknown_ce2_11) //ccw 20 july 2000 : 28 mar 2001
875                 thread->proc->exitCode_ = WEXITSTATUS(status);
876 #endif
877                 thread->exitCode = thread->proc->exitCode();
878                 thread->lastSignal = 0; /* XXX Make into some constant */
879                 thread->setUnreportedTermination(true);
880             }
881         }
882 #if !(defined i386_unknown_nt4_0) && !(defined mips_unknown_ce2_11) //ccw 20 july 2000 : 28 mar 2001
883
884         handleSigChild(pid, status);
885 #ifdef notdef
886         if (thread->lastSignal == SIGSTOP) {
887             // need to continue process after initial sigstop
888             // thread->continueExecution();
889             printf("BPatch past handleSigChild for SIGSTOP\n");
890             if (thread->proc->wasCreatedViaFork()) {
891                 printf("marking forked process stopped\n");
892                 thread->proc->status_ = stopped;
893                 // thread->lastSignal = SIGSTOP;
894                 // thread->setUnreportedStop(true);
895                 // thread->proc->continueProc();
896             }
897         }
898 #endif
899 #endif
900     }
901
902     return result;
903 }
904
905
906 /*
907  * havePendingEvent
908  *
909  * Returns true if any thread has stopped or terminated and that fact hasn't
910  * been reported to the user of the library.  Otherwise, returns false.
911  */
912 bool BPatch::havePendingEvent()
913 {
914 #if defined(i386_unknown_nt4_0) || defined(mips_unknown_ce2_11) //ccw 20 july 2001 : 28 mar 2001
915     // On NT, we need to poll for events as often as possible, so that we can
916     // handle traps.
917     if (getThreadEvent(false))
918         return true;
919 #endif
920
921     // For now, we'll do it by iterating over the threads and checking them,
922     // and we'll change it to something more efficient later on.
923     dictionary_hash_iter<int, BPatch_thread *> ti(info->threadsByPid);
924
925     int pid;
926     BPatch_thread *thread;
927
928     while (ti.next(pid, thread)) {
929         if (thread != NULL &&
930             (thread->pendingUnreportedStop() ||
931              thread->pendingUnreportedTermination())) {
932             return true;
933         }
934     }
935
936     return false;
937 }
938
939
940 /*
941  * pollForStatusChange
942  *
943  * Checks for unreported changes to the status of any child process, and
944  * returns true if any are detected.  Returns false otherwise.
945  *
946  * This function is declared as a friend of BPatch_thread so that it can use
947  * the BPatch_thread::getThreadEvent call to check for status changes.
948  */
949 bool BPatch::pollForStatusChange()
950 {
951     if (havePendingEvent())
952         return true;
953   
954     // No changes were previously detected, so check for new changes
955     return getThreadEvent(false);
956 }
957
958
959 /*
960  * waitForStatusChange
961  *
962  * Blocks waiting for a change to occur in the running status of a child
963  * process.  Returns true upon success, false upon failure.
964  *
965  * This function is declared as a friend of BPatch_thread so that it can use
966  * the BPatch_thread::getThreadEvent call to check for status changes.
967  */
968 bool BPatch::waitForStatusChange()
969 {
970     if (havePendingEvent())
971         return true;
972
973     // No changes were previously detected, so wait for a new change
974     return getThreadEvent(true);
975 }
976
977 /*
978  * createEnum
979  *
980  * This function is a wrapper for the BPatch_type constructors for API/User
981  * created types.
982  *
983  * It returns a pointer to a BPatch_type that was added to the APITypes
984  * collection.
985  */
986 BPatch_type * BPatch::createEnum( const char * name, 
987                                   BPatch_Vector<char *> elementNames,
988                                   BPatch_Vector<int> elementIds)
989 {
990
991     if (elementNames.size() != elementIds.size()) {
992       return NULL;
993     }
994
995     BPatch_type * newType = new BPatch_type( name, BPatch_dataEnumerated );
996     if (!newType) return NULL;
997     
998     APITypes->addType(newType);
999
1000     // ADD components to type
1001     for (unsigned int i=0; i < elementNames.size(); i++) {
1002         newType->addField(elementNames[i], BPatch_dataScalar, elementIds[i]);
1003     }
1004
1005     return(newType);
1006 }
1007
1008
1009 /*
1010  * createEnum
1011  *
1012  * This function is a wrapper for the BPatch_type constructors for API/User
1013  * created types.  The user has left element id specification to us
1014  *
1015  * It returns a pointer to a BPatch_type that was added to the APITypes
1016  * collection.
1017  */
1018 BPatch_type * BPatch::createEnum( const char * name, 
1019                                   BPatch_Vector<char *> elementNames)
1020 {
1021     BPatch_type * newType = new BPatch_type( name, BPatch_dataEnumerated );
1022
1023     if (!newType) return NULL;
1024     
1025     APITypes->addType(newType);
1026
1027     // ADD components to type
1028     for (unsigned int i=0; i < elementNames.size(); i++) {
1029         newType->addField(elementNames[i], BPatch_dataScalar, i);
1030     }
1031
1032     return(newType);
1033 }
1034
1035 /*
1036  * createStructs
1037  *
1038  * This function is a wrapper for the BPatch_type constructors for API/User
1039  * created types.
1040  *
1041  * It returns a pointer to a BPatch_type that was added to the APITypes
1042  * collection.
1043  */
1044
1045 BPatch_type * BPatch::createStruct( const char * name,
1046                                     BPatch_Vector<char *> fieldNames,
1047                                     BPatch_Vector<BPatch_type *> fieldTypes)
1048 {
1049     unsigned int i;
1050     int offset, size;
1051
1052     offset = size = 0;
1053     if (fieldNames.size() != fieldTypes.size()) {
1054       return NULL;
1055     }
1056
1057     //Compute the size of the struct
1058     for (i=0; i < fieldNames.size(); i++) {
1059         BPatch_type *type = fieldTypes[i];
1060         size = type->getSize();
1061         size += size;
1062     }
1063   
1064     BPatch_type *newType = new BPatch_type(name, BPatch_dataStructure, size);
1065     if (!newType) return NULL;
1066     
1067     APITypes->addType(newType);
1068
1069     // ADD components to type
1070     size = 0;
1071     for (i=0; i < fieldNames.size(); i++) {
1072         BPatch_type *type = fieldTypes[i];
1073         size = type->getSize();
1074         newType->addField(fieldNames[i], type->getDataClass(), type, offset, size);
1075   
1076         // Calculate next offset (in bits) into the struct
1077         offset += (size * 8);
1078     }
1079
1080     return(newType);
1081 }
1082
1083 /*
1084  * createUnions
1085  *
1086  * This function is a wrapper for the BPatch_type constructors for API/User
1087  * created types.
1088  *
1089  * It returns a pointer to a BPatch_type that was added to the APITypes
1090  * collection.
1091  */
1092
1093 BPatch_type * BPatch::createUnion( const char * name, 
1094                                    BPatch_Vector<char *> fieldNames,
1095                                    BPatch_Vector<BPatch_type *> fieldTypes)
1096 {
1097     unsigned int i;
1098     int offset, size, newsize;
1099     offset = size = newsize = 0;
1100
1101     if (fieldNames.size() != fieldTypes.size()) {
1102         return NULL;
1103     }
1104
1105     // Compute the size of the union
1106     for (i=0; i < fieldTypes.size(); i++) {
1107         BPatch_type *type = fieldTypes[i];
1108         newsize = type->getSize();
1109         if(size < newsize) size = newsize;
1110     }
1111   
1112     BPatch_type * newType = new BPatch_type(name, BPatch_dataUnion, size);
1113     if (!newType) return NULL;
1114
1115     APITypes->addType(newType);
1116
1117     // ADD components to type
1118     for (i=0; i < fieldNames.size(); i++) {
1119         BPatch_type *type = fieldTypes[i];
1120         size = type->getSize();
1121         newType->addField(fieldNames[i], type->getDataClass(), type, offset, size);
1122     }  
1123     return(newType);
1124 }
1125
1126
1127 /*
1128  * createArray for Arrays and SymTypeRanges
1129  *
1130  * This function is a wrapper for the BPatch_type constructors for API/User
1131  * created types.
1132  *
1133  * It returns a pointer to a BPatch_type that was added to the APITypes
1134  * collection.
1135  */
1136 BPatch_type * BPatch::createArray( const char * name, BPatch_type * ptr,
1137                                    unsigned int low, unsigned int hi)
1138 {
1139
1140     BPatch_type * newType;
1141
1142     if (!ptr) {
1143         return NULL;
1144     } else {
1145         newType = new BPatch_type(name, BPatch_dataArray , ptr, low, hi);
1146         if (!newType) return NULL;
1147     }
1148
1149     APITypes->addType(newType);
1150
1151     return newType;
1152 }
1153
1154 /*
1155  * createPointer for BPatch_pointers
1156  *
1157  * This function is a wrapper for the BPatch_type constructors for API/User
1158  * created types.
1159  *
1160  * It returns a pointer to a BPatch_type that was added to the APITypes
1161  * collection.
1162  */
1163 BPatch_type * BPatch::createPointer(const char * name, BPatch_type * ptr,
1164                                     int size)
1165 {
1166
1167     BPatch_type * newType = new BPatch_type(name, ptr, size);
1168     if(!newType) return NULL;
1169
1170     APITypes->addType(newType);
1171   
1172     return newType;
1173 }
1174
1175 /*
1176  * createScalar for scalars with a size and no range
1177  *
1178  * This function is a wrapper for the BPatch_type constructors for API/User
1179  * created types.
1180  *
1181  * It returns a pointer to a BPatch_type that was added to the APITypes
1182  * collection.
1183  */
1184
1185 BPatch_type * BPatch::createScalar( const char * name, int size)
1186 {
1187     BPatch_type * newType = new BPatch_type(name, BPatch_dataScalar, size);
1188     if (!newType) return NULL;
1189
1190     APITypes->addType(newType);
1191  
1192     return newType;
1193 }
1194
1195 /*
1196  * createType for typedefs
1197  *
1198  * This function is a wrapper for the BPatch_type constructors for API/User
1199  * created types.
1200  *
1201  * It returns a pointer to a BPatch_type that was added to the APITypes
1202  * collection.
1203  */
1204 BPatch_type * BPatch::createTypedef( const char * name, BPatch_type * ptr)
1205 {
1206     BPatch_type * newType = new BPatch_type(name, ptr);
1207
1208     if (!newType) return NULL;
1209
1210     APITypes->addType(newType);
1211   
1212     return newType;
1213 }
1214
1215 bool BPatch::waitUntilStopped(BPatch_thread *appThread){
1216         while (!appThread->isStopped() && !appThread->isTerminated())
1217                 this->waitForStatusChange();
1218
1219         if (!appThread->isStopped())
1220         {
1221                 cerr << "ERROR : process did not signal mutator via stop"
1222                      << endl;
1223                 return false;
1224         }
1225 #if defined(i386_unknown_nt4_0) || \
1226     defined(mips_unknown_ce2_11)
1227         else if((appThread->stopSignal() != SIGTRAP) && 
1228                 (appThread->stopSignal() != -1))
1229         {
1230                 cerr << "ERROR : process stopped on signal different"
1231                      << " than SIGTRAP" << endl;
1232                 return false;
1233         }
1234 #else
1235 #ifdef DETACH_ON_THE_FLY
1236         else if ((appThread->stopSignal() != SIGSTOP) &&
1237                  (appThread->stopSignal() != SIGHUP) &&
1238                  (appThread->stopSignal() != SIGILL)) {
1239 #else
1240         else if ((appThread->stopSignal() != SIGSTOP) &&
1241 #ifdef USE_IRIX_FIXES
1242                  (appThread->stopSignal() != SIGEMT) &&
1243 #endif /* USE_IRIX_FIXES */
1244                  (appThread->stopSignal() != SIGHUP)) {
1245 #endif /* DETACH_ON_THE_FLY */
1246                 cerr << "ERROR :  process stopped on signal "
1247                      << "different than SIGSTOP" << endl;
1248                 return false;
1249         }
1250 #endif
1251         return true;
1252 }
1253
1254 #ifdef IBM_BPATCH_COMPAT
1255
1256 /*
1257  * Register a function to call when an RPC (i.e. oneshot) is done.
1258  *
1259  * dyninst version is a callback that is defined for BPatch_thread
1260  *
1261  */
1262 BPatchThreadEventCallback BPatch::registerRPCTerminationCallback(BPatchThreadEventCallback func)
1263 {
1264     BPatchThreadEventCallback ret;
1265
1266     ret = RPCdoneCallback;
1267     RPCdoneCallback = func;
1268
1269     return ret;
1270 }
1271
1272 void setLogging_NP(BPatchLoggingCallback, int)
1273 {
1274     return;
1275 }
1276
1277 #endif
1278
1279 /*
1280  * BPatch::launchDeferredOneTimeCode
1281  *
1282  * Launch any deferred oneTimeCode calls (aka inferior RPCs) that might exist,
1283  * if it is now okay to do so.
1284  */
1285 void BPatch::launchDeferredOneTimeCode()
1286 {
1287     for (unsigned int p = 0; p < processVec.size(); p++) {
1288         process *proc = processVec[p];
1289
1290         if (proc == NULL)
1291             continue;
1292
1293         if (proc->status() == exited || proc->status() == neonatal)
1294             continue;
1295
1296         proc->launchRPCifAppropriate(proc->status() == running, false);
1297     }
1298 }