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