Add tests for PR ld/16452 and PR ld/16457
[platform/upstream/binutils.git] / gdb / record-full.c
1 /* Process record and replay target for GDB, the GNU debugger.
2
3    Copyright (C) 2013-2014 Free Software Foundation, Inc.
4
5    This file is part of GDB.
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU 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, see <http://www.gnu.org/licenses/>.  */
19
20 #include "defs.h"
21 #include "gdbcmd.h"
22 #include "regcache.h"
23 #include "gdbthread.h"
24 #include "event-top.h"
25 #include "completer.h"
26 #include "arch-utils.h"
27 #include "gdbcore.h"
28 #include "exec.h"
29 #include "record.h"
30 #include "record-full.h"
31 #include "elf-bfd.h"
32 #include "gcore.h"
33 #include "event-loop.h"
34 #include "inf-loop.h"
35 #include "gdb_bfd.h"
36 #include "observer.h"
37 #include "infrun.h"
38
39 #include <signal.h>
40
41 /* This module implements "target record-full", also known as "process
42    record and replay".  This target sits on top of a "normal" target
43    (a target that "has execution"), and provides a record and replay
44    functionality, including reverse debugging.
45
46    Target record has two modes: recording, and replaying.
47
48    In record mode, we intercept the to_resume and to_wait methods.
49    Whenever gdb resumes the target, we run the target in single step
50    mode, and we build up an execution log in which, for each executed
51    instruction, we record all changes in memory and register state.
52    This is invisible to the user, to whom it just looks like an
53    ordinary debugging session (except for performance degredation).
54
55    In replay mode, instead of actually letting the inferior run as a
56    process, we simulate its execution by playing back the recorded
57    execution log.  For each instruction in the log, we simulate the
58    instruction's side effects by duplicating the changes that it would
59    have made on memory and registers.  */
60
61 #define DEFAULT_RECORD_FULL_INSN_MAX_NUM        200000
62
63 #define RECORD_FULL_IS_REPLAY \
64      (record_full_list->next || execution_direction == EXEC_REVERSE)
65
66 #define RECORD_FULL_FILE_MAGIC  netorder32(0x20091016)
67
68 /* These are the core structs of the process record functionality.
69
70    A record_full_entry is a record of the value change of a register
71    ("record_full_reg") or a part of memory ("record_full_mem").  And each
72    instruction must have a struct record_full_entry ("record_full_end")
73    that indicates that this is the last struct record_full_entry of this
74    instruction.
75
76    Each struct record_full_entry is linked to "record_full_list" by "prev"
77    and "next" pointers.  */
78
79 struct record_full_mem_entry
80 {
81   CORE_ADDR addr;
82   int len;
83   /* Set this flag if target memory for this entry
84      can no longer be accessed.  */
85   int mem_entry_not_accessible;
86   union
87   {
88     gdb_byte *ptr;
89     gdb_byte buf[sizeof (gdb_byte *)];
90   } u;
91 };
92
93 struct record_full_reg_entry
94 {
95   unsigned short num;
96   unsigned short len;
97   union 
98   {
99     gdb_byte *ptr;
100     gdb_byte buf[2 * sizeof (gdb_byte *)];
101   } u;
102 };
103
104 struct record_full_end_entry
105 {
106   enum gdb_signal sigval;
107   ULONGEST insn_num;
108 };
109
110 enum record_full_type
111 {
112   record_full_end = 0,
113   record_full_reg,
114   record_full_mem
115 };
116
117 /* This is the data structure that makes up the execution log.
118
119    The execution log consists of a single linked list of entries
120    of type "struct record_full_entry".  It is doubly linked so that it
121    can be traversed in either direction.
122
123    The start of the list is anchored by a struct called
124    "record_full_first".  The pointer "record_full_list" either points
125    to the last entry that was added to the list (in record mode), or to
126    the next entry in the list that will be executed (in replay mode).
127
128    Each list element (struct record_full_entry), in addition to next
129    and prev pointers, consists of a union of three entry types: mem,
130    reg, and end.  A field called "type" determines which entry type is
131    represented by a given list element.
132
133    Each instruction that is added to the execution log is represented
134    by a variable number of list elements ('entries').  The instruction
135    will have one "reg" entry for each register that is changed by 
136    executing the instruction (including the PC in every case).  It 
137    will also have one "mem" entry for each memory change.  Finally,
138    each instruction will have an "end" entry that separates it from
139    the changes associated with the next instruction.  */
140
141 struct record_full_entry
142 {
143   struct record_full_entry *prev;
144   struct record_full_entry *next;
145   enum record_full_type type;
146   union
147   {
148     /* reg */
149     struct record_full_reg_entry reg;
150     /* mem */
151     struct record_full_mem_entry mem;
152     /* end */
153     struct record_full_end_entry end;
154   } u;
155 };
156
157 /* If true, query if PREC cannot record memory
158    change of next instruction.  */
159 int record_full_memory_query = 0;
160
161 struct record_full_core_buf_entry
162 {
163   struct record_full_core_buf_entry *prev;
164   struct target_section *p;
165   bfd_byte *buf;
166 };
167
168 /* Record buf with core target.  */
169 static gdb_byte *record_full_core_regbuf = NULL;
170 static struct target_section *record_full_core_start;
171 static struct target_section *record_full_core_end;
172 static struct record_full_core_buf_entry *record_full_core_buf_list = NULL;
173
174 /* The following variables are used for managing the linked list that
175    represents the execution log.
176
177    record_full_first is the anchor that holds down the beginning of
178    the list.
179
180    record_full_list serves two functions:
181      1) In record mode, it anchors the end of the list.
182      2) In replay mode, it traverses the list and points to
183         the next instruction that must be emulated.
184
185    record_full_arch_list_head and record_full_arch_list_tail are used
186    to manage a separate list, which is used to build up the change
187    elements of the currently executing instruction during record mode.
188    When this instruction has been completely annotated in the "arch
189    list", it will be appended to the main execution log.  */
190
191 static struct record_full_entry record_full_first;
192 static struct record_full_entry *record_full_list = &record_full_first;
193 static struct record_full_entry *record_full_arch_list_head = NULL;
194 static struct record_full_entry *record_full_arch_list_tail = NULL;
195
196 /* 1 ask user. 0 auto delete the last struct record_full_entry.  */
197 static int record_full_stop_at_limit = 1;
198 /* Maximum allowed number of insns in execution log.  */
199 static unsigned int record_full_insn_max_num
200         = DEFAULT_RECORD_FULL_INSN_MAX_NUM;
201 /* Actual count of insns presently in execution log.  */
202 static unsigned int record_full_insn_num = 0;
203 /* Count of insns logged so far (may be larger
204    than count of insns presently in execution log).  */
205 static ULONGEST record_full_insn_count;
206
207 /* The target_ops of process record.  */
208 static struct target_ops record_full_ops;
209 static struct target_ops record_full_core_ops;
210
211 /* See record-full.h.  */
212
213 int
214 record_full_is_used (void)
215 {
216   struct target_ops *t;
217
218   t = find_record_target ();
219   return (t == &record_full_ops
220           || t == &record_full_core_ops);
221 }
222
223
224 /* Command lists for "set/show record full".  */
225 static struct cmd_list_element *set_record_full_cmdlist;
226 static struct cmd_list_element *show_record_full_cmdlist;
227
228 /* Command list for "record full".  */
229 static struct cmd_list_element *record_full_cmdlist;
230
231 static void record_full_goto_insn (struct record_full_entry *entry,
232                                    enum exec_direction_kind dir);
233 static void record_full_save (struct target_ops *self,
234                               const char *recfilename);
235
236 /* Alloc and free functions for record_full_reg, record_full_mem, and
237    record_full_end entries.  */
238
239 /* Alloc a record_full_reg record entry.  */
240
241 static inline struct record_full_entry *
242 record_full_reg_alloc (struct regcache *regcache, int regnum)
243 {
244   struct record_full_entry *rec;
245   struct gdbarch *gdbarch = get_regcache_arch (regcache);
246
247   rec = xcalloc (1, sizeof (struct record_full_entry));
248   rec->type = record_full_reg;
249   rec->u.reg.num = regnum;
250   rec->u.reg.len = register_size (gdbarch, regnum);
251   if (rec->u.reg.len > sizeof (rec->u.reg.u.buf))
252     rec->u.reg.u.ptr = (gdb_byte *) xmalloc (rec->u.reg.len);
253
254   return rec;
255 }
256
257 /* Free a record_full_reg record entry.  */
258
259 static inline void
260 record_full_reg_release (struct record_full_entry *rec)
261 {
262   gdb_assert (rec->type == record_full_reg);
263   if (rec->u.reg.len > sizeof (rec->u.reg.u.buf))
264     xfree (rec->u.reg.u.ptr);
265   xfree (rec);
266 }
267
268 /* Alloc a record_full_mem record entry.  */
269
270 static inline struct record_full_entry *
271 record_full_mem_alloc (CORE_ADDR addr, int len)
272 {
273   struct record_full_entry *rec;
274
275   rec = xcalloc (1, sizeof (struct record_full_entry));
276   rec->type = record_full_mem;
277   rec->u.mem.addr = addr;
278   rec->u.mem.len = len;
279   if (rec->u.mem.len > sizeof (rec->u.mem.u.buf))
280     rec->u.mem.u.ptr = (gdb_byte *) xmalloc (len);
281
282   return rec;
283 }
284
285 /* Free a record_full_mem record entry.  */
286
287 static inline void
288 record_full_mem_release (struct record_full_entry *rec)
289 {
290   gdb_assert (rec->type == record_full_mem);
291   if (rec->u.mem.len > sizeof (rec->u.mem.u.buf))
292     xfree (rec->u.mem.u.ptr);
293   xfree (rec);
294 }
295
296 /* Alloc a record_full_end record entry.  */
297
298 static inline struct record_full_entry *
299 record_full_end_alloc (void)
300 {
301   struct record_full_entry *rec;
302
303   rec = xcalloc (1, sizeof (struct record_full_entry));
304   rec->type = record_full_end;
305
306   return rec;
307 }
308
309 /* Free a record_full_end record entry.  */
310
311 static inline void
312 record_full_end_release (struct record_full_entry *rec)
313 {
314   xfree (rec);
315 }
316
317 /* Free one record entry, any type.
318    Return entry->type, in case caller wants to know.  */
319
320 static inline enum record_full_type
321 record_full_entry_release (struct record_full_entry *rec)
322 {
323   enum record_full_type type = rec->type;
324
325   switch (type) {
326   case record_full_reg:
327     record_full_reg_release (rec);
328     break;
329   case record_full_mem:
330     record_full_mem_release (rec);
331     break;
332   case record_full_end:
333     record_full_end_release (rec);
334     break;
335   }
336   return type;
337 }
338
339 /* Free all record entries in list pointed to by REC.  */
340
341 static void
342 record_full_list_release (struct record_full_entry *rec)
343 {
344   if (!rec)
345     return;
346
347   while (rec->next)
348     rec = rec->next;
349
350   while (rec->prev)
351     {
352       rec = rec->prev;
353       record_full_entry_release (rec->next);
354     }
355
356   if (rec == &record_full_first)
357     {
358       record_full_insn_num = 0;
359       record_full_first.next = NULL;
360     }
361   else
362     record_full_entry_release (rec);
363 }
364
365 /* Free all record entries forward of the given list position.  */
366
367 static void
368 record_full_list_release_following (struct record_full_entry *rec)
369 {
370   struct record_full_entry *tmp = rec->next;
371
372   rec->next = NULL;
373   while (tmp)
374     {
375       rec = tmp->next;
376       if (record_full_entry_release (tmp) == record_full_end)
377         {
378           record_full_insn_num--;
379           record_full_insn_count--;
380         }
381       tmp = rec;
382     }
383 }
384
385 /* Delete the first instruction from the beginning of the log, to make
386    room for adding a new instruction at the end of the log.
387
388    Note -- this function does not modify record_full_insn_num.  */
389
390 static void
391 record_full_list_release_first (void)
392 {
393   struct record_full_entry *tmp;
394
395   if (!record_full_first.next)
396     return;
397
398   /* Loop until a record_full_end.  */
399   while (1)
400     {
401       /* Cut record_full_first.next out of the linked list.  */
402       tmp = record_full_first.next;
403       record_full_first.next = tmp->next;
404       tmp->next->prev = &record_full_first;
405
406       /* tmp is now isolated, and can be deleted.  */
407       if (record_full_entry_release (tmp) == record_full_end)
408         break;  /* End loop at first record_full_end.  */
409
410       if (!record_full_first.next)
411         {
412           gdb_assert (record_full_insn_num == 1);
413           break;        /* End loop when list is empty.  */
414         }
415     }
416 }
417
418 /* Add a struct record_full_entry to record_full_arch_list.  */
419
420 static void
421 record_full_arch_list_add (struct record_full_entry *rec)
422 {
423   if (record_debug > 1)
424     fprintf_unfiltered (gdb_stdlog,
425                         "Process record: record_full_arch_list_add %s.\n",
426                         host_address_to_string (rec));
427
428   if (record_full_arch_list_tail)
429     {
430       record_full_arch_list_tail->next = rec;
431       rec->prev = record_full_arch_list_tail;
432       record_full_arch_list_tail = rec;
433     }
434   else
435     {
436       record_full_arch_list_head = rec;
437       record_full_arch_list_tail = rec;
438     }
439 }
440
441 /* Return the value storage location of a record entry.  */
442 static inline gdb_byte *
443 record_full_get_loc (struct record_full_entry *rec)
444 {
445   switch (rec->type) {
446   case record_full_mem:
447     if (rec->u.mem.len > sizeof (rec->u.mem.u.buf))
448       return rec->u.mem.u.ptr;
449     else
450       return rec->u.mem.u.buf;
451   case record_full_reg:
452     if (rec->u.reg.len > sizeof (rec->u.reg.u.buf))
453       return rec->u.reg.u.ptr;
454     else
455       return rec->u.reg.u.buf;
456   case record_full_end:
457   default:
458     gdb_assert_not_reached ("unexpected record_full_entry type");
459     return NULL;
460   }
461 }
462
463 /* Record the value of a register NUM to record_full_arch_list.  */
464
465 int
466 record_full_arch_list_add_reg (struct regcache *regcache, int regnum)
467 {
468   struct record_full_entry *rec;
469
470   if (record_debug > 1)
471     fprintf_unfiltered (gdb_stdlog,
472                         "Process record: add register num = %d to "
473                         "record list.\n",
474                         regnum);
475
476   rec = record_full_reg_alloc (regcache, regnum);
477
478   regcache_raw_read (regcache, regnum, record_full_get_loc (rec));
479
480   record_full_arch_list_add (rec);
481
482   return 0;
483 }
484
485 /* Record the value of a region of memory whose address is ADDR and
486    length is LEN to record_full_arch_list.  */
487
488 int
489 record_full_arch_list_add_mem (CORE_ADDR addr, int len)
490 {
491   struct record_full_entry *rec;
492
493   if (record_debug > 1)
494     fprintf_unfiltered (gdb_stdlog,
495                         "Process record: add mem addr = %s len = %d to "
496                         "record list.\n",
497                         paddress (target_gdbarch (), addr), len);
498
499   if (!addr)    /* FIXME: Why?  Some arch must permit it...  */
500     return 0;
501
502   rec = record_full_mem_alloc (addr, len);
503
504   if (record_read_memory (target_gdbarch (), addr,
505                           record_full_get_loc (rec), len))
506     {
507       record_full_mem_release (rec);
508       return -1;
509     }
510
511   record_full_arch_list_add (rec);
512
513   return 0;
514 }
515
516 /* Add a record_full_end type struct record_full_entry to
517    record_full_arch_list.  */
518
519 int
520 record_full_arch_list_add_end (void)
521 {
522   struct record_full_entry *rec;
523
524   if (record_debug > 1)
525     fprintf_unfiltered (gdb_stdlog,
526                         "Process record: add end to arch list.\n");
527
528   rec = record_full_end_alloc ();
529   rec->u.end.sigval = GDB_SIGNAL_0;
530   rec->u.end.insn_num = ++record_full_insn_count;
531
532   record_full_arch_list_add (rec);
533
534   return 0;
535 }
536
537 static void
538 record_full_check_insn_num (int set_terminal)
539 {
540   if (record_full_insn_num == record_full_insn_max_num)
541     {
542       /* Ask user what to do.  */
543       if (record_full_stop_at_limit)
544         {
545           int q;
546
547           if (set_terminal)
548             target_terminal_ours ();
549           q = yquery (_("Do you want to auto delete previous execution "
550                         "log entries when record/replay buffer becomes "
551                         "full (record full stop-at-limit)?"));
552           if (set_terminal)
553             target_terminal_inferior ();
554           if (q)
555             record_full_stop_at_limit = 0;
556           else
557             error (_("Process record: stopped by user."));
558         }
559     }
560 }
561
562 static void
563 record_full_arch_list_cleanups (void *ignore)
564 {
565   record_full_list_release (record_full_arch_list_tail);
566 }
567
568 /* Before inferior step (when GDB record the running message, inferior
569    only can step), GDB will call this function to record the values to
570    record_full_list.  This function will call gdbarch_process_record to
571    record the running message of inferior and set them to
572    record_full_arch_list, and add it to record_full_list.  */
573
574 static int
575 record_full_message (struct regcache *regcache, enum gdb_signal signal)
576 {
577   int ret;
578   struct gdbarch *gdbarch = get_regcache_arch (regcache);
579   struct cleanup *old_cleanups
580     = make_cleanup (record_full_arch_list_cleanups, 0);
581
582   record_full_arch_list_head = NULL;
583   record_full_arch_list_tail = NULL;
584
585   /* Check record_full_insn_num.  */
586   record_full_check_insn_num (1);
587
588   /* If gdb sends a signal value to target_resume,
589      save it in the 'end' field of the previous instruction.
590
591      Maybe process record should record what really happened,
592      rather than what gdb pretends has happened.
593
594      So if Linux delivered the signal to the child process during
595      the record mode, we will record it and deliver it again in
596      the replay mode.
597
598      If user says "ignore this signal" during the record mode, then
599      it will be ignored again during the replay mode (no matter if
600      the user says something different, like "deliver this signal"
601      during the replay mode).
602
603      User should understand that nothing he does during the replay
604      mode will change the behavior of the child.  If he tries,
605      then that is a user error.
606
607      But we should still deliver the signal to gdb during the replay,
608      if we delivered it during the recording.  Therefore we should
609      record the signal during record_full_wait, not
610      record_full_resume.  */
611   if (record_full_list != &record_full_first)  /* FIXME better way to check */
612     {
613       gdb_assert (record_full_list->type == record_full_end);
614       record_full_list->u.end.sigval = signal;
615     }
616
617   if (signal == GDB_SIGNAL_0
618       || !gdbarch_process_record_signal_p (gdbarch))
619     ret = gdbarch_process_record (gdbarch,
620                                   regcache,
621                                   regcache_read_pc (regcache));
622   else
623     ret = gdbarch_process_record_signal (gdbarch,
624                                          regcache,
625                                          signal);
626
627   if (ret > 0)
628     error (_("Process record: inferior program stopped."));
629   if (ret < 0)
630     error (_("Process record: failed to record execution log."));
631
632   discard_cleanups (old_cleanups);
633
634   record_full_list->next = record_full_arch_list_head;
635   record_full_arch_list_head->prev = record_full_list;
636   record_full_list = record_full_arch_list_tail;
637
638   if (record_full_insn_num == record_full_insn_max_num)
639     record_full_list_release_first ();
640   else
641     record_full_insn_num++;
642
643   return 1;
644 }
645
646 struct record_full_message_args {
647   struct regcache *regcache;
648   enum gdb_signal signal;
649 };
650
651 static int
652 record_full_message_wrapper (void *args)
653 {
654   struct record_full_message_args *record_full_args = args;
655
656   return record_full_message (record_full_args->regcache,
657                               record_full_args->signal);
658 }
659
660 static int
661 record_full_message_wrapper_safe (struct regcache *regcache,
662                                   enum gdb_signal signal)
663 {
664   struct record_full_message_args args;
665
666   args.regcache = regcache;
667   args.signal = signal;
668
669   return catch_errors (record_full_message_wrapper, &args, NULL,
670                        RETURN_MASK_ALL);
671 }
672
673 /* Set to 1 if record_full_store_registers and record_full_xfer_partial
674    doesn't need record.  */
675
676 static int record_full_gdb_operation_disable = 0;
677
678 struct cleanup *
679 record_full_gdb_operation_disable_set (void)
680 {
681   struct cleanup *old_cleanups = NULL;
682
683   old_cleanups =
684     make_cleanup_restore_integer (&record_full_gdb_operation_disable);
685   record_full_gdb_operation_disable = 1;
686
687   return old_cleanups;
688 }
689
690 /* Flag set to TRUE for target_stopped_by_watchpoint.  */
691 static int record_full_hw_watchpoint = 0;
692
693 /* Execute one instruction from the record log.  Each instruction in
694    the log will be represented by an arbitrary sequence of register
695    entries and memory entries, followed by an 'end' entry.  */
696
697 static inline void
698 record_full_exec_insn (struct regcache *regcache,
699                        struct gdbarch *gdbarch,
700                        struct record_full_entry *entry)
701 {
702   switch (entry->type)
703     {
704     case record_full_reg: /* reg */
705       {
706         gdb_byte reg[MAX_REGISTER_SIZE];
707
708         if (record_debug > 1)
709           fprintf_unfiltered (gdb_stdlog,
710                               "Process record: record_full_reg %s to "
711                               "inferior num = %d.\n",
712                               host_address_to_string (entry),
713                               entry->u.reg.num);
714
715         regcache_cooked_read (regcache, entry->u.reg.num, reg);
716         regcache_cooked_write (regcache, entry->u.reg.num, 
717                                record_full_get_loc (entry));
718         memcpy (record_full_get_loc (entry), reg, entry->u.reg.len);
719       }
720       break;
721
722     case record_full_mem: /* mem */
723       {
724         /* Nothing to do if the entry is flagged not_accessible.  */
725         if (!entry->u.mem.mem_entry_not_accessible)
726           {
727             gdb_byte *mem = alloca (entry->u.mem.len);
728
729             if (record_debug > 1)
730               fprintf_unfiltered (gdb_stdlog,
731                                   "Process record: record_full_mem %s to "
732                                   "inferior addr = %s len = %d.\n",
733                                   host_address_to_string (entry),
734                                   paddress (gdbarch, entry->u.mem.addr),
735                                   entry->u.mem.len);
736
737             if (record_read_memory (gdbarch,
738                                     entry->u.mem.addr, mem, entry->u.mem.len))
739               entry->u.mem.mem_entry_not_accessible = 1;
740             else
741               {
742                 if (target_write_memory (entry->u.mem.addr, 
743                                          record_full_get_loc (entry),
744                                          entry->u.mem.len))
745                   {
746                     entry->u.mem.mem_entry_not_accessible = 1;
747                     if (record_debug)
748                       warning (_("Process record: error writing memory at "
749                                  "addr = %s len = %d."),
750                                paddress (gdbarch, entry->u.mem.addr),
751                                entry->u.mem.len);
752                   }
753                 else
754                   {
755                     memcpy (record_full_get_loc (entry), mem,
756                             entry->u.mem.len);
757
758                     /* We've changed memory --- check if a hardware
759                        watchpoint should trap.  Note that this
760                        presently assumes the target beneath supports
761                        continuable watchpoints.  On non-continuable
762                        watchpoints target, we'll want to check this
763                        _before_ actually doing the memory change, and
764                        not doing the change at all if the watchpoint
765                        traps.  */
766                     if (hardware_watchpoint_inserted_in_range
767                         (get_regcache_aspace (regcache),
768                          entry->u.mem.addr, entry->u.mem.len))
769                       record_full_hw_watchpoint = 1;
770                   }
771               }
772           }
773       }
774       break;
775     }
776 }
777
778 static void record_full_restore (void);
779
780 /* Asynchronous signal handle registered as event loop source for when
781    we have pending events ready to be passed to the core.  */
782
783 static struct async_event_handler *record_full_async_inferior_event_token;
784
785 static void
786 record_full_async_inferior_event_handler (gdb_client_data data)
787 {
788   inferior_event_handler (INF_REG_EVENT, NULL);
789 }
790
791 /* Open the process record target.  */
792
793 static void
794 record_full_core_open_1 (const char *name, int from_tty)
795 {
796   struct regcache *regcache = get_current_regcache ();
797   int regnum = gdbarch_num_regs (get_regcache_arch (regcache));
798   int i;
799
800   /* Get record_full_core_regbuf.  */
801   target_fetch_registers (regcache, -1);
802   record_full_core_regbuf = xmalloc (MAX_REGISTER_SIZE * regnum);
803   for (i = 0; i < regnum; i ++)
804     regcache_raw_collect (regcache, i,
805                           record_full_core_regbuf + MAX_REGISTER_SIZE * i);
806
807   /* Get record_full_core_start and record_full_core_end.  */
808   if (build_section_table (core_bfd, &record_full_core_start,
809                            &record_full_core_end))
810     {
811       xfree (record_full_core_regbuf);
812       record_full_core_regbuf = NULL;
813       error (_("\"%s\": Can't find sections: %s"),
814              bfd_get_filename (core_bfd), bfd_errmsg (bfd_get_error ()));
815     }
816
817   push_target (&record_full_core_ops);
818   record_full_restore ();
819 }
820
821 /* "to_open" target method for 'live' processes.  */
822
823 static void
824 record_full_open_1 (const char *name, int from_tty)
825 {
826   if (record_debug)
827     fprintf_unfiltered (gdb_stdlog, "Process record: record_full_open\n");
828
829   /* check exec */
830   if (!target_has_execution)
831     error (_("Process record: the program is not being run."));
832   if (non_stop)
833     error (_("Process record target can't debug inferior in non-stop mode "
834              "(non-stop)."));
835
836   if (!gdbarch_process_record_p (target_gdbarch ()))
837     error (_("Process record: the current architecture doesn't support "
838              "record function."));
839
840   push_target (&record_full_ops);
841 }
842
843 static void record_full_init_record_breakpoints (void);
844
845 /* "to_open" target method.  Open the process record target.  */
846
847 static void
848 record_full_open (const char *name, int from_tty)
849 {
850   struct target_ops *t;
851
852   if (record_debug)
853     fprintf_unfiltered (gdb_stdlog, "Process record: record_full_open\n");
854
855   record_preopen ();
856
857   /* Reset */
858   record_full_insn_num = 0;
859   record_full_insn_count = 0;
860   record_full_list = &record_full_first;
861   record_full_list->next = NULL;
862
863   if (core_bfd)
864     record_full_core_open_1 (name, from_tty);
865   else
866     record_full_open_1 (name, from_tty);
867
868   /* Register extra event sources in the event loop.  */
869   record_full_async_inferior_event_token
870     = create_async_event_handler (record_full_async_inferior_event_handler,
871                                   NULL);
872
873   record_full_init_record_breakpoints ();
874
875   observer_notify_record_changed (current_inferior (),  1);
876 }
877
878 /* "to_close" target method.  Close the process record target.  */
879
880 static void
881 record_full_close (struct target_ops *self)
882 {
883   struct record_full_core_buf_entry *entry;
884
885   if (record_debug)
886     fprintf_unfiltered (gdb_stdlog, "Process record: record_full_close\n");
887
888   record_full_list_release (record_full_list);
889
890   /* Release record_full_core_regbuf.  */
891   if (record_full_core_regbuf)
892     {
893       xfree (record_full_core_regbuf);
894       record_full_core_regbuf = NULL;
895     }
896
897   /* Release record_full_core_buf_list.  */
898   if (record_full_core_buf_list)
899     {
900       for (entry = record_full_core_buf_list->prev; entry;
901            entry = entry->prev)
902         {
903           xfree (record_full_core_buf_list);
904           record_full_core_buf_list = entry;
905         }
906       record_full_core_buf_list = NULL;
907     }
908
909   if (record_full_async_inferior_event_token)
910     delete_async_event_handler (&record_full_async_inferior_event_token);
911 }
912
913 static int record_full_resume_step = 0;
914
915 /* True if we've been resumed, and so each record_full_wait call should
916    advance execution.  If this is false, record_full_wait will return a
917    TARGET_WAITKIND_IGNORE.  */
918 static int record_full_resumed = 0;
919
920 /* The execution direction of the last resume we got.  This is
921    necessary for async mode.  Vis (order is not strictly accurate):
922
923    1. user has the global execution direction set to forward
924    2. user does a reverse-step command
925    3. record_full_resume is called with global execution direction
926       temporarily switched to reverse
927    4. GDB's execution direction is reverted back to forward
928    5. target record notifies event loop there's an event to handle
929    6. infrun asks the target which direction was it going, and switches
930       the global execution direction accordingly (to reverse)
931    7. infrun polls an event out of the record target, and handles it
932    8. GDB goes back to the event loop, and goto #4.
933 */
934 static enum exec_direction_kind record_full_execution_dir = EXEC_FORWARD;
935
936 /* "to_resume" target method.  Resume the process record target.  */
937
938 static void
939 record_full_resume (struct target_ops *ops, ptid_t ptid, int step,
940                     enum gdb_signal signal)
941 {
942   record_full_resume_step = step;
943   record_full_resumed = 1;
944   record_full_execution_dir = execution_direction;
945
946   if (!RECORD_FULL_IS_REPLAY)
947     {
948       struct gdbarch *gdbarch = target_thread_architecture (ptid);
949
950       record_full_message (get_current_regcache (), signal);
951
952       if (!step)
953         {
954           /* This is not hard single step.  */
955           if (!gdbarch_software_single_step_p (gdbarch))
956             {
957               /* This is a normal continue.  */
958               step = 1;
959             }
960           else
961             {
962               /* This arch support soft sigle step.  */
963               if (single_step_breakpoints_inserted ())
964                 {
965                   /* This is a soft single step.  */
966                   record_full_resume_step = 1;
967                 }
968               else
969                 {
970                   /* This is a continue.
971                      Try to insert a soft single step breakpoint.  */
972                   if (!gdbarch_software_single_step (gdbarch,
973                                                      get_current_frame ()))
974                     {
975                       /* This system don't want use soft single step.
976                          Use hard sigle step.  */
977                       step = 1;
978                     }
979                 }
980             }
981         }
982
983       /* Make sure the target beneath reports all signals.  */
984       target_pass_signals (0, NULL);
985
986       ops->beneath->to_resume (ops->beneath, ptid, step, signal);
987     }
988
989   /* We are about to start executing the inferior (or simulate it),
990      let's register it with the event loop.  */
991   if (target_can_async_p ())
992     {
993       target_async (inferior_event_handler, 0);
994       /* Notify the event loop there's an event to wait for.  We do
995          most of the work in record_full_wait.  */
996       mark_async_event_handler (record_full_async_inferior_event_token);
997     }
998 }
999
1000 static int record_full_get_sig = 0;
1001
1002 /* SIGINT signal handler, registered by "to_wait" method.  */
1003
1004 static void
1005 record_full_sig_handler (int signo)
1006 {
1007   if (record_debug)
1008     fprintf_unfiltered (gdb_stdlog, "Process record: get a signal\n");
1009
1010   /* It will break the running inferior in replay mode.  */
1011   record_full_resume_step = 1;
1012
1013   /* It will let record_full_wait set inferior status to get the signal
1014      SIGINT.  */
1015   record_full_get_sig = 1;
1016 }
1017
1018 static void
1019 record_full_wait_cleanups (void *ignore)
1020 {
1021   if (execution_direction == EXEC_REVERSE)
1022     {
1023       if (record_full_list->next)
1024         record_full_list = record_full_list->next;
1025     }
1026   else
1027     record_full_list = record_full_list->prev;
1028 }
1029
1030 /* "to_wait" target method for process record target.
1031
1032    In record mode, the target is always run in singlestep mode
1033    (even when gdb says to continue).  The to_wait method intercepts
1034    the stop events and determines which ones are to be passed on to
1035    gdb.  Most stop events are just singlestep events that gdb is not
1036    to know about, so the to_wait method just records them and keeps
1037    singlestepping.
1038
1039    In replay mode, this function emulates the recorded execution log, 
1040    one instruction at a time (forward or backward), and determines 
1041    where to stop.  */
1042
1043 static ptid_t
1044 record_full_wait_1 (struct target_ops *ops,
1045                     ptid_t ptid, struct target_waitstatus *status,
1046                     int options)
1047 {
1048   struct cleanup *set_cleanups = record_full_gdb_operation_disable_set ();
1049
1050   if (record_debug)
1051     fprintf_unfiltered (gdb_stdlog,
1052                         "Process record: record_full_wait "
1053                         "record_full_resume_step = %d, "
1054                         "record_full_resumed = %d, direction=%s\n",
1055                         record_full_resume_step, record_full_resumed,
1056                         record_full_execution_dir == EXEC_FORWARD
1057                         ? "forward" : "reverse");
1058
1059   if (!record_full_resumed)
1060     {
1061       gdb_assert ((options & TARGET_WNOHANG) != 0);
1062
1063       /* No interesting event.  */
1064       status->kind = TARGET_WAITKIND_IGNORE;
1065       return minus_one_ptid;
1066     }
1067
1068   record_full_get_sig = 0;
1069   signal (SIGINT, record_full_sig_handler);
1070
1071   if (!RECORD_FULL_IS_REPLAY && ops != &record_full_core_ops)
1072     {
1073       if (record_full_resume_step)
1074         {
1075           /* This is a single step.  */
1076           return ops->beneath->to_wait (ops->beneath, ptid, status, options);
1077         }
1078       else
1079         {
1080           /* This is not a single step.  */
1081           ptid_t ret;
1082           CORE_ADDR tmp_pc;
1083           struct gdbarch *gdbarch = target_thread_architecture (inferior_ptid);
1084
1085           while (1)
1086             {
1087               ret = ops->beneath->to_wait (ops->beneath, ptid, status, options);
1088               if (status->kind == TARGET_WAITKIND_IGNORE)
1089                 {
1090                   if (record_debug)
1091                     fprintf_unfiltered (gdb_stdlog,
1092                                         "Process record: record_full_wait "
1093                                         "target beneath not done yet\n");
1094                   return ret;
1095                 }
1096
1097               if (single_step_breakpoints_inserted ())
1098                 remove_single_step_breakpoints ();
1099
1100               if (record_full_resume_step)
1101                 return ret;
1102
1103               /* Is this a SIGTRAP?  */
1104               if (status->kind == TARGET_WAITKIND_STOPPED
1105                   && status->value.sig == GDB_SIGNAL_TRAP)
1106                 {
1107                   struct regcache *regcache;
1108                   struct address_space *aspace;
1109
1110                   /* Yes -- this is likely our single-step finishing,
1111                      but check if there's any reason the core would be
1112                      interested in the event.  */
1113
1114                   registers_changed ();
1115                   regcache = get_current_regcache ();
1116                   tmp_pc = regcache_read_pc (regcache);
1117                   aspace = get_regcache_aspace (regcache);
1118
1119                   if (target_stopped_by_watchpoint ())
1120                     {
1121                       /* Always interested in watchpoints.  */
1122                     }
1123                   else if (breakpoint_inserted_here_p (aspace, tmp_pc))
1124                     {
1125                       /* There is a breakpoint here.  Let the core
1126                          handle it.  */
1127                       if (software_breakpoint_inserted_here_p (aspace, tmp_pc))
1128                         {
1129                           struct gdbarch *gdbarch
1130                             = get_regcache_arch (regcache);
1131                           CORE_ADDR decr_pc_after_break
1132                             = target_decr_pc_after_break (gdbarch);
1133                           if (decr_pc_after_break)
1134                             regcache_write_pc (regcache,
1135                                                tmp_pc + decr_pc_after_break);
1136                         }
1137                     }
1138                   else
1139                     {
1140                       /* This is a single-step trap.  Record the
1141                          insn and issue another step.
1142                          FIXME: this part can be a random SIGTRAP too.
1143                          But GDB cannot handle it.  */
1144                       int step = 1;
1145
1146                       if (!record_full_message_wrapper_safe (regcache,
1147                                                              GDB_SIGNAL_0))
1148                         {
1149                            status->kind = TARGET_WAITKIND_STOPPED;
1150                            status->value.sig = GDB_SIGNAL_0;
1151                            break;
1152                         }
1153
1154                       if (gdbarch_software_single_step_p (gdbarch))
1155                         {
1156                           /* Try to insert the software single step breakpoint.
1157                              If insert success, set step to 0.  */
1158                           set_executing (inferior_ptid, 0);
1159                           reinit_frame_cache ();
1160                           if (gdbarch_software_single_step (gdbarch,
1161                                                             get_current_frame ()))
1162                             step = 0;
1163                           set_executing (inferior_ptid, 1);
1164                         }
1165
1166                       if (record_debug)
1167                         fprintf_unfiltered (gdb_stdlog,
1168                                             "Process record: record_full_wait "
1169                                             "issuing one more step in the "
1170                                             "target beneath\n");
1171                       ops->beneath->to_resume (ops->beneath, ptid, step,
1172                                                GDB_SIGNAL_0);
1173                       continue;
1174                     }
1175                 }
1176
1177               /* The inferior is broken by a breakpoint or a signal.  */
1178               break;
1179             }
1180
1181           return ret;
1182         }
1183     }
1184   else
1185     {
1186       struct regcache *regcache = get_current_regcache ();
1187       struct gdbarch *gdbarch = get_regcache_arch (regcache);
1188       struct address_space *aspace = get_regcache_aspace (regcache);
1189       int continue_flag = 1;
1190       int first_record_full_end = 1;
1191       struct cleanup *old_cleanups
1192         = make_cleanup (record_full_wait_cleanups, 0);
1193       CORE_ADDR tmp_pc;
1194
1195       record_full_hw_watchpoint = 0;
1196       status->kind = TARGET_WAITKIND_STOPPED;
1197
1198       /* Check breakpoint when forward execute.  */
1199       if (execution_direction == EXEC_FORWARD)
1200         {
1201           tmp_pc = regcache_read_pc (regcache);
1202           if (breakpoint_inserted_here_p (aspace, tmp_pc))
1203             {
1204               int decr_pc_after_break = target_decr_pc_after_break (gdbarch);
1205
1206               if (record_debug)
1207                 fprintf_unfiltered (gdb_stdlog,
1208                                     "Process record: break at %s.\n",
1209                                     paddress (gdbarch, tmp_pc));
1210
1211               if (decr_pc_after_break
1212                   && !record_full_resume_step
1213                   && software_breakpoint_inserted_here_p (aspace, tmp_pc))
1214                 regcache_write_pc (regcache,
1215                                    tmp_pc + decr_pc_after_break);
1216               goto replay_out;
1217             }
1218         }
1219
1220       /* If GDB is in terminal_inferior mode, it will not get the signal.
1221          And in GDB replay mode, GDB doesn't need to be in terminal_inferior
1222          mode, because inferior will not executed.
1223          Then set it to terminal_ours to make GDB get the signal.  */
1224       target_terminal_ours ();
1225
1226       /* In EXEC_FORWARD mode, record_full_list points to the tail of prev
1227          instruction.  */
1228       if (execution_direction == EXEC_FORWARD && record_full_list->next)
1229         record_full_list = record_full_list->next;
1230
1231       /* Loop over the record_full_list, looking for the next place to
1232          stop.  */
1233       do
1234         {
1235           /* Check for beginning and end of log.  */
1236           if (execution_direction == EXEC_REVERSE
1237               && record_full_list == &record_full_first)
1238             {
1239               /* Hit beginning of record log in reverse.  */
1240               status->kind = TARGET_WAITKIND_NO_HISTORY;
1241               break;
1242             }
1243           if (execution_direction != EXEC_REVERSE && !record_full_list->next)
1244             {
1245               /* Hit end of record log going forward.  */
1246               status->kind = TARGET_WAITKIND_NO_HISTORY;
1247               break;
1248             }
1249
1250           record_full_exec_insn (regcache, gdbarch, record_full_list);
1251
1252           if (record_full_list->type == record_full_end)
1253             {
1254               if (record_debug > 1)
1255                 fprintf_unfiltered (gdb_stdlog,
1256                                     "Process record: record_full_end %s to "
1257                                     "inferior.\n",
1258                                     host_address_to_string (record_full_list));
1259
1260               if (first_record_full_end && execution_direction == EXEC_REVERSE)
1261                 {
1262                   /* When reverse excute, the first record_full_end is the
1263                      part of current instruction.  */
1264                   first_record_full_end = 0;
1265                 }
1266               else
1267                 {
1268                   /* In EXEC_REVERSE mode, this is the record_full_end of prev
1269                      instruction.
1270                      In EXEC_FORWARD mode, this is the record_full_end of
1271                      current instruction.  */
1272                   /* step */
1273                   if (record_full_resume_step)
1274                     {
1275                       if (record_debug > 1)
1276                         fprintf_unfiltered (gdb_stdlog,
1277                                             "Process record: step.\n");
1278                       continue_flag = 0;
1279                     }
1280
1281                   /* check breakpoint */
1282                   tmp_pc = regcache_read_pc (regcache);
1283                   if (breakpoint_inserted_here_p (aspace, tmp_pc))
1284                     {
1285                       int decr_pc_after_break
1286                         = target_decr_pc_after_break (gdbarch);
1287
1288                       if (record_debug)
1289                         fprintf_unfiltered (gdb_stdlog,
1290                                             "Process record: break "
1291                                             "at %s.\n",
1292                                             paddress (gdbarch, tmp_pc));
1293                       if (decr_pc_after_break
1294                           && execution_direction == EXEC_FORWARD
1295                           && !record_full_resume_step
1296                           && software_breakpoint_inserted_here_p (aspace,
1297                                                                   tmp_pc))
1298                         regcache_write_pc (regcache,
1299                                            tmp_pc + decr_pc_after_break);
1300                       continue_flag = 0;
1301                     }
1302
1303                   if (record_full_hw_watchpoint)
1304                     {
1305                       if (record_debug)
1306                         fprintf_unfiltered (gdb_stdlog,
1307                                             "Process record: hit hw "
1308                                             "watchpoint.\n");
1309                       continue_flag = 0;
1310                     }
1311                   /* Check target signal */
1312                   if (record_full_list->u.end.sigval != GDB_SIGNAL_0)
1313                     /* FIXME: better way to check */
1314                     continue_flag = 0;
1315                 }
1316             }
1317
1318           if (continue_flag)
1319             {
1320               if (execution_direction == EXEC_REVERSE)
1321                 {
1322                   if (record_full_list->prev)
1323                     record_full_list = record_full_list->prev;
1324                 }
1325               else
1326                 {
1327                   if (record_full_list->next)
1328                     record_full_list = record_full_list->next;
1329                 }
1330             }
1331         }
1332       while (continue_flag);
1333
1334 replay_out:
1335       if (record_full_get_sig)
1336         status->value.sig = GDB_SIGNAL_INT;
1337       else if (record_full_list->u.end.sigval != GDB_SIGNAL_0)
1338         /* FIXME: better way to check */
1339         status->value.sig = record_full_list->u.end.sigval;
1340       else
1341         status->value.sig = GDB_SIGNAL_TRAP;
1342
1343       discard_cleanups (old_cleanups);
1344     }
1345
1346   signal (SIGINT, handle_sigint);
1347
1348   do_cleanups (set_cleanups);
1349   return inferior_ptid;
1350 }
1351
1352 static ptid_t
1353 record_full_wait (struct target_ops *ops,
1354                   ptid_t ptid, struct target_waitstatus *status,
1355                   int options)
1356 {
1357   ptid_t return_ptid;
1358
1359   return_ptid = record_full_wait_1 (ops, ptid, status, options);
1360   if (status->kind != TARGET_WAITKIND_IGNORE)
1361     {
1362       /* We're reporting a stop.  Make sure any spurious
1363          target_wait(WNOHANG) doesn't advance the target until the
1364          core wants us resumed again.  */
1365       record_full_resumed = 0;
1366     }
1367   return return_ptid;
1368 }
1369
1370 static int
1371 record_full_stopped_by_watchpoint (struct target_ops *ops)
1372 {
1373   if (RECORD_FULL_IS_REPLAY)
1374     return record_full_hw_watchpoint;
1375   else
1376     return ops->beneath->to_stopped_by_watchpoint (ops->beneath);
1377 }
1378
1379 static int
1380 record_full_stopped_data_address (struct target_ops *ops, CORE_ADDR *addr_p)
1381 {
1382   if (RECORD_FULL_IS_REPLAY)
1383     return 0;
1384   else
1385     return ops->beneath->to_stopped_data_address (ops->beneath, addr_p);
1386 }
1387
1388 /* Record registers change (by user or by GDB) to list as an instruction.  */
1389
1390 static void
1391 record_full_registers_change (struct regcache *regcache, int regnum)
1392 {
1393   /* Check record_full_insn_num.  */
1394   record_full_check_insn_num (0);
1395
1396   record_full_arch_list_head = NULL;
1397   record_full_arch_list_tail = NULL;
1398
1399   if (regnum < 0)
1400     {
1401       int i;
1402
1403       for (i = 0; i < gdbarch_num_regs (get_regcache_arch (regcache)); i++)
1404         {
1405           if (record_full_arch_list_add_reg (regcache, i))
1406             {
1407               record_full_list_release (record_full_arch_list_tail);
1408               error (_("Process record: failed to record execution log."));
1409             }
1410         }
1411     }
1412   else
1413     {
1414       if (record_full_arch_list_add_reg (regcache, regnum))
1415         {
1416           record_full_list_release (record_full_arch_list_tail);
1417           error (_("Process record: failed to record execution log."));
1418         }
1419     }
1420   if (record_full_arch_list_add_end ())
1421     {
1422       record_full_list_release (record_full_arch_list_tail);
1423       error (_("Process record: failed to record execution log."));
1424     }
1425   record_full_list->next = record_full_arch_list_head;
1426   record_full_arch_list_head->prev = record_full_list;
1427   record_full_list = record_full_arch_list_tail;
1428
1429   if (record_full_insn_num == record_full_insn_max_num)
1430     record_full_list_release_first ();
1431   else
1432     record_full_insn_num++;
1433 }
1434
1435 /* "to_store_registers" method for process record target.  */
1436
1437 static void
1438 record_full_store_registers (struct target_ops *ops,
1439                              struct regcache *regcache,
1440                              int regno)
1441 {
1442   if (!record_full_gdb_operation_disable)
1443     {
1444       if (RECORD_FULL_IS_REPLAY)
1445         {
1446           int n;
1447
1448           /* Let user choose if he wants to write register or not.  */
1449           if (regno < 0)
1450             n =
1451               query (_("Because GDB is in replay mode, changing the "
1452                        "value of a register will make the execution "
1453                        "log unusable from this point onward.  "
1454                        "Change all registers?"));
1455           else
1456             n =
1457               query (_("Because GDB is in replay mode, changing the value "
1458                        "of a register will make the execution log unusable "
1459                        "from this point onward.  Change register %s?"),
1460                       gdbarch_register_name (get_regcache_arch (regcache),
1461                                                regno));
1462
1463           if (!n)
1464             {
1465               /* Invalidate the value of regcache that was set in function
1466                  "regcache_raw_write".  */
1467               if (regno < 0)
1468                 {
1469                   int i;
1470
1471                   for (i = 0;
1472                        i < gdbarch_num_regs (get_regcache_arch (regcache));
1473                        i++)
1474                     regcache_invalidate (regcache, i);
1475                 }
1476               else
1477                 regcache_invalidate (regcache, regno);
1478
1479               error (_("Process record canceled the operation."));
1480             }
1481
1482           /* Destroy the record from here forward.  */
1483           record_full_list_release_following (record_full_list);
1484         }
1485
1486       record_full_registers_change (regcache, regno);
1487     }
1488   ops->beneath->to_store_registers (ops->beneath, regcache, regno);
1489 }
1490
1491 /* "to_xfer_partial" method.  Behavior is conditional on
1492    RECORD_FULL_IS_REPLAY.
1493    In replay mode, we cannot write memory unles we are willing to
1494    invalidate the record/replay log from this point forward.  */
1495
1496 static enum target_xfer_status
1497 record_full_xfer_partial (struct target_ops *ops, enum target_object object,
1498                           const char *annex, gdb_byte *readbuf,
1499                           const gdb_byte *writebuf, ULONGEST offset,
1500                           ULONGEST len, ULONGEST *xfered_len)
1501 {
1502   if (!record_full_gdb_operation_disable
1503       && (object == TARGET_OBJECT_MEMORY
1504           || object == TARGET_OBJECT_RAW_MEMORY) && writebuf)
1505     {
1506       if (RECORD_FULL_IS_REPLAY)
1507         {
1508           /* Let user choose if he wants to write memory or not.  */
1509           if (!query (_("Because GDB is in replay mode, writing to memory "
1510                         "will make the execution log unusable from this "
1511                         "point onward.  Write memory at address %s?"),
1512                        paddress (target_gdbarch (), offset)))
1513             error (_("Process record canceled the operation."));
1514
1515           /* Destroy the record from here forward.  */
1516           record_full_list_release_following (record_full_list);
1517         }
1518
1519       /* Check record_full_insn_num */
1520       record_full_check_insn_num (0);
1521
1522       /* Record registers change to list as an instruction.  */
1523       record_full_arch_list_head = NULL;
1524       record_full_arch_list_tail = NULL;
1525       if (record_full_arch_list_add_mem (offset, len))
1526         {
1527           record_full_list_release (record_full_arch_list_tail);
1528           if (record_debug)
1529             fprintf_unfiltered (gdb_stdlog,
1530                                 "Process record: failed to record "
1531                                 "execution log.");
1532           return TARGET_XFER_E_IO;
1533         }
1534       if (record_full_arch_list_add_end ())
1535         {
1536           record_full_list_release (record_full_arch_list_tail);
1537           if (record_debug)
1538             fprintf_unfiltered (gdb_stdlog,
1539                                 "Process record: failed to record "
1540                                 "execution log.");
1541           return TARGET_XFER_E_IO;
1542         }
1543       record_full_list->next = record_full_arch_list_head;
1544       record_full_arch_list_head->prev = record_full_list;
1545       record_full_list = record_full_arch_list_tail;
1546
1547       if (record_full_insn_num == record_full_insn_max_num)
1548         record_full_list_release_first ();
1549       else
1550         record_full_insn_num++;
1551     }
1552
1553   return ops->beneath->to_xfer_partial (ops->beneath, object, annex,
1554                                         readbuf, writebuf, offset,
1555                                         len, xfered_len);
1556 }
1557
1558 /* This structure represents a breakpoint inserted while the record
1559    target is active.  We use this to know when to install/remove
1560    breakpoints in/from the target beneath.  For example, a breakpoint
1561    may be inserted while recording, but removed when not replaying nor
1562    recording.  In that case, the breakpoint had not been inserted on
1563    the target beneath, so we should not try to remove it there.  */
1564
1565 struct record_full_breakpoint
1566 {
1567   /* The address and address space the breakpoint was set at.  */
1568   struct address_space *address_space;
1569   CORE_ADDR addr;
1570
1571   /* True when the breakpoint has been also installed in the target
1572      beneath.  This will be false for breakpoints set during replay or
1573      when recording.  */
1574   int in_target_beneath;
1575 };
1576
1577 typedef struct record_full_breakpoint *record_full_breakpoint_p;
1578 DEF_VEC_P(record_full_breakpoint_p);
1579
1580 /* The list of breakpoints inserted while the record target is
1581    active.  */
1582 VEC(record_full_breakpoint_p) *record_full_breakpoints = NULL;
1583
1584 static void
1585 record_full_sync_record_breakpoints (struct bp_location *loc, void *data)
1586 {
1587   if (loc->loc_type != bp_loc_software_breakpoint)
1588       return;
1589
1590   if (loc->inserted)
1591     {
1592       struct record_full_breakpoint *bp = XNEW (struct record_full_breakpoint);
1593
1594       bp->addr = loc->target_info.placed_address;
1595       bp->address_space = loc->target_info.placed_address_space;
1596
1597       bp->in_target_beneath = 1;
1598
1599       VEC_safe_push (record_full_breakpoint_p, record_full_breakpoints, bp);
1600     }
1601 }
1602
1603 /* Sync existing breakpoints to record_full_breakpoints.  */
1604
1605 static void
1606 record_full_init_record_breakpoints (void)
1607 {
1608   VEC_free (record_full_breakpoint_p, record_full_breakpoints);
1609
1610   iterate_over_bp_locations (record_full_sync_record_breakpoints);
1611 }
1612
1613 /* Behavior is conditional on RECORD_FULL_IS_REPLAY.  We will not actually
1614    insert or remove breakpoints in the real target when replaying, nor
1615    when recording.  */
1616
1617 static int
1618 record_full_insert_breakpoint (struct target_ops *ops,
1619                                struct gdbarch *gdbarch,
1620                                struct bp_target_info *bp_tgt)
1621 {
1622   struct record_full_breakpoint *bp;
1623   int in_target_beneath = 0;
1624
1625   if (!RECORD_FULL_IS_REPLAY)
1626     {
1627       /* When recording, we currently always single-step, so we don't
1628          really need to install regular breakpoints in the inferior.
1629          However, we do have to insert software single-step
1630          breakpoints, in case the target can't hardware step.  To keep
1631          things single, we always insert.  */
1632       struct cleanup *old_cleanups;
1633       int ret;
1634
1635       old_cleanups = record_full_gdb_operation_disable_set ();
1636       ret = ops->beneath->to_insert_breakpoint (ops->beneath, gdbarch, bp_tgt);
1637       do_cleanups (old_cleanups);
1638
1639       if (ret != 0)
1640         return ret;
1641
1642       in_target_beneath = 1;
1643     }
1644
1645   bp = XNEW (struct record_full_breakpoint);
1646   bp->addr = bp_tgt->placed_address;
1647   bp->address_space = bp_tgt->placed_address_space;
1648   bp->in_target_beneath = in_target_beneath;
1649   VEC_safe_push (record_full_breakpoint_p, record_full_breakpoints, bp);
1650   return 0;
1651 }
1652
1653 /* "to_remove_breakpoint" method for process record target.  */
1654
1655 static int
1656 record_full_remove_breakpoint (struct target_ops *ops,
1657                                struct gdbarch *gdbarch,
1658                                struct bp_target_info *bp_tgt)
1659 {
1660   struct record_full_breakpoint *bp;
1661   int ix;
1662
1663   for (ix = 0;
1664        VEC_iterate (record_full_breakpoint_p,
1665                     record_full_breakpoints, ix, bp);
1666        ++ix)
1667     {
1668       if (bp->addr == bp_tgt->placed_address
1669           && bp->address_space == bp_tgt->placed_address_space)
1670         {
1671           if (bp->in_target_beneath)
1672             {
1673               struct cleanup *old_cleanups;
1674               int ret;
1675
1676               old_cleanups = record_full_gdb_operation_disable_set ();
1677               ret = ops->beneath->to_remove_breakpoint (ops->beneath, gdbarch,
1678                                                         bp_tgt);
1679               do_cleanups (old_cleanups);
1680
1681               if (ret != 0)
1682                 return ret;
1683             }
1684
1685           VEC_unordered_remove (record_full_breakpoint_p,
1686                                 record_full_breakpoints, ix);
1687           return 0;
1688         }
1689     }
1690
1691   gdb_assert_not_reached ("removing unknown breakpoint");
1692 }
1693
1694 /* "to_can_execute_reverse" method for process record target.  */
1695
1696 static int
1697 record_full_can_execute_reverse (struct target_ops *self)
1698 {
1699   return 1;
1700 }
1701
1702 /* "to_get_bookmark" method for process record and prec over core.  */
1703
1704 static gdb_byte *
1705 record_full_get_bookmark (struct target_ops *self, const char *args,
1706                           int from_tty)
1707 {
1708   char *ret = NULL;
1709
1710   /* Return stringified form of instruction count.  */
1711   if (record_full_list && record_full_list->type == record_full_end)
1712     ret = xstrdup (pulongest (record_full_list->u.end.insn_num));
1713
1714   if (record_debug)
1715     {
1716       if (ret)
1717         fprintf_unfiltered (gdb_stdlog,
1718                             "record_full_get_bookmark returns %s\n", ret);
1719       else
1720         fprintf_unfiltered (gdb_stdlog,
1721                             "record_full_get_bookmark returns NULL\n");
1722     }
1723   return (gdb_byte *) ret;
1724 }
1725
1726 /* "to_goto_bookmark" method for process record and prec over core.  */
1727
1728 static void
1729 record_full_goto_bookmark (struct target_ops *self,
1730                            const gdb_byte *raw_bookmark, int from_tty)
1731 {
1732   const char *bookmark = (const char *) raw_bookmark;
1733   struct cleanup *cleanup = make_cleanup (null_cleanup, NULL);
1734
1735   if (record_debug)
1736     fprintf_unfiltered (gdb_stdlog,
1737                         "record_full_goto_bookmark receives %s\n", bookmark);
1738
1739   if (bookmark[0] == '\'' || bookmark[0] == '\"')
1740     {
1741       char *copy;
1742
1743       if (bookmark[strlen (bookmark) - 1] != bookmark[0])
1744         error (_("Unbalanced quotes: %s"), bookmark);
1745
1746
1747       copy = savestring (bookmark + 1, strlen (bookmark) - 2);
1748       make_cleanup (xfree, copy);
1749       bookmark = copy;
1750     }
1751
1752   record_goto (bookmark);
1753
1754   do_cleanups (cleanup);
1755 }
1756
1757 static enum exec_direction_kind
1758 record_full_execution_direction (struct target_ops *self)
1759 {
1760   return record_full_execution_dir;
1761 }
1762
1763 static void
1764 record_full_info (struct target_ops *self)
1765 {
1766   struct record_full_entry *p;
1767
1768   if (RECORD_FULL_IS_REPLAY)
1769     printf_filtered (_("Replay mode:\n"));
1770   else
1771     printf_filtered (_("Record mode:\n"));
1772
1773   /* Find entry for first actual instruction in the log.  */
1774   for (p = record_full_first.next;
1775        p != NULL && p->type != record_full_end;
1776        p = p->next)
1777     ;
1778
1779   /* Do we have a log at all?  */
1780   if (p != NULL && p->type == record_full_end)
1781     {
1782       /* Display instruction number for first instruction in the log.  */
1783       printf_filtered (_("Lowest recorded instruction number is %s.\n"),
1784                        pulongest (p->u.end.insn_num));
1785
1786       /* If in replay mode, display where we are in the log.  */
1787       if (RECORD_FULL_IS_REPLAY)
1788         printf_filtered (_("Current instruction number is %s.\n"),
1789                          pulongest (record_full_list->u.end.insn_num));
1790
1791       /* Display instruction number for last instruction in the log.  */
1792       printf_filtered (_("Highest recorded instruction number is %s.\n"),
1793                        pulongest (record_full_insn_count));
1794
1795       /* Display log count.  */
1796       printf_filtered (_("Log contains %u instructions.\n"),
1797                        record_full_insn_num);
1798     }
1799   else
1800     printf_filtered (_("No instructions have been logged.\n"));
1801
1802   /* Display max log size.  */
1803   printf_filtered (_("Max logged instructions is %u.\n"),
1804                    record_full_insn_max_num);
1805 }
1806
1807 /* The "to_record_delete" target method.  */
1808
1809 static void
1810 record_full_delete (struct target_ops *self)
1811 {
1812   record_full_list_release_following (record_full_list);
1813 }
1814
1815 /* The "to_record_is_replaying" target method.  */
1816
1817 static int
1818 record_full_is_replaying (struct target_ops *self)
1819 {
1820   return RECORD_FULL_IS_REPLAY;
1821 }
1822
1823 /* Go to a specific entry.  */
1824
1825 static void
1826 record_full_goto_entry (struct record_full_entry *p)
1827 {
1828   if (p == NULL)
1829     error (_("Target insn not found."));
1830   else if (p == record_full_list)
1831     error (_("Already at target insn."));
1832   else if (p->u.end.insn_num > record_full_list->u.end.insn_num)
1833     {
1834       printf_filtered (_("Go forward to insn number %s\n"),
1835                        pulongest (p->u.end.insn_num));
1836       record_full_goto_insn (p, EXEC_FORWARD);
1837     }
1838   else
1839     {
1840       printf_filtered (_("Go backward to insn number %s\n"),
1841                        pulongest (p->u.end.insn_num));
1842       record_full_goto_insn (p, EXEC_REVERSE);
1843     }
1844
1845   registers_changed ();
1846   reinit_frame_cache ();
1847   print_stack_frame (get_selected_frame (NULL), 1, SRC_AND_LOC, 1);
1848 }
1849
1850 /* The "to_goto_record_begin" target method.  */
1851
1852 static void
1853 record_full_goto_begin (struct target_ops *self)
1854 {
1855   struct record_full_entry *p = NULL;
1856
1857   for (p = &record_full_first; p != NULL; p = p->next)
1858     if (p->type == record_full_end)
1859       break;
1860
1861   record_full_goto_entry (p);
1862 }
1863
1864 /* The "to_goto_record_end" target method.  */
1865
1866 static void
1867 record_full_goto_end (struct target_ops *self)
1868 {
1869   struct record_full_entry *p = NULL;
1870
1871   for (p = record_full_list; p->next != NULL; p = p->next)
1872     ;
1873   for (; p!= NULL; p = p->prev)
1874     if (p->type == record_full_end)
1875       break;
1876
1877   record_full_goto_entry (p);
1878 }
1879
1880 /* The "to_goto_record" target method.  */
1881
1882 static void
1883 record_full_goto (struct target_ops *self, ULONGEST target_insn)
1884 {
1885   struct record_full_entry *p = NULL;
1886
1887   for (p = &record_full_first; p != NULL; p = p->next)
1888     if (p->type == record_full_end && p->u.end.insn_num == target_insn)
1889       break;
1890
1891   record_full_goto_entry (p);
1892 }
1893
1894 static void
1895 init_record_full_ops (void)
1896 {
1897   record_full_ops.to_shortname = "record-full";
1898   record_full_ops.to_longname = "Process record and replay target";
1899   record_full_ops.to_doc =
1900     "Log program while executing and replay execution from log.";
1901   record_full_ops.to_open = record_full_open;
1902   record_full_ops.to_close = record_full_close;
1903   record_full_ops.to_resume = record_full_resume;
1904   record_full_ops.to_wait = record_full_wait;
1905   record_full_ops.to_disconnect = record_disconnect;
1906   record_full_ops.to_detach = record_detach;
1907   record_full_ops.to_mourn_inferior = record_mourn_inferior;
1908   record_full_ops.to_kill = record_kill;
1909   record_full_ops.to_store_registers = record_full_store_registers;
1910   record_full_ops.to_xfer_partial = record_full_xfer_partial;
1911   record_full_ops.to_insert_breakpoint = record_full_insert_breakpoint;
1912   record_full_ops.to_remove_breakpoint = record_full_remove_breakpoint;
1913   record_full_ops.to_stopped_by_watchpoint = record_full_stopped_by_watchpoint;
1914   record_full_ops.to_stopped_data_address = record_full_stopped_data_address;
1915   record_full_ops.to_can_execute_reverse = record_full_can_execute_reverse;
1916   record_full_ops.to_stratum = record_stratum;
1917   /* Add bookmark target methods.  */
1918   record_full_ops.to_get_bookmark = record_full_get_bookmark;
1919   record_full_ops.to_goto_bookmark = record_full_goto_bookmark;
1920   record_full_ops.to_execution_direction = record_full_execution_direction;
1921   record_full_ops.to_info_record = record_full_info;
1922   record_full_ops.to_save_record = record_full_save;
1923   record_full_ops.to_delete_record = record_full_delete;
1924   record_full_ops.to_record_is_replaying = record_full_is_replaying;
1925   record_full_ops.to_goto_record_begin = record_full_goto_begin;
1926   record_full_ops.to_goto_record_end = record_full_goto_end;
1927   record_full_ops.to_goto_record = record_full_goto;
1928   record_full_ops.to_magic = OPS_MAGIC;
1929 }
1930
1931 /* "to_resume" method for prec over corefile.  */
1932
1933 static void
1934 record_full_core_resume (struct target_ops *ops, ptid_t ptid, int step,
1935                          enum gdb_signal signal)
1936 {
1937   record_full_resume_step = step;
1938   record_full_resumed = 1;
1939   record_full_execution_dir = execution_direction;
1940
1941   /* We are about to start executing the inferior (or simulate it),
1942      let's register it with the event loop.  */
1943   if (target_can_async_p ())
1944     {
1945       target_async (inferior_event_handler, 0);
1946
1947       /* Notify the event loop there's an event to wait for.  */
1948       mark_async_event_handler (record_full_async_inferior_event_token);
1949     }
1950 }
1951
1952 /* "to_kill" method for prec over corefile.  */
1953
1954 static void
1955 record_full_core_kill (struct target_ops *ops)
1956 {
1957   if (record_debug)
1958     fprintf_unfiltered (gdb_stdlog, "Process record: record_full_core_kill\n");
1959
1960   unpush_target (&record_full_core_ops);
1961 }
1962
1963 /* "to_fetch_registers" method for prec over corefile.  */
1964
1965 static void
1966 record_full_core_fetch_registers (struct target_ops *ops,
1967                                   struct regcache *regcache,
1968                                   int regno)
1969 {
1970   if (regno < 0)
1971     {
1972       int num = gdbarch_num_regs (get_regcache_arch (regcache));
1973       int i;
1974
1975       for (i = 0; i < num; i ++)
1976         regcache_raw_supply (regcache, i,
1977                              record_full_core_regbuf + MAX_REGISTER_SIZE * i);
1978     }
1979   else
1980     regcache_raw_supply (regcache, regno,
1981                          record_full_core_regbuf + MAX_REGISTER_SIZE * regno);
1982 }
1983
1984 /* "to_prepare_to_store" method for prec over corefile.  */
1985
1986 static void
1987 record_full_core_prepare_to_store (struct target_ops *self,
1988                                    struct regcache *regcache)
1989 {
1990 }
1991
1992 /* "to_store_registers" method for prec over corefile.  */
1993
1994 static void
1995 record_full_core_store_registers (struct target_ops *ops,
1996                              struct regcache *regcache,
1997                              int regno)
1998 {
1999   if (record_full_gdb_operation_disable)
2000     regcache_raw_collect (regcache, regno,
2001                           record_full_core_regbuf + MAX_REGISTER_SIZE * regno);
2002   else
2003     error (_("You can't do that without a process to debug."));
2004 }
2005
2006 /* "to_xfer_partial" method for prec over corefile.  */
2007
2008 static enum target_xfer_status
2009 record_full_core_xfer_partial (struct target_ops *ops,
2010                                enum target_object object,
2011                                const char *annex, gdb_byte *readbuf,
2012                                const gdb_byte *writebuf, ULONGEST offset,
2013                                ULONGEST len, ULONGEST *xfered_len)
2014 {
2015   if (object == TARGET_OBJECT_MEMORY)
2016     {
2017       if (record_full_gdb_operation_disable || !writebuf)
2018         {
2019           struct target_section *p;
2020
2021           for (p = record_full_core_start; p < record_full_core_end; p++)
2022             {
2023               if (offset >= p->addr)
2024                 {
2025                   struct record_full_core_buf_entry *entry;
2026                   ULONGEST sec_offset;
2027
2028                   if (offset >= p->endaddr)
2029                     continue;
2030
2031                   if (offset + len > p->endaddr)
2032                     len = p->endaddr - offset;
2033
2034                   sec_offset = offset - p->addr;
2035
2036                   /* Read readbuf or write writebuf p, offset, len.  */
2037                   /* Check flags.  */
2038                   if (p->the_bfd_section->flags & SEC_CONSTRUCTOR
2039                       || (p->the_bfd_section->flags & SEC_HAS_CONTENTS) == 0)
2040                     {
2041                       if (readbuf)
2042                         memset (readbuf, 0, len);
2043
2044                       *xfered_len = len;
2045                       return TARGET_XFER_OK;
2046                     }
2047                   /* Get record_full_core_buf_entry.  */
2048                   for (entry = record_full_core_buf_list; entry;
2049                        entry = entry->prev)
2050                     if (entry->p == p)
2051                       break;
2052                   if (writebuf)
2053                     {
2054                       if (!entry)
2055                         {
2056                           /* Add a new entry.  */
2057                           entry = (struct record_full_core_buf_entry *)
2058                             xmalloc
2059                             (sizeof (struct record_full_core_buf_entry));
2060                           entry->p = p;
2061                           if (!bfd_malloc_and_get_section
2062                                 (p->the_bfd_section->owner,
2063                                  p->the_bfd_section,
2064                                  &entry->buf))
2065                             {
2066                               xfree (entry);
2067                               return TARGET_XFER_EOF;
2068                             }
2069                           entry->prev = record_full_core_buf_list;
2070                           record_full_core_buf_list = entry;
2071                         }
2072
2073                       memcpy (entry->buf + sec_offset, writebuf,
2074                               (size_t) len);
2075                     }
2076                   else
2077                     {
2078                       if (!entry)
2079                         return ops->beneath->to_xfer_partial (ops->beneath,
2080                                                               object, annex,
2081                                                               readbuf, writebuf,
2082                                                               offset, len,
2083                                                               xfered_len);
2084
2085                       memcpy (readbuf, entry->buf + sec_offset,
2086                               (size_t) len);
2087                     }
2088
2089                   *xfered_len = len;
2090                   return TARGET_XFER_OK;
2091                 }
2092             }
2093
2094           return TARGET_XFER_E_IO;
2095         }
2096       else
2097         error (_("You can't do that without a process to debug."));
2098     }
2099
2100   return ops->beneath->to_xfer_partial (ops->beneath, object, annex,
2101                                         readbuf, writebuf, offset, len,
2102                                         xfered_len);
2103 }
2104
2105 /* "to_insert_breakpoint" method for prec over corefile.  */
2106
2107 static int
2108 record_full_core_insert_breakpoint (struct target_ops *ops,
2109                                     struct gdbarch *gdbarch,
2110                                     struct bp_target_info *bp_tgt)
2111 {
2112   return 0;
2113 }
2114
2115 /* "to_remove_breakpoint" method for prec over corefile.  */
2116
2117 static int
2118 record_full_core_remove_breakpoint (struct target_ops *ops,
2119                                     struct gdbarch *gdbarch,
2120                                     struct bp_target_info *bp_tgt)
2121 {
2122   return 0;
2123 }
2124
2125 /* "to_has_execution" method for prec over corefile.  */
2126
2127 static int
2128 record_full_core_has_execution (struct target_ops *ops, ptid_t the_ptid)
2129 {
2130   return 1;
2131 }
2132
2133 static void
2134 init_record_full_core_ops (void)
2135 {
2136   record_full_core_ops.to_shortname = "record-core";
2137   record_full_core_ops.to_longname = "Process record and replay target";
2138   record_full_core_ops.to_doc =
2139     "Log program while executing and replay execution from log.";
2140   record_full_core_ops.to_open = record_full_open;
2141   record_full_core_ops.to_close = record_full_close;
2142   record_full_core_ops.to_resume = record_full_core_resume;
2143   record_full_core_ops.to_wait = record_full_wait;
2144   record_full_core_ops.to_kill = record_full_core_kill;
2145   record_full_core_ops.to_fetch_registers = record_full_core_fetch_registers;
2146   record_full_core_ops.to_prepare_to_store = record_full_core_prepare_to_store;
2147   record_full_core_ops.to_store_registers = record_full_core_store_registers;
2148   record_full_core_ops.to_xfer_partial = record_full_core_xfer_partial;
2149   record_full_core_ops.to_insert_breakpoint
2150     = record_full_core_insert_breakpoint;
2151   record_full_core_ops.to_remove_breakpoint
2152     = record_full_core_remove_breakpoint;
2153   record_full_core_ops.to_stopped_by_watchpoint
2154     = record_full_stopped_by_watchpoint;
2155   record_full_core_ops.to_stopped_data_address
2156     = record_full_stopped_data_address;
2157   record_full_core_ops.to_can_execute_reverse
2158     = record_full_can_execute_reverse;
2159   record_full_core_ops.to_has_execution = record_full_core_has_execution;
2160   record_full_core_ops.to_stratum = record_stratum;
2161   /* Add bookmark target methods.  */
2162   record_full_core_ops.to_get_bookmark = record_full_get_bookmark;
2163   record_full_core_ops.to_goto_bookmark = record_full_goto_bookmark;
2164   record_full_core_ops.to_execution_direction
2165     = record_full_execution_direction;
2166   record_full_core_ops.to_info_record = record_full_info;
2167   record_full_core_ops.to_delete_record = record_full_delete;
2168   record_full_core_ops.to_record_is_replaying = record_full_is_replaying;
2169   record_full_core_ops.to_goto_record_begin = record_full_goto_begin;
2170   record_full_core_ops.to_goto_record_end = record_full_goto_end;
2171   record_full_core_ops.to_goto_record = record_full_goto;
2172   record_full_core_ops.to_magic = OPS_MAGIC;
2173 }
2174
2175 /* Record log save-file format
2176    Version 1 (never released)
2177
2178    Header:
2179      4 bytes: magic number htonl(0x20090829).
2180        NOTE: be sure to change whenever this file format changes!
2181
2182    Records:
2183      record_full_end:
2184        1 byte:  record type (record_full_end, see enum record_full_type).
2185      record_full_reg:
2186        1 byte:  record type (record_full_reg, see enum record_full_type).
2187        8 bytes: register id (network byte order).
2188        MAX_REGISTER_SIZE bytes: register value.
2189      record_full_mem:
2190        1 byte:  record type (record_full_mem, see enum record_full_type).
2191        8 bytes: memory length (network byte order).
2192        8 bytes: memory address (network byte order).
2193        n bytes: memory value (n == memory length).
2194
2195    Version 2
2196      4 bytes: magic number netorder32(0x20091016).
2197        NOTE: be sure to change whenever this file format changes!
2198
2199    Records:
2200      record_full_end:
2201        1 byte:  record type (record_full_end, see enum record_full_type).
2202        4 bytes: signal
2203        4 bytes: instruction count
2204      record_full_reg:
2205        1 byte:  record type (record_full_reg, see enum record_full_type).
2206        4 bytes: register id (network byte order).
2207        n bytes: register value (n == actual register size).
2208                 (eg. 4 bytes for x86 general registers).
2209      record_full_mem:
2210        1 byte:  record type (record_full_mem, see enum record_full_type).
2211        4 bytes: memory length (network byte order).
2212        8 bytes: memory address (network byte order).
2213        n bytes: memory value (n == memory length).
2214
2215 */
2216
2217 /* bfdcore_read -- read bytes from a core file section.  */
2218
2219 static inline void
2220 bfdcore_read (bfd *obfd, asection *osec, void *buf, int len, int *offset)
2221 {
2222   int ret = bfd_get_section_contents (obfd, osec, buf, *offset, len);
2223
2224   if (ret)
2225     *offset += len;
2226   else
2227     error (_("Failed to read %d bytes from core file %s ('%s')."),
2228            len, bfd_get_filename (obfd),
2229            bfd_errmsg (bfd_get_error ()));
2230 }
2231
2232 static inline uint64_t
2233 netorder64 (uint64_t input)
2234 {
2235   uint64_t ret;
2236
2237   store_unsigned_integer ((gdb_byte *) &ret, sizeof (ret), 
2238                           BFD_ENDIAN_BIG, input);
2239   return ret;
2240 }
2241
2242 static inline uint32_t
2243 netorder32 (uint32_t input)
2244 {
2245   uint32_t ret;
2246
2247   store_unsigned_integer ((gdb_byte *) &ret, sizeof (ret), 
2248                           BFD_ENDIAN_BIG, input);
2249   return ret;
2250 }
2251
2252 static inline uint16_t
2253 netorder16 (uint16_t input)
2254 {
2255   uint16_t ret;
2256
2257   store_unsigned_integer ((gdb_byte *) &ret, sizeof (ret), 
2258                           BFD_ENDIAN_BIG, input);
2259   return ret;
2260 }
2261
2262 /* Restore the execution log from a core_bfd file.  */
2263 static void
2264 record_full_restore (void)
2265 {
2266   uint32_t magic;
2267   struct cleanup *old_cleanups;
2268   struct record_full_entry *rec;
2269   asection *osec;
2270   uint32_t osec_size;
2271   int bfd_offset = 0;
2272   struct regcache *regcache;
2273
2274   /* We restore the execution log from the open core bfd,
2275      if there is one.  */
2276   if (core_bfd == NULL)
2277     return;
2278
2279   /* "record_full_restore" can only be called when record list is empty.  */
2280   gdb_assert (record_full_first.next == NULL);
2281  
2282   if (record_debug)
2283     fprintf_unfiltered (gdb_stdlog, "Restoring recording from core file.\n");
2284
2285   /* Now need to find our special note section.  */
2286   osec = bfd_get_section_by_name (core_bfd, "null0");
2287   if (record_debug)
2288     fprintf_unfiltered (gdb_stdlog, "Find precord section %s.\n",
2289                         osec ? "succeeded" : "failed");
2290   if (osec == NULL)
2291     return;
2292   osec_size = bfd_section_size (core_bfd, osec);
2293   if (record_debug)
2294     fprintf_unfiltered (gdb_stdlog, "%s", bfd_section_name (core_bfd, osec));
2295
2296   /* Check the magic code.  */
2297   bfdcore_read (core_bfd, osec, &magic, sizeof (magic), &bfd_offset);
2298   if (magic != RECORD_FULL_FILE_MAGIC)
2299     error (_("Version mis-match or file format error in core file %s."),
2300            bfd_get_filename (core_bfd));
2301   if (record_debug)
2302     fprintf_unfiltered (gdb_stdlog,
2303                         "  Reading 4-byte magic cookie "
2304                         "RECORD_FULL_FILE_MAGIC (0x%s)\n",
2305                         phex_nz (netorder32 (magic), 4));
2306
2307   /* Restore the entries in recfd into record_full_arch_list_head and
2308      record_full_arch_list_tail.  */
2309   record_full_arch_list_head = NULL;
2310   record_full_arch_list_tail = NULL;
2311   record_full_insn_num = 0;
2312   old_cleanups = make_cleanup (record_full_arch_list_cleanups, 0);
2313   regcache = get_current_regcache ();
2314
2315   while (1)
2316     {
2317       uint8_t rectype;
2318       uint32_t regnum, len, signal, count;
2319       uint64_t addr;
2320
2321       /* We are finished when offset reaches osec_size.  */
2322       if (bfd_offset >= osec_size)
2323         break;
2324       bfdcore_read (core_bfd, osec, &rectype, sizeof (rectype), &bfd_offset);
2325
2326       switch (rectype)
2327         {
2328         case record_full_reg: /* reg */
2329           /* Get register number to regnum.  */
2330           bfdcore_read (core_bfd, osec, &regnum,
2331                         sizeof (regnum), &bfd_offset);
2332           regnum = netorder32 (regnum);
2333
2334           rec = record_full_reg_alloc (regcache, regnum);
2335
2336           /* Get val.  */
2337           bfdcore_read (core_bfd, osec, record_full_get_loc (rec),
2338                         rec->u.reg.len, &bfd_offset);
2339
2340           if (record_debug)
2341             fprintf_unfiltered (gdb_stdlog,
2342                                 "  Reading register %d (1 "
2343                                 "plus %lu plus %d bytes)\n",
2344                                 rec->u.reg.num,
2345                                 (unsigned long) sizeof (regnum),
2346                                 rec->u.reg.len);
2347           break;
2348
2349         case record_full_mem: /* mem */
2350           /* Get len.  */
2351           bfdcore_read (core_bfd, osec, &len, 
2352                         sizeof (len), &bfd_offset);
2353           len = netorder32 (len);
2354
2355           /* Get addr.  */
2356           bfdcore_read (core_bfd, osec, &addr,
2357                         sizeof (addr), &bfd_offset);
2358           addr = netorder64 (addr);
2359
2360           rec = record_full_mem_alloc (addr, len);
2361
2362           /* Get val.  */
2363           bfdcore_read (core_bfd, osec, record_full_get_loc (rec),
2364                         rec->u.mem.len, &bfd_offset);
2365
2366           if (record_debug)
2367             fprintf_unfiltered (gdb_stdlog,
2368                                 "  Reading memory %s (1 plus "
2369                                 "%lu plus %lu plus %d bytes)\n",
2370                                 paddress (get_current_arch (),
2371                                           rec->u.mem.addr),
2372                                 (unsigned long) sizeof (addr),
2373                                 (unsigned long) sizeof (len),
2374                                 rec->u.mem.len);
2375           break;
2376
2377         case record_full_end: /* end */
2378           rec = record_full_end_alloc ();
2379           record_full_insn_num ++;
2380
2381           /* Get signal value.  */
2382           bfdcore_read (core_bfd, osec, &signal, 
2383                         sizeof (signal), &bfd_offset);
2384           signal = netorder32 (signal);
2385           rec->u.end.sigval = signal;
2386
2387           /* Get insn count.  */
2388           bfdcore_read (core_bfd, osec, &count, 
2389                         sizeof (count), &bfd_offset);
2390           count = netorder32 (count);
2391           rec->u.end.insn_num = count;
2392           record_full_insn_count = count + 1;
2393           if (record_debug)
2394             fprintf_unfiltered (gdb_stdlog,
2395                                 "  Reading record_full_end (1 + "
2396                                 "%lu + %lu bytes), offset == %s\n",
2397                                 (unsigned long) sizeof (signal),
2398                                 (unsigned long) sizeof (count),
2399                                 paddress (get_current_arch (),
2400                                           bfd_offset));
2401           break;
2402
2403         default:
2404           error (_("Bad entry type in core file %s."),
2405                  bfd_get_filename (core_bfd));
2406           break;
2407         }
2408
2409       /* Add rec to record arch list.  */
2410       record_full_arch_list_add (rec);
2411     }
2412
2413   discard_cleanups (old_cleanups);
2414
2415   /* Add record_full_arch_list_head to the end of record list.  */
2416   record_full_first.next = record_full_arch_list_head;
2417   record_full_arch_list_head->prev = &record_full_first;
2418   record_full_arch_list_tail->next = NULL;
2419   record_full_list = &record_full_first;
2420
2421   /* Update record_full_insn_max_num.  */
2422   if (record_full_insn_num > record_full_insn_max_num)
2423     {
2424       record_full_insn_max_num = record_full_insn_num;
2425       warning (_("Auto increase record/replay buffer limit to %u."),
2426                record_full_insn_max_num);
2427     }
2428
2429   /* Succeeded.  */
2430   printf_filtered (_("Restored records from core file %s.\n"),
2431                    bfd_get_filename (core_bfd));
2432
2433   print_stack_frame (get_selected_frame (NULL), 1, SRC_AND_LOC, 1);
2434 }
2435
2436 /* bfdcore_write -- write bytes into a core file section.  */
2437
2438 static inline void
2439 bfdcore_write (bfd *obfd, asection *osec, void *buf, int len, int *offset)
2440 {
2441   int ret = bfd_set_section_contents (obfd, osec, buf, *offset, len);
2442
2443   if (ret)
2444     *offset += len;
2445   else
2446     error (_("Failed to write %d bytes to core file %s ('%s')."),
2447            len, bfd_get_filename (obfd),
2448            bfd_errmsg (bfd_get_error ()));
2449 }
2450
2451 /* Restore the execution log from a file.  We use a modified elf
2452    corefile format, with an extra section for our data.  */
2453
2454 static void
2455 cmd_record_full_restore (char *args, int from_tty)
2456 {
2457   core_file_command (args, from_tty);
2458   record_full_open (args, from_tty);
2459 }
2460
2461 static void
2462 record_full_save_cleanups (void *data)
2463 {
2464   bfd *obfd = data;
2465   char *pathname = xstrdup (bfd_get_filename (obfd));
2466
2467   gdb_bfd_unref (obfd);
2468   unlink (pathname);
2469   xfree (pathname);
2470 }
2471
2472 /* Save the execution log to a file.  We use a modified elf corefile
2473    format, with an extra section for our data.  */
2474
2475 static void
2476 record_full_save (struct target_ops *self, const char *recfilename)
2477 {
2478   struct record_full_entry *cur_record_full_list;
2479   uint32_t magic;
2480   struct regcache *regcache;
2481   struct gdbarch *gdbarch;
2482   struct cleanup *old_cleanups;
2483   struct cleanup *set_cleanups;
2484   bfd *obfd;
2485   int save_size = 0;
2486   asection *osec = NULL;
2487   int bfd_offset = 0;
2488
2489   /* Open the save file.  */
2490   if (record_debug)
2491     fprintf_unfiltered (gdb_stdlog, "Saving execution log to core file '%s'\n",
2492                         recfilename);
2493
2494   /* Open the output file.  */
2495   obfd = create_gcore_bfd (recfilename);
2496   old_cleanups = make_cleanup (record_full_save_cleanups, obfd);
2497
2498   /* Save the current record entry to "cur_record_full_list".  */
2499   cur_record_full_list = record_full_list;
2500
2501   /* Get the values of regcache and gdbarch.  */
2502   regcache = get_current_regcache ();
2503   gdbarch = get_regcache_arch (regcache);
2504
2505   /* Disable the GDB operation record.  */
2506   set_cleanups = record_full_gdb_operation_disable_set ();
2507
2508   /* Reverse execute to the begin of record list.  */
2509   while (1)
2510     {
2511       /* Check for beginning and end of log.  */
2512       if (record_full_list == &record_full_first)
2513         break;
2514
2515       record_full_exec_insn (regcache, gdbarch, record_full_list);
2516
2517       if (record_full_list->prev)
2518         record_full_list = record_full_list->prev;
2519     }
2520
2521   /* Compute the size needed for the extra bfd section.  */
2522   save_size = 4;        /* magic cookie */
2523   for (record_full_list = record_full_first.next; record_full_list;
2524        record_full_list = record_full_list->next)
2525     switch (record_full_list->type)
2526       {
2527       case record_full_end:
2528         save_size += 1 + 4 + 4;
2529         break;
2530       case record_full_reg:
2531         save_size += 1 + 4 + record_full_list->u.reg.len;
2532         break;
2533       case record_full_mem:
2534         save_size += 1 + 4 + 8 + record_full_list->u.mem.len;
2535         break;
2536       }
2537
2538   /* Make the new bfd section.  */
2539   osec = bfd_make_section_anyway_with_flags (obfd, "precord",
2540                                              SEC_HAS_CONTENTS
2541                                              | SEC_READONLY);
2542   if (osec == NULL)
2543     error (_("Failed to create 'precord' section for corefile %s: %s"),
2544            recfilename,
2545            bfd_errmsg (bfd_get_error ()));
2546   bfd_set_section_size (obfd, osec, save_size);
2547   bfd_set_section_vma (obfd, osec, 0);
2548   bfd_set_section_alignment (obfd, osec, 0);
2549   bfd_section_lma (obfd, osec) = 0;
2550
2551   /* Save corefile state.  */
2552   write_gcore_file (obfd);
2553
2554   /* Write out the record log.  */
2555   /* Write the magic code.  */
2556   magic = RECORD_FULL_FILE_MAGIC;
2557   if (record_debug)
2558     fprintf_unfiltered (gdb_stdlog,
2559                         "  Writing 4-byte magic cookie "
2560                         "RECORD_FULL_FILE_MAGIC (0x%s)\n",
2561                       phex_nz (magic, 4));
2562   bfdcore_write (obfd, osec, &magic, sizeof (magic), &bfd_offset);
2563
2564   /* Save the entries to recfd and forward execute to the end of
2565      record list.  */
2566   record_full_list = &record_full_first;
2567   while (1)
2568     {
2569       /* Save entry.  */
2570       if (record_full_list != &record_full_first)
2571         {
2572           uint8_t type;
2573           uint32_t regnum, len, signal, count;
2574           uint64_t addr;
2575
2576           type = record_full_list->type;
2577           bfdcore_write (obfd, osec, &type, sizeof (type), &bfd_offset);
2578
2579           switch (record_full_list->type)
2580             {
2581             case record_full_reg: /* reg */
2582               if (record_debug)
2583                 fprintf_unfiltered (gdb_stdlog,
2584                                     "  Writing register %d (1 "
2585                                     "plus %lu plus %d bytes)\n",
2586                                     record_full_list->u.reg.num,
2587                                     (unsigned long) sizeof (regnum),
2588                                     record_full_list->u.reg.len);
2589
2590               /* Write regnum.  */
2591               regnum = netorder32 (record_full_list->u.reg.num);
2592               bfdcore_write (obfd, osec, &regnum,
2593                              sizeof (regnum), &bfd_offset);
2594
2595               /* Write regval.  */
2596               bfdcore_write (obfd, osec,
2597                              record_full_get_loc (record_full_list),
2598                              record_full_list->u.reg.len, &bfd_offset);
2599               break;
2600
2601             case record_full_mem: /* mem */
2602               if (record_debug)
2603                 fprintf_unfiltered (gdb_stdlog,
2604                                     "  Writing memory %s (1 plus "
2605                                     "%lu plus %lu plus %d bytes)\n",
2606                                     paddress (gdbarch,
2607                                               record_full_list->u.mem.addr),
2608                                     (unsigned long) sizeof (addr),
2609                                     (unsigned long) sizeof (len),
2610                                     record_full_list->u.mem.len);
2611
2612               /* Write memlen.  */
2613               len = netorder32 (record_full_list->u.mem.len);
2614               bfdcore_write (obfd, osec, &len, sizeof (len), &bfd_offset);
2615
2616               /* Write memaddr.  */
2617               addr = netorder64 (record_full_list->u.mem.addr);
2618               bfdcore_write (obfd, osec, &addr, 
2619                              sizeof (addr), &bfd_offset);
2620
2621               /* Write memval.  */
2622               bfdcore_write (obfd, osec,
2623                              record_full_get_loc (record_full_list),
2624                              record_full_list->u.mem.len, &bfd_offset);
2625               break;
2626
2627               case record_full_end:
2628                 if (record_debug)
2629                   fprintf_unfiltered (gdb_stdlog,
2630                                       "  Writing record_full_end (1 + "
2631                                       "%lu + %lu bytes)\n", 
2632                                       (unsigned long) sizeof (signal),
2633                                       (unsigned long) sizeof (count));
2634                 /* Write signal value.  */
2635                 signal = netorder32 (record_full_list->u.end.sigval);
2636                 bfdcore_write (obfd, osec, &signal,
2637                                sizeof (signal), &bfd_offset);
2638
2639                 /* Write insn count.  */
2640                 count = netorder32 (record_full_list->u.end.insn_num);
2641                 bfdcore_write (obfd, osec, &count,
2642                                sizeof (count), &bfd_offset);
2643                 break;
2644             }
2645         }
2646
2647       /* Execute entry.  */
2648       record_full_exec_insn (regcache, gdbarch, record_full_list);
2649
2650       if (record_full_list->next)
2651         record_full_list = record_full_list->next;
2652       else
2653         break;
2654     }
2655
2656   /* Reverse execute to cur_record_full_list.  */
2657   while (1)
2658     {
2659       /* Check for beginning and end of log.  */
2660       if (record_full_list == cur_record_full_list)
2661         break;
2662
2663       record_full_exec_insn (regcache, gdbarch, record_full_list);
2664
2665       if (record_full_list->prev)
2666         record_full_list = record_full_list->prev;
2667     }
2668
2669   do_cleanups (set_cleanups);
2670   gdb_bfd_unref (obfd);
2671   discard_cleanups (old_cleanups);
2672
2673   /* Succeeded.  */
2674   printf_filtered (_("Saved core file %s with execution log.\n"),
2675                    recfilename);
2676 }
2677
2678 /* record_full_goto_insn -- rewind the record log (forward or backward,
2679    depending on DIR) to the given entry, changing the program state
2680    correspondingly.  */
2681
2682 static void
2683 record_full_goto_insn (struct record_full_entry *entry,
2684                        enum exec_direction_kind dir)
2685 {
2686   struct cleanup *set_cleanups = record_full_gdb_operation_disable_set ();
2687   struct regcache *regcache = get_current_regcache ();
2688   struct gdbarch *gdbarch = get_regcache_arch (regcache);
2689
2690   /* Assume everything is valid: we will hit the entry,
2691      and we will not hit the end of the recording.  */
2692
2693   if (dir == EXEC_FORWARD)
2694     record_full_list = record_full_list->next;
2695
2696   do
2697     {
2698       record_full_exec_insn (regcache, gdbarch, record_full_list);
2699       if (dir == EXEC_REVERSE)
2700         record_full_list = record_full_list->prev;
2701       else
2702         record_full_list = record_full_list->next;
2703     } while (record_full_list != entry);
2704   do_cleanups (set_cleanups);
2705 }
2706
2707 /* Alias for "target record-full".  */
2708
2709 static void
2710 cmd_record_full_start (char *args, int from_tty)
2711 {
2712   execute_command ("target record-full", from_tty);
2713 }
2714
2715 static void
2716 set_record_full_insn_max_num (char *args, int from_tty,
2717                               struct cmd_list_element *c)
2718 {
2719   if (record_full_insn_num > record_full_insn_max_num)
2720     {
2721       /* Count down record_full_insn_num while releasing records from list.  */
2722       while (record_full_insn_num > record_full_insn_max_num)
2723        {
2724          record_full_list_release_first ();
2725          record_full_insn_num--;
2726        }
2727     }
2728 }
2729
2730 /* The "set record full" command.  */
2731
2732 static void
2733 set_record_full_command (char *args, int from_tty)
2734 {
2735   printf_unfiltered (_("\"set record full\" must be followed "
2736                        "by an apporpriate subcommand.\n"));
2737   help_list (set_record_full_cmdlist, "set record full ", all_commands,
2738              gdb_stdout);
2739 }
2740
2741 /* The "show record full" command.  */
2742
2743 static void
2744 show_record_full_command (char *args, int from_tty)
2745 {
2746   cmd_show_list (show_record_full_cmdlist, from_tty, "");
2747 }
2748
2749 /* Provide a prototype to silence -Wmissing-prototypes.  */
2750 extern initialize_file_ftype _initialize_record_full;
2751
2752 void
2753 _initialize_record_full (void)
2754 {
2755   struct cmd_list_element *c;
2756
2757   /* Init record_full_first.  */
2758   record_full_first.prev = NULL;
2759   record_full_first.next = NULL;
2760   record_full_first.type = record_full_end;
2761
2762   init_record_full_ops ();
2763   add_target (&record_full_ops);
2764   add_deprecated_target_alias (&record_full_ops, "record");
2765   init_record_full_core_ops ();
2766   add_target (&record_full_core_ops);
2767
2768   add_prefix_cmd ("full", class_obscure, cmd_record_full_start,
2769                   _("Start full execution recording."), &record_full_cmdlist,
2770                   "record full ", 0, &record_cmdlist);
2771
2772   c = add_cmd ("restore", class_obscure, cmd_record_full_restore,
2773                _("Restore the execution log from a file.\n\
2774 Argument is filename.  File must be created with 'record save'."),
2775                &record_full_cmdlist);
2776   set_cmd_completer (c, filename_completer);
2777
2778   /* Deprecate the old version without "full" prefix.  */
2779   c = add_alias_cmd ("restore", "full restore", class_obscure, 1,
2780                      &record_cmdlist);
2781   set_cmd_completer (c, filename_completer);
2782   deprecate_cmd (c, "record full restore");
2783
2784   add_prefix_cmd ("full", class_support, set_record_full_command,
2785                   _("Set record options"), &set_record_full_cmdlist,
2786                   "set record full ", 0, &set_record_cmdlist);
2787
2788   add_prefix_cmd ("full", class_support, show_record_full_command,
2789                   _("Show record options"), &show_record_full_cmdlist,
2790                   "show record full ", 0, &show_record_cmdlist);
2791
2792   /* Record instructions number limit command.  */
2793   add_setshow_boolean_cmd ("stop-at-limit", no_class,
2794                            &record_full_stop_at_limit, _("\
2795 Set whether record/replay stops when record/replay buffer becomes full."), _("\
2796 Show whether record/replay stops when record/replay buffer becomes full."),
2797                            _("Default is ON.\n\
2798 When ON, if the record/replay buffer becomes full, ask user what to do.\n\
2799 When OFF, if the record/replay buffer becomes full,\n\
2800 delete the oldest recorded instruction to make room for each new one."),
2801                            NULL, NULL,
2802                            &set_record_full_cmdlist, &show_record_full_cmdlist);
2803
2804   c = add_alias_cmd ("stop-at-limit", "full stop-at-limit", no_class, 1,
2805                      &set_record_cmdlist);
2806   deprecate_cmd (c, "set record full stop-at-limit");
2807
2808   c = add_alias_cmd ("stop-at-limit", "full stop-at-limit", no_class, 1,
2809                      &show_record_cmdlist);
2810   deprecate_cmd (c, "show record full stop-at-limit");
2811
2812   add_setshow_uinteger_cmd ("insn-number-max", no_class,
2813                             &record_full_insn_max_num,
2814                             _("Set record/replay buffer limit."),
2815                             _("Show record/replay buffer limit."), _("\
2816 Set the maximum number of instructions to be stored in the\n\
2817 record/replay buffer.  A value of either \"unlimited\" or zero means no\n\
2818 limit.  Default is 200000."),
2819                             set_record_full_insn_max_num,
2820                             NULL, &set_record_full_cmdlist,
2821                             &show_record_full_cmdlist);
2822
2823   c = add_alias_cmd ("insn-number-max", "full insn-number-max", no_class, 1,
2824                      &set_record_cmdlist);
2825   deprecate_cmd (c, "set record full insn-number-max");
2826
2827   c = add_alias_cmd ("insn-number-max", "full insn-number-max", no_class, 1,
2828                      &show_record_cmdlist);
2829   deprecate_cmd (c, "show record full insn-number-max");
2830
2831   add_setshow_boolean_cmd ("memory-query", no_class,
2832                            &record_full_memory_query, _("\
2833 Set whether query if PREC cannot record memory change of next instruction."),
2834                            _("\
2835 Show whether query if PREC cannot record memory change of next instruction."),
2836                            _("\
2837 Default is OFF.\n\
2838 When ON, query if PREC cannot record memory change of next instruction."),
2839                            NULL, NULL,
2840                            &set_record_full_cmdlist,
2841                            &show_record_full_cmdlist);
2842
2843   c = add_alias_cmd ("memory-query", "full memory-query", no_class, 1,
2844                      &set_record_cmdlist);
2845   deprecate_cmd (c, "set record full memory-query");
2846
2847   c = add_alias_cmd ("memory-query", "full memory-query", no_class, 1,
2848                      &show_record_cmdlist);
2849   deprecate_cmd (c, "show record full memory-query");
2850 }