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