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