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