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