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