Fix cloning of libraries with Dwarf support
[platform/upstream/ltrace.git] / proc.c
1 /*
2  * This file is part of ltrace.
3  * Copyright (C) 2011,2012,2013,2014 Petr Machata, Red Hat Inc.
4  * Copyright (C) 2010 Joe Damato
5  * Copyright (C) 1998,2009 Juan Cespedes
6  *
7  * This program is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License as
9  * published by the Free Software Foundation; either version 2 of the
10  * License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful, but
13  * WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
20  * 02110-1301 USA
21  */
22
23 #include "config.h"
24
25 #include <sys/types.h>
26 #include <assert.h>
27 #include <errno.h>
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <string.h>
31
32 #include "backend.h"
33 #include "breakpoint.h"
34 #include "debug.h"
35 #include "fetch.h"
36 #include "options.h"
37 #include "proc.h"
38 #include "value_dict.h"
39 #include "dwarf_prototypes.h"
40
41 #ifndef OS_HAVE_PROCESS_DATA
42 int
43 os_process_init(struct process *proc)
44 {
45         return 0;
46 }
47
48 void
49 os_process_destroy(struct process *proc)
50 {
51 }
52
53 int
54 os_process_clone(struct process *retp, struct process *proc)
55 {
56         return 0;
57 }
58
59 int
60 os_process_exec(struct process *proc)
61 {
62         return 0;
63 }
64 #endif
65
66 #ifndef ARCH_HAVE_PROCESS_DATA
67 int
68 arch_process_init(struct process *proc)
69 {
70         return 0;
71 }
72
73 void
74 arch_process_destroy(struct process *proc)
75 {
76 }
77
78 int
79 arch_process_clone(struct process *retp, struct process *proc)
80 {
81         return 0;
82 }
83
84 int
85 arch_process_exec(struct process *proc)
86 {
87         return 0;
88 }
89 #endif
90
91 #ifndef ARCH_HAVE_DYNLINK_DONE
92 void
93 arch_dynlink_done(struct process *proc)
94 {
95 }
96 #endif
97
98 static int add_process(struct process *proc, int was_exec);
99 static void unlist_process(struct process *proc);
100
101 static void
102 destroy_unwind(struct process *proc)
103 {
104 #if defined(HAVE_LIBUNWIND)
105         if (proc->unwind_priv != NULL)
106                 _UPT_destroy(proc->unwind_priv);
107         if (proc->unwind_as != NULL)
108                 unw_destroy_addr_space(proc->unwind_as);
109 #endif /* defined(HAVE_LIBUNWIND) */
110
111 #if defined(HAVE_LIBDW)
112         if (proc->dwfl != NULL)
113                 dwfl_end(proc->dwfl);
114 #endif /* defined(HAVE_LIBDW) */
115 }
116
117 static int
118 process_bare_init(struct process *proc, const char *filename,
119                   pid_t pid, int was_exec)
120 {
121         if (!was_exec) {
122                 memset(proc, 0, sizeof(*proc));
123
124                 proc->filename = strdup(filename);
125                 if (proc->filename == NULL) {
126                 fail:
127                         free(proc->filename);
128                         if (proc->breakpoints != NULL) {
129                                 dict_destroy(proc->breakpoints,
130                                              NULL, NULL, NULL);
131                                 free(proc->breakpoints);
132                                 proc->breakpoints = NULL;
133                         }
134                         return -1;
135                 }
136         }
137
138         /* Add process so that we know who the leader is.  */
139         proc->pid = pid;
140         if (add_process(proc, was_exec) < 0)
141                 goto fail;
142         if (proc->leader == NULL) {
143         unlist_and_fail:
144                 if (!was_exec)
145                         unlist_process(proc);
146                 goto fail;
147         }
148
149         if (proc->leader == proc) {
150                 proc->breakpoints = malloc(sizeof(*proc->breakpoints));
151                 if (proc->breakpoints == NULL)
152                         goto unlist_and_fail;
153                 DICT_INIT(proc->breakpoints,
154                           arch_addr_t, struct breakpoint *,
155                           arch_addr_hash, arch_addr_eq, NULL);
156         } else {
157                 proc->breakpoints = NULL;
158         }
159
160 #if defined(HAVE_LIBUNWIND)
161         if (options.bt_depth > 0) {
162                 proc->unwind_priv = _UPT_create(pid);
163                 proc->unwind_as = unw_create_addr_space(&_UPT_accessors, 0);
164
165                 if (proc->unwind_priv == NULL || proc->unwind_as == NULL) {
166                         fprintf(stderr,
167                                 "Couldn't initialize unwinding "
168                                 "for process %d\n", proc->pid);
169                         destroy_unwind(proc);
170                         proc->unwind_priv = NULL;
171                         proc->unwind_as = NULL;
172                 }
173         }
174 #endif /* defined(HAVE_LIBUNWIND) */
175
176 #if defined(HAVE_LIBDW)
177         proc->dwfl = NULL; /* Initialize for leader only on first library.  */
178         proc->should_attach_dwfl = 1; /* should try to attach the DWFL data */
179 #endif /* defined(HAVE_LIBDW) */
180
181         return 0;
182 }
183
184 static void
185 process_bare_destroy(struct process *proc, int was_exec)
186 {
187         dict_destroy(proc->breakpoints, NULL, NULL, NULL);
188         free(proc->breakpoints);
189         if (!was_exec) {
190                 free(proc->filename);
191                 unlist_process(proc);
192                 destroy_unwind(proc);
193         }
194 }
195
196 static int
197 process_init_main(struct process *proc)
198 {
199         if (breakpoints_init(proc) < 0) {
200                 fprintf(stderr, "failed to init breakpoints %d\n",
201                         proc->pid);
202                 return -1;
203         }
204
205         return 0;
206 }
207
208 int
209 process_init(struct process *proc, const char *filename, pid_t pid)
210 {
211         if (process_bare_init(proc, filename, pid, 0) < 0) {
212         fail:
213                 fprintf(stderr, "failed to initialize process %d: %s\n",
214                         pid, strerror(errno));
215                 return -1;
216         }
217
218         if (os_process_init(proc) < 0) {
219                 process_bare_destroy(proc, 0);
220                 goto fail;
221         }
222
223         if (arch_process_init(proc) < 0) {
224                 os_process_destroy(proc);
225                 process_bare_destroy(proc, 0);
226                 goto fail;
227         }
228
229         if (proc->leader != proc) {
230                 proc->e_machine = proc->leader->e_machine;
231                 proc->e_class = proc->leader->e_class;
232                 get_arch_dep(proc);
233         } else if (process_init_main(proc) < 0) {
234                 process_bare_destroy(proc, 0);
235                 goto fail;
236         }
237         return 0;
238 }
239
240 static enum callback_status
241 destroy_breakpoint_cb(struct process *proc, struct breakpoint *bp, void *data)
242 {
243         breakpoint_destroy(bp);
244         free(bp);
245         return CBS_CONT;
246 }
247
248 // XXX see comment in handle_event.c
249 void callstack_pop(struct process *proc);
250
251 static void
252 private_process_destroy(struct process *proc, int was_exec)
253 {
254         /* Pop remaining stack elements.  */
255         while (proc->callstack_depth > 0) {
256                 /* When this is called just before a process is
257                  * destroyed, the breakpoints should either have been
258                  * retracted by now, or were killed by exec.  In any
259                  * case, it's safe to pretend that there are no
260                  * breakpoints associated with the stack elements, so
261                  * that stack_pop doesn't attempt to destroy them.  */
262                 size_t i = proc->callstack_depth - 1;
263                 if (!proc->callstack[i].is_syscall)
264                         proc->callstack[i].return_addr = 0;
265
266                 callstack_pop(proc);
267         }
268
269         if (!was_exec)
270                 free(proc->filename);
271
272         /* Libraries and symbols.  This is only relevant in
273          * leader.  */
274         struct library *lib;
275         for (lib = proc->libraries; lib != NULL; ) {
276                 struct library *next = lib->next;
277                 library_destroy(lib);
278                 free(lib);
279                 lib = next;
280         }
281         proc->libraries = NULL;
282
283         /* Breakpoints.  */
284         if (proc->breakpoints != NULL) {
285                 proc_each_breakpoint(proc, NULL, destroy_breakpoint_cb, NULL);
286                 dict_destroy(proc->breakpoints, NULL, NULL, NULL);
287                 free(proc->breakpoints);
288                 proc->breakpoints = NULL;
289         }
290
291         destroy_unwind(proc);
292 }
293
294 void
295 process_destroy(struct process *proc)
296 {
297         arch_process_destroy(proc);
298         os_process_destroy(proc);
299         private_process_destroy(proc, 0);
300 }
301
302 int
303 process_exec(struct process *proc)
304 {
305         /* Call exec handlers first, before we destroy the main
306          * state.  */
307         if (arch_process_exec(proc) < 0
308             || os_process_exec(proc) < 0)
309                 return -1;
310
311         private_process_destroy(proc, 1);
312
313         if (process_bare_init(proc, NULL, proc->pid, 1) < 0)
314                 return -1;
315         if (process_init_main(proc) < 0) {
316                 process_bare_destroy(proc, 1);
317                 return -1;
318         }
319         return 0;
320 }
321
322 struct process *
323 open_program(const char *filename, pid_t pid)
324 {
325         assert(pid != 0);
326         struct process *proc = malloc(sizeof(*proc));
327         if (proc == NULL || process_init(proc, filename, pid) < 0) {
328                 free(proc);
329                 return NULL;
330         }
331         return proc;
332 }
333
334 struct clone_single_bp_data {
335         struct process *old_proc;
336         struct process *new_proc;
337 };
338
339 static enum callback_status
340 clone_single_bp(arch_addr_t *key, struct breakpoint **bpp, void *u)
341 {
342         struct breakpoint *bp = *bpp;
343         struct clone_single_bp_data *data = u;
344
345         struct breakpoint *clone = malloc(sizeof(*clone));
346         if (clone == NULL
347             || breakpoint_clone(clone, data->new_proc, bp) < 0) {
348         fail:
349                 free(clone);
350                 return CBS_STOP;
351         }
352         if (proc_add_breakpoint(data->new_proc->leader, clone) < 0) {
353                 breakpoint_destroy(clone);
354                 goto fail;
355         }
356         return CBS_CONT;
357 }
358
359 int
360 process_clone(struct process *retp, struct process *proc, pid_t pid)
361 {
362         if (process_bare_init(retp, proc->filename, pid, 0) < 0) {
363         fail1:
364                 fprintf(stderr, "Failed to clone process %d to %d: %s\n",
365                         proc->pid, pid, strerror(errno));
366                 return -1;
367         }
368
369         retp->tracesysgood = proc->tracesysgood;
370         retp->e_machine = proc->e_machine;
371         retp->e_class = proc->e_class;
372
373         /* For non-leader processes, that's all we need to do.  */
374         if (retp->leader != retp)
375                 return 0;
376
377         /* Clone symbols first so that we can clone and relink
378          * breakpoints.  */
379         struct library *lib;
380         struct library **nlibp = &retp->libraries;
381         for (lib = proc->leader->libraries; lib != NULL; lib = lib->next) {
382                 *nlibp = malloc(sizeof(**nlibp));
383
384                 if (*nlibp == NULL
385                     || library_clone(*nlibp, lib) < 0) {
386                         free(*nlibp);
387                         *nlibp = NULL;
388
389                 fail2:
390                         process_bare_destroy(retp, 0);
391
392                         /* Error when cloning.  Unroll what was done.  */
393                         for (lib = retp->libraries; lib != NULL; ) {
394                                 struct library *next = lib->next;
395                                 library_destroy(lib);
396                                 free(lib);
397                                 lib = next;
398                         }
399                         goto fail1;
400                 }
401
402                 nlibp = &(*nlibp)->next;
403         }
404
405         /* Now clone breakpoints.  Symbol relinking is done in
406          * clone_single_bp.  */
407         struct clone_single_bp_data data = {
408                 .old_proc = proc,
409                 .new_proc = retp,
410         };
411         if (DICT_EACH(proc->leader->breakpoints,
412                       arch_addr_t, struct breakpoint *, NULL,
413                       clone_single_bp, &data) != NULL)
414                 goto fail2;
415
416         /* And finally the call stack.  */
417         /* XXX clearly the callstack handling should be moved to a
418          * separate module and this whole business extracted to
419          * callstack_clone, or callstack_element_clone.  */
420         memcpy(retp->callstack, proc->callstack, sizeof(retp->callstack));
421         retp->callstack_depth = proc->callstack_depth;
422
423         size_t i;
424         for (i = 0; i < retp->callstack_depth; ++i) {
425                 struct callstack_element *elem = &retp->callstack[i];
426                 struct fetch_context *ctx = elem->fetch_context;
427                 if (ctx != NULL) {
428                         struct fetch_context *nctx = fetch_arg_clone(retp, ctx);
429                         if (nctx == NULL) {
430                                 size_t j;
431                         fail3:
432                                 for (j = 0; j < i; ++j) {
433                                         nctx = retp->callstack[j].fetch_context;
434                                         fetch_arg_done(nctx);
435                                         elem->fetch_context = NULL;
436                                 }
437                                 goto fail2;
438                         }
439                         elem->fetch_context = nctx;
440                 }
441
442                 if (elem->arguments != NULL) {
443                         struct value_dict *nargs = malloc(sizeof(*nargs));
444                         if (nargs == NULL
445                             || val_dict_clone(nargs, elem->arguments) < 0) {
446                                 size_t j;
447                                 for (j = 0; j < i; ++j) {
448                                         nargs = retp->callstack[j].arguments;
449                                         val_dict_destroy(nargs);
450                                         free(nargs);
451                                         elem->arguments = NULL;
452                                 }
453
454                                 /* Pretend that this round went well,
455                                  * so that fail3 frees I-th
456                                  * fetch_context.  */
457                                 ++i;
458                                 goto fail3;
459                         }
460                         elem->arguments = nargs;
461                 }
462
463                 /* If it's not a syscall, we need to find the
464                  * corresponding library symbol in the cloned
465                  * library.  */
466                 if (!elem->is_syscall && elem->c_un.libfunc != NULL) {
467                         struct library_symbol *libfunc = elem->c_un.libfunc;
468                         int rc = proc_find_symbol(retp, libfunc,
469                                                   NULL, &elem->c_un.libfunc);
470                         assert(rc == 0);
471                 }
472         }
473
474         /* At this point, retp is fully initialized, except for OS and
475          * arch parts, and we can call private_process_destroy.  */
476         if (os_process_clone(retp, proc) < 0) {
477                 private_process_destroy(retp, 0);
478                 return -1;
479         }
480         if (arch_process_clone(retp, proc) < 0) {
481                 os_process_destroy(retp);
482                 private_process_destroy(retp, 0);
483                 return -1;
484         }
485
486         return 0;
487 }
488
489 static int
490 open_one_pid(pid_t pid)
491 {
492         debug(DEBUG_PROCESS, "open_one_pid(pid=%d)", pid);
493
494         /* Get the filename first.  Should the trace_pid fail, we can
495          * easily free it, untracing is more work.  */
496         char *filename = pid2name(pid);
497         if (filename == NULL || trace_pid(pid) < 0) {
498         fail:
499                 free(filename);
500                 return -1;
501         }
502
503         struct process *proc = open_program(filename, pid);
504         if (proc == NULL)
505                 goto fail;
506         free(filename);
507         trace_set_options(proc);
508
509         return 0;
510 }
511
512 static enum callback_status
513 start_one_pid(struct process *proc, void *data)
514 {
515         continue_process(proc->pid);
516         return CBS_CONT;
517 }
518
519 static enum callback_status
520 is_main(struct process *proc, struct library *lib, void *data)
521 {
522         return CBS_STOP_IF(lib->type == LT_LIBTYPE_MAIN);
523 }
524
525 void
526 process_hit_start(struct process *proc)
527 {
528         struct process *leader = proc->leader;
529         assert(leader != NULL);
530
531         struct library *mainlib
532                 = proc_each_library(leader, NULL, is_main, NULL);
533         assert(mainlib != NULL);
534         linkmap_init(leader, mainlib->dyn_addr);
535         arch_dynlink_done(leader);
536 }
537
538 void
539 open_pid(pid_t pid)
540 {
541         debug(DEBUG_PROCESS, "open_pid(pid=%d)", pid);
542         /* If we are already tracing this guy, we should be seeing all
543          * his children via normal tracing route.  */
544         if (pid2proc(pid) != NULL)
545                 return;
546
547         /* First, see if we can attach the requested PID itself.  */
548         if (open_one_pid(pid) < 0) {
549                 fprintf(stderr, "Cannot attach to pid %u: %s\n",
550                         pid, strerror(errno));
551                 trace_fail_warning(pid);
552                 return;
553         }
554
555         /* Now attach to all tasks that belong to that PID.  There's a
556          * race between process_tasks and open_one_pid.  So when we
557          * fail in open_one_pid below, we just do another round.
558          * Chances are that by then that PID will have gone away, and
559          * that's why we have seen the failure.  The processes that we
560          * manage to open_one_pid are stopped, so we should eventually
561          * reach a point where process_tasks doesn't give any new
562          * processes (because there's nobody left to produce
563          * them).  */
564         size_t old_ntasks = 0;
565         int have_all;
566         while (1) {
567                 pid_t *tasks;
568                 size_t ntasks;
569                 size_t i;
570
571                 if (process_tasks(pid, &tasks, &ntasks) < 0) {
572                         fprintf(stderr, "Cannot obtain tasks of pid %u: %s\n",
573                                 pid, strerror(errno));
574                         break;
575                 }
576
577                 have_all = 1;
578                 for (i = 0; i < ntasks; ++i)
579                         if (pid2proc(tasks[i]) == NULL
580                             && open_one_pid(tasks[i]) < 0)
581                                 have_all = 0;
582
583                 free(tasks);
584
585                 if (have_all && old_ntasks == ntasks)
586                         break;
587                 old_ntasks = ntasks;
588         }
589
590         struct process *leader = pid2proc(pid)->leader;
591
592         /* XXX Is there a way to figure out whether _start has
593          * actually already been hit?  */
594         process_hit_start(leader);
595
596         /* Done.  Continue everyone.  */
597         each_task(leader, NULL, start_one_pid, NULL);
598 }
599
600 static enum callback_status
601 find_proc(struct process *proc, void *data)
602 {
603         return CBS_STOP_IF(proc->pid == (pid_t)(uintptr_t)data);
604 }
605
606 struct process *
607 pid2proc(pid_t pid)
608 {
609         return each_process(NULL, &find_proc, (void *)(uintptr_t)pid);
610 }
611
612 static struct process *list_of_processes = NULL;
613
614 static void
615 unlist_process(struct process *proc)
616 {
617         if (list_of_processes == proc) {
618                 list_of_processes = list_of_processes->next;
619                 return;
620         }
621
622         struct process *tmp;
623         for (tmp = list_of_processes; ; tmp = tmp->next) {
624                 /* If the following assert fails, the process wasn't
625                  * in the list.  */
626                 assert(tmp->next != NULL);
627
628                 if (tmp->next == proc) {
629                         tmp->next = tmp->next->next;
630                         return;
631                 }
632         }
633 }
634
635 struct process *
636 each_process(struct process *start_after,
637              enum callback_status(*cb)(struct process *proc, void *data),
638              void *data)
639 {
640         struct process *it = start_after == NULL ? list_of_processes
641                 : start_after->next;
642
643         while (it != NULL) {
644                 /* Callback might call remove_process.  */
645                 struct process *next = it->next;
646                 switch ((*cb)(it, data)) {
647                 case CBS_FAIL:
648                         /* XXX handle me */
649                 case CBS_STOP:
650                         return it;
651                 case CBS_CONT:
652                         break;
653                 }
654                 it = next;
655         }
656         return NULL;
657 }
658
659 struct process *
660 each_task(struct process *proc, struct process *start_after,
661           enum callback_status(*cb)(struct process *proc, void *data),
662           void *data)
663 {
664         assert(proc != NULL);
665         struct process *it = start_after == NULL ? proc->leader
666                 : start_after->next;
667
668         if (it != NULL) {
669                 struct process *leader = it->leader;
670                 while (it != NULL && it->leader == leader) {
671                         /* Callback might call remove_process.  */
672                         struct process *next = it->next;
673                         switch ((*cb)(it, data)) {
674                         case CBS_FAIL:
675                                 /* XXX handle me */
676                         case CBS_STOP:
677                                 return it;
678                         case CBS_CONT:
679                                 break;
680                         }
681                         it = next;
682                 }
683         }
684         return NULL;
685 }
686
687 static int
688 add_process(struct process *proc, int was_exec)
689 {
690         struct process **leaderp = &list_of_processes;
691         if (proc->pid) {
692                 pid_t tgid = process_leader(proc->pid);
693                 if (tgid == 0)
694                         /* Must have been terminated before we managed
695                          * to fully attach.  */
696                         return -1;
697                 if (tgid == proc->pid) {
698                         proc->leader = proc;
699                 } else {
700                         struct process *leader = pid2proc(tgid);
701                         proc->leader = leader;
702                         if (leader != NULL)
703                                 leaderp = &leader->next;
704                 }
705         }
706
707         if (!was_exec) {
708                 proc->next = *leaderp;
709                 *leaderp = proc;
710         }
711         return 0;
712 }
713
714 void
715 change_process_leader(struct process *proc, struct process *leader)
716 {
717         struct process **leaderp = &list_of_processes;
718         if (proc->leader == leader)
719                 return;
720
721         assert(leader != NULL);
722         unlist_process(proc);
723         if (proc != leader)
724                 leaderp = &leader->next;
725
726         proc->leader = leader;
727         proc->next = *leaderp;
728         *leaderp = proc;
729 }
730
731 static enum callback_status
732 clear_leader(struct process *proc, void *data)
733 {
734         debug(DEBUG_FUNCTION, "detach_task %d from leader %d",
735               proc->pid, proc->leader->pid);
736         proc->leader = NULL;
737         return CBS_CONT;
738 }
739
740 void
741 remove_process(struct process *proc)
742 {
743         debug(DEBUG_FUNCTION, "remove_proc(pid=%d)", proc->pid);
744
745         if (proc->leader == proc)
746                 each_task(proc, NULL, &clear_leader, NULL);
747
748         unlist_process(proc);
749         process_removed(proc);
750         process_destroy(proc);
751         free(proc);
752 }
753
754 void
755 install_event_handler(struct process *proc, struct event_handler *handler)
756 {
757         debug(DEBUG_FUNCTION, "install_event_handler(pid=%d, %p)", proc->pid, handler);
758         assert(proc->event_handler == NULL);
759         proc->event_handler = handler;
760 }
761
762 void
763 destroy_event_handler(struct process *proc)
764 {
765         struct event_handler *handler = proc->event_handler;
766         debug(DEBUG_FUNCTION, "destroy_event_handler(pid=%d, %p)", proc->pid, handler);
767         assert(handler != NULL);
768         if (handler->destroy != NULL)
769                 handler->destroy(handler);
770         free(handler);
771         proc->event_handler = NULL;
772 }
773
774 static int
775 breakpoint_for_symbol(struct library_symbol *libsym, struct process *proc)
776 {
777         arch_addr_t bp_addr;
778         assert(proc->leader == proc);
779
780         /* Don't enable latent or delayed symbols.  */
781         if (libsym->latent || libsym->delayed) {
782                 debug(DEBUG_FUNCTION,
783                       "delayed and/or latent breakpoint pid=%d, %s@%p",
784                       proc->pid, libsym->name, libsym->enter_addr);
785                 return 0;
786         }
787
788         bp_addr = sym2addr(proc, libsym);
789
790         /* If there is an artificial breakpoint on the same address,
791          * its libsym will be NULL, and we can smuggle our libsym
792          * there.  That artificial breakpoint is there presumably for
793          * the callbacks, which we don't touch.  If there is a real
794          * breakpoint, then this is a bug.  ltrace-elf.c should filter
795          * symbols and ignore extra symbol aliases.
796          *
797          * The other direction is more complicated and currently not
798          * supported.  If a breakpoint has custom callbacks, it might
799          * be also custom-allocated, and we would really need to swap
800          * the two: delete the one now in the dictionary, swap values
801          * around, and put the new breakpoint back in.  */
802         struct breakpoint *bp;
803         if (DICT_FIND_VAL(proc->breakpoints, &bp_addr, &bp) == 0) {
804                 /* MIPS backend makes duplicate requests.  This is
805                  * likely a bug in the backend.  Currently there's no
806                  * point assigning more than one symbol to a
807                  * breakpoint, because when it hits, we won't know
808                  * what to print out.  But it's easier to fix it here
809                  * before someone who understands MIPS has the time to
810                  * look into it.  So turn the sanity check off on
811                  * MIPS.  References:
812                  *
813                  *   http://lists.alioth.debian.org/pipermail/ltrace-devel/2012-November/000764.html
814                  *   http://lists.alioth.debian.org/pipermail/ltrace-devel/2012-November/000770.html
815                  */
816 #ifndef __mips__
817                 assert(bp->libsym == NULL);
818                 bp->libsym = libsym;
819 #endif
820                 return 0;
821         }
822
823         bp = malloc(sizeof(*bp));
824         if (bp == NULL
825             || breakpoint_init(bp, proc, bp_addr, libsym) < 0) {
826         fail:
827                 free(bp);
828                 return -1;
829         }
830         if (proc_add_breakpoint(proc, bp) < 0) {
831                 breakpoint_destroy(bp);
832                 goto fail;
833         }
834
835         if (breakpoint_turn_on(bp, proc) < 0) {
836                 proc_remove_breakpoint(proc, bp);
837                 breakpoint_destroy(bp);
838                 goto fail;
839         }
840
841         return 0;
842 }
843
844 static enum callback_status
845 cb_breakpoint_for_symbol(struct library_symbol *libsym, void *data)
846 {
847         return CBS_STOP_IF(breakpoint_for_symbol(libsym, data) < 0);
848 }
849
850 static int
851 proc_activate_latent_symbol(struct process *proc,
852                             struct library_symbol *libsym)
853 {
854         assert(libsym->latent);
855         libsym->latent = 0;
856         debug(DEBUG_FUNCTION, "activated latent symbol");
857         return breakpoint_for_symbol(libsym, proc);
858 }
859
860 int
861 proc_activate_delayed_symbol(struct process *proc,
862                              struct library_symbol *libsym)
863 {
864         assert(libsym->delayed);
865         libsym->delayed = 0;
866         debug(DEBUG_FUNCTION, "activated delayed symbol");
867         return breakpoint_for_symbol(libsym, proc);
868 }
869
870
871 struct activate_latent_in_context
872 {
873         struct process *proc;
874         struct library_exported_names *exported_names;
875 };
876 static enum callback_status
877 activate_latent_in_cb(struct library_symbol *libsym, void *data)
878 {
879         struct activate_latent_in_context *ctx =
880                 (struct activate_latent_in_context*)data;
881
882         if (libsym->latent &&
883             library_exported_names_contains(ctx->exported_names,
884                                             libsym->name) != 0)
885                 proc_activate_latent_symbol(ctx->proc, libsym);
886
887         return CBS_CONT;
888 }
889
890 static enum callback_status
891 activate_latent_in(struct process *proc, struct library *lib, void *data)
892 {
893         struct library_symbol *libsym = NULL;
894
895         struct library_exported_names *exported_names =
896                 (struct library_exported_names*)data;
897
898         struct activate_latent_in_context ctx =
899                 {.proc = proc,
900                  .exported_names = exported_names};
901
902         if (library_each_symbol(lib, libsym,
903                                 activate_latent_in_cb,
904                                 &ctx) != NULL)
905                 return CBS_FAIL;
906
907         return CBS_CONT;
908 }
909
910 void
911 proc_add_library(struct process *proc, struct library *lib)
912 {
913         assert(lib->next == NULL);
914         lib->next = proc->libraries;
915         proc->libraries = lib;
916         debug(DEBUG_PROCESS, "added library %s@%p (%s) to %d",
917               lib->soname, lib->base, lib->pathname, proc->pid);
918
919 #if defined(HAVE_LIBDW)
920         Dwfl *dwfl = NULL;
921         Dwfl_Module *dwfl_module = NULL;
922
923         /* Setup module tracking for libdwfl unwinding.  */
924         struct process *leader = proc->leader;
925         dwfl = leader->dwfl;
926         if (dwfl == NULL) {
927                 static const Dwfl_Callbacks proc_callbacks = {
928                         .find_elf = dwfl_linux_proc_find_elf,
929                         .find_debuginfo = dwfl_standard_find_debuginfo
930                 };
931                 dwfl = dwfl_begin(&proc_callbacks);
932                 if (dwfl == NULL)
933                         fprintf(stderr,
934                                 "Couldn't initialize libdwfl unwinding "
935                                 "for process %d: %s\n", leader->pid,
936                                 dwfl_errmsg (-1));
937         }
938
939         if (dwfl != NULL) {
940                 dwfl_report_begin_add(dwfl);
941                 dwfl_module =
942                         dwfl_report_elf(dwfl, lib->soname,
943                                         lib->pathname, -1,
944                                         (GElf_Addr) lib->base,
945                                         false);
946                 if (dwfl_module == NULL)
947                         fprintf(stderr,
948                                 "dwfl_report_elf %s@%p (%s) %d: %s\n",
949                                 lib->soname, lib->base, lib->pathname,
950                                 proc->pid, dwfl_errmsg (-1));
951
952                 dwfl_report_end(dwfl, NULL, NULL);
953
954                 if (options.bt_depth > 0) {
955                         if (proc->should_attach_dwfl) {
956                                 int r = dwfl_linux_proc_attach(dwfl,
957                                                                leader->pid,
958                                                                true);
959                                 proc->should_attach_dwfl = 0;
960                                 if (r != 0) {
961                                         const char *msg;
962                                         dwfl_end(dwfl);
963                                         if (r < 0)
964                                                 msg = dwfl_errmsg(-1);
965                                         else
966                                                 msg = strerror(r);
967                                         fprintf(stderr, "Couldn't initialize "
968                                                 "libdwfl (unwinding, prototype "
969                                                 "import) for process %d: %s\n",
970                                                 leader->pid, msg);
971                                 }
972                         }
973                 }
974         }
975
976         lib->dwfl_module = dwfl_module;
977         leader->dwfl = dwfl;
978
979 #endif /* defined(HAVE_LIBDW) */
980
981         /* Insert breakpoints for all active (non-latent) symbols.  */
982         struct library_symbol *libsym = NULL;
983         while ((libsym = library_each_symbol(lib, libsym,
984                                              cb_breakpoint_for_symbol,
985                                              proc)) != NULL)
986                 fprintf(stderr,
987                         "Couldn't insert breakpoint for %s to %d: %s.\n",
988                         libsym->name, proc->pid, strerror(errno));
989
990         if (lib->should_activate_latent != 0) {
991                 /* Look through export list of the new library and compare it
992                  * with latent symbols of all libraries (including this
993                  * library itself).  */
994                 struct library *lib2 = NULL;
995
996                 while ((lib2 = proc_each_library(proc, lib2, activate_latent_in,
997                                                  &lib->exported_names)) != NULL)
998                         fprintf(stderr,
999                                 "Couldn't activate latent symbols "
1000                                 "for %s in %d: %s.\n",
1001                                 lib2->soname, proc->pid, strerror(errno));
1002         }
1003 }
1004
1005 int
1006 proc_remove_library(struct process *proc, struct library *lib)
1007 {
1008         struct library **libp;
1009         for (libp = &proc->libraries; *libp != NULL; libp = &(*libp)->next)
1010                 if (*libp == lib) {
1011                         *libp = lib->next;
1012                         return 0;
1013                 }
1014         return -1;
1015 }
1016
1017 struct library *
1018 proc_each_library(struct process *proc, struct library *it,
1019                   enum callback_status (*cb)(struct process *proc,
1020                                              struct library *lib, void *data),
1021                   void *data)
1022 {
1023         if (it == NULL)
1024                 it = proc->libraries;
1025         else
1026                 it = it->next;
1027
1028         while (it != NULL) {
1029                 struct library *next = it->next;
1030
1031                 switch (cb(proc, it, data)) {
1032                 case CBS_FAIL:
1033                         /* XXX handle me */
1034                 case CBS_STOP:
1035                         return it;
1036                 case CBS_CONT:
1037                         break;
1038                 }
1039
1040                 it = next;
1041         }
1042
1043         return NULL;
1044 }
1045
1046 static void
1047 check_leader(struct process *proc)
1048 {
1049         /* Only the group leader should be getting the breakpoints and
1050          * thus have ->breakpoint initialized.  */
1051         assert(proc->leader != NULL);
1052         assert(proc->leader == proc);
1053         assert(proc->breakpoints != NULL);
1054 }
1055
1056 int
1057 proc_add_breakpoint(struct process *proc, struct breakpoint *bp)
1058 {
1059         debug(DEBUG_FUNCTION, "proc_add_breakpoint(pid=%d, %s@%p)",
1060               proc->pid, breakpoint_name(bp), bp->addr);
1061         check_leader(proc);
1062
1063         /* XXX We might merge bp->libsym instead of the following
1064          * assert, but that's not necessary right now.  Read the
1065          * comment in breakpoint_for_symbol.  */
1066         assert(dict_find(proc->breakpoints, &bp->addr) == NULL);
1067
1068         if (DICT_INSERT(proc->breakpoints, &bp->addr, &bp) < 0) {
1069                 fprintf(stderr,
1070                         "couldn't enter breakpoint %s@%p to dictionary: %s\n",
1071                         breakpoint_name(bp), bp->addr, strerror(errno));
1072                 return -1;
1073         }
1074
1075         return 0;
1076 }
1077
1078 void
1079 proc_remove_breakpoint(struct process *proc, struct breakpoint *bp)
1080 {
1081         debug(DEBUG_FUNCTION, "proc_remove_breakpoint(pid=%d, %s@%p)",
1082               proc->pid, breakpoint_name(bp), bp->addr);
1083         check_leader(proc);
1084         int rc = DICT_ERASE(proc->breakpoints, &bp->addr, struct breakpoint *,
1085                             NULL, NULL, NULL);
1086         assert(rc == 0);
1087 }
1088
1089 struct each_breakpoint_data
1090 {
1091         struct process *proc;
1092         enum callback_status (*cb)(struct process *proc,
1093                                    struct breakpoint *bp,
1094                                    void *data);
1095         void *cb_data;
1096 };
1097
1098 static enum callback_status
1099 each_breakpoint_cb(arch_addr_t *key, struct breakpoint **bpp, void *d)
1100 {
1101         struct each_breakpoint_data *data = d;
1102         return data->cb(data->proc, *bpp, data->cb_data);
1103 }
1104
1105 arch_addr_t *
1106 proc_each_breakpoint(struct process *proc, arch_addr_t *start,
1107                      enum callback_status (*cb)(struct process *proc,
1108                                                 struct breakpoint *bp,
1109                                                 void *data), void *data)
1110 {
1111         struct each_breakpoint_data dd = {
1112                 .proc = proc,
1113                 .cb = cb,
1114                 .cb_data = data,
1115         };
1116         return DICT_EACH(proc->breakpoints,
1117                          arch_addr_t, struct breakpoint *, start,
1118                          &each_breakpoint_cb, &dd);
1119 }
1120
1121 int
1122 proc_find_symbol(struct process *proc, struct library_symbol *sym,
1123                  struct library **retlib, struct library_symbol **retsym)
1124 {
1125         struct library *lib = sym->lib;
1126         assert(lib != NULL);
1127
1128         struct library *flib
1129                 = proc_each_library(proc, NULL, library_with_key_cb, &lib->key);
1130         if (flib == NULL)
1131                 return -1;
1132
1133         struct library_symbol *fsym
1134                 = library_each_symbol(flib, NULL, library_symbol_named_cb,
1135                                       (char *)sym->name);
1136         if (fsym == NULL)
1137                 return -1;
1138
1139         if (retlib != NULL)
1140                 *retlib = flib;
1141         if (retsym != NULL)
1142                 *retsym = fsym;
1143
1144         return 0;
1145 }
1146
1147 struct library_symbol *
1148 proc_each_symbol(struct process *proc, struct library_symbol *start_after,
1149                  enum callback_status (*cb)(struct library_symbol *, void *),
1150                  void *data)
1151 {
1152         struct library *lib;
1153         for (lib = start_after != NULL ? start_after->lib : proc->libraries;
1154              lib != NULL; lib = lib->next) {
1155                 start_after = library_each_symbol(lib, start_after, cb, data);
1156                 if (start_after != NULL)
1157                         return start_after;
1158         }
1159
1160         return NULL;
1161 }
1162
1163 #define DEF_READER(NAME, SIZE)                                          \
1164         int                                                             \
1165         NAME(struct process *proc, arch_addr_t addr,                    \
1166              uint##SIZE##_t *lp)                                        \
1167         {                                                               \
1168                 union {                                                 \
1169                         uint##SIZE##_t dst;                             \
1170                         char buf[0];                                    \
1171                 } u;                                                    \
1172                 if (umovebytes(proc, addr, &u.buf, sizeof(u.dst))       \
1173                     != sizeof(u.dst))                                   \
1174                         return -1;                                      \
1175                 *lp = u.dst;                                            \
1176                 return 0;                                               \
1177         }
1178
1179 DEF_READER(proc_read_8, 8)
1180 DEF_READER(proc_read_16, 16)
1181 DEF_READER(proc_read_32, 32)
1182 DEF_READER(proc_read_64, 64)
1183
1184 #undef DEF_READER