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