I now import functions using their linkage name
[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 #include "filter.h"
41
42 #ifndef OS_HAVE_PROCESS_DATA
43 int
44 os_process_init(struct process *proc)
45 {
46         return 0;
47 }
48
49 void
50 os_process_destroy(struct process *proc)
51 {
52 }
53
54 int
55 os_process_clone(struct process *retp, struct process *proc)
56 {
57         return 0;
58 }
59
60 int
61 os_process_exec(struct process *proc)
62 {
63         return 0;
64 }
65 #endif
66
67 #ifndef ARCH_HAVE_PROCESS_DATA
68 int
69 arch_process_init(struct process *proc)
70 {
71         return 0;
72 }
73
74 void
75 arch_process_destroy(struct process *proc)
76 {
77 }
78
79 int
80 arch_process_clone(struct process *retp, struct process *proc)
81 {
82         return 0;
83 }
84
85 int
86 arch_process_exec(struct process *proc)
87 {
88         return 0;
89 }
90 #endif
91
92 #ifndef ARCH_HAVE_DYNLINK_DONE
93 void
94 arch_dynlink_done(struct process *proc)
95 {
96 }
97 #endif
98
99 static int add_process(struct process *proc, int was_exec);
100 static void unlist_process(struct process *proc);
101
102 static void
103 destroy_unwind(struct process *proc)
104 {
105 #if defined(HAVE_LIBUNWIND)
106         if (proc->unwind_priv != NULL)
107                 _UPT_destroy(proc->unwind_priv);
108         if (proc->unwind_as != NULL)
109                 unw_destroy_addr_space(proc->unwind_as);
110 #endif /* defined(HAVE_LIBUNWIND) */
111
112 #if defined(HAVE_LIBDW)
113         if (proc->dwfl != NULL)
114                 dwfl_end(proc->dwfl);
115 #endif /* defined(HAVE_LIBDW) */
116 }
117
118 static int
119 process_bare_init(struct process *proc, const char *filename,
120                   pid_t pid, int was_exec)
121 {
122         if (!was_exec) {
123                 memset(proc, 0, sizeof(*proc));
124
125                 proc->filename = strdup(filename);
126                 if (proc->filename == NULL) {
127                 fail:
128                         free(proc->filename);
129                         if (proc->breakpoints != NULL) {
130                                 dict_destroy(proc->breakpoints,
131                                              NULL, NULL, NULL);
132                                 free(proc->breakpoints);
133                                 proc->breakpoints = NULL;
134                         }
135                         return -1;
136                 }
137         }
138
139         /* Add process so that we know who the leader is.  */
140         proc->pid = pid;
141         if (add_process(proc, was_exec) < 0)
142                 goto fail;
143         if (proc->leader == NULL) {
144         unlist_and_fail:
145                 if (!was_exec)
146                         unlist_process(proc);
147                 goto fail;
148         }
149
150         if (proc->leader == proc) {
151                 proc->breakpoints = malloc(sizeof(*proc->breakpoints));
152                 if (proc->breakpoints == NULL)
153                         goto unlist_and_fail;
154                 DICT_INIT(proc->breakpoints,
155                           arch_addr_t, struct breakpoint *,
156                           arch_addr_hash, arch_addr_eq, NULL);
157         } else {
158                 proc->breakpoints = NULL;
159         }
160
161 #if defined(HAVE_LIBUNWIND)
162         if (options.bt_depth > 0) {
163                 proc->unwind_priv = _UPT_create(pid);
164                 proc->unwind_as = unw_create_addr_space(&_UPT_accessors, 0);
165
166                 if (proc->unwind_priv == NULL || proc->unwind_as == NULL) {
167                         fprintf(stderr,
168                                 "Couldn't initialize unwinding "
169                                 "for process %d\n", proc->pid);
170                         destroy_unwind(proc);
171                         proc->unwind_priv = NULL;
172                         proc->unwind_as = NULL;
173                 }
174         }
175 #endif /* defined(HAVE_LIBUNWIND) */
176
177 #if defined(HAVE_LIBDW)
178         proc->dwfl = NULL; /* Initialize for leader only on first library.  */
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 static enum callback_status
871 activate_latent_in(struct process *proc, struct library *lib, void *data)
872 {
873         struct library_exported_name *exported;
874         for (exported = data; exported != NULL; exported = exported->next) {
875                 struct library_symbol *libsym = NULL;
876                 while ((libsym = library_each_symbol(lib, libsym,
877                                                      library_symbol_named_cb,
878                                                      (void *)exported->name))
879                        != NULL)
880                         if (libsym->latent
881                             && proc_activate_latent_symbol(proc, libsym) < 0)
882                                 return CBS_FAIL;
883         }
884         return CBS_CONT;
885 }
886
887 void
888 proc_add_library(struct process *proc, struct library *lib)
889 {
890         assert(lib->next == NULL);
891         lib->next = proc->libraries;
892         proc->libraries = lib;
893         debug(DEBUG_PROCESS, "added library %s@%p (%s) to %d",
894               lib->soname, lib->base, lib->pathname, proc->pid);
895
896 #if defined(HAVE_LIBDW)
897         Dwfl *dwfl = NULL;
898
899         /* Setup module tracking for libdwfl unwinding.  */
900         struct process *leader = proc->leader;
901         dwfl = leader->dwfl;
902         if (dwfl == NULL) {
903                 static const Dwfl_Callbacks proc_callbacks = {
904                         .find_elf = dwfl_linux_proc_find_elf,
905                         .find_debuginfo = dwfl_standard_find_debuginfo
906                 };
907                 dwfl = dwfl_begin(&proc_callbacks);
908                 if (dwfl == NULL)
909                         fprintf(stderr,
910                                         "Couldn't initialize libdwfl unwinding "
911                                         "for process %d: %s\n", leader->pid,
912                                         dwfl_errmsg (-1));
913         }
914
915         if (dwfl != NULL) {
916                 dwfl_report_begin_add(dwfl);
917                 if (dwfl_report_elf(dwfl, lib->soname,
918                                                         lib->pathname, -1,
919                                                         (GElf_Addr) lib->base,
920                                                         false) == NULL)
921                         fprintf(stderr,
922                                         "dwfl_report_elf %s@%p (%s) %d: %s\n",
923                                         lib->soname, lib->base, lib->pathname,
924                                         proc->pid, dwfl_errmsg (-1));
925                 dwfl_report_end(dwfl, NULL, NULL);
926
927                 if (options.bt_depth > 0) {
928                         if (leader->dwfl == NULL) {
929                                 int r = dwfl_linux_proc_attach(dwfl,
930                                                                                            leader->pid,
931                                                                                            true);
932                                 if (r == 0)
933                                         leader->dwfl = dwfl;
934                                 else {
935                                         const char *msg;
936                                         dwfl_end(dwfl);
937                                         if (r < 0)
938                                                 msg = dwfl_errmsg(-1);
939                                         else
940                                                 msg = strerror(r);
941                                         fprintf(stderr, "Couldn't initialize "
942                                                 "libdwfl unwinding for "
943                                                 "process %d: %s\n",
944                                                 leader->pid, msg);
945                                 }
946                         }
947                 }
948         }
949
950         if( dwfl != NULL &&
951                 ( filter_matches_library(options.plt_filter,    lib ) ||
952                   filter_matches_library(options.static_filter, lib ) ||
953                   filter_matches_library(options.export_filter, lib ) ) )
954         {
955                 import_DWARF_prototypes( lib->protolib, lib, dwfl );
956         }
957
958 #endif /* defined(HAVE_LIBDW) */
959
960         /* Insert breakpoints for all active (non-latent) symbols.  */
961         struct library_symbol *libsym = NULL;
962         while ((libsym = library_each_symbol(lib, libsym,
963                                              cb_breakpoint_for_symbol,
964                                              proc)) != NULL)
965                 fprintf(stderr,
966                         "Couldn't insert breakpoint for %s to %d: %s.\n",
967                         libsym->name, proc->pid, strerror(errno));
968
969         /* Look through export list of the new library and compare it
970          * with latent symbols of all libraries (including this
971          * library itself).  */
972         struct library *lib2 = NULL;
973         while ((lib2 = proc_each_library(proc, lib2, activate_latent_in,
974                                          lib->exported_names)) != NULL)
975                 fprintf(stderr,
976                         "Couldn't activate latent symbols for %s in %d: %s.\n",
977                         lib2->soname, proc->pid, strerror(errno));
978 }
979
980 int
981 proc_remove_library(struct process *proc, struct library *lib)
982 {
983         struct library **libp;
984         for (libp = &proc->libraries; *libp != NULL; libp = &(*libp)->next)
985                 if (*libp == lib) {
986                         *libp = lib->next;
987                         return 0;
988                 }
989         return -1;
990 }
991
992 struct library *
993 proc_each_library(struct process *proc, struct library *it,
994                   enum callback_status (*cb)(struct process *proc,
995                                              struct library *lib, void *data),
996                   void *data)
997 {
998         if (it == NULL)
999                 it = proc->libraries;
1000         else
1001                 it = it->next;
1002
1003         while (it != NULL) {
1004                 struct library *next = it->next;
1005
1006                 switch (cb(proc, it, data)) {
1007                 case CBS_FAIL:
1008                         /* XXX handle me */
1009                 case CBS_STOP:
1010                         return it;
1011                 case CBS_CONT:
1012                         break;
1013                 }
1014
1015                 it = next;
1016         }
1017
1018         return NULL;
1019 }
1020
1021 static void
1022 check_leader(struct process *proc)
1023 {
1024         /* Only the group leader should be getting the breakpoints and
1025          * thus have ->breakpoint initialized.  */
1026         assert(proc->leader != NULL);
1027         assert(proc->leader == proc);
1028         assert(proc->breakpoints != NULL);
1029 }
1030
1031 int
1032 proc_add_breakpoint(struct process *proc, struct breakpoint *bp)
1033 {
1034         debug(DEBUG_FUNCTION, "proc_add_breakpoint(pid=%d, %s@%p)",
1035               proc->pid, breakpoint_name(bp), bp->addr);
1036         check_leader(proc);
1037
1038         /* XXX We might merge bp->libsym instead of the following
1039          * assert, but that's not necessary right now.  Read the
1040          * comment in breakpoint_for_symbol.  */
1041         assert(dict_find(proc->breakpoints, &bp->addr) == NULL);
1042
1043         if (DICT_INSERT(proc->breakpoints, &bp->addr, &bp) < 0) {
1044                 fprintf(stderr,
1045                         "couldn't enter breakpoint %s@%p to dictionary: %s\n",
1046                         breakpoint_name(bp), bp->addr, strerror(errno));
1047                 return -1;
1048         }
1049
1050         return 0;
1051 }
1052
1053 void
1054 proc_remove_breakpoint(struct process *proc, struct breakpoint *bp)
1055 {
1056         debug(DEBUG_FUNCTION, "proc_remove_breakpoint(pid=%d, %s@%p)",
1057               proc->pid, breakpoint_name(bp), bp->addr);
1058         check_leader(proc);
1059         int rc = DICT_ERASE(proc->breakpoints, &bp->addr, struct breakpoint *,
1060                             NULL, NULL, NULL);
1061         assert(rc == 0);
1062 }
1063
1064 struct each_breakpoint_data
1065 {
1066         struct process *proc;
1067         enum callback_status (*cb)(struct process *proc,
1068                                    struct breakpoint *bp,
1069                                    void *data);
1070         void *cb_data;
1071 };
1072
1073 static enum callback_status
1074 each_breakpoint_cb(arch_addr_t *key, struct breakpoint **bpp, void *d)
1075 {
1076         struct each_breakpoint_data *data = d;
1077         return data->cb(data->proc, *bpp, data->cb_data);
1078 }
1079
1080 arch_addr_t *
1081 proc_each_breakpoint(struct process *proc, arch_addr_t *start,
1082                      enum callback_status (*cb)(struct process *proc,
1083                                                 struct breakpoint *bp,
1084                                                 void *data), void *data)
1085 {
1086         struct each_breakpoint_data dd = {
1087                 .proc = proc,
1088                 .cb = cb,
1089                 .cb_data = data,
1090         };
1091         return DICT_EACH(proc->breakpoints,
1092                          arch_addr_t, struct breakpoint *, start,
1093                          &each_breakpoint_cb, &dd);
1094 }
1095
1096 int
1097 proc_find_symbol(struct process *proc, struct library_symbol *sym,
1098                  struct library **retlib, struct library_symbol **retsym)
1099 {
1100         struct library *lib = sym->lib;
1101         assert(lib != NULL);
1102
1103         struct library *flib
1104                 = proc_each_library(proc, NULL, library_with_key_cb, &lib->key);
1105         if (flib == NULL)
1106                 return -1;
1107
1108         struct library_symbol *fsym
1109                 = library_each_symbol(flib, NULL, library_symbol_named_cb,
1110                                       (char *)sym->name);
1111         if (fsym == NULL)
1112                 return -1;
1113
1114         if (retlib != NULL)
1115                 *retlib = flib;
1116         if (retsym != NULL)
1117                 *retsym = fsym;
1118
1119         return 0;
1120 }
1121
1122 struct library_symbol *
1123 proc_each_symbol(struct process *proc, struct library_symbol *start_after,
1124                  enum callback_status (*cb)(struct library_symbol *, void *),
1125                  void *data)
1126 {
1127         struct library *lib;
1128         for (lib = start_after != NULL ? start_after->lib : proc->libraries;
1129              lib != NULL; lib = lib->next) {
1130                 start_after = library_each_symbol(lib, start_after, cb, data);
1131                 if (start_after != NULL)
1132                         return start_after;
1133         }
1134
1135         return NULL;
1136 }
1137
1138 #define DEF_READER(NAME, SIZE)                                          \
1139         int                                                             \
1140         NAME(struct process *proc, arch_addr_t addr,                    \
1141              uint##SIZE##_t *lp)                                        \
1142         {                                                               \
1143                 union {                                                 \
1144                         uint##SIZE##_t dst;                             \
1145                         char buf[0];                                    \
1146                 } u;                                                    \
1147                 if (umovebytes(proc, addr, &u.buf, sizeof(u.dst))       \
1148                     != sizeof(u.dst))                                   \
1149                         return -1;                                      \
1150                 *lp = u.dst;                                            \
1151                 return 0;                                               \
1152         }
1153
1154 DEF_READER(proc_read_8, 8)
1155 DEF_READER(proc_read_16, 16)
1156 DEF_READER(proc_read_32, 32)
1157 DEF_READER(proc_read_64, 64)
1158
1159 #undef DEF_READER