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