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