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