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