Changed 'int' types to 'dynthread_t' so that we can hold thread IDs
[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) P_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 class BPatch_eventMailbox {
111   typedef struct {
112     BPatch_asyncEventType type;
113     void *cb;
114     void *arg1;
115     void *arg2;
116     void *arg3;
117     void *arg4;
118     void *arg5;
119     void *arg6;
120   } mb_callback_t;
121   pdvector<mb_callback_t> cbs;
122
123   public:
124   BPatch_eventMailbox() {}
125   ~BPatch_eventMailbox() {}
126
127   bool executeUserCallbacks();
128   bool registerCallback(BPatch_asyncEventType type,
129                         BPatch_process *p, dynthread_t tid,
130                         int lwp, unsigned index, 
131                         unsigned long stack_addr,
132                         unsigned long start_pc);
133   bool registerCallback(BPatch_process *proc,
134                         void *buf, unsigned int bufsize);
135   bool registerCallback(BPatchDynamicCallSiteCallback _cb,
136                         BPatch_point *p, BPatch_function *f);
137   bool executeOrRegisterCallback(BPatchErrorCallback _cb,
138                                  BPatchErrorLevel lvl,
139                                  int number, const char *params);
140   bool executeOrRegisterCallback(BPatch_asyncEventType type,
141                                  BPatch_process *p, unsigned index);
142   bool executeOrRegisterCallback(BPatchDynLibraryCallback _cb,
143                                  BPatch_process * proc,
144                                  BPatch_module * mod,
145                                  bool load);
146   bool executeOrRegisterCallback(BPatchForkCallback _cb,
147                                  BPatch_asyncEventType t,
148                                  BPatch_process * parent,
149                                  BPatch_process * child);
150   bool executeOrRegisterCallback(BPatchExecCallback _cb,
151                                  BPatch_process * proc);
152   bool executeOrRegisterCallback(BPatchExitCallback _cb,
153                                  BPatch_process * proc,
154                                  BPatch_exitType exit_type);
155   bool executeOrRegisterCallback(BPatchSignalCallback _cb,
156                                  BPatch_process * proc,
157                                  int signum);
158   bool executeOrRegisterCallback(BPatchOneTimeCodeCallback _cb,
159                                  BPatch_process * proc,
160                                  void * user_data,
161                                  void * return_value);
162   void triggerThreadCallback(BPatch_asyncEventType type,
163                              BPatch_process *p, unsigned index);
164 };
165
166 typedef struct {
167     BPatchDynamicCallSiteCallback cb;
168     void *handle;
169     BPatch_point *pt;
170 } dyncall_cb_record;
171
172 typedef struct {
173     BPatchUserEventCallback cb;
174 } user_event_cb_record;
175
176 typedef struct {
177     pdvector<BPatch_function *> *mutatee_side_cbs;
178     pdvector<BPatchSnippetHandle *> *handles;
179 } thread_event_cb_record;
180
181 typedef struct {
182   BPatch_process *process;
183   int fd;
184 } process_record;
185
186 const char *asyncEventType2Str(BPatch_asyncEventType evtype); 
187
188 #ifdef DYNINST_CLASS_NAME
189 #undef DYNINST_CLASS_NAME
190 #endif
191 #define DYNINST_CLASS_NAME BPatch_asyncEventHandler
192
193 class BPatch_asyncEventHandler : public BPatch_eventLock {
194   friend THREAD_RETURN asyncHandlerWrapper(void *);
195   friend class BPatch;  // only BPatch constructs & does init
196   friend class BPatch_eventMailbox;
197   public:
198     //  BPatch_asyncEventHandler::connectToProcess()
199     //  Tells the async event handler that there is a new process
200     //  to listen for.
201     bool connectToProcess(BPatch_process *p);
202
203     //  BPatch_asyncEventHandler::detachFromProcess()
204     //  stop paying attention to events from specified process
205     bool detachFromProcess(BPatch_process *p);
206
207     //  BPatch_asyncEventHandler::registerDynamicCallCallback()
208     //  Specify a function to be called when a function is called
209     //  at the specified dynamic callsite
210     void *registerDynamicCallCallback(BPatchDynamicCallSiteCallback cb,
211                                       BPatch_point *pt);
212
213     //  BPatch_asyncEventHandler::removeDynamicCallCallback()
214     //  Using handle obtained from registerDynamicCallCallback, stop
215     //  monitoring that particular callsite with that particular
216     //  callback.
217     bool removeDynamicCallCallback(void *handle);
218
219     //  BPatch_asyncEventHandler::registerThreadEventCallback
220     //  Specify a function to be called when a thread event of 
221     //  <type> occurs.
222     bool registerThreadEventCallback(BPatch_asyncEventType type,
223                                      BPatchAsyncThreadEventCallback cb);
224
225     //  BPatch_asyncEventHandler::registerThreadEventCallback()
226     //  Specify a function to be called in the mutatee when a
227     //  the event of <type> occurs.
228     bool registerThreadEventCallback(BPatch_process *proc,
229                                      BPatch_asyncEventType type,
230                                      BPatch_function *cb);
231
232     //  BPatch_asyncEventHandler::removeThreadEventCallback()
233     //  
234     bool removeThreadEventCallback(BPatch_asyncEventType type,
235                                    BPatchAsyncThreadEventCallback cb);
236
237     //  BPatch_asyncEventHandler::removeThreadEventCallback()
238     //  
239     bool removeThreadEventCallback(BPatch_process *proc,
240                                    BPatch_asyncEventType type,
241                                    BPatch_function *cb);
242
243
244     //  BPatch_asyncEventHandler::registerUserEventCallback
245     //  Specify a function to be called when a user event  
246     bool registerUserEventCallback(BPatchUserEventCallback cb);
247
248
249     //  BPatch_asyncEventHandler::removeUserEventCallback()
250     //  
251     bool removeUserEventCallback(BPatchUserEventCallback cb);
252
253     bool startupThread();
254     //  BPatch_asyncEventHandler::removeThreadEventCallback()
255 #if !defined (os_windows)
256     //  NOTE:  right now stop()/pause() is expensive in terms of waiting time
257     //  (requires select loop to wake up on its own before pause request
258     //  is encountered).  Ultimately we should not need this function.
259     //  It seems to be a useful debug mechanism however, (ie. something is
260     //  not working, let's see if its because the other thread is somehow
261     //  interfering ).
262
263     //  BPatch_asyncEventHandler::pause()
264     //  pause the event handling thread
265     bool pause();
266
267     //  BPatch_asyncEventHandler::unpause()
268     //  unpause the event handling thread (after pause)
269     bool unpause();
270
271     //  BPatch_asyncEventHandler::stop()
272     //  Stop the event handling thread (thread will fully exit)
273     bool stop();
274
275     //  BPatch_asyncEventHandler::resume()
276     //  Resume the event handling thread (re-create) 
277     bool resume();
278 #endif
279
280   private: 
281     BPatch_asyncEventHandler();
282     bool initialize();  //  want to catch init errors, so we do most init here
283     virtual ~BPatch_asyncEventHandler();
284
285     //  BPatch_asyncEventHandler::createThread()
286     //  platform indep. way of starting the thread.
287     bool createThread();
288
289     //  BPatch_asyncEventHandler::main()
290     //  The "main" function for the async event thread.
291     void main();
292
293     //  BPatch_asyncEventHandler::shutDown()
294     //  Sets a flag that the async thread will check during its next iteration.
295     //  When set, the mutatee will shut itself down.
296     bool shutDown();
297
298 #if !defined (os_windows)
299     //  a mutex/cond for doing simple comms between main thread
300     //  and async thread.  Used in pause/stop _only_.  Possibly not
301     //  a good idea to begin with.
302     pthread_mutex_t pause_mutex;
303     bool paused;
304     bool stop_req;
305     pthread_cond_t pause_cond;
306
307     //  BPatch_asyncEventHandler::handlePauseRequest()
308     //  This only exists to keep the main event loop uncluttered
309     void handlePauseRequest();
310
311     //  BPatch_asyncEventHandler::handleStopRequest()
312     //  This only exists to keep the main event loop uncluttered
313     void handleStopRequest();
314 #endif
315
316     //  BPatch_asyncEventHandler::waitNextEvent()
317     //  Wait for the next event to come from a mutatee.  Essentially 
318     //  a big call to select().
319     bool waitNextEvent(BPatch_asyncEventRecord &ev);
320
321     //  BPatch_asyncEventHandler::handleEvent()
322     //  called after waitNextEvent, obtains global lock and handles event.
323     //  Since event handling needs to be a locked operation (esp. if it 
324     //  requires accessing lower level dyninst data structures), this is
325     //  where it should be done.
326     bool handleEvent(BPatch_asyncEventRecord &ev)
327          { LOCK_FUNCTION(bool, handleEventLocked, (ev)); }
328     bool handleEventLocked(BPatch_asyncEventRecord &ev);
329
330     //  BPatch_asyncEventHandler::readEvent()
331     //  Reads from the async fd connection to the mutatee
332     static bool readEvent(PDSOCKET fd, void *ev, ssize_t sz);
333     static bool readEvent(PDSOCKET fd, BPatch_asyncEventRecord &ev);
334
335     //  BPatch_asyncEventHandler::mutateeDetach()
336     //  use oneTimeCode to call a function in the mutatee to handle
337     //  closing of the comms socket.
338
339     bool mutateeDetach(BPatch_process *p);
340
341     //  BPatch_asyncEventHandler::cleanUpTerminatedProcs()
342     //  clean up any references to terminated processes in our lists
343     //  (including any user specified callbacks).
344     bool cleanUpTerminatedProcs();
345     //  BPatch_asyncEventHandler::instrumentThreadEvent
346     //  Associates a function in the thread library with a BPatch_asyncEventType
347     BPatchSnippetHandle *instrumentThreadEvent(BPatch_process *process,
348                                                BPatch_asyncEventType t,
349                                                BPatch_function *f);
350
351     //  These vars are only modified as part of init (before/while threads are
352     //  created) so we do not need to worry about locking them:
353     PDSOCKET sock;
354     bool shutDownFlag;
355 #if defined (os_windows)
356     unsigned int listen_port;
357     unsigned long handler_thread;
358 #else
359     pthread_t handler_thread;
360 #endif
361
362     //  The rest:  Data in this class that is not exclusively set during init
363     //   will have to be locked.  
364     pdvector<process_record> process_fds;
365
366     //  dyn_pts holds BPatch_point and callback info for dynamic call events.
367     //  XXX -- since this is linearly searched for each dynamic call event
368     //  it could get prohibitively slow in cases where there are a lot of
369     //  requests to monitor dynamic calls.  Maybe a (somewhat more complex)
370     //  data structure is necessary?
371     pdvector<dyncall_cb_record> dyn_pts;
372
373     pdvector<BPatchAsyncThreadEventCallback> *getCBsForType(BPatch_asyncEventType t);
374     pdvector<BPatchAsyncThreadEventCallback> thread_create_cbs;
375     pdvector<BPatchAsyncThreadEventCallback> thread_destroy_cbs;
376     pdvector<user_event_cb_record> user_event_cbs;
377
378     BPatchSnippetHandle *reportThreadCreateHandle;
379     BPatchSnippetHandle *reportThreadDestroyHandle;
380     bool isRunning;
381 };
382
383
384
385 #endif // __BPATCH_EVENT_HANDLER_H__