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