adds user defined communications event interface (a la tracelink) to dyninst API,
[dyninst.git] / dyninstAPI / src / BPatch_asyncEventHandler.h
1 /*
2  * Copyright (c) 1996-2004 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
43 #ifndef __BPATCH_ASYNC_EVENT_HANDLER_H__
44 #define __BPATCH_ASYNC_EVENT_HANDLER_H__
45
46 #if defined (os_osf)
47 //#ifndef _XOPEN_SOURCE
48 //#define _XOPEN_SOURCE 500
49 #include <standards.h>
50 //#endif
51 //#ifndef _XOPEN_SOURCE_EXTENDED
52 //#error
53 //#endif
54 #endif
55
56 #include <errno.h>
57 #include <BPatch_eventLock.h>
58 #include <BPatch.h>
59 #include <BPatch_process.h>
60 #include <BPatch_image.h>
61 #include <BPatch_Vector.h>
62 #include "common/h/Pair.h"
63 #include "common/h/Vector.h"
64 #include "dyninstAPI_RT/h/dyninstAPI_RT.h" // for BPatch_asyncEventType
65                                            //  and BPatch_asyncEventRecord
66 #if defined(os_windows)
67
68 #include <winsock2.h>
69 #define ssize_t int
70 typedef SOCKET PDSOCKET;
71 #define DYNINST_ASYNC_PORT 28003
72 #define CLOSEPDSOCKET(s) closesocket(s)
73 #define PDSOCKET_ERRNO WSAGetLastError()
74 #define INVALID_PDSOCKET (INVALID_SOCKET)
75 #define PDSOCKET_ERROR SOCKET_ERROR
76 #define SOCKET_TYPE PF_INET
77 #define THREAD_RETURN void
78 #define DO_THREAD_RETURN return
79 #define SOCKLEN_T unsigned int
80
81 #else
82 #include <sys/types.h>
83 #include <sys/socket.h>
84 #include <pthread.h>
85 typedef int PDSOCKET;
86
87 #define CLOSEPDSOCKET(s) close(s)
88 #define PDSOCKET_ERRNO errno
89 #define INVALID_PDSOCKET (-1)
90 #define PDSOCKET_ERROR (-1)
91 #define SOCKET_TYPE PF_UNIX
92 #define THREAD_RETURN void *
93 #define DO_THREAD_RETURN return NULL
94 #if defined(os_osf)
95 #define SOCKLEN_T size_t 
96 #elif defined(os_irix)
97 #define SOCKLEN_T std::size_t 
98 #else
99 #define SOCKLEN_T socklen_t 
100 #endif
101 #endif
102
103 typedef struct {
104   unsigned int pid;
105   BPatch_asyncEventType type;
106   unsigned int event_fd;
107   unsigned int size;
108 } BPatch_asyncEventRecord;
109
110
111 class BPatch_eventMailbox {
112   typedef struct {
113     BPatch_asyncEventType type;
114     void *cb;
115     void *arg1;
116     void *arg2;
117     void *arg3;
118   } mb_callback_t;
119   pdvector<mb_callback_t> cbs;
120
121   public:
122   BPatch_eventMailbox() {}
123   ~BPatch_eventMailbox() {}
124
125   bool executeUserCallbacks();
126   bool registerCallback(BPatch_asyncEventType type,
127                         BPatchAsyncThreadEventCallback _cb,
128                         BPatch_process *p, unsigned long tid);
129   bool registerCallback(BPatchUserEventCallback _cb,
130                         void *buf, unsigned int bufsize);
131   bool registerCallback(BPatchDynamicCallSiteCallback _cb,
132                         BPatch_point *p, BPatch_function *f);
133   bool executeOrRegisterCallback(BPatchErrorCallback _cb,
134                                  BPatchErrorLevel lvl,
135                                  int number, const char *params);
136   bool executeOrRegisterCallback(BPatchDynLibraryCallback _cb,
137                                  BPatch_process * proc,
138                                  BPatch_module * mod,
139                                  bool load);
140   bool executeOrRegisterCallback(BPatchForkCallback _cb,
141                                  BPatch_asyncEventType t,
142                                  BPatch_process * parent,
143                                  BPatch_process * child);
144   bool executeOrRegisterCallback(BPatchExecCallback _cb,
145                                  BPatch_process * proc);
146   bool executeOrRegisterCallback(BPatchExitCallback _cb,
147                                  BPatch_process * proc,
148                                  BPatch_exitType exit_type);
149   bool executeOrRegisterCallback(BPatchSignalCallback _cb,
150                                  BPatch_process * proc,
151                                  int signum);
152   bool executeOrRegisterCallback(BPatchOneTimeCodeCallback _cb,
153                                  BPatch_process * proc,
154                                  void * user_data,
155                                  void * return_value);
156
157 };
158
159 #if defined (os_windows)
160 #define THREAD_LIB_NAME "MSVCRT"
161 #elif defined (os_solaris)
162 #define THREAD_LIB_NAME "libthread"
163 #else
164 #define THREAD_LIB_NAME "libpthread"
165 #endif
166
167 class ThreadLibrary {
168
169    public:
170
171    ThreadLibrary(BPatch_process *proc, const char *libName);
172    ~ThreadLibrary(); 
173
174    bool addThreadEventFunction(BPatch_asyncEventType t, const char *name);
175    bool hasCapability(BPatch_asyncEventType t);
176    unsigned int numberOfFuncsForEvent(BPatch_asyncEventType t);
177    BPatch_function *funcForEvent(BPatch_asyncEventType t, int index);
178    bool exists() {return (NULL != threadModule);}
179    char *getLibName() {return libname;}
180    BPatch_module *getDyninstRT() {return dyninst_rt;}
181
182    BPatch_function *getDYNINSTreportFunc(BPatch_asyncEventType t);
183    private:
184
185    BPatch_Vector<BPatch_function *> *funcsForType(BPatch_asyncEventType t);
186    char *libname;
187    BPatch_module *threadModule;
188    BPatch_module *dyninst_rt;
189    BPatch_Vector<BPatch_function *> threadCreateFuncs;
190    BPatch_Vector<BPatch_function *> threadDestroyFuncs;
191    BPatch_Vector<BPatch_function *> threadStartFuncs;
192    BPatch_Vector<BPatch_function *> threadStopFuncs;
193
194    //  keep pointers to thread reporting functions handy
195    BPatch_function *DYNINSTasyncThreadCreate;
196    BPatch_function *DYNINSTasyncThreadDestroy;
197    BPatch_function *DYNINSTasyncThreadStart;
198    BPatch_function *DYNINSTasyncThreadStop;
199 };
200
201 /*
202 These are defined in dyninstAPI_RT.h
203 typedef enum {
204   BPatch_nullEvent,
205   BPatch_newConnectionEvent,
206   BPatch_internalShutDownEvent,
207   BPatch_threadCreateEvent,
208   BPatch_threadStartEvent,
209   BPatch_threadStopEvent,
210   BPatch_threadDestroyEvent,
211   BPatch_dynamicCallEvent
212 } BPatch_asyncEventType;
213
214 typedef struct {
215   unsigned int tid;
216   void *start_func_addr;
217 } BPatch_threadEventRecord;
218
219
220 typedef struct {
221   unsigned int pid;
222   BPatch_asyncEventType type;
223   unsigned int event_fd;
224 } BPatch_asyncEventRecord;
225 */
226
227 typedef struct {
228     BPatchDynamicCallSiteCallback cb;
229     void *handle;
230     BPatch_point *pt;
231 } dyncall_cb_record;
232
233 typedef struct {
234     BPatchUserEventCallback cb;
235     BPatch_process *proc;
236 } user_event_cb_record;
237
238 typedef struct {
239     pdvector<BPatchAsyncThreadEventCallback> *cbs;
240     pdvector<BPatch_function *> *mutatee_side_cbs;
241     pdvector<BPatchSnippetHandle *> *handles;
242     BPatch_process *proc;
243 } thread_event_cb_record;
244
245 typedef struct {
246   BPatch_process *process;
247   int fd;
248   ThreadLibrary *threadlib;
249 } process_record;
250
251 const char *asyncEventType2Str(BPatch_asyncEventType evtype); 
252
253 #ifdef DYNINST_CLASS_NAME
254 #undef DYNINST_CLASS_NAME
255 #endif
256 #define DYNINST_CLASS_NAME BPatch_asyncEventHandler
257
258 class BPatch_asyncEventHandler : public BPatch_eventLock {
259   friend THREAD_RETURN asyncHandlerWrapper(void *);
260   friend class BPatch;  // only BPatch constructs & does init
261
262   public:
263     //  BPatch_asyncEventHandler::connectToProcess()
264     //  Tells the async event handler that there is a new process
265     //  to listen for.
266     bool connectToProcess(BPatch_process *p);
267
268     //  BPatch_asyncEventHandler::detachFromProcess()
269     //  stop paying attention to events from specified process
270     bool detachFromProcess(BPatch_process *p);
271
272     //  BPatch_asyncEventHandler::registerDynamicCallCallback()
273     //  Specify a function to be called when a function is called
274     //  at the specified dynamic callsite
275     void *registerDynamicCallCallback(BPatchDynamicCallSiteCallback cb,
276                                       BPatch_point *pt);
277
278     //  BPatch_asyncEventHandler::removeDynamicCallCallback()
279     //  Using handle obtained from registerDynamicCallCallback, stop
280     //  monitoring that particular callsite with that particular
281     //  callback.
282     bool removeDynamicCallCallback(void *handle);
283
284     //  BPatch_asyncEventHandler::registerThreadEventCallback
285     //  Specify a function to be called when a thread event of 
286     //  <type> occurs.
287     bool registerThreadEventCallback(BPatch_process *proc,
288                                      BPatch_asyncEventType type,
289                                      BPatchAsyncThreadEventCallback cb);
290
291     //  BPatch_asyncEventHandler::registerThreadEventCallback()
292     //  Specify a function to be called in the mutatee when a
293     //  the event of <type> occurs.
294     bool registerThreadEventCallback(BPatch_process *proc,
295                                      BPatch_asyncEventType type,
296                                      BPatch_function *cb);
297
298     //  BPatch_asyncEventHandler::removeThreadEventCallback()
299     //  
300     bool removeThreadEventCallback(BPatch_process *proc,
301                                    BPatch_asyncEventType type,
302                                    BPatchAsyncThreadEventCallback cb);
303
304     //  BPatch_asyncEventHandler::removeThreadEventCallback()
305     //  
306     bool removeThreadEventCallback(BPatch_process *proc,
307                                    BPatch_asyncEventType type,
308                                    BPatch_function *cb);
309
310
311     //  BPatch_asyncEventHandler::registerUserEventCallback
312     //  Specify a function to be called when a user event  
313     bool registerUserEventCallback(BPatch_process *proc,
314                                    BPatchUserEventCallback cb);
315
316
317     //  BPatch_asyncEventHandler::removeUserEventCallback()
318     //  
319     bool removeUserEventCallback(BPatch_process *proc,
320                                    BPatchUserEventCallback cb);
321
322     //  BPatch_asyncEventHandler::removeThreadEventCallback()
323 #if !defined (os_windows)
324     //  NOTE:  right now stop()/pause() is expensive in terms of waiting time
325     //  (requires select loop to wake up on its own before pause request
326     //  is encountered).  Ultimately we should not need this function.
327     //  It seems to be a useful debug mechanism however, (ie. something is
328     //  not working, let's see if its because the other thread is somehow
329     //  interfering ).
330
331     //  BPatch_asyncEventHandler::pause()
332     //  pause the event handling thread
333     bool pause();
334
335     //  BPatch_asyncEventHandler::unpause()
336     //  unpause the event handling thread (after pause)
337     bool unpause();
338
339     //  BPatch_asyncEventHandler::stop()
340     //  Stop the event handling thread (thread will fully exit)
341     bool stop();
342
343     //  BPatch_asyncEventHandler::resume()
344     //  Resume the event handling thread (re-create) 
345     bool resume();
346 #endif
347
348   private: 
349     BPatch_asyncEventHandler();
350     bool initialize();  //  want to catch init errors, so we do most init here
351     virtual ~BPatch_asyncEventHandler();
352
353     //  BPatch_asyncEventHandler::createThread()
354     //  platform indep. way of starting the thread.
355     bool createThread();
356
357     //  BPatch_asyncEventHandler::main()
358     //  The "main" function for the async event thread.
359     void main();
360
361     //  BPatch_asyncEventHandler::shutDown()
362     //  Sets a flag that the async thread will check during its next iteration.
363     //  When set, the mutatee will shut itself down.
364     bool shutDown();
365
366 #if !defined (os_windows)
367     //  a mutex/cond for doing simple comms between main thread
368     //  and async thread.  Used in pause/stop _only_.  Possibly not
369     //  a good idea to begin with.
370     pthread_mutex_t pause_mutex;
371     bool paused;
372     bool stop_req;
373     pthread_cond_t pause_cond;
374
375     //  BPatch_asyncEventHandler::handlePauseRequest()
376     //  This only exists to keep the main event loop uncluttered
377     void handlePauseRequest();
378
379     //  BPatch_asyncEventHandler::handleStopRequest()
380     //  This only exists to keep the main event loop uncluttered
381     void handleStopRequest();
382 #endif
383
384     //  BPatch_asyncEventHandler::waitNextEvent()
385     //  Wait for the next event to come from a mutatee.  Essentially 
386     //  a big call to select().
387     bool waitNextEvent(BPatch_asyncEventRecord &ev);
388
389     //  BPatch_asyncEventHandler::handleEvent()
390     //  called after waitNextEvent, obtains global lock and handles event.
391     //  Since event handling needs to be a locked operation (esp. if it 
392     //  requires accessing lower level dyninst data structures), this is
393     //  where it should be done.
394     bool handleEvent(BPatch_asyncEventRecord &ev)
395          { LOCK_FUNCTION(bool, handleEventLocked, (ev)); }
396     bool handleEventLocked(BPatch_asyncEventRecord &ev);
397
398     //  BPatch_asyncEventHandler::readEvent()
399     //  Reads from the async fd connection to the mutatee
400     static bool readEvent(PDSOCKET fd, void *ev, ssize_t sz);
401     static bool readEvent(PDSOCKET fd, BPatch_asyncEventRecord &ev);
402
403     //  BPatch_asyncEventHandler::mutateeDetach()
404     //  use oneTimeCode to call a function in the mutatee to handle
405     //  closing of the comms socket.
406
407     bool mutateeDetach(BPatch_process *p);
408
409     //  BPatch_asyncEventHandler::cleanUpTerminatedProcs()
410     //  clean up any references to terminated processes in our lists
411     //  (including any user specified callbacks).
412     bool cleanUpTerminatedProcs();
413     //  BPatch_asyncEventHandler::instrumentThreadEvent
414     //  Associates a function in the thread library with a BPatch_asyncEventType
415     BPatchSnippetHandle *instrumentThreadEvent(BPatch_process *process,
416                                                ThreadLibrary *threadLib,
417                                                BPatch_asyncEventType t,
418                                                BPatch_function *f);
419
420     //  BPatch_asyncEventHandler::newThreadLibrary()
421     //  Creates a new ThreadLibrary for the given BPatch_process.
422     ThreadLibrary *newThreadLibrary(BPatch_process *process);
423
424     //  These vars are only modified as part of init (before/while threads are
425     //  created) so we do not need to worry about locking them:
426     PDSOCKET sock;
427     bool shutDownFlag;
428 #if defined (os_windows)
429     unsigned int listen_port;
430     unsigned long handler_thread;
431 #else
432     pthread_t handler_thread;
433 #endif
434
435     //  The rest:  Data in this class that is not exclusively set during init
436     //   will have to be locked.  
437     pdvector<process_record> process_fds;
438
439     //  dyn_pts holds BPatch_point and callback info for dynamic call events.
440     //  XXX -- since this is linearly searched for each dynamic call event
441     //  it could get prohibitively slow in cases where there are a lot of
442     //  requests to monitor dynamic calls.  Maybe a (somewhat more complex)
443     //  data structure is necessary?
444     pdvector<dyncall_cb_record> dyn_pts;
445
446     pdvector<thread_event_cb_record> *getCBsForType(BPatch_asyncEventType);
447     pdvector<thread_event_cb_record> thread_start_cbs;
448     pdvector<thread_event_cb_record> thread_stop_cbs;
449     pdvector<thread_event_cb_record> thread_create_cbs;
450     pdvector<thread_event_cb_record> thread_destroy_cbs;
451     pdvector<user_event_cb_record> user_event_cbs;
452
453     BPatchSnippetHandle *reportThreadCreateHandle;
454     BPatchSnippetHandle *reportThreadDestroyHandle;
455     BPatchSnippetHandle *reportThreadStartHandle;
456     BPatchSnippetHandle *reportThreadStopHandle;
457     bool isRunning;
458
459 };
460
461
462
463 #endif // __BPATCH_EVENT_HANDLER_H__