Fix SW issues that cropped up in merge. Recreate deleted commits.
[dyninst.git] / proccontrol / src / handler.C
1 /*
2  * Copyright (c) 1996-2011 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  * By your use of Paradyn, you understand and agree that we (or any
12  * other person or entity with proprietary rights in Paradyn) are
13  * under no obligation to provide either maintenance services,
14  * update services, notices of latent defects, or correction of
15  * defects for Paradyn.
16  * 
17  * This library is free software; you can redistribute it and/or
18  * modify it under the terms of the GNU Lesser General Public
19  * License as published by the Free Software Foundation; either
20  * version 2.1 of the License, or (at your option) any later version.
21  * 
22  * This library is distributed in the hope that it will be useful,
23  * but WITHOUT ANY WARRANTY; without even the implied warranty of
24  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
25  * Lesser General Public License for more details.
26  * 
27  * You should have received a copy of the GNU Lesser General Public
28  * License along with this library; if not, write to the Free Software
29  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
30  */
31 #include "proccontrol/h/Handler.h"
32 #include "proccontrol/h/PCErrors.h"
33 #include "proccontrol/h/PCProcess.h"
34 #include "proccontrol/h/Mailbox.h"
35
36 #include "proccontrol/src/int_process.h"
37 #include "proccontrol/src/int_handler.h"
38 #include "proccontrol/src/procpool.h"
39 #include "proccontrol/src/irpc.h"
40 #include "proccontrol/src/response.h"
41 #include "proccontrol/src/int_event.h"
42 #include "dynutil/h/dyn_regs.h"
43
44 #if defined(os_windows)
45 #include "proccontrol/src/windows_process.h"
46 #endif
47
48 using namespace Dyninst;
49 using namespace std;
50
51 #include <assert.h>
52
53 Handler::Handler(std::string name_) :
54    name(name_)
55 {
56 }
57
58 Handler::~Handler()
59 {
60 }
61
62 int Handler::getPriority() const
63 {
64    return DefaultPriority;
65 }
66
67 Event::ptr Handler::convertEventForCB(Event::ptr /*orig*/)
68 {
69    return Event::ptr();
70 }
71
72 std::string Handler::getName() const
73 {
74    return name;
75 }
76
77 HandlerPool::HandlerPool(int_process *p) :
78    proc(p),
79    nop_cur_event(false)
80 {
81 }
82
83 HandlerPool::~HandlerPool()
84 {
85    for (HandlerMap_t::iterator i = handlers.begin(); i != handlers.end(); i++) {
86       delete (*i).second;
87    }
88    //Do not delete actual Handler* objects.
89    handlers.clear();
90 }
91
92 static bool print_add_handler = true;
93 void HandlerPool::addHandlerInt(EventType etype, Handler *handler)
94 {
95    if (print_add_handler)
96       pthrd_printf("Handler %s will handle event %s\n", handler->getName().c_str(), 
97                    etype.name().c_str());
98    assert(etype.time() != EventType::Any);
99    HandlerMap_t::iterator i = handlers.find(etype);
100    HandlerSet_t *theset = NULL;
101    if (i == handlers.end()) {
102       theset = new HandlerSet_t();
103       handlers[etype] = theset;
104    }
105    else {
106       theset = (*i).second;
107    }   
108    theset->insert(handler);
109
110    HandleCallbacks *cb = HandleCallbacks::getCB();
111    if (cb != handler) {
112       cb->alleventtypes.insert(etype);
113       if (!(etype.code() >= EventType::InternalEvents && etype.code() < EventType::MaxProcCtrlEvent))
114          addHandlerInt(etype, cb);
115    }
116 }
117
118 void HandlerPool::addHandler(Handler *handler)
119 {
120    std::vector<EventType> etypes;
121    handler->getEventTypesHandled(etypes);
122
123    for (std::vector<EventType>::iterator i = etypes.begin(); i != etypes.end(); i++)
124    {
125       if ((*i).time() == EventType::Any) {
126          addHandlerInt(EventType(EventType::Pre, (*i).code()), handler);
127          addHandlerInt(EventType(EventType::Post, (*i).code()), handler);
128          addHandlerInt(EventType(EventType::None, (*i).code()), handler);
129       }
130       else {
131          addHandlerInt(*i, handler);
132       }
133    }
134 }
135
136 struct eh_cmp_func
137 {
138    bool operator()(const pair<Event::ptr, Handler*> &a,
139                    const pair<Event::ptr, Handler*> &b)
140    {
141       //Async events go first
142       if (a.first->getEventType().code() != EventType::Async ||
143           b.first->getEventType().code() != EventType::Async)
144       {
145          if (a.first->getEventType().code() == EventType::Async)
146             return true;
147          if (b.first->getEventType().code() == EventType::Async)
148             return false;
149       }
150
151       //Others are run via handler priority
152       if (a.second->getPriority() != b.second->getPriority())
153          return a.second->getPriority() < b.second->getPriority();
154
155       //Hard-coded rule.  UserThreadDestroy always comes before LWPDestroy
156       if (a.first->getEventType().code() == EventType::LWPDestroy &&
157           b.first->getEventType().code() == EventType::UserThreadDestroy)
158          return false;
159       if (b.first->getEventType().code() == EventType::LWPDestroy &&
160           a.first->getEventType().code() == EventType::UserThreadDestroy)
161          return true;
162       
163       //Subservient events run latter in handler tie
164       if (a.first->subservientTo().lock() == b.first)
165          return false;
166       if (b.first->subservientTo().lock() == a.first)
167          return true;
168
169       //Events are equal in order--just choose a consistent ordering at this point
170       eventtype_cmp cmp;
171       if (cmp(a.first->getEventType(), b.first->getEventType()))
172          return true;
173       if (cmp(b.first->getEventType(), a.first->getEventType()))
174          return false;
175       return a.first < b.first;
176    }
177 };
178
179 Event::ptr HandlerPool::curEvent()
180 {
181    if (!cur_event && nop_cur_event) {
182       //Lazily create a NOP event as the current event.
183       EventNop::ptr nop_event = EventNop::ptr(new EventNop());
184       nop_event->setProcess(proc->proc());
185       nop_event->setThread(proc->threadPool()->initialThread()->thread());
186       nop_event->setSyncType(Event::async);
187       cur_event = nop_event;
188    }
189
190    return cur_event;
191 }
192
193 void HandlerPool::setNopAsCurEvent()
194 {
195    assert(!cur_event);
196    nop_cur_event = true;
197 }
198
199 void HandlerPool::clearNopAsCurEvent()
200 {
201    nop_cur_event = false;
202    cur_event = Event::ptr();
203 }
204
205 void HandlerPool::addLateEvent(Event::ptr ev)
206 {
207    late_events.insert(ev);
208 }
209
210 bool HandlerPool::hasLateEvents() const
211 {
212    return !late_events.empty();
213 }
214
215 void HandlerPool::collectLateEvents(Event::ptr parent_ev)
216 {
217    for (set<Event::ptr>::iterator i = late_events.begin(); i != late_events.end(); i++) {
218       parent_ev->addSubservientEvent(*i);
219    }
220    late_events.clear();
221 }
222
223 Event::ptr HandlerPool::getRealParent(Event::ptr ev) const
224 {
225    Event::ptr master_ev = ev;
226    for (;;) {
227       Event::ptr parent = master_ev->subservientTo().lock();
228       if (!parent || parent->getEventType().code() == EventType::Async)
229          break;
230       master_ev = parent;
231    }
232    return master_ev;
233 }
234
235 void HandlerPool::notifyOfPendingAsyncs(const std::set<response::ptr> &asyncs, Event::ptr ev)
236 {
237    Event::ptr master_ev = getRealParent(ev);
238       
239    for (set<response::ptr>::const_iterator i = asyncs.begin(); i != asyncs.end(); i++) {
240       (*i)->setEvent(master_ev);
241    }
242 }
243
244 void HandlerPool::notifyOfPendingAsyncs(response::ptr async, Event::ptr ev)
245 {
246    async->setEvent(getRealParent(ev));
247 }
248
249 bool HandlerPool::isEventAsyncPostponed(Event::ptr ev) const
250 {
251    return (pending_async_events.find(ev) != pending_async_events.end());
252 }
253
254 bool HandlerPool::hasAsyncEvent() const
255 {
256    return !pending_async_events.empty();
257 }
258
259 void HandlerPool::markEventAsyncPending(Event::ptr ev)
260 {
261    set<Event::ptr>::iterator i = pending_async_events.find(ev);
262    if (i != pending_async_events.end()) {
263       pthrd_printf("Async event %s on %d/%d has already been marked, leaving alone.\n",
264                    ev->name().c_str(), ev->getProcess()->llproc()->getPid(), 
265                    ev->getThread()->llthrd()->getLWP());
266       return;
267    }
268    bool was_empty = insertAsyncPendingEvent(ev);
269    pthrd_printf("Event %s async marked.  pending_async_size = %d, (was_empty = %s)\n", 
270                 ev->name().c_str(),
271                 (int) pending_async_events.size(),
272                 was_empty ? "true" : "false");
273    for (set<Event::ptr>::iterator j = pending_async_events.begin(); j != pending_async_events.end(); j++) {
274       pthrd_printf("\tEvent %s (%p)\n", (*j)->name().c_str(), (*j).get());
275    }
276
277    if (was_empty) {
278       markProcAsyncPending(this);
279    }
280 }
281
282 void HandlerPool::clearEventAsync(Event::ptr ev)
283 {
284    bool result = removeAsyncPendingEvent(ev);
285    if (!result)
286       return;
287    pthrd_printf("Erasing event %s (%p) from list\n", ev->name().c_str(), ev.get());
288    for (set<Event::ptr>::iterator j = pending_async_events.begin(); j != pending_async_events.end(); j++) {
289       pthrd_printf("\tEvent %s (%p)\n", (*j)->name().c_str(), (*j).get());
290    }
291
292    if (pending_async_events.empty()) {
293       clearProcAsyncPending(this);
294    }
295 }
296
297 bool HandlerPool::insertAsyncPendingEvent(Event::ptr ev)
298 {
299    bool was_empty = pending_async_events.empty();
300    pair<set<Event::ptr>::iterator, bool> ret = pending_async_events.insert(ev);
301    if (ret.second) {
302       //This is a new async event.
303       proc->asyncEventCount().inc();
304
305       /**
306        * Desync the async state for the thread.  This keeps the process or thread
307        * stopped while we handle the async event.
308        **/
309       if (ev->getSyncType() == Event::sync_thread) {
310          int_thread *thr = ev->getThread()->llthrd();
311          pthrd_printf("Desync'ing async thread state of %d/%d\n", proc->getPid(), thr->getLWP());
312          thr->getAsyncState().desyncState(int_thread::ditto);
313       }
314       else {
315          pthrd_printf("Desync'ing async process state of %d\n", proc->getPid());
316          proc->threadPool()->initialThread()->getAsyncState().desyncStateProc(int_thread::ditto);
317       }
318    }
319    return was_empty;
320 }
321
322 bool HandlerPool::removeAsyncPendingEvent(Event::ptr ev)
323 {
324    set<Event::ptr>::iterator i = pending_async_events.find(ev);
325    if (i == pending_async_events.end()) {
326       return false;
327    }
328    pending_async_events.erase(ev);
329    proc->asyncEventCount().dec();
330
331    /**
332     * Undo the previous desync.  After the last restore operation, then thread/process
333     * should be able to run again.
334     **/
335    if (ev->getSyncType() == Event::sync_thread) {
336       int_thread *thr = ev->getThread()->llthrd();
337       pthrd_printf("Restoring'ing async thread state of %d/%d\n", proc->getPid(), thr->getLWP());
338       thr->getAsyncState().restoreState();
339    }
340    else {
341       pthrd_printf("Restoring'ing async process state of %d\n", proc->getPid());
342       proc->threadPool()->initialThread()->getAsyncState().restoreStateProc();
343    }
344
345    return true;
346 }
347
348 void HandlerPool::addEventToSet(Event::ptr ev, set<Event::ptr> &ev_set) const
349 {
350    ev_set.insert(ev);
351    for (vector<Event::ptr>::iterator i = ev->subservient_events.begin(); 
352         i != ev->subservient_events.end(); i++)
353    {
354       addEventToSet(*i, ev_set);
355    }
356 }
357
358
359 bool HandlerPool::handleEvent(Event::ptr orig_ev)
360 {
361    EventType etype = orig_ev->getEventType();
362    Event::ptr cb_replacement_ev = Event::ptr();
363
364    /**
365     * An event and its subservient events are a set of events that
366     * are processed at the same time.  As an example, on SysV systems
367     * a Library event is triggered by a breakpoint.  We want to do both the
368     * breakpoint handling and the library handling at the same time,
369     * but don't want to seperate the handling of these events.  In this
370     * example the Library event is subservient to the Breakpoint event.
371     *
372     * We'll take the event and all its subservient set and run handlers
373     * for all of them.
374     **/
375    set<Event::ptr> all_events;
376    addEventToSet(orig_ev, all_events);
377
378    typedef set<pair<Event::ptr, Handler *>, eh_cmp_func > ev_hndler_set_t;
379    ev_hndler_set_t events_and_handlers;
380    for (set<Event::ptr>::iterator i = all_events.begin(); i != all_events.end(); i++)
381    {
382       Event::ptr ev = *i;
383       EventType etype = ev->getEventType();
384       HandlerMap_t::iterator j = handlers.find(etype);
385       if (j == handlers.end()) {
386          perr_printf("Event %s has no handlers registered\n", etype.name().c_str());
387          continue;
388       }
389       HandlerSet_t *hset = j->second;
390       for (HandlerSet_t::iterator k = hset->begin(); k != hset->end(); k++)
391       {
392          Handler *hnd = *k;
393          bool already_handled = (ev->handled_by.find(hnd) != ev->handled_by.end());
394          if (already_handled) {
395             pthrd_printf("Have event %s on %s (already handled)\n", 
396                          ev->name().c_str(), hnd->getName().c_str());
397             continue;
398          }
399                  pthrd_printf("Event %s added to handle list with handler %s\n",
400                          ev->name().c_str(), hnd->getName().c_str());
401          events_and_handlers.insert(pair<Event::ptr, Handler*>(ev, hnd));
402       }
403    }
404
405    /**
406     * We should have all events and handlers properly sorted into the
407     * events_and_handlers set in the order we want to run them in.
408     * Now it's finally time to run the handlers.
409     **/
410    bool handled_something = false;
411    bool had_error = true;
412
413    ev_hndler_set_t::iterator i;
414
415    if (dyninst_debug_proccontrol) {
416       for (i = events_and_handlers.begin(); i != events_and_handlers.end(); i++) {
417          pthrd_printf("Have event %s on %s\n", i->first->name().c_str(), i->second->getName().c_str());
418       }
419    }
420
421    for (i = events_and_handlers.begin(); i != events_and_handlers.end(); i++)
422    {
423       handled_something = true;
424       Event::ptr event = i->first;
425       Handler *handler = i->second;
426       EventType etype = event->getEventType();
427
428       if (handler->getPriority() != Handler::CallbackPriority) {
429          //We don't want the callback handler getting async events
430          // from user operations in the callback.
431          cur_event = getRealParent(event);
432       }
433
434       pthrd_printf("Handling event '%s' with handler '%s'\n", etype.name().c_str(),
435                    handler->getName().c_str());
436       Handler::handler_ret_t result = handler->handleEvent(event);
437
438       cur_event = Event::ptr();
439       if (result == Handler::ret_async) {
440          pthrd_printf("Handler %s did not complete due to pending asyncs\n",
441                       handler->getName().c_str());
442          markEventAsyncPending(event);
443          return true;
444       }
445       if (result == Handler::ret_cbdelay) {
446          pthrd_printf("Handler %s delaying for user thread\n",
447                       handler->getName().c_str());
448          mbox()->enqueue_user(orig_ev);
449          return true;
450       }
451       event->handled_by.insert(handler);
452       if (result == Handler::ret_error) {
453          pthrd_printf("Error handling event %s with %s\n", etype.name().c_str(),
454                       handler->getName().c_str());
455          had_error = true;
456       }
457       
458       if (hasLateEvents()) {
459          /**
460           * A handler can choose to add new events to the current set by
461           * calling HandlerPool::addLateEvent(...).  We'll check for late
462           * events after each handle call, add them as new subservient events,
463           * and then recursively call handleEvents.  The recursive call shouldn't
464           * re-trigger already-run handlers due to the 'handled_by' mechanism.
465           **/
466          pthrd_printf("Handler added late events.  Recursively calling handleEvent\n");
467          collectLateEvents(event);
468          return handleEvent(orig_ev);
469       }
470    }
471
472    for (set<Event::ptr>::iterator i = all_events.begin(); i != all_events.end(); i++) {
473       Event::ptr event = *i;
474       clearEventAsync(event); //nop if ev wasn't async
475    }
476
477    return !had_error && handled_something;
478 }
479
480 std::set<HandlerPool *> HandlerPool::procsAsyncPending;
481 Mutex HandlerPool::asyncPendingLock;
482
483 void HandlerPool::markProcAsyncPending(HandlerPool *p)
484 {
485    asyncPendingLock.lock();
486    assert(procsAsyncPending.find(p) == procsAsyncPending.end());
487    procsAsyncPending.insert(p);
488    asyncPendingLock.unlock();
489 }
490
491 void HandlerPool::clearProcAsyncPending(HandlerPool *p)
492 {
493    asyncPendingLock.lock();
494    std::set<HandlerPool *>::iterator i = procsAsyncPending.find(p);
495    assert(i != procsAsyncPending.end());
496    procsAsyncPending.erase(i);
497    asyncPendingLock.unlock();
498 }
499
500 bool HandlerPool::hasProcAsyncPending()
501 {
502    asyncPendingLock.lock();
503    bool result = !procsAsyncPending.empty();
504    if (result) {
505       pthrd_printf("Pending async proc: %d\n", (*procsAsyncPending.begin())->proc->getPid());
506    }
507    asyncPendingLock.unlock();
508    return result;
509 }
510
511 HandlePreBootstrap::HandlePreBootstrap() :
512 Handler(std::string("Pre-bootstrap"))
513 {
514 }
515 HandlePreBootstrap::~HandlePreBootstrap()
516 {
517 }
518
519 void HandlePreBootstrap::getEventTypesHandled(std::vector<EventType> &etypes)
520 {
521         etypes.push_back(EventType(EventType::None, EventType::PreBootstrap));
522 }
523
524 Handler::handler_ret_t HandlePreBootstrap::handleEvent(Event::ptr)
525 {
526         //int_process* p = ev->getProcess()->llproc();
527         //p->setForceGeneratorBlock(true);
528         return ret_success;
529 }
530
531
532 HandleBootstrap::HandleBootstrap() :
533    Handler(std::string("Bootstrap"))
534 {
535 }
536
537 HandleBootstrap::~HandleBootstrap()
538 {
539 }
540
541 void HandleBootstrap::getEventTypesHandled(std::vector<EventType> &etypes)
542 {
543    etypes.push_back(EventType(EventType::None, EventType::Bootstrap));
544 }
545
546 Handler::handler_ret_t HandleBootstrap::handleEvent(Event::ptr ev)
547 {
548    int_process *proc = ev->getProcess()->llproc();
549    int_thread *thrd = ev->getThread()->llthrd();
550
551    assert(proc);
552    pthrd_printf("Handling bootstrap for %d\n", proc->getPid());
553
554    if (proc->getState() != int_process::neonatal_intermediate)
555       return ret_success;
556
557    thrd->getUserState().setState(int_thread::stopped);
558    
559    bool all_bootstrapped = true;
560    int_threadPool *tp = proc->threadPool();
561    for (int_threadPool::iterator i = tp->begin(); i != tp->end(); i++) {
562       int_thread *thr = *i;
563       if (thr->getHandlerState().getState() == int_thread::neonatal_intermediate) {
564          pthrd_printf("Thread %d is not yet bootstrapped\n", thr->getLWP());
565          all_bootstrapped = false;
566          break;
567       }
568    }
569
570    if (all_bootstrapped) {
571       pthrd_printf("All threads are bootstrapped, marking process bootstrapped\n");
572       proc->setState(int_process::running);
573    }
574
575    return ret_success;
576 }
577
578 HandleSignal::HandleSignal() :
579    Handler(std::string("Signal"))
580 {
581 }
582
583 HandleSignal::~HandleSignal()
584 {
585 }
586
587 void HandleSignal::getEventTypesHandled(std::vector<EventType> &etypes)
588 {
589    etypes.push_back(EventType(EventType::None, EventType::Signal));
590 }
591
592 Handler::handler_ret_t HandleSignal::handleEvent(Event::ptr ev)
593 {
594    int_thread *thrd = ev->getThread()->llthrd();
595    
596    EventSignal *sigev = static_cast<EventSignal *>(ev.get());
597    thrd->setContSignal(sigev->getSignal());
598
599    return ret_success;
600 }
601
602 HandlePostExit::HandlePostExit() :
603    Handler("Post Exit")
604 {
605 }
606
607 HandlePostExit::~HandlePostExit()
608 {
609 }
610
611 void HandlePostExit::getEventTypesHandled(std::vector<EventType> &etypes)
612 {
613    etypes.push_back(EventType(EventType::Post, EventType::Exit));
614 }
615
616 Handler::handler_ret_t HandlePostExit::handleEvent(Event::ptr ev)
617 {
618    int_process *proc = ev->getProcess()->llproc();
619    assert(proc);
620    if(ev->getThread()) {
621            int_thread *thrd = ev->getThread()->llthrd();
622            assert(thrd);
623            pthrd_printf("Handling post-exit for process %d on thread %d\n",
624                    proc->getPid(), thrd->getLWP());
625    } else {
626            pthrd_printf("Handling post-exit for process %d, all threads gone\n",
627                    proc->getPid());
628    }
629
630    EventExit *event = static_cast<EventExit *>(ev.get());
631    
632    ProcPool()->condvar()->lock();
633
634 #if !defined(os_windows)
635    // On Windows, this is the only callback we get, so delay setting exited
636    // until cleanup
637    proc->setState(int_process::exited);
638 #endif
639    ProcPool()->rmProcess(proc);
640    if(proc->wasForcedTerminated())
641    {
642            proc->getStartupTeardownProcs().dec();
643            ev->setSuppressCB(true);
644    }
645    else
646    {
647            proc->setExitCode(event->getExitCode());
648    }
649    ProcPool()->condvar()->broadcast();
650    ProcPool()->condvar()->unlock();
651
652    return ret_success;
653 }
654
655 HandlePostExitCleanup::HandlePostExitCleanup() :
656    Handler("Post Exit Cleanup")
657 {
658 }
659
660 HandlePostExitCleanup::~HandlePostExitCleanup()
661 {
662 }
663
664 void HandlePostExitCleanup::getEventTypesHandled(std::vector<EventType> &etypes)
665 {
666    etypes.push_back(EventType(EventType::Post, EventType::Exit));
667    etypes.push_back(EventType(EventType::None, EventType::Crash));
668 }
669
670 Handler::handler_ret_t HandlePostExitCleanup::handleEvent(Event::ptr ev)
671 {
672    int_process *proc = ev->getProcess()->llproc();
673    int_thread *thrd = ev->getThread() ? ev->getThread()->llthrd() : NULL;
674    assert(proc);
675
676 #if defined(os_windows)
677    // On Windows, this is the only callback we get, so delay setting exited
678    // until cleanup
679    proc->setState(int_process::exited);
680 #endif
681 //   assert(thrd);
682    pthrd_printf("Handling post-exit/crash cleanup for process %d on thread %d\n",
683            proc->getPid(), thrd ? thrd->getLWP() : (Dyninst::LWP)(-1));
684
685    if (int_process::in_waitHandleProc == proc) {
686       pthrd_printf("Postponing delete due to being in waitAndHandleForProc\n");
687    } else {
688       delete proc;
689    }
690
691    return ret_success;
692 }
693
694 int HandlePostExitCleanup::getPriority() const
695 {
696    return Handler::PostCallbackPriority;
697 }
698
699 HandleCrash::HandleCrash() :
700    Handler("Crash")
701 {
702 }
703
704 HandleCrash::~HandleCrash()
705 {
706 }
707
708 void HandleCrash::getEventTypesHandled(std::vector<EventType> &etypes)
709 {
710    etypes.push_back(EventType(EventType::None, EventType::Crash));
711 }
712
713 Handler::handler_ret_t HandleCrash::handleEvent(Event::ptr ev)
714 {
715    pthrd_printf("Handling crash for process %d on thread %d\n",
716                 ev->getProcess()->getPid(), ev->getThread()->getLWP());
717 //                evproc->getPid(), thrd->getLWP());   
718    int_process *proc = ev->getProcess()->llproc();
719    int_thread *thrd = ev->getThread()->llthrd();
720    assert(proc);
721    assert(thrd);
722    EventCrash *event = static_cast<EventCrash *>(ev.get());
723
724    if (proc->wasForcedTerminated()) {
725       pthrd_printf("Crash was due to process::terminate, not reporting\n");
726       event->setSuppressCB(true);
727    }
728    else {
729       proc->setCrashSignal(event->getTermSignal());
730    }
731    
732    ProcPool()->condvar()->lock();
733
734    proc->setState(int_process::exited);
735    ProcPool()->rmProcess(proc);
736
737    ProcPool()->condvar()->broadcast();
738    ProcPool()->condvar()->unlock();
739
740    return ret_success;
741 }
742
743 HandleForceTerminate::HandleForceTerminate() :
744     Handler("ForceTerminate")
745 {
746 }
747
748 HandleForceTerminate::~HandleForceTerminate()
749 {
750 }
751
752 void HandleForceTerminate::getEventTypesHandled(std::vector<EventType> &etypes)
753 {
754     etypes.push_back(EventType(EventType::Post, EventType::ForceTerminate));
755 }
756
757 Handler::handler_ret_t HandleForceTerminate::handleEvent(Event::ptr ev) {
758    int_process *proc = ev->getProcess()->llproc();
759    Thread::const_ptr t = ev->getThread();
760    int_thread* thrd = NULL;
761    if(t)
762            thrd = t->llthrd();
763
764    assert(proc);
765    // assert(thrd);
766    pthrd_printf("Handling force terminate for process %d on thread %d\n",
767            proc->getPid(), thrd ? thrd->getLWP() : (Dyninst::LWP)(-1));
768
769    ProcPool()->condvar()->lock();
770
771    proc->setState(int_process::exited);
772    ProcPool()->rmProcess(proc);
773
774    ProcPool()->condvar()->broadcast();
775    ProcPool()->condvar()->unlock();
776
777    proc->getStartupTeardownProcs().dec();
778
779    if (int_process::in_waitHandleProc == proc) {
780       pthrd_printf("Postponing delete due to being in waitAndHandleForProc\n");
781    } else {
782       delete proc;
783    }
784
785    return ret_success;
786 }
787
788 int HandleForceTerminate::getPriority() const {
789    return PostCallbackPriority;
790 }
791
792 HandlePreExit::HandlePreExit() :
793    Handler("Pre Exit")
794 {
795 }
796
797 HandlePreExit::~HandlePreExit()
798 {
799 }
800
801 void HandlePreExit::getEventTypesHandled(std::vector<EventType> &etypes)
802 {
803    etypes.push_back(EventType(EventType::Pre, EventType::Exit));
804 }
805
806 Handler::handler_ret_t HandlePreExit::handleEvent(Event::ptr ev)
807 {
808    int_process *proc = ev->getProcess()->llproc();
809    int_thread *thread = ev->getThread()->llthrd();
810    pthrd_printf("Handling pre-exit for process %d on thread %d\n",
811                 proc->getPid(), thread->getLWP());
812
813    thread->setExiting(true);
814    if (proc->wasForcedTerminated()) {
815       //Linux sometimes throws an extraneous exit after
816       // calling ptrace(PTRACE_KILL, ...).  It's not a real exit
817       pthrd_printf("Proc pre-exit was due to process::terminate, not reporting\n");
818       ev->setSuppressCB(true);
819       if (ev->getSyncType() == Event::sync_thread)
820          thread->getExitingState().setState(int_thread::running);
821       else
822          thread->getExitingState().setStateProc(int_thread::running);
823       
824    }
825
826    return ret_success;
827 }
828
829 HandleThreadCreate::HandleThreadCreate() :
830    Handler("Thread Create")
831 {
832 }
833
834 HandleThreadCreate::~HandleThreadCreate()
835 {
836 }
837
838 void HandleThreadCreate::getEventTypesHandled(std::vector<EventType> &etypes)
839 {
840    etypes.push_back(EventType(EventType::None, EventType::ThreadCreate));
841    etypes.push_back(EventType(EventType::None, EventType::UserThreadCreate));
842    etypes.push_back(EventType(EventType::None, EventType::LWPCreate));
843 }
844
845 Handler::handler_ret_t HandleThreadCreate::handleEvent(Event::ptr ev)
846 {
847    int_process *proc = ev->getProcess()->llproc();
848    Thread::const_ptr hl_thrd = ev->getThread();
849    int_thread* thrd = NULL;
850    if(hl_thrd) thrd = hl_thrd->llthrd();
851    EventNewThread *threadev = static_cast<EventNewThread *>(ev.get());
852
853    pthrd_printf("Handle thread create for %d/%d with new thread %d\n",
854            proc->getPid(), thrd ? thrd->getLWP() : (Dyninst::LWP)(-1), threadev->getLWP());
855
856    if ((ev->getEventType().code() == EventType::UserThreadCreate))  {
857       //If we support both user and LWP thread creation, and we're doing a user
858       // creation, then the Thread object may already exist.  Do nothing.
859       int_thread *thr = proc->threadPool()->findThreadByLWP(threadev->getLWP());
860       if (thr) {
861          pthrd_printf("Thread object already exists, ThreadCreate handler doing nothing\n");
862          return ret_success;
863       }
864    }
865    ProcPool()->condvar()->lock();
866    int_thread *newthr = int_thread::createThread(proc, NULL_THR_ID, threadev->getLWP(), false);
867
868    newthr->getGeneratorState().setState(int_thread::stopped);
869    newthr->getHandlerState().setState(int_thread::stopped);
870
871    if (!thrd) {
872       //This happens on BG/P with user thread events.
873       pthrd_printf("Setting new event to have occured on new thread\n");
874       ev->setThread(newthr->thread());
875       thrd = newthr;
876    }
877
878    int_thread *inherit_from = (thrd == newthr) ? proc->threadPool()->initialThread() : thrd;
879    newthr->getUserState().setState(inherit_from->getUserState().getState());
880    
881    pthrd_printf("Initializing new thread states to match rest of process\n");
882    map<int, int> &states = proc->getProcDesyncdStates();
883    for (map<int, int>::iterator i = states.begin(); i != states.end(); i++) {
884            if (!i->second)
885          continue;
886       int_thread::StateTracker &statet = thrd->getStateByID(i->first);
887       int_thread::State ns = proc->threadPool()->initialThread()->getStateByID(i->first).getState();
888       if (statet.getID() == int_thread::BreakpointResumeStateID) {
889          //Special case, new threads always go to stopped for breakpoint resume.
890          ns = int_thread::stopped;
891       }
892       for (int j = 0; j < i->second; j++) {
893          statet.desyncState(ns);
894       }
895    }
896
897         int_thread* tmp = ProcPool()->findThread(threadev->getLWP());
898         assert(tmp);
899
900    ProcPool()->condvar()->broadcast();
901    ProcPool()->condvar()->unlock();
902
903    return ret_success;
904 }
905
906 HandleThreadDestroy::HandleThreadDestroy() :
907    Handler("Thread Destroy")
908 {
909 }
910
911 HandleThreadDestroy::~HandleThreadDestroy()
912 {
913 }
914
915 void HandleThreadDestroy::getEventTypesHandled(std::vector<EventType> &etypes)
916 {
917    etypes.push_back(EventType(EventType::Any, EventType::UserThreadDestroy));
918    etypes.push_back(EventType(EventType::Any, EventType::LWPDestroy));
919    etypes.push_back(EventType(EventType::Any, EventType::WinStopThreadDestroy));
920 }
921
922 int HandleThreadDestroy::getPriority() const
923 {
924    return Handler::PostPlatformPriority + 2; //After thread_db destroy handler
925 }
926
927 Handler::handler_ret_t HandleThreadDestroy::handleEvent(Event::ptr ev)
928 {
929    int_thread *thrd = ev->getThread()->llthrd();
930    int_process *proc = ev->getProcess()->llproc();
931
932         if (!thrd->isUser()) {
933                 ev->setSuppressCB(true);
934         }
935
936    if (ev->getEventType().time() == EventType::Pre && proc->plat_supportLWPPostDestroy()) {
937       pthrd_printf("Handling pre-thread destroy for %d\n", thrd->getLWP());
938       return ret_success;
939    }
940
941    if (ev->getEventType().code() == EventType::UserThreadDestroy &&
942        (proc->plat_supportLWPPostDestroy() || proc->plat_supportLWPPreDestroy())) 
943    {
944       //This is a user thread delete, but we still have an upcoming LWP 
945       // delete.  Don't actually do anything yet.
946       pthrd_printf("Handling user thread... postponing clean of %d/%d until LWP delete\n", 
947                    proc->getPid(), thrd->getLWP());
948       return ret_success;
949    }
950
951    pthrd_printf("Handling post-thread destroy for %d/%d\n", proc->getPid(), thrd->getLWP());
952
953    if (proc->wasForcedTerminated()) {
954       //Linux sometimes throws an extraneous thread terminate after
955       // calling ptrace(PTRACE_KILL, ...).  It's not a real thread terminate.
956       pthrd_printf("Thread terminate was due to process::terminate, not reporting\n");
957       ev->setSuppressCB(true);
958    }
959
960    return ret_success;
961 }
962
963 HandleThreadCleanup::HandleThreadCleanup() :
964    Handler("Thread Cleanup")
965 {
966 }
967
968 HandleThreadCleanup::~HandleThreadCleanup()
969 {
970 }
971
972 void HandleThreadCleanup::getEventTypesHandled(vector<EventType> &etypes)
973 {
974    etypes.push_back(EventType(EventType::Any, EventType::UserThreadDestroy));
975    etypes.push_back(EventType(EventType::Any, EventType::LWPDestroy));
976    etypes.push_back(EventType(EventType::Any, EventType::WinStopThreadDestroy));
977 }
978
979 int HandleThreadCleanup::getPriority() const
980 {
981    return Handler::PostCallbackPriority + 1;
982 }
983
984
985 Handler::handler_ret_t HandleThreadCleanup::handleEvent(Event::ptr ev)
986 {
987    /**
988     * This is a seperate handler so that the cleanup happens after any
989     * user callback.
990     **/
991    int_process *proc = ev->getProcess()->llproc();
992    if(!proc) {
993            pthrd_printf("Process for thread cleanup event is NULL. We have no work we can do.\n");
994            return ret_success;
995    }
996    if ((ev->getEventType().code() == EventType::UserThreadDestroy) &&
997        (proc->plat_supportLWPPreDestroy() || proc->plat_supportLWPPostDestroy()))
998    {
999       //Have a user thread destroy, but platform supports LWP destroys.  Will clean with a latter event.
1000       pthrd_printf("Nothing to do in HandleThreadCleanup\n");
1001       return ret_success;
1002    }
1003    if ((ev->getEventType().code() == EventType::LWPDestroy && ev->getEventType().time() == EventType::Pre) &&
1004        proc->plat_supportLWPPostDestroy())
1005    {
1006       //Have a pre-lwp destroy, but platform supports post-lwp destroy.  Will clean with a latter event.
1007       pthrd_printf("Nothing to do in HandleThreadCleanup\n");
1008       return ret_success;
1009    }
1010    bool should_delete = true;
1011    if ((ev->getEventType().code() == EventType::UserThreadDestroy && 
1012         !proc->plat_supportLWPPreDestroy() && !proc->plat_supportLWPPostDestroy()))
1013    {
1014       //Have a user thread destroy, and platform doesn't support LWP destroys.  Will partially clean,
1015       // but leave thread object thread throws any events before it deletes.
1016       should_delete = false;
1017    }
1018
1019
1020    int_thread *thrd = ev->getThread()->llthrd();
1021    pthrd_printf("Cleaning thread %d/%d from HandleThreadCleanup handler.\n", 
1022                 proc->getPid(), thrd->getLWP());
1023    int_thread::cleanFromHandler(thrd, should_delete);
1024    return ret_success;
1025 }
1026
1027 HandleThreadStop::HandleThreadStop() :
1028    Handler(std::string("Thread Stop"))
1029 {
1030 }
1031
1032 HandleThreadStop::~HandleThreadStop()
1033 {
1034 }
1035
1036 int HandleThreadStop::getPriority() const
1037 {
1038         return DefaultPriority;
1039 }
1040
1041 void HandleThreadStop::getEventTypesHandled(std::vector<EventType> &etypes)
1042 {
1043    etypes.push_back(EventType(EventType::None, EventType::Stop));
1044 }
1045
1046 Handler::handler_ret_t HandleThreadStop::handleEvent(Event::ptr ev)
1047 {
1048    int_process *proc = ev->getProcess()->llproc();
1049
1050    if (ev->getSyncType() == Event::sync_process) {
1051       pthrd_printf("Handling process stop for %d\n", proc->getPid());
1052       bool found_pending_stop = false;
1053 #if defined(os_windows)
1054           windows_process *wproc = dynamic_cast<windows_process *>(proc);
1055           if (wproc && wproc->pendingDebugBreak()) {
1056                   found_pending_stop = true;
1057                   wproc->clearPendingDebugBreak();
1058           }
1059 #endif
1060
1061       for (int_threadPool::iterator i = proc->threadPool()->begin(); i != proc->threadPool()->end(); i++) {
1062          int_thread *thrd = *i;
1063          pthrd_printf("Handling process stop for %d/%d\n", proc->getPid(), thrd->getLWP());
1064          if (thrd->hasPendingStop()) {
1065             found_pending_stop = true;
1066             thrd->setPendingStop(false);
1067          }
1068       }
1069       assert(found_pending_stop);
1070    }
1071    else {
1072       int_thread *thrd = ev->getThread()->llthrd();
1073       pthrd_printf("Handling thread stop for %d/%d\n", proc->getPid(), thrd->getLWP());
1074       assert(thrd->hasPendingStop());
1075       thrd->setPendingStop(false);
1076    }
1077    return ret_success;
1078 }
1079
1080
1081 HandlePostFork::HandlePostFork() :
1082    Handler("Post Fork")
1083 {
1084 }
1085
1086 HandlePostFork::~HandlePostFork()
1087 {
1088 }
1089
1090 void HandlePostFork::getEventTypesHandled(std::vector<EventType> &etypes)
1091 {
1092    etypes.push_back(EventType(EventType::Post, EventType::Fork));
1093 }
1094
1095 Handler::handler_ret_t HandlePostFork::handleEvent(Event::ptr ev)
1096 {
1097    EventFork *efork = static_cast<EventFork *>(ev.get());
1098    Dyninst::PID child_pid = efork->getPID();
1099    int_process *parent_proc = ev->getProcess()->llproc();
1100    pthrd_printf("Handling fork for parent %d to child %d\n",
1101                 parent_proc->getPid(), child_pid);
1102
1103    int_process *child_proc = ProcPool()->findProcByPid(child_pid);
1104    if( child_proc == NULL ) {
1105        child_proc = int_process::createProcess(child_pid, parent_proc);
1106    }
1107
1108    assert(child_proc);
1109    return child_proc->forked() ? ret_success : ret_error;
1110 }
1111
1112 HandlePostForkCont::HandlePostForkCont() :
1113    Handler("Post Fork Continue")
1114 {
1115 }
1116
1117 HandlePostForkCont::~HandlePostForkCont()
1118 {
1119 }
1120
1121 void HandlePostForkCont::getEventTypesHandled(std::vector<EventType> &etypes)
1122 {
1123    etypes.push_back(EventType(EventType::Post, EventType::Fork));
1124 }
1125
1126 Handler::handler_ret_t HandlePostForkCont::handleEvent(Event::ptr ev)
1127 {
1128    EventFork *efork = static_cast<EventFork *>(ev.get());
1129    Dyninst::PID child_pid = efork->getPID();
1130    int_process *child_proc = ProcPool()->findProcByPid(child_pid);
1131    pthrd_printf("Handling post-fork continue for child %d\n", child_pid);
1132    assert(child_proc);
1133
1134    //We need syncRunState to run for the new process to continue it.
1135    // do so by throwing a NOP event on the new process.
1136    child_proc->throwNopEvent();
1137    return ret_success;
1138 }
1139
1140 int HandlePostForkCont::getPriority() const {
1141    return PostCallbackPriority;
1142 }
1143
1144 HandlePostExec::HandlePostExec() :
1145    Handler("Post Exec")
1146 {
1147 }
1148
1149 HandlePostExec::~HandlePostExec()
1150 {
1151 }
1152
1153 void HandlePostExec::getEventTypesHandled(std::vector<EventType> &etypes)
1154 {
1155    etypes.push_back(EventType(EventType::Post, EventType::Exec));
1156 }
1157
1158 Handler::handler_ret_t HandlePostExec::handleEvent(Event::ptr ev)
1159 {
1160    EventExec *eexec = static_cast<EventExec *>(ev.get());
1161    int_process *proc = ev->getProcess()->llproc();
1162    pthrd_printf("Handling exec for process %d\n",
1163                 proc->getPid());
1164
1165    bool result = proc->execed();
1166    if (!result) 
1167       return ret_error;
1168    
1169    eexec->setExecPath(proc->getExecutable());
1170    eexec->setThread(proc->threadPool()->initialThread()->thread());
1171    return ret_success;
1172 }
1173
1174 HandleSingleStep::HandleSingleStep() :
1175    Handler("Single Step")
1176 {
1177 }
1178
1179 HandleSingleStep::~HandleSingleStep()
1180 {
1181 }
1182
1183 void HandleSingleStep::getEventTypesHandled(vector<EventType> &etypes)
1184 {
1185    etypes.push_back(EventType(EventType::None, EventType::SingleStep));
1186 }
1187
1188 Handler::handler_ret_t HandleSingleStep::handleEvent(Event::ptr ev)
1189 {
1190    pthrd_printf("Handling event single step on %d/%d\n", 
1191                 ev->getProcess()->llproc()->getPid(), 
1192                 ev->getThread()->llthrd()->getLWP());
1193    return ret_success;
1194 }
1195
1196 /**
1197  * This handler is triggered when a breakpoint is first hit (e.g., on
1198  * the SIGTRAP signal.  It's main purpose is to prepare the thread state
1199  * before the user callback
1200  **/
1201 HandleBreakpoint::HandleBreakpoint() :
1202    Handler("Breakpoint")
1203 {
1204 }
1205
1206 HandleBreakpoint::~HandleBreakpoint()
1207 {
1208 }
1209
1210 void HandleBreakpoint::getEventTypesHandled(vector<EventType> &etypes)
1211 {
1212    etypes.push_back(EventType(EventType::None, EventType::Breakpoint));
1213 }
1214
1215 Handler::handler_ret_t HandleBreakpoint::handleEvent(Event::ptr ev)
1216 {
1217    int_process *proc = ev->getProcess()->llproc();
1218    int_thread *thrd = ev->getThread()->llthrd();
1219
1220    EventBreakpoint *ebp = static_cast<EventBreakpoint *>(ev.get());
1221    pthrd_printf("Handling breakpoint at %lx\n", ebp->getAddress());
1222    int_eventBreakpoint *int_ebp = ebp->getInternal();
1223    bp_instance *breakpoint = int_ebp->lookupInstalledBreakpoint();
1224
1225    if (!breakpoint) {
1226       //Likely someone cleaned the breakpoint.
1227       pthrd_printf("No breakpoint installed at location of BP hit.\n");
1228       return ret_success;
1229    }
1230    sw_breakpoint *swbp = breakpoint->swBP();
1231
1232    /**
1233     * Move the PC if it's a control transfer breakpoint, or if the
1234     * current architecture advances the PC forward upon breakpoint
1235     * hit (x86 or x86_64).
1236     **/
1237    bool changePC = false;
1238    Address changePCTo = 0x0;
1239    int_breakpoint *transferbp = breakpoint->getCtrlTransferBP(thrd);
1240    if (transferbp) {
1241       changePC = true;
1242       changePCTo = transferbp->toAddr();
1243       pthrd_printf("Breakpoint has control transfer.  Moving PC to %lx\n", changePCTo);
1244    }
1245    else if (swbp && proc->plat_breakpointAdvancesPC()) {
1246       changePC = true;
1247       changePCTo = breakpoint->getAddr();
1248       pthrd_printf("Breakpoint shifted PC.  Moving PC to %lx\n", changePCTo);
1249    }
1250
1251    if (changePC && !int_ebp->pc_regset) {
1252       int_ebp->pc_regset = result_response::createResultResponse();
1253       MachRegister pcreg = MachRegister::getPC(proc->getTargetArch());
1254       thrd->setRegister(pcreg, changePCTo, int_ebp->pc_regset);
1255    }
1256    if (int_ebp->pc_regset && int_ebp->pc_regset->hasError()) {
1257       pthrd_printf("Error setting pc register on breakpoint\n");
1258       ev->setLastError(err_internal, "Could not set pc register upon breakpoint\n");
1259       return ret_error;
1260    }
1261    if (int_ebp->pc_regset && !int_ebp->pc_regset->isReady()) {
1262       //We're probably on Bluegene and waiting for async to finish.
1263       proc->handlerPool()->notifyOfPendingAsyncs(int_ebp->pc_regset, ev);
1264       pthrd_printf("Returning async from BP handler while setting PC\n");
1265       return ret_async;
1266    }
1267
1268    /**
1269     * Check if any of the breakpoints should trigger a callback
1270     **/
1271    vector<Breakpoint::ptr> hl_bps;
1272    ebp->getBreakpoints(hl_bps);
1273    int_ebp->cb_bps.clear();
1274    for (vector<Breakpoint::ptr>::iterator i = hl_bps.begin(); i != hl_bps.end(); i++) {
1275       int_breakpoint *bp = (*i)->llbp();
1276       if (bp->isOneTimeBreakpoint() && bp->isOneTimeBreakpointHit())
1277          continue;
1278       if (bp->isThreadSpecific() && !bp->isThreadSpecificTo(ev->getThread()))
1279          continue;
1280       int_ebp->cb_bps.insert(*i);
1281    }
1282    pthrd_printf("In breakpoint handler, %ld breakpoints for user callback\n",
1283                 (long int) int_ebp->cb_bps.size());
1284    if (int_ebp->cb_bps.empty())
1285       ebp->setSuppressCB(true);
1286
1287    /**
1288     * Handle onetime breakpoints.  These are essentially auto-deleted
1289     * the first time they're hit.  onetime breakpoints that are thread
1290     * specific are only auto-deleted if they are hit by their thread.
1291     **/
1292    for (bp_instance::iterator i = breakpoint->begin(); i != breakpoint->end(); i++) {
1293       int_breakpoint *bp = *i;
1294       if (!bp->isOneTimeBreakpoint())
1295          continue;
1296       if (bp->isThreadSpecific() && !bp->isThreadSpecificTo(ev->getThread()))
1297          continue;
1298       if (bp->isOneTimeBreakpointHit()) {
1299          pthrd_printf("One time breakpoint was hit twice, should have CB dropped.\n");
1300          continue;
1301       }
1302       pthrd_printf("Marking oneTimeBreakpoint as hit\n");
1303       bp->markOneTimeHit();
1304    }
1305
1306    /**
1307     * Breakpoints show up as permanent stops to the user.  If they do a 
1308     * default cb_ret_t, then the process remains stopped.
1309     **/
1310    if (!int_ebp->cb_bps.empty())
1311    {
1312       pthrd_printf("BP handler is setting user state to reflect breakpoint\n");
1313       switch (ebp->getSyncType()) {
1314          case Event::sync_process: {
1315             int_threadPool *pool = proc->threadPool();
1316             for (int_threadPool::iterator i = pool->begin(); i != pool->end(); i++)
1317                (*i)->getUserState().setState(int_thread::stopped);
1318             break;
1319          }
1320          case Event::sync_thread: 
1321             thrd->getUserState().setState(int_thread::stopped);
1322             break;
1323          case Event::async:
1324             assert(0); //Async BPs don't make sense to me
1325             break;
1326          case Event::unset:
1327             assert(0);
1328             break;
1329       }
1330    }
1331
1332    /**
1333     * Mark the thread as being stopped on this breakpoint.  Control transfer
1334     * bps don't leave their thread stopped at the BP, so don't do them.
1335     **/
1336    if (!transferbp && breakpoint->needsClear()) {
1337       pthrd_printf("Breakpoint handler decided BP needs clearing\n");
1338       thrd->markStoppedOnBP(breakpoint);
1339    }
1340    else {
1341       pthrd_printf("Breakpoint handler decided BP does not need clearing\n");
1342    }
1343
1344    return ret_success;
1345 }
1346
1347 HandleBreakpointContinue::HandleBreakpointContinue() :
1348    Handler("BreakpointContinue")
1349 {
1350 }
1351
1352 HandleBreakpointContinue::~HandleBreakpointContinue()
1353 {
1354 }
1355
1356 void HandleBreakpointContinue::getEventTypesHandled(vector<EventType> &etypes)
1357 {
1358    etypes.push_back(EventType(EventType::None, EventType::Breakpoint));
1359 }
1360
1361 int HandleBreakpointContinue::getPriority() const
1362 {
1363    return PostCallbackPriority;
1364 }
1365
1366 Handler::handler_ret_t HandleBreakpointContinue::handleEvent(Event::ptr ev)
1367 {
1368    /**
1369     * This is in a seperate handler from Breakpoint to make it run after
1370     * any subservient events associated with Breakpoint.  Library or SysV
1371     * events want to operate on a stopped process, so we've postponed this
1372     * continue until after those events are done.
1373     **/
1374    EventBreakpoint *ebp = static_cast<EventBreakpoint *>(ev.get());
1375    int_eventBreakpoint *int_bp = ebp->getInternal();
1376    
1377    if (int_bp->stopped_proc) {
1378       ebp->getThread()->llthrd()->getInternalState().restoreStateProc();
1379    }
1380    return Handler::ret_success;
1381 }
1382
1383 HandleBreakpointClear::HandleBreakpointClear() :
1384    Handler("BreakpointClear")
1385 {
1386 }
1387
1388 HandleBreakpointClear::~HandleBreakpointClear()
1389 {
1390 }
1391
1392 void HandleBreakpointClear::getEventTypesHandled(vector<EventType> &etypes)
1393 {
1394    etypes.push_back(EventType(EventType::None, EventType::BreakpointClear));
1395 }
1396
1397 /**
1398  * The handler triggers when a thread stopped on a breakpoint is continued.
1399  **/
1400 Handler::handler_ret_t HandleBreakpointClear::handleEvent(Event::ptr ev)
1401 {
1402    int_process *proc = ev->getProcess()->llproc();
1403    int_thread *thrd = ev->getThread()->llthrd();
1404
1405    EventBreakpointClear *evbpc = static_cast<EventBreakpointClear *>(ev.get());
1406    int_eventBreakpointClear *int_bpc = evbpc->getInternal();
1407    bp_instance *ibp = thrd->isStoppedOnBP();
1408    hw_breakpoint *hwbp = dynamic_cast<hw_breakpoint *>(ibp);
1409
1410    if (!ibp || !ibp->isInstalled()) {
1411       pthrd_printf("HandleBreakpointClear on thread without breakpoint.  BP must have been deleted\n");
1412       thrd->getBreakpointState().restoreStateProc();
1413       thrd->markStoppedOnBP(NULL);
1414       return Handler::ret_success;
1415    }
1416    assert(!int_bpc->stopped_proc ||
1417           proc->threadPool()->allStopped(int_thread::BreakpointStateID) ||
1418           proc->threadPool()->allStopped(int_thread::AsyncStateID));
1419
1420    /**
1421     * Suspend breakpoint
1422     **/
1423    if (!int_bpc->started_bp_suspends) {
1424       pthrd_printf("Removing breakpoint from memory under HandleBreakpointClear\n");
1425       int_bpc->started_bp_suspends = true;
1426       bool result = ibp->suspend(proc, int_bpc->bp_suspend);
1427       if (!result) {
1428          pthrd_printf("Error suspending breakpoint in HandleBreakpointClear\n");
1429          return Handler::ret_error;
1430       }
1431    }
1432
1433    /**
1434     * Handle cases where breakpoint suspends are async and not completed.
1435     **/
1436    for (set<response::ptr>::iterator i = int_bpc->bp_suspend.begin(); i != int_bpc->bp_suspend.end();) {
1437       response::ptr resp = *i;
1438       if (!resp || !resp->isPosted() || resp->isReady())
1439          int_bpc->bp_suspend.erase(i++);
1440       else
1441          i++;
1442    }
1443    if (!int_bpc->bp_suspend.empty()) {
1444       pthrd_printf("Breakpoint clear is pending in HandleBreakpointClear.  Returning async\n");
1445       proc->handlerPool()->notifyOfPendingAsyncs(int_bpc->bp_suspend, ev);
1446       return Handler::ret_async;
1447    }
1448
1449    /**
1450     * Check if any of the int_breakpoints are going to be restored
1451     **/
1452    bool restore_bp = false;
1453    for (sw_breakpoint::iterator i = ibp->begin(); i != ibp->end(); i++) {
1454       if ((*i)->isOneTimeBreakpoint() && (*i)->isOneTimeBreakpointHit())
1455          continue;
1456       restore_bp = true;
1457       break;
1458    }
1459
1460    thrd->markStoppedOnBP(NULL);
1461    if (restore_bp) {
1462       pthrd_printf("HandleBreakpointClear restoring BP.  Single stepping the process.\n");
1463       thrd->markClearingBreakpoint(ibp);
1464       thrd->setSingleStepMode(true);
1465
1466       pthrd_printf("Making stop/continue decisions for handleBreakpointClear when stepping over BP\n");
1467
1468       //Threads without breakpoint restores get set to stopped.  Threads resuming breakpoints
1469       // are set-to/left-at running.
1470       for (int_threadPool::iterator i = proc->threadPool()->begin(); i != proc->threadPool()->end(); i++) {
1471          if (hwbp && *i != hwbp->getThread()) {
1472             //Hardware breakpoints don't desync the whole process
1473             continue;
1474          }
1475          int_thread::StateTracker &st = (*i)->getBreakpointResumeState();
1476          if (st.getState() == int_thread::running || *i == thrd)
1477             st.desyncState(int_thread::running); //This thread is resuming, desync
1478          else if (int_bpc->stopped_proc)
1479             st.desyncState(int_thread::stopped); //Mark this as stopped as we restore the BP
1480       }
1481       if (!hwbp) {
1482          //If new threads come in during a BP clear, then they should be
1483          //created stopped.
1484          int bpr_stateid = int_thread::BreakpointResumeStateID;
1485          proc->getProcDesyncdStates()[bpr_stateid]++;
1486       }
1487    }
1488    else {
1489       pthrd_printf("HandleBreakpointClear will not restore BP.  Restoring process state.\n");
1490    }
1491    
1492    if (int_bpc->stopped_proc)
1493       thrd->getBreakpointState().restoreStateProc();
1494    else
1495       thrd->getBreakpointState().restoreState();
1496
1497    return Handler::ret_success;
1498 }
1499
1500
1501 HandleBreakpointRestore::HandleBreakpointRestore() :
1502    Handler("Breakpoint Restore")
1503 {
1504 }
1505
1506 HandleBreakpointRestore::~HandleBreakpointRestore()
1507 {
1508 }
1509
1510 void HandleBreakpointRestore::getEventTypesHandled(vector<EventType> &etypes)
1511 {
1512    etypes.push_back(EventType(EventType::None, EventType::BreakpointRestore));
1513 }
1514
1515 Handler::handler_ret_t HandleBreakpointRestore::handleEvent(Event::ptr ev)
1516 {
1517    int_process *proc = ev->getProcess()->llproc();
1518    int_thread *thrd = ev->getThread()->llthrd();
1519    EventBreakpointRestore *bpc = static_cast<EventBreakpointRestore *>(ev.get());
1520    int_eventBreakpointRestore *int_bpc = bpc->getInternal();
1521    bp_instance *bp = int_bpc->bp;
1522    sw_breakpoint *swbp = bp->swBP();
1523    bool result;   
1524    
1525    if (!int_bpc->set_states) {
1526       pthrd_printf("Restoring breakpoint at %lx for %d/%d\n", bp->getAddr(), proc->getPid(), thrd->getLWP());
1527       thrd->markClearingBreakpoint(NULL);
1528       thrd->setSingleStepMode(false);
1529       thrd->getBreakpointResumeState().setState(int_thread::stopped);
1530       int_bpc->set_states = true;
1531    }
1532    
1533    //Time to restore this bp (maybe, the BP will actually resume when it's last thread is done restoring)
1534    pthrd_printf("Restoring breakpoint to process\n");
1535    if (!int_bpc->bp_resume_started) {
1536       int_bpc->bp_resume_started = true;
1537       result = bp->resume(proc, int_bpc->bp_resume);
1538       if (!result) {
1539          pthrd_printf("Error resuming breakpoint in handler\n");
1540          return ret_error;
1541       }
1542    }
1543    for (set<response::ptr>::iterator i = int_bpc->bp_resume.begin(); i != int_bpc->bp_resume.end();) {
1544       response::ptr resp = *i;
1545       if (!resp || !resp->isPosted() || resp->isReady())
1546          int_bpc->bp_resume.erase(i++);
1547       else
1548          i++;
1549    }
1550    if (!int_bpc->bp_resume.empty()) {
1551       pthrd_printf("Postponing breakpoint clear while waiting for memwrite\n");
1552       proc->handlerPool()->notifyOfPendingAsyncs(int_bpc->bp_resume, ev);
1553       return ret_async;
1554    }
1555
1556    pthrd_printf("Restoring thread state after breakpoint restore\n");
1557    if (swbp)
1558       thrd->getBreakpointResumeState().restoreStateProc();
1559    else
1560       thrd->getBreakpointResumeState().restoreState();
1561
1562    return ret_success;
1563 }
1564
1565 HandleEmulatedSingleStep::HandleEmulatedSingleStep() :
1566    Handler("Emulated Single Step")
1567 {
1568 }
1569
1570 HandleEmulatedSingleStep::~HandleEmulatedSingleStep()
1571 {
1572 }
1573
1574
1575 void HandleEmulatedSingleStep::getEventTypesHandled(vector<EventType> &etypes)
1576 {
1577    etypes.push_back(EventType(EventType::None, EventType::Breakpoint));
1578 }
1579
1580 Handler::handler_ret_t HandleEmulatedSingleStep::handleEvent(Event::ptr ev)
1581 {
1582    int_process *proc = ev->getProcess()->llproc();
1583    int_thread *thrd = ev->getThread()->llthrd();
1584
1585    emulated_singlestep *em_singlestep = thrd->getEmulatedSingleStep();
1586    if (!em_singlestep)
1587       return ret_success;
1588    
1589    EventBreakpoint::ptr ev_bp = ev->getEventBreakpoint();
1590    Address addr = ev_bp->getInternal()->addr;
1591    assert(ev_bp);
1592    if (!em_singlestep->containsBreakpoint(addr))
1593       return ret_success;
1594
1595    pthrd_printf("Breakpoint %lx corresponds to emulated single step.  Clearing BPs\n", addr);
1596    async_ret_t aresult = em_singlestep->clear();
1597    if (aresult == aret_async) {
1598       proc->handlerPool()->notifyOfPendingAsyncs(em_singlestep->clear_resps, ev);
1599       return ret_async;
1600    }
1601
1602    EventSingleStep::ptr ev_ss = EventSingleStep::ptr(new EventSingleStep());
1603    ev_ss->setProcess(proc->proc());
1604    ev_ss->setThread(thrd->thread());
1605    ev_ss->setSyncType(ev->getSyncType());
1606    proc->handlerPool()->addLateEvent(ev_ss);
1607
1608    em_singlestep->restoreSSMode();
1609    thrd->rmEmulatedSingleStep(em_singlestep);
1610    
1611    return ret_success;
1612 }
1613
1614 int HandleEmulatedSingleStep::getPriority() const
1615 {
1616    return PostPlatformPriority;
1617 }
1618
1619 HandleLibrary::HandleLibrary() :
1620    Handler("Library Handler")
1621 {
1622 }
1623
1624 HandleLibrary::~HandleLibrary()
1625 {
1626 }
1627
1628 Handler::handler_ret_t HandleLibrary::handleEvent(Event::ptr ev)
1629 {
1630    pthrd_printf("Handling library load/unload\n");
1631    EventLibrary *lev = static_cast<EventLibrary *>(ev.get());
1632    if(!lev->libsAdded().empty())
1633    {
1634            MTLock lock_this_block;
1635            // this happens on Windows, where we already did the decode when we got the event
1636            for(std::set<Library::ptr>::const_iterator lib = lev->libsAdded().begin();
1637                    lib != lev->libsAdded().end();
1638                    ++lib)
1639            {
1640                    ev->getProcess()->llproc()->memory()->libs.insert((*lib)->debug());
1641            }
1642    }
1643    if(!lev->libsRemoved().empty())
1644    {
1645            MTLock lock_this_block;
1646            for(std::set<Library::ptr>::const_iterator lib = lev->libsRemoved().begin();
1647                    lib != lev->libsRemoved().end();
1648                    ++lib)
1649            {
1650                    ev->getProcess()->llproc()->memory()->libs.erase((*lib)->debug());
1651            }
1652    }
1653    if(!lev->libsAdded().empty() || !lev->libsRemoved().empty())
1654            return ret_success;
1655
1656    int_process *proc = ev->getProcess()->llproc();
1657    set<int_library *> ll_added, ll_rmd;
1658    set<response::ptr> async_responses;
1659    bool async_pending = false;
1660    bool result = proc->refresh_libraries(ll_added, ll_rmd, async_pending, async_responses);
1661    if (!result && async_pending) {
1662       proc->handlerPool()->notifyOfPendingAsyncs(async_responses, ev);
1663       return ret_async;
1664    }
1665    if (!result) {
1666       pthrd_printf("Failed to refresh library list\n");
1667       return ret_error;
1668    }
1669    if (ll_added.empty() && ll_rmd.empty()) {
1670       pthrd_printf("Could not find actual changes in lib state\n");
1671       return ret_success;
1672    }
1673
1674    set<Library::ptr> added, rmd;
1675    for (set<int_library*>::iterator i = ll_added.begin(); i != ll_added.end(); i++) {
1676       added.insert((*i)->getUpPtr());
1677    }
1678    for (set<int_library*>::iterator i = ll_rmd.begin(); i != ll_rmd.end(); i++) {
1679       rmd.insert((*i)->getUpPtr());
1680    }
1681    for (set<int_library*>::iterator i = ll_rmd.begin(); i != ll_rmd.end(); i++) {
1682       (*i)->markAsCleanable();
1683    }
1684    lev->setLibs(added, rmd);
1685    return ret_success;
1686 }
1687
1688 void HandleLibrary::getEventTypesHandled(std::vector<EventType> &etypes)
1689 {
1690    etypes.push_back(EventType(EventType::None, EventType::Library));
1691 }
1692
1693 HandleDetach::HandleDetach() :
1694    Handler("Detach")
1695 {
1696 }
1697
1698 HandleDetach::~HandleDetach()
1699 {
1700 }
1701    
1702 Handler::handler_ret_t HandleDetach::handleEvent(Event::ptr ev)
1703 {
1704    int_process *proc = ev->getProcess()->llproc();
1705    EventDetach::ptr detach_ev = ev->getEventDetach();
1706    int_eventDetach *int_detach_ev = detach_ev->getInternal();
1707    bool temporary = int_detach_ev->temporary_detach;
1708    bool &removed_bps = int_detach_ev->removed_bps;
1709    result_response::ptr &detach_response = int_detach_ev->detach_response;
1710    std::set<response::ptr> &async_responses = int_detach_ev->async_responses;
1711    mem_state::ptr mem = proc->memory();
1712    bool err = true;
1713
1714    if (!removed_bps) 
1715    {
1716       if (!temporary) {
1717          while (!mem->breakpoints.empty())
1718          {
1719             std::map<Dyninst::Address, sw_breakpoint *>::iterator i = mem->breakpoints.begin();
1720             bool result = i->second->uninstall(proc, async_responses);
1721             if (!result) {
1722                perr_printf("Error removing breakpoint at %lx\n", i->first);
1723                ev->setLastError(err_internal, "Error removing breakpoint before detach\n");
1724                goto done;
1725             }
1726          }
1727       }
1728       else {
1729          for(std::map<Dyninst::Address, sw_breakpoint *>::iterator i = mem->breakpoints.begin();
1730              i != mem->breakpoints.end(); ++i)
1731          {
1732             bool result = i->second->suspend(proc, async_responses);
1733             if(!result) {
1734                perr_printf("Error suspending breakpoint at %lx\n", i->first);
1735                ev->setLastError(err_internal, "Error suspending breakpoint before detach\n");
1736                goto done;
1737             }
1738          }
1739       }
1740       removed_bps = true;
1741    }
1742
1743    for (set<response::ptr>::iterator i = async_responses.begin(); i != async_responses.end(); i++) {
1744       if ((*i)->hasError()) {
1745          perr_printf("Failed to remove breakpoints\n");
1746          ev->setLastError(err_internal, "Error removing breakpoint before detach\n");
1747          goto done;
1748       }
1749       if (!(*i)->isReady()) {
1750          pthrd_printf("Suspending detach due to async in breakpoint removal.\n");
1751          proc->handlerPool()->notifyOfPendingAsyncs(async_responses, ev);
1752          return ret_async;
1753       }
1754    }
1755
1756    if (!detach_response) {
1757       pthrd_printf("Detach handler is triggering platform detach\n");
1758       detach_response = result_response::createResultResponse();
1759       bool result = proc->plat_detach(detach_response);
1760       if (!result) {
1761          pthrd_printf("Error performing platform detach on %d\n", proc->getPid());
1762          goto done;
1763       }
1764    }
1765    if (detach_response->isPosted() && !detach_response->isReady()) {
1766       pthrd_printf("Suspending detach operation while waiting for detach response\n");
1767       proc->handlerPool()->notifyOfPendingAsyncs(detach_response, ev);
1768       return ret_async;
1769    }
1770
1771    if (temporary) {
1772       proc->setState(int_process::detached);
1773       proc->threadPool()->initialThread()->getDetachState().setStateProc(int_thread::detached);
1774    }
1775    else {
1776       ProcPool()->condvar()->lock();
1777
1778       proc->setState(int_process::exited);
1779       ProcPool()->rmProcess(proc);
1780
1781       ProcPool()->condvar()->broadcast();
1782       ProcPool()->condvar()->unlock();
1783    }
1784
1785    err = false;
1786   done:
1787    int_detach_ev->done = true;
1788    proc->getStartupTeardownProcs().dec();
1789    return err ? ret_error : ret_success;
1790 }
1791  
1792 void HandleDetach::getEventTypesHandled(std::vector<EventType> &etypes)
1793 {
1794    etypes.push_back(EventType(EventType::None, EventType::Detach));
1795 }
1796
1797 HandleAsync::HandleAsync() :
1798    Handler("Async")
1799 {
1800 }
1801
1802 HandleAsync::~HandleAsync()
1803 {
1804 }
1805    
1806 Handler::handler_ret_t HandleAsync::handleEvent(Event::ptr ev)
1807 {
1808    EventAsync::ptr eAsync = ev->getEventAsync();
1809    set<response::ptr> &resps = eAsync->getInternal()->getResponses();
1810
1811    pthrd_printf("Handling %lu async event(s) on %d/%d\n", 
1812                 (unsigned long) resps.size(),
1813                 eAsync->getProcess()->llproc()->getPid(),
1814                 eAsync->getThread()->llthrd()->getLWP());
1815
1816    assert(eAsync->getProcess()->llproc()->plat_needsAsyncIO());
1817    for (set<response::ptr>::iterator i = resps.begin(); i != resps.end(); i++) {
1818       response::ptr resp = *i;
1819       resp->markReady();
1820       resp->setEvent(Event::ptr());
1821    }
1822
1823    return ret_success;
1824 }
1825
1826 void HandleAsync::getEventTypesHandled(std::vector<EventType> &etypes)
1827 {
1828    etypes.push_back(EventType(EventType::None, EventType::Async));
1829 }
1830
1831 HandleNop::HandleNop() :
1832    Handler("Nop Handler")
1833 {
1834 }
1835
1836 HandleNop::~HandleNop()
1837 {
1838 }
1839
1840 Handler::handler_ret_t HandleNop::handleEvent(Event::ptr)
1841 {
1842    //Trivial handler, by definition
1843    return ret_success;
1844 }
1845
1846 void HandleNop::getEventTypesHandled(std::vector<EventType> &etypes)
1847 {
1848    etypes.push_back(EventType(EventType::None, EventType::Nop));
1849 }
1850
1851 HandleCallbacks::HandleCallbacks() : 
1852    Handler("Callback")
1853 {
1854 }
1855
1856 HandleCallbacks::~HandleCallbacks()
1857 {
1858 }
1859
1860 HandleCallbacks *HandleCallbacks::getCB()
1861 {
1862    static HandleCallbacks *cb = NULL;
1863    if (!cb) {
1864       cb = new HandleCallbacks();
1865       assert(cb);
1866       HandlerPool *hp = createDefaultHandlerPool(NULL);
1867       delete hp;
1868    }
1869    return cb;
1870 }
1871
1872 int HandleCallbacks::getPriority() const
1873 {
1874    return CallbackPriority;
1875 }
1876
1877 void HandleCallbacks::getEventTypesHandled(std::vector<EventType> & /*etypes*/)
1878 {
1879    //Callbacks are special cased, they respond to all event types.
1880 }
1881
1882 bool HandleCallbacks::hasCBs(Event::const_ptr ev)
1883 {
1884    return cbfuncs.find(ev->getEventType()) != cbfuncs.end();
1885 }
1886
1887 bool HandleCallbacks::hasCBs(EventType et)
1888 {
1889    return cbfuncs.find(et) != cbfuncs.end();
1890 }
1891
1892 bool HandleCallbacks::requiresCB(Event::const_ptr ev)
1893 {
1894    return hasCBs(ev) && !ev->suppressCB();
1895 }
1896
1897 Handler::handler_ret_t HandleCallbacks::handleEvent(Event::ptr ev)
1898 {
1899    int_thread *thr = NULL;
1900    if(ev->getThread()) thr = ev->getThread()->llthrd();
1901    int_process *proc = ev->getProcess()->llproc();
1902    
1903    if (ev->noted_event) {
1904       //Reset the event status here if the callback already had a delivery attempt
1905       notify()->clearEvent();
1906       if (thr)
1907          thr->getCallbackState().restoreStateProc();
1908       else
1909          proc->threadPool()->initialThread()->getCallbackState().restoreStateProc();
1910       ev->noted_event = false;
1911    }
1912
1913    EventType evtype = ev->getEventType();
1914    std::map<EventType, std::set<Process::cb_func_t>, eventtype_cmp>::iterator i = cbfuncs.find(evtype);
1915    if (i == cbfuncs.end()) {
1916       pthrd_printf("No callback registered for event type '%s'\n", ev->name().c_str());
1917       return ret_success;
1918    }
1919
1920    if (proc &&
1921        (proc->getState() == int_process::neonatal ||
1922         proc->getState() == int_process::neonatal_intermediate))
1923    {
1924       pthrd_printf("No callback for neonatal process %d\n", proc->getPid());
1925       return ret_success;
1926    }
1927    const std::set<Process::cb_func_t> &cbs = i->second;
1928
1929    if (ev->suppressCB()) {
1930       pthrd_printf("Suppressing callbacks for event %s\n", ev->name().c_str());
1931       return ret_success;
1932    }
1933
1934    if (proc->isRunningSilent()) {
1935       pthrd_printf("Suppressing callback for event %s due to process being in silent mode\n",
1936                    ev->name().c_str());
1937       return ret_success;
1938    }
1939    
1940    return deliverCallback(ev, cbs);
1941 }
1942
1943 static const char *action_str(Process::cb_action_t action)
1944 {
1945    switch (action) {
1946       case Process::cbThreadContinue:
1947          return "cbThreadContinue";
1948       case Process::cbThreadStop:
1949          return "cbThreadStop";
1950       case Process::cbProcContinue:
1951          return "cbProcContinue";
1952       case Process::cbProcStop:
1953          return "cbProcStop";
1954       case Process::cbDefault:
1955          return "cbDefault";
1956       default:
1957          return "cbInvalid";
1958    }
1959    return NULL;
1960 }
1961
1962 bool HandleCallbacks::handleCBReturn(Process::const_ptr proc, Thread::const_ptr thrd, 
1963                                      Process::cb_action_t ret)
1964 {
1965    if (!thrd) {
1966       thrd = proc->llproc()->threadPool()->initialThread()->thread();
1967    }
1968    switch (ret) {
1969       case Process::cbThreadContinue:
1970                   if (!thrd->llthrd()->isUser()) break;
1971                   if (thrd == Thread::const_ptr()) {
1972             perr_printf("User returned invalid action %s for event\n", 
1973                         action_str(ret));
1974             return false;
1975          }
1976          pthrd_printf("Callbacks returned thread continue\n");
1977          thrd->llthrd()->getUserState().setState(int_thread::running);
1978          break;
1979       case Process::cbThreadStop:
1980                   if (!thrd->llthrd()->isUser()) break;
1981          if (thrd == Thread::const_ptr()) {
1982             perr_printf("User returned invalid action %s for event\n", 
1983                         action_str(ret));
1984             return false;
1985          }
1986          pthrd_printf("Callbacks returned thread stop\n");
1987          thrd->llthrd()->getUserState().setState(int_thread::stopped);
1988          break;
1989       case Process::cbProcContinue: {
1990          if (proc == Process::const_ptr()) {
1991             perr_printf("User returned invalid action %s for event\n", 
1992                         action_str(ret));
1993             return false;
1994          }
1995          pthrd_printf("Callbacks returned process continue\n");
1996          thrd->llthrd()->getUserState().setStateProc(int_thread::running);
1997          break;
1998       }
1999       case Process::cbProcStop: {
2000          if (proc == Process::const_ptr()) {
2001             perr_printf("User returned invalid action %s for event\n", 
2002                         action_str(ret));
2003             return false;
2004          }
2005          pthrd_printf("Callbacks returned process stop\n");
2006          thrd->llthrd()->getUserState().setStateProc(int_thread::stopped);
2007          break;
2008       }
2009       case Process::cbDefault:
2010          pthrd_printf("Callbacks returned default\n");
2011          break;
2012    }
2013    return true;
2014 }
2015
2016 Handler::handler_ret_t HandleCallbacks::deliverCallback(Event::ptr ev, const set<Process::cb_func_t> &cbset)
2017 {
2018    //We want the thread to remain in its appropriate state while the CB is in flight.
2019         int_thread *thr = ev->getThread() ? ev->getThread()->llthrd() : NULL;
2020    int_process *proc = ev->getProcess()->llproc();
2021    assert(proc);
2022
2023    pthrd_printf("Changing callback state of %d before CB\n", proc->getPid());
2024    int_thread::StateTracker &cb_state = thr ? thr->getCallbackState() : proc->threadPool()->initialThread()->getCallbackState();
2025    cb_state.desyncStateProc(int_thread::ditto);
2026
2027    if (isHandlerThread() && mt()->getThreadMode() != Process::CallbackThreading) {
2028       //We're not going to allow a handler thread to deliver a callback in this mode
2029       // trigger the notify, then return a request to delay from the delivery of this
2030       // callback to the user thread.
2031       ev->noted_event = true;
2032       notify()->noteEvent();
2033       return ret_cbdelay;
2034    }
2035
2036    // Make sure the user can operate on the process in the callback
2037    // But if this is a PostCrash or PostExit, the underlying process and
2038    // threads are already gone and thus no operations on them really make sense
2039    if (!ev->getProcess()->isTerminated()) {
2040       ev->getProcess()->llproc()->threadPool()->saveUserState(ev);
2041    }
2042
2043    //The following code loops over each callback registered for this event type
2044    // and triggers the callback for the user.  Return results are aggregated.
2045    unsigned k = 0;
2046    pthrd_printf("Triggering callback for event '%s'\n", ev->name().c_str());
2047    Process::cb_action_t parent_result = Process::cbDefault;
2048    Process::cb_action_t child_result = Process::cbDefault;
2049    std::set<Process::cb_func_t>::const_iterator j;
2050    for (j = cbset.begin(); j != cbset.end(); j++, k++) {
2051       pthrd_printf("Triggering callback #%u for event '%s'\n", k, ev->name().c_str());
2052       int_process::setInCB(true);
2053       Process::cb_ret_t ret = (*j)(ev);
2054       int_process::setInCB(false);
2055
2056       if (ret.parent != Process::cbDefault)
2057          parent_result = ret.parent;
2058       if (ret.child != Process::cbDefault)
2059          child_result = ret.child;
2060
2061       pthrd_printf("Callback #%u return %s/%s\n", k, action_str(ret.parent),
2062                    action_str(ret.child));
2063    }
2064
2065    // Don't allow the user to change the state of forced terminated processes 
2066    if( ev->getProcess()->llproc() && ev->getProcess()->llproc()->wasForcedTerminated() ) {
2067        parent_result = Process::cbDefault;
2068        child_result = Process::cbDefault;
2069    }
2070
2071    // Now that the callback is over, return the state to what it was before the
2072    // callback so the return value from the callback can be used to update the state
2073    if (!ev->getProcess()->isTerminated()) {
2074       ev->getProcess()->llproc()->threadPool()->restoreUserState();
2075       
2076       if (ev->getThread()->llthrd() != NULL) {
2077          //Given the callback return result, change the user state to the appropriate
2078          // setting.
2079          pthrd_printf("Handling return value for main process\n");
2080          handleCBReturn(ev->getProcess(), ev->getThread(), parent_result);
2081       }
2082    }
2083
2084    pthrd_printf("Handling return value for child process/thread\n");
2085    Process::const_ptr child_proc = Process::const_ptr();
2086    Thread::const_ptr child_thread = Thread::const_ptr();
2087    bool event_has_child = false;
2088    switch (ev->getEventType().code()) {
2089       case EventType::Fork:
2090          event_has_child = true;
2091          child_proc = static_cast<EventFork *>(ev.get())->getChildProcess();
2092          break;
2093       case EventType::ThreadCreate:
2094       case EventType::UserThreadCreate:
2095       case EventType::LWPCreate:
2096          event_has_child = true;
2097          child_thread = static_cast<EventNewThread *>(ev.get())->getNewThread();
2098          break;
2099    }
2100    if (event_has_child)
2101       handleCBReturn(child_proc, child_thread, child_result);
2102
2103    pthrd_printf("Restoring callback state of %d/%d after CB\n", ev->getProcess()->getPid(), 
2104                 ev->getThread()->getLWP());
2105    cb_state.restoreStateProc();
2106
2107    return ret_success;
2108 }
2109
2110 void HandleCallbacks::getRealEvents(EventType ev, std::vector<EventType> &out_evs)
2111 {
2112    switch (ev.code()) {
2113       case EventType::Terminate:
2114          out_evs.push_back(EventType(ev.time(), EventType::Exit));
2115          out_evs.push_back(EventType(ev.time(), EventType::Crash));
2116          out_evs.push_back(EventType(ev.time(), EventType::ForceTerminate));
2117          break;
2118       case EventType::ThreadCreate:
2119          out_evs.push_back(EventType(ev.time(), EventType::UserThreadCreate));
2120          out_evs.push_back(EventType(ev.time(), EventType::LWPCreate));
2121          break;
2122       case EventType::ThreadDestroy:
2123          pthrd_printf("ThreadDestroy handled in getRealEvents, adding UserThreadDestroy and LWPDestroy\n");
2124          out_evs.push_back(EventType(ev.time(), EventType::UserThreadDestroy));
2125          out_evs.push_back(EventType(ev.time(), EventType::LWPDestroy));
2126          break;
2127       default:
2128          out_evs.push_back(ev);
2129    }
2130 }
2131
2132 bool HandleCallbacks::registerCallback_int(EventType ev, Process::cb_func_t func)
2133 {
2134    pthrd_printf("Registering event %s with callback function %p\n", ev.name().c_str(), func);
2135    std::set<EventType, Dyninst::ProcControlAPI::eventtype_cmp>::iterator i = alleventtypes.find(ev);
2136    if (i == alleventtypes.end()) {
2137       pthrd_printf("Event %s does not have any handler\n", ev.name().c_str());
2138       return false;
2139    }
2140    cbfuncs[ev].insert(func);
2141    return true;
2142 }
2143
2144 bool HandleCallbacks::registerCallback(EventType oev, Process::cb_func_t func)
2145 {
2146    bool registered_cb = false;
2147    std::vector<EventType> real_evs;
2148    getRealEvents(oev, real_evs);
2149    
2150    for (std::vector<EventType>::iterator i = real_evs.begin(); i != real_evs.end(); i++)
2151    {
2152       EventType ev = *i;
2153       switch (ev.time()) {
2154          case EventType::Pre:
2155          case EventType::Post:
2156          case EventType::None: {
2157             bool result = registerCallback_int(ev, func);
2158             if (result)
2159                registered_cb = true;
2160             break;
2161          }
2162          case EventType::Any: {
2163             bool result1 = registerCallback_int(EventType(EventType::Pre, ev.code()), func);
2164             bool result2 = registerCallback_int(EventType(EventType::Post, ev.code()), func);
2165             bool result3 = registerCallback_int(EventType(EventType::None, ev.code()), func);
2166             if (result1 || result2 || result3)
2167                registered_cb = true;
2168             break;
2169          }
2170       }
2171    }
2172    if (!registered_cb) {
2173       pthrd_printf("Did not register any callbacks for %s\n", oev.name().c_str());
2174       ProcControlAPI::globalSetLastError(err_noevents, "EventType does not exist");
2175       return false;
2176    }
2177    return true;
2178 }
2179
2180 bool HandleCallbacks::removeCallback_int(EventType et, Process::cb_func_t func)
2181 {
2182    cbfuncs_t::iterator i = cbfuncs.find(et);
2183    if (i == cbfuncs.end()) {
2184       return false;
2185    }
2186    set<Process::cb_func_t> &func_set = i->second;
2187    set<Process::cb_func_t>::iterator j = func_set.find(func);
2188    if (j == func_set.end()) {
2189       return false;
2190    }
2191    func_set.erase(j);
2192    return true;
2193 }
2194
2195 bool HandleCallbacks::removeCallback(EventType oet, Process::cb_func_t func)
2196 {
2197    bool removed_cb = false;
2198    std::vector<EventType> real_ets;
2199    getRealEvents(oet, real_ets);
2200    
2201    for (std::vector<EventType>::iterator i = real_ets.begin(); i != real_ets.end(); i++)
2202    {
2203       EventType et = *i;
2204
2205       switch (et.time()) {
2206          case EventType::Pre:
2207          case EventType::Post:
2208          case EventType::None: {
2209             bool result = removeCallback_int(et, func);
2210             if (result)
2211                removed_cb = true;
2212          }
2213          case EventType::Any: {
2214             bool result1 = removeCallback_int(EventType(EventType::Pre, et.code()), func);
2215             bool result2 = removeCallback_int(EventType(EventType::Post,et.code()), func);
2216             bool result3 = removeCallback_int(EventType(EventType::None,et.code()), func);
2217             if (result1 || result2 || result3)
2218                removed_cb = true;
2219          }
2220       }
2221    }
2222
2223    if (!removed_cb) {
2224       perr_printf("Attempted to remove non-existant callback %s\n", 
2225                   oet.name().c_str());
2226       ProcControlAPI::globalSetLastError(err_badparam, "Callback does not exist");
2227       return false;
2228    }
2229    return true;
2230 }
2231
2232 bool HandleCallbacks::removeCallback_int(EventType et)
2233 {
2234    cbfuncs_t::iterator i = cbfuncs.find(et);
2235    if (i == cbfuncs.end()) {
2236       return false;
2237    }
2238    cbfuncs.erase(i);
2239    return true;
2240 }
2241
2242 bool HandleCallbacks::removeCallback(EventType et)
2243 {
2244    bool result = false;
2245    switch (et.time()) {
2246       case EventType::Pre:
2247       case EventType::Post:
2248       case EventType::None: {
2249          result = removeCallback_int(et);
2250       }
2251       case EventType::Any: {
2252          bool result1 = removeCallback_int(EventType(EventType::Pre, et.code()));
2253          bool result2 = removeCallback_int(EventType(EventType::Post,et.code()));
2254          bool result3 = removeCallback_int(EventType(EventType::None,et.code()));
2255          result = (result1 || result2 || result3);
2256       }
2257    }
2258    if (!result) {
2259       perr_printf("Attempted to remove non-existant callback %s\n", 
2260                   et.name().c_str());
2261       ProcControlAPI::globalSetLastError(err_badparam, "Callback does not exist");
2262       return false;
2263    }
2264    return true;
2265 }
2266
2267 bool HandleCallbacks::removeCallback(Process::cb_func_t func)
2268 {
2269    bool rmd_something = false;
2270    for (cbfuncs_t::iterator i = cbfuncs.begin(); i != cbfuncs.end(); i++)
2271    {
2272       EventType et = i->first;
2273       bool result = removeCallback_int(et, func);
2274       if (result) 
2275          rmd_something = true;
2276    }
2277    if (!rmd_something) {
2278       perr_printf("Attempted to remove non-existant callback %p\n", func);
2279       ProcControlAPI::globalSetLastError(err_badparam, "Callback does not exist");
2280       return false;
2281    }
2282    return true;
2283 }
2284
2285 HandlerPool *createDefaultHandlerPool(int_process *p)
2286 {
2287    static bool initialized = false;
2288    static HandleBootstrap *hbootstrap = NULL;
2289    static HandleSignal *hsignal = NULL;
2290    static HandlePostExit *hpostexit = NULL;
2291    static HandlePreExit *hpreexit = NULL;
2292    static HandlePostExitCleanup *hpostexitcleanup = NULL;
2293    static HandleThreadCreate *hthreadcreate = NULL;
2294    static HandleThreadDestroy *hthreaddestroy = NULL;
2295    static HandleThreadCleanup *hthreadcleanup = NULL;
2296    static HandleThreadStop *hthreadstop = NULL;
2297    static HandleSingleStep *hsinglestep = NULL;
2298    static HandleCrash *hcrash = NULL;
2299    static HandleBreakpoint *hbpoint = NULL;
2300    static HandleBreakpointContinue *hbpcontinue = NULL;
2301    static HandleBreakpointClear *hbpclear = NULL;
2302    static HandleBreakpointRestore *hbprestore = NULL;
2303    static HandleLibrary *hlibrary = NULL;
2304    static HandlePostFork *hpostfork = NULL;
2305    static HandlePostForkCont *hpostforkcont = NULL;
2306    static HandlePostExec *hpostexec = NULL;
2307    static HandleAsync *hasync = NULL;
2308    static HandleForceTerminate *hforceterm = NULL;
2309    static HandleNop *hnop = NULL;
2310    static HandleDetach *hdetach = NULL;
2311    static HandleEmulatedSingleStep *hemulatedsinglestep = NULL;
2312    static iRPCHandler *hrpc = NULL;
2313    static iRPCPreCallbackHandler *hprerpc = NULL;
2314    static HandlePreBootstrap* hprebootstrap = NULL;
2315    static iRPCLaunchHandler *hrpclaunch = NULL;
2316    if (!initialized) {
2317       hbootstrap = new HandleBootstrap();
2318       hsignal = new HandleSignal();
2319       hpostexit = new HandlePostExit();
2320       hpostexitcleanup = new HandlePostExitCleanup();
2321       hpreexit = new HandlePreExit();
2322       hthreadcreate = new HandleThreadCreate();
2323       hthreaddestroy = new HandleThreadDestroy();
2324       hthreadcleanup = new HandleThreadCleanup();
2325       hthreadstop = new HandleThreadStop();
2326       hsinglestep = new HandleSingleStep();
2327       hcrash = new HandleCrash();
2328       hbpoint = new HandleBreakpoint();
2329       hbpcontinue = new HandleBreakpointContinue();
2330       hbpclear = new HandleBreakpointClear();
2331       hbprestore = new HandleBreakpointRestore();
2332       hrpc = new iRPCHandler();
2333       hprerpc = new iRPCPreCallbackHandler();
2334       hrpclaunch = new iRPCLaunchHandler();
2335       hlibrary = new HandleLibrary();
2336       hpostfork = new HandlePostFork();
2337       hpostforkcont = new HandlePostForkCont();
2338       hpostexec = new HandlePostExec();
2339       hasync = new HandleAsync();
2340       hforceterm = new HandleForceTerminate();
2341       hprebootstrap = new HandlePreBootstrap();
2342       hnop = new HandleNop();
2343       hdetach = new HandleDetach();
2344       hemulatedsinglestep = new HandleEmulatedSingleStep();
2345       initialized = true;
2346    }
2347    HandlerPool *hpool = new HandlerPool(p);
2348    hpool->addHandler(hbootstrap);
2349    hpool->addHandler(hsignal);
2350    hpool->addHandler(hpostexit);
2351    hpool->addHandler(hpostexitcleanup);
2352    hpool->addHandler(hpreexit);
2353    hpool->addHandler(hthreadcreate);
2354    hpool->addHandler(hthreaddestroy);
2355    hpool->addHandler(hthreadcleanup);
2356    hpool->addHandler(hthreadstop);
2357    hpool->addHandler(hsinglestep);
2358    hpool->addHandler(hcrash);
2359    hpool->addHandler(hbpoint);
2360    hpool->addHandler(hbpcontinue);
2361    hpool->addHandler(hbpclear);
2362    hpool->addHandler(hbprestore);
2363    hpool->addHandler(hrpc);
2364    hpool->addHandler(hprerpc);
2365    hpool->addHandler(hlibrary);
2366    hpool->addHandler(hpostfork);
2367    hpool->addHandler(hpostforkcont);
2368    hpool->addHandler(hpostexec);
2369    hpool->addHandler(hrpclaunch);
2370    hpool->addHandler(hasync);
2371    hpool->addHandler(hforceterm);
2372    hpool->addHandler(hprebootstrap);
2373    hpool->addHandler(hnop);
2374    hpool->addHandler(hdetach);
2375    hpool->addHandler(hemulatedsinglestep);
2376    plat_createDefaultHandlerPool(hpool);
2377
2378    print_add_handler = false;
2379    return hpool;
2380 }