Update copyright year range in all GDB files.
[external/binutils.git] / gdb / record-full.c
1 /* Process record and replay target for GDB, the GNU debugger.
2
3    Copyright (C) 2013-2019 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 "inferior.h"
25 #include "event-top.h"
26 #include "completer.h"
27 #include "arch-utils.h"
28 #include "gdbcore.h"
29 #include "exec.h"
30 #include "record.h"
31 #include "record-full.h"
32 #include "elf-bfd.h"
33 #include "gcore.h"
34 #include "event-loop.h"
35 #include "inf-loop.h"
36 #include "gdb_bfd.h"
37 #include "observable.h"
38 #include "infrun.h"
39 #include "common/gdb_unlinker.h"
40 #include "common/byte-vector.h"
41
42 #include <signal.h>
43
44 /* This module implements "target record-full", also known as "process
45    record and replay".  This target sits on top of a "normal" target
46    (a target that "has execution"), and provides a record and replay
47    functionality, including reverse debugging.
48
49    Target record has two modes: recording, and replaying.
50
51    In record mode, we intercept the resume and wait methods.
52    Whenever gdb resumes the target, we run the target in single step
53    mode, and we build up an execution log in which, for each executed
54    instruction, we record all changes in memory and register state.
55    This is invisible to the user, to whom it just looks like an
56    ordinary debugging session (except for performance degredation).
57
58    In replay mode, instead of actually letting the inferior run as a
59    process, we simulate its execution by playing back the recorded
60    execution log.  For each instruction in the log, we simulate the
61    instruction's side effects by duplicating the changes that it would
62    have made on memory and registers.  */
63
64 #define DEFAULT_RECORD_FULL_INSN_MAX_NUM        200000
65
66 #define RECORD_FULL_IS_REPLAY \
67   (record_full_list->next || ::execution_direction == EXEC_REVERSE)
68
69 #define RECORD_FULL_FILE_MAGIC  netorder32(0x20091016)
70
71 /* These are the core structs of the process record functionality.
72
73    A record_full_entry is a record of the value change of a register
74    ("record_full_reg") or a part of memory ("record_full_mem").  And each
75    instruction must have a struct record_full_entry ("record_full_end")
76    that indicates that this is the last struct record_full_entry of this
77    instruction.
78
79    Each struct record_full_entry is linked to "record_full_list" by "prev"
80    and "next" pointers.  */
81
82 struct record_full_mem_entry
83 {
84   CORE_ADDR addr;
85   int len;
86   /* Set this flag if target memory for this entry
87      can no longer be accessed.  */
88   int mem_entry_not_accessible;
89   union
90   {
91     gdb_byte *ptr;
92     gdb_byte buf[sizeof (gdb_byte *)];
93   } u;
94 };
95
96 struct record_full_reg_entry
97 {
98   unsigned short num;
99   unsigned short len;
100   union 
101   {
102     gdb_byte *ptr;
103     gdb_byte buf[2 * sizeof (gdb_byte *)];
104   } u;
105 };
106
107 struct record_full_end_entry
108 {
109   enum gdb_signal sigval;
110   ULONGEST insn_num;
111 };
112
113 enum record_full_type
114 {
115   record_full_end = 0,
116   record_full_reg,
117   record_full_mem
118 };
119
120 /* This is the data structure that makes up the execution log.
121
122    The execution log consists of a single linked list of entries
123    of type "struct record_full_entry".  It is doubly linked so that it
124    can be traversed in either direction.
125
126    The start of the list is anchored by a struct called
127    "record_full_first".  The pointer "record_full_list" either points
128    to the last entry that was added to the list (in record mode), or to
129    the next entry in the list that will be executed (in replay mode).
130
131    Each list element (struct record_full_entry), in addition to next
132    and prev pointers, consists of a union of three entry types: mem,
133    reg, and end.  A field called "type" determines which entry type is
134    represented by a given list element.
135
136    Each instruction that is added to the execution log is represented
137    by a variable number of list elements ('entries').  The instruction
138    will have one "reg" entry for each register that is changed by 
139    executing the instruction (including the PC in every case).  It 
140    will also have one "mem" entry for each memory change.  Finally,
141    each instruction will have an "end" entry that separates it from
142    the changes associated with the next instruction.  */
143
144 struct record_full_entry
145 {
146   struct record_full_entry *prev;
147   struct record_full_entry *next;
148   enum record_full_type type;
149   union
150   {
151     /* reg */
152     struct record_full_reg_entry reg;
153     /* mem */
154     struct record_full_mem_entry mem;
155     /* end */
156     struct record_full_end_entry end;
157   } u;
158 };
159
160 /* If true, query if PREC cannot record memory
161    change of next instruction.  */
162 int record_full_memory_query = 0;
163
164 struct record_full_core_buf_entry
165 {
166   struct record_full_core_buf_entry *prev;
167   struct target_section *p;
168   bfd_byte *buf;
169 };
170
171 /* Record buf with core target.  */
172 static detached_regcache *record_full_core_regbuf = NULL;
173 static struct target_section *record_full_core_start;
174 static struct target_section *record_full_core_end;
175 static struct record_full_core_buf_entry *record_full_core_buf_list = NULL;
176
177 /* The following variables are used for managing the linked list that
178    represents the execution log.
179
180    record_full_first is the anchor that holds down the beginning of
181    the list.
182
183    record_full_list serves two functions:
184      1) In record mode, it anchors the end of the list.
185      2) In replay mode, it traverses the list and points to
186         the next instruction that must be emulated.
187
188    record_full_arch_list_head and record_full_arch_list_tail are used
189    to manage a separate list, which is used to build up the change
190    elements of the currently executing instruction during record mode.
191    When this instruction has been completely annotated in the "arch
192    list", it will be appended to the main execution log.  */
193
194 static struct record_full_entry record_full_first;
195 static struct record_full_entry *record_full_list = &record_full_first;
196 static struct record_full_entry *record_full_arch_list_head = NULL;
197 static struct record_full_entry *record_full_arch_list_tail = NULL;
198
199 /* 1 ask user. 0 auto delete the last struct record_full_entry.  */
200 static int record_full_stop_at_limit = 1;
201 /* Maximum allowed number of insns in execution log.  */
202 static unsigned int record_full_insn_max_num
203         = DEFAULT_RECORD_FULL_INSN_MAX_NUM;
204 /* Actual count of insns presently in execution log.  */
205 static unsigned int record_full_insn_num = 0;
206 /* Count of insns logged so far (may be larger
207    than count of insns presently in execution log).  */
208 static ULONGEST record_full_insn_count;
209
210 static const char record_longname[]
211   = N_("Process record and replay target");
212 static const char record_doc[]
213   = N_("Log program while executing and replay execution from log.");
214
215 /* Base class implementing functionality common to both the
216    "record-full" and "record-core" targets.  */
217
218 class record_full_base_target : public target_ops
219 {
220 public:
221   const target_info &info () const override = 0;
222
223   strata stratum () const override { return record_stratum; }
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               ret = ops->beneath ()->wait (ptid, status, options);
1204               if (status->kind == TARGET_WAITKIND_IGNORE)
1205                 {
1206                   if (record_debug)
1207                     fprintf_unfiltered (gdb_stdlog,
1208                                         "Process record: record_full_wait "
1209                                         "target beneath not done yet\n");
1210                   return ret;
1211                 }
1212
1213               for (thread_info *tp : all_non_exited_threads ())
1214                 delete_single_step_breakpoints (tp);
1215
1216               if (record_full_resume_step)
1217                 return ret;
1218
1219               /* Is this a SIGTRAP?  */
1220               if (status->kind == TARGET_WAITKIND_STOPPED
1221                   && status->value.sig == GDB_SIGNAL_TRAP)
1222                 {
1223                   struct regcache *regcache;
1224                   enum target_stop_reason *stop_reason_p
1225                     = &record_full_stop_reason;
1226
1227                   /* Yes -- this is likely our single-step finishing,
1228                      but check if there's any reason the core would be
1229                      interested in the event.  */
1230
1231                   registers_changed ();
1232                   regcache = get_current_regcache ();
1233                   tmp_pc = regcache_read_pc (regcache);
1234                   const struct address_space *aspace = regcache->aspace ();
1235
1236                   if (target_stopped_by_watchpoint ())
1237                     {
1238                       /* Always interested in watchpoints.  */
1239                     }
1240                   else if (record_check_stopped_by_breakpoint (aspace, tmp_pc,
1241                                                                stop_reason_p))
1242                     {
1243                       /* There is a breakpoint here.  Let the core
1244                          handle it.  */
1245                     }
1246                   else
1247                     {
1248                       /* This is a single-step trap.  Record the
1249                          insn and issue another step.
1250                          FIXME: this part can be a random SIGTRAP too.
1251                          But GDB cannot handle it.  */
1252                       int step = 1;
1253
1254                       if (!record_full_message_wrapper_safe (regcache,
1255                                                              GDB_SIGNAL_0))
1256                         {
1257                            status->kind = TARGET_WAITKIND_STOPPED;
1258                            status->value.sig = GDB_SIGNAL_0;
1259                            break;
1260                         }
1261
1262                       if (gdbarch_software_single_step_p (gdbarch))
1263                         {
1264                           /* Try to insert the software single step breakpoint.
1265                              If insert success, set step to 0.  */
1266                           set_executing (inferior_ptid, 0);
1267                           reinit_frame_cache ();
1268
1269                           step = !insert_single_step_breakpoints (gdbarch);
1270
1271                           set_executing (inferior_ptid, 1);
1272                         }
1273
1274                       if (record_debug)
1275                         fprintf_unfiltered (gdb_stdlog,
1276                                             "Process record: record_full_wait "
1277                                             "issuing one more step in the "
1278                                             "target beneath\n");
1279                       ops->beneath ()->resume (ptid, step, GDB_SIGNAL_0);
1280                       ops->beneath ()->commit_resume ();
1281                       continue;
1282                     }
1283                 }
1284
1285               /* The inferior is broken by a breakpoint or a signal.  */
1286               break;
1287             }
1288
1289           return ret;
1290         }
1291     }
1292   else
1293     {
1294       struct regcache *regcache = get_current_regcache ();
1295       struct gdbarch *gdbarch = regcache->arch ();
1296       const struct address_space *aspace = regcache->aspace ();
1297       int continue_flag = 1;
1298       int first_record_full_end = 1;
1299
1300       TRY
1301         {
1302           CORE_ADDR tmp_pc;
1303
1304           record_full_stop_reason = TARGET_STOPPED_BY_NO_REASON;
1305           status->kind = TARGET_WAITKIND_STOPPED;
1306
1307           /* Check breakpoint when forward execute.  */
1308           if (execution_direction == EXEC_FORWARD)
1309             {
1310               tmp_pc = regcache_read_pc (regcache);
1311               if (record_check_stopped_by_breakpoint (aspace, tmp_pc,
1312                                                       &record_full_stop_reason))
1313                 {
1314                   if (record_debug)
1315                     fprintf_unfiltered (gdb_stdlog,
1316                                         "Process record: break at %s.\n",
1317                                         paddress (gdbarch, tmp_pc));
1318                   goto replay_out;
1319                 }
1320             }
1321
1322           /* If GDB is in terminal_inferior mode, it will not get the
1323              signal.  And in GDB replay mode, GDB doesn't need to be
1324              in terminal_inferior mode, because inferior will not
1325              executed.  Then set it to terminal_ours to make GDB get
1326              the signal.  */
1327           target_terminal::ours ();
1328
1329           /* In EXEC_FORWARD mode, record_full_list points to the tail of prev
1330              instruction.  */
1331           if (execution_direction == EXEC_FORWARD && record_full_list->next)
1332             record_full_list = record_full_list->next;
1333
1334           /* Loop over the record_full_list, looking for the next place to
1335              stop.  */
1336           do
1337             {
1338               /* Check for beginning and end of log.  */
1339               if (execution_direction == EXEC_REVERSE
1340                   && record_full_list == &record_full_first)
1341                 {
1342                   /* Hit beginning of record log in reverse.  */
1343                   status->kind = TARGET_WAITKIND_NO_HISTORY;
1344                   break;
1345                 }
1346               if (execution_direction != EXEC_REVERSE
1347                   && !record_full_list->next)
1348                 {
1349                   /* Hit end of record log going forward.  */
1350                   status->kind = TARGET_WAITKIND_NO_HISTORY;
1351                   break;
1352                 }
1353
1354               record_full_exec_insn (regcache, gdbarch, record_full_list);
1355
1356               if (record_full_list->type == record_full_end)
1357                 {
1358                   if (record_debug > 1)
1359                     fprintf_unfiltered
1360                       (gdb_stdlog,
1361                        "Process record: record_full_end %s to "
1362                        "inferior.\n",
1363                        host_address_to_string (record_full_list));
1364
1365                   if (first_record_full_end
1366                       && execution_direction == EXEC_REVERSE)
1367                     {
1368                       /* When reverse excute, the first
1369                          record_full_end is the part of current
1370                          instruction.  */
1371                       first_record_full_end = 0;
1372                     }
1373                   else
1374                     {
1375                       /* In EXEC_REVERSE mode, this is the
1376                          record_full_end of prev instruction.  In
1377                          EXEC_FORWARD mode, this is the
1378                          record_full_end of current instruction.  */
1379                       /* step */
1380                       if (record_full_resume_step)
1381                         {
1382                           if (record_debug > 1)
1383                             fprintf_unfiltered (gdb_stdlog,
1384                                                 "Process record: step.\n");
1385                           continue_flag = 0;
1386                         }
1387
1388                       /* check breakpoint */
1389                       tmp_pc = regcache_read_pc (regcache);
1390                       if (record_check_stopped_by_breakpoint
1391                           (aspace, tmp_pc, &record_full_stop_reason))
1392                         {
1393                           if (record_debug)
1394                             fprintf_unfiltered (gdb_stdlog,
1395                                                 "Process record: break "
1396                                                 "at %s.\n",
1397                                                 paddress (gdbarch, tmp_pc));
1398
1399                           continue_flag = 0;
1400                         }
1401
1402                       if (record_full_stop_reason
1403                           == TARGET_STOPPED_BY_WATCHPOINT)
1404                         {
1405                           if (record_debug)
1406                             fprintf_unfiltered (gdb_stdlog,
1407                                                 "Process record: hit hw "
1408                                                 "watchpoint.\n");
1409                           continue_flag = 0;
1410                         }
1411                       /* Check target signal */
1412                       if (record_full_list->u.end.sigval != GDB_SIGNAL_0)
1413                         /* FIXME: better way to check */
1414                         continue_flag = 0;
1415                     }
1416                 }
1417
1418               if (continue_flag)
1419                 {
1420                   if (execution_direction == EXEC_REVERSE)
1421                     {
1422                       if (record_full_list->prev)
1423                         record_full_list = record_full_list->prev;
1424                     }
1425                   else
1426                     {
1427                       if (record_full_list->next)
1428                         record_full_list = record_full_list->next;
1429                     }
1430                 }
1431             }
1432           while (continue_flag);
1433
1434         replay_out:
1435           if (record_full_get_sig)
1436             status->value.sig = GDB_SIGNAL_INT;
1437           else if (record_full_list->u.end.sigval != GDB_SIGNAL_0)
1438             /* FIXME: better way to check */
1439             status->value.sig = record_full_list->u.end.sigval;
1440           else
1441             status->value.sig = GDB_SIGNAL_TRAP;
1442         }
1443       CATCH (ex, RETURN_MASK_ALL)
1444         {
1445           if (execution_direction == EXEC_REVERSE)
1446             {
1447               if (record_full_list->next)
1448                 record_full_list = record_full_list->next;
1449             }
1450           else
1451             record_full_list = record_full_list->prev;
1452
1453           throw_exception (ex);
1454         }
1455       END_CATCH
1456     }
1457
1458   signal (SIGINT, handle_sigint);
1459
1460   return inferior_ptid;
1461 }
1462
1463 ptid_t
1464 record_full_base_target::wait (ptid_t ptid, struct target_waitstatus *status,
1465                                int options)
1466 {
1467   ptid_t return_ptid;
1468
1469   return_ptid = record_full_wait_1 (this, ptid, status, options);
1470   if (status->kind != TARGET_WAITKIND_IGNORE)
1471     {
1472       /* We're reporting a stop.  Make sure any spurious
1473          target_wait(WNOHANG) doesn't advance the target until the
1474          core wants us resumed again.  */
1475       record_full_resumed = 0;
1476     }
1477   return return_ptid;
1478 }
1479
1480 bool
1481 record_full_base_target::stopped_by_watchpoint ()
1482 {
1483   if (RECORD_FULL_IS_REPLAY)
1484     return record_full_stop_reason == TARGET_STOPPED_BY_WATCHPOINT;
1485   else
1486     return beneath ()->stopped_by_watchpoint ();
1487 }
1488
1489 bool
1490 record_full_base_target::stopped_data_address (CORE_ADDR *addr_p)
1491 {
1492   if (RECORD_FULL_IS_REPLAY)
1493     return false;
1494   else
1495     return this->beneath ()->stopped_data_address (addr_p);
1496 }
1497
1498 /* The stopped_by_sw_breakpoint method of target record-full.  */
1499
1500 bool
1501 record_full_base_target::stopped_by_sw_breakpoint ()
1502 {
1503   return record_full_stop_reason == TARGET_STOPPED_BY_SW_BREAKPOINT;
1504 }
1505
1506 /* The supports_stopped_by_sw_breakpoint method of target
1507    record-full.  */
1508
1509 bool
1510 record_full_base_target::supports_stopped_by_sw_breakpoint ()
1511 {
1512   return true;
1513 }
1514
1515 /* The stopped_by_hw_breakpoint method of target record-full.  */
1516
1517 bool
1518 record_full_base_target::stopped_by_hw_breakpoint ()
1519 {
1520   return record_full_stop_reason == TARGET_STOPPED_BY_HW_BREAKPOINT;
1521 }
1522
1523 /* The supports_stopped_by_sw_breakpoint method of target
1524    record-full.  */
1525
1526 bool
1527 record_full_base_target::supports_stopped_by_hw_breakpoint ()
1528 {
1529   return true;
1530 }
1531
1532 /* Record registers change (by user or by GDB) to list as an instruction.  */
1533
1534 static void
1535 record_full_registers_change (struct regcache *regcache, int regnum)
1536 {
1537   /* Check record_full_insn_num.  */
1538   record_full_check_insn_num ();
1539
1540   record_full_arch_list_head = NULL;
1541   record_full_arch_list_tail = NULL;
1542
1543   if (regnum < 0)
1544     {
1545       int i;
1546
1547       for (i = 0; i < gdbarch_num_regs (regcache->arch ()); i++)
1548         {
1549           if (record_full_arch_list_add_reg (regcache, i))
1550             {
1551               record_full_list_release (record_full_arch_list_tail);
1552               error (_("Process record: failed to record execution log."));
1553             }
1554         }
1555     }
1556   else
1557     {
1558       if (record_full_arch_list_add_reg (regcache, regnum))
1559         {
1560           record_full_list_release (record_full_arch_list_tail);
1561           error (_("Process record: failed to record execution log."));
1562         }
1563     }
1564   if (record_full_arch_list_add_end ())
1565     {
1566       record_full_list_release (record_full_arch_list_tail);
1567       error (_("Process record: failed to record execution log."));
1568     }
1569   record_full_list->next = record_full_arch_list_head;
1570   record_full_arch_list_head->prev = record_full_list;
1571   record_full_list = record_full_arch_list_tail;
1572
1573   if (record_full_insn_num == record_full_insn_max_num)
1574     record_full_list_release_first ();
1575   else
1576     record_full_insn_num++;
1577 }
1578
1579 /* "store_registers" method for process record target.  */
1580
1581 void
1582 record_full_target::store_registers (struct regcache *regcache, int regno)
1583 {
1584   if (!record_full_gdb_operation_disable)
1585     {
1586       if (RECORD_FULL_IS_REPLAY)
1587         {
1588           int n;
1589
1590           /* Let user choose if he wants to write register or not.  */
1591           if (regno < 0)
1592             n =
1593               query (_("Because GDB is in replay mode, changing the "
1594                        "value of a register will make the execution "
1595                        "log unusable from this point onward.  "
1596                        "Change all registers?"));
1597           else
1598             n =
1599               query (_("Because GDB is in replay mode, changing the value "
1600                        "of a register will make the execution log unusable "
1601                        "from this point onward.  Change register %s?"),
1602                       gdbarch_register_name (regcache->arch (),
1603                                                regno));
1604
1605           if (!n)
1606             {
1607               /* Invalidate the value of regcache that was set in function
1608                  "regcache_raw_write".  */
1609               if (regno < 0)
1610                 {
1611                   int i;
1612
1613                   for (i = 0;
1614                        i < gdbarch_num_regs (regcache->arch ());
1615                        i++)
1616                     regcache->invalidate (i);
1617                 }
1618               else
1619                 regcache->invalidate (regno);
1620
1621               error (_("Process record canceled the operation."));
1622             }
1623
1624           /* Destroy the record from here forward.  */
1625           record_full_list_release_following (record_full_list);
1626         }
1627
1628       record_full_registers_change (regcache, regno);
1629     }
1630   this->beneath ()->store_registers (regcache, regno);
1631 }
1632
1633 /* "xfer_partial" method.  Behavior is conditional on
1634    RECORD_FULL_IS_REPLAY.
1635    In replay mode, we cannot write memory unles we are willing to
1636    invalidate the record/replay log from this point forward.  */
1637
1638 enum target_xfer_status
1639 record_full_target::xfer_partial (enum target_object object,
1640                                   const char *annex, gdb_byte *readbuf,
1641                                   const gdb_byte *writebuf, ULONGEST offset,
1642                                   ULONGEST len, ULONGEST *xfered_len)
1643 {
1644   if (!record_full_gdb_operation_disable
1645       && (object == TARGET_OBJECT_MEMORY
1646           || object == TARGET_OBJECT_RAW_MEMORY) && writebuf)
1647     {
1648       if (RECORD_FULL_IS_REPLAY)
1649         {
1650           /* Let user choose if he wants to write memory or not.  */
1651           if (!query (_("Because GDB is in replay mode, writing to memory "
1652                         "will make the execution log unusable from this "
1653                         "point onward.  Write memory at address %s?"),
1654                        paddress (target_gdbarch (), offset)))
1655             error (_("Process record canceled the operation."));
1656
1657           /* Destroy the record from here forward.  */
1658           record_full_list_release_following (record_full_list);
1659         }
1660
1661       /* Check record_full_insn_num */
1662       record_full_check_insn_num ();
1663
1664       /* Record registers change to list as an instruction.  */
1665       record_full_arch_list_head = NULL;
1666       record_full_arch_list_tail = NULL;
1667       if (record_full_arch_list_add_mem (offset, len))
1668         {
1669           record_full_list_release (record_full_arch_list_tail);
1670           if (record_debug)
1671             fprintf_unfiltered (gdb_stdlog,
1672                                 "Process record: failed to record "
1673                                 "execution log.");
1674           return TARGET_XFER_E_IO;
1675         }
1676       if (record_full_arch_list_add_end ())
1677         {
1678           record_full_list_release (record_full_arch_list_tail);
1679           if (record_debug)
1680             fprintf_unfiltered (gdb_stdlog,
1681                                 "Process record: failed to record "
1682                                 "execution log.");
1683           return TARGET_XFER_E_IO;
1684         }
1685       record_full_list->next = record_full_arch_list_head;
1686       record_full_arch_list_head->prev = record_full_list;
1687       record_full_list = record_full_arch_list_tail;
1688
1689       if (record_full_insn_num == record_full_insn_max_num)
1690         record_full_list_release_first ();
1691       else
1692         record_full_insn_num++;
1693     }
1694
1695   return this->beneath ()->xfer_partial (object, annex, readbuf, writebuf,
1696                                          offset, len, xfered_len);
1697 }
1698
1699 /* This structure represents a breakpoint inserted while the record
1700    target is active.  We use this to know when to install/remove
1701    breakpoints in/from the target beneath.  For example, a breakpoint
1702    may be inserted while recording, but removed when not replaying nor
1703    recording.  In that case, the breakpoint had not been inserted on
1704    the target beneath, so we should not try to remove it there.  */
1705
1706 struct record_full_breakpoint
1707 {
1708   record_full_breakpoint (struct address_space *address_space_,
1709                           CORE_ADDR addr_,
1710                           bool in_target_beneath_)
1711     : address_space (address_space_),
1712       addr (addr_),
1713       in_target_beneath (in_target_beneath_)
1714   {
1715   }
1716
1717   /* The address and address space the breakpoint was set at.  */
1718   struct address_space *address_space;
1719   CORE_ADDR addr;
1720
1721   /* True when the breakpoint has been also installed in the target
1722      beneath.  This will be false for breakpoints set during replay or
1723      when recording.  */
1724   bool in_target_beneath;
1725 };
1726
1727 /* The list of breakpoints inserted while the record target is
1728    active.  */
1729 static std::vector<record_full_breakpoint> record_full_breakpoints;
1730
1731 static void
1732 record_full_sync_record_breakpoints (struct bp_location *loc, void *data)
1733 {
1734   if (loc->loc_type != bp_loc_software_breakpoint)
1735       return;
1736
1737   if (loc->inserted)
1738     {
1739       record_full_breakpoints.emplace_back
1740         (loc->target_info.placed_address_space,
1741          loc->target_info.placed_address,
1742          1);
1743     }
1744 }
1745
1746 /* Sync existing breakpoints to record_full_breakpoints.  */
1747
1748 static void
1749 record_full_init_record_breakpoints (void)
1750 {
1751   record_full_breakpoints.clear ();
1752
1753   iterate_over_bp_locations (record_full_sync_record_breakpoints);
1754 }
1755
1756 /* Behavior is conditional on RECORD_FULL_IS_REPLAY.  We will not actually
1757    insert or remove breakpoints in the real target when replaying, nor
1758    when recording.  */
1759
1760 int
1761 record_full_target::insert_breakpoint (struct gdbarch *gdbarch,
1762                                        struct bp_target_info *bp_tgt)
1763 {
1764   bool in_target_beneath = false;
1765
1766   if (!RECORD_FULL_IS_REPLAY)
1767     {
1768       /* When recording, we currently always single-step, so we don't
1769          really need to install regular breakpoints in the inferior.
1770          However, we do have to insert software single-step
1771          breakpoints, in case the target can't hardware step.  To keep
1772          things simple, we always insert.  */
1773
1774       scoped_restore restore_operation_disable
1775         = record_full_gdb_operation_disable_set ();
1776
1777       int ret = this->beneath ()->insert_breakpoint (gdbarch, bp_tgt);
1778       if (ret != 0)
1779         return ret;
1780
1781       in_target_beneath = true;
1782     }
1783
1784   /* Use the existing entries if found in order to avoid duplication
1785      in record_full_breakpoints.  */
1786
1787   for (const record_full_breakpoint &bp : record_full_breakpoints)
1788     {
1789       if (bp.addr == bp_tgt->placed_address
1790           && bp.address_space == bp_tgt->placed_address_space)
1791         {
1792           gdb_assert (bp.in_target_beneath == in_target_beneath);
1793           return 0;
1794         }
1795     }
1796
1797   record_full_breakpoints.emplace_back (bp_tgt->placed_address_space,
1798                                         bp_tgt->placed_address,
1799                                         in_target_beneath);
1800   return 0;
1801 }
1802
1803 /* "remove_breakpoint" method for process record target.  */
1804
1805 int
1806 record_full_target::remove_breakpoint (struct gdbarch *gdbarch,
1807                                        struct bp_target_info *bp_tgt,
1808                                        enum remove_bp_reason reason)
1809 {
1810   for (auto iter = record_full_breakpoints.begin ();
1811        iter != record_full_breakpoints.end ();
1812        ++iter)
1813     {
1814       struct record_full_breakpoint &bp = *iter;
1815
1816       if (bp.addr == bp_tgt->placed_address
1817           && bp.address_space == bp_tgt->placed_address_space)
1818         {
1819           if (bp.in_target_beneath)
1820             {
1821               scoped_restore restore_operation_disable
1822                 = record_full_gdb_operation_disable_set ();
1823
1824               int ret = this->beneath ()->remove_breakpoint (gdbarch, bp_tgt,
1825                                                              reason);
1826               if (ret != 0)
1827                 return ret;
1828             }
1829
1830           if (reason == REMOVE_BREAKPOINT)
1831             unordered_remove (record_full_breakpoints, iter);
1832           return 0;
1833         }
1834     }
1835
1836   gdb_assert_not_reached ("removing unknown breakpoint");
1837 }
1838
1839 /* "can_execute_reverse" method for process record target.  */
1840
1841 bool
1842 record_full_base_target::can_execute_reverse ()
1843 {
1844   return true;
1845 }
1846
1847 /* "get_bookmark" method for process record and prec over core.  */
1848
1849 gdb_byte *
1850 record_full_base_target::get_bookmark (const char *args, int from_tty)
1851 {
1852   char *ret = NULL;
1853
1854   /* Return stringified form of instruction count.  */
1855   if (record_full_list && record_full_list->type == record_full_end)
1856     ret = xstrdup (pulongest (record_full_list->u.end.insn_num));
1857
1858   if (record_debug)
1859     {
1860       if (ret)
1861         fprintf_unfiltered (gdb_stdlog,
1862                             "record_full_get_bookmark returns %s\n", ret);
1863       else
1864         fprintf_unfiltered (gdb_stdlog,
1865                             "record_full_get_bookmark returns NULL\n");
1866     }
1867   return (gdb_byte *) ret;
1868 }
1869
1870 /* "goto_bookmark" method for process record and prec over core.  */
1871
1872 void
1873 record_full_base_target::goto_bookmark (const gdb_byte *raw_bookmark,
1874                                         int from_tty)
1875 {
1876   const char *bookmark = (const char *) raw_bookmark;
1877
1878   if (record_debug)
1879     fprintf_unfiltered (gdb_stdlog,
1880                         "record_full_goto_bookmark receives %s\n", bookmark);
1881
1882   std::string name_holder;
1883   if (bookmark[0] == '\'' || bookmark[0] == '\"')
1884     {
1885       if (bookmark[strlen (bookmark) - 1] != bookmark[0])
1886         error (_("Unbalanced quotes: %s"), bookmark);
1887
1888       name_holder = std::string (bookmark + 1, strlen (bookmark) - 2);
1889       bookmark = name_holder.c_str ();
1890     }
1891
1892   record_goto (bookmark);
1893 }
1894
1895 enum exec_direction_kind
1896 record_full_base_target::execution_direction ()
1897 {
1898   return record_full_execution_dir;
1899 }
1900
1901 /* The record_method method of target record-full.  */
1902
1903 enum record_method
1904 record_full_base_target::record_method (ptid_t ptid)
1905 {
1906   return RECORD_METHOD_FULL;
1907 }
1908
1909 void
1910 record_full_base_target::info_record ()
1911 {
1912   struct record_full_entry *p;
1913
1914   if (RECORD_FULL_IS_REPLAY)
1915     printf_filtered (_("Replay mode:\n"));
1916   else
1917     printf_filtered (_("Record mode:\n"));
1918
1919   /* Find entry for first actual instruction in the log.  */
1920   for (p = record_full_first.next;
1921        p != NULL && p->type != record_full_end;
1922        p = p->next)
1923     ;
1924
1925   /* Do we have a log at all?  */
1926   if (p != NULL && p->type == record_full_end)
1927     {
1928       /* Display instruction number for first instruction in the log.  */
1929       printf_filtered (_("Lowest recorded instruction number is %s.\n"),
1930                        pulongest (p->u.end.insn_num));
1931
1932       /* If in replay mode, display where we are in the log.  */
1933       if (RECORD_FULL_IS_REPLAY)
1934         printf_filtered (_("Current instruction number is %s.\n"),
1935                          pulongest (record_full_list->u.end.insn_num));
1936
1937       /* Display instruction number for last instruction in the log.  */
1938       printf_filtered (_("Highest recorded instruction number is %s.\n"),
1939                        pulongest (record_full_insn_count));
1940
1941       /* Display log count.  */
1942       printf_filtered (_("Log contains %u instructions.\n"),
1943                        record_full_insn_num);
1944     }
1945   else
1946     printf_filtered (_("No instructions have been logged.\n"));
1947
1948   /* Display max log size.  */
1949   printf_filtered (_("Max logged instructions is %u.\n"),
1950                    record_full_insn_max_num);
1951 }
1952
1953 bool
1954 record_full_base_target::supports_delete_record ()
1955 {
1956   return true;
1957 }
1958
1959 /* The "delete_record" target method.  */
1960
1961 void
1962 record_full_base_target::delete_record ()
1963 {
1964   record_full_list_release_following (record_full_list);
1965 }
1966
1967 /* The "record_is_replaying" target method.  */
1968
1969 bool
1970 record_full_base_target::record_is_replaying (ptid_t ptid)
1971 {
1972   return RECORD_FULL_IS_REPLAY;
1973 }
1974
1975 /* The "record_will_replay" target method.  */
1976
1977 bool
1978 record_full_base_target::record_will_replay (ptid_t ptid, int dir)
1979 {
1980   /* We can currently only record when executing forwards.  Should we be able
1981      to record when executing backwards on targets that support reverse
1982      execution, this needs to be changed.  */
1983
1984   return RECORD_FULL_IS_REPLAY || dir == EXEC_REVERSE;
1985 }
1986
1987 /* Go to a specific entry.  */
1988
1989 static void
1990 record_full_goto_entry (struct record_full_entry *p)
1991 {
1992   if (p == NULL)
1993     error (_("Target insn not found."));
1994   else if (p == record_full_list)
1995     error (_("Already at target insn."));
1996   else if (p->u.end.insn_num > record_full_list->u.end.insn_num)
1997     {
1998       printf_filtered (_("Go forward to insn number %s\n"),
1999                        pulongest (p->u.end.insn_num));
2000       record_full_goto_insn (p, EXEC_FORWARD);
2001     }
2002   else
2003     {
2004       printf_filtered (_("Go backward to insn number %s\n"),
2005                        pulongest (p->u.end.insn_num));
2006       record_full_goto_insn (p, EXEC_REVERSE);
2007     }
2008
2009   registers_changed ();
2010   reinit_frame_cache ();
2011   inferior_thread ()->suspend.stop_pc
2012     = regcache_read_pc (get_current_regcache ());
2013   print_stack_frame (get_selected_frame (NULL), 1, SRC_AND_LOC, 1);
2014 }
2015
2016 /* The "goto_record_begin" target method.  */
2017
2018 void
2019 record_full_base_target::goto_record_begin ()
2020 {
2021   struct record_full_entry *p = NULL;
2022
2023   for (p = &record_full_first; p != NULL; p = p->next)
2024     if (p->type == record_full_end)
2025       break;
2026
2027   record_full_goto_entry (p);
2028 }
2029
2030 /* The "goto_record_end" target method.  */
2031
2032 void
2033 record_full_base_target::goto_record_end ()
2034 {
2035   struct record_full_entry *p = NULL;
2036
2037   for (p = record_full_list; p->next != NULL; p = p->next)
2038     ;
2039   for (; p!= NULL; p = p->prev)
2040     if (p->type == record_full_end)
2041       break;
2042
2043   record_full_goto_entry (p);
2044 }
2045
2046 /* The "goto_record" target method.  */
2047
2048 void
2049 record_full_base_target::goto_record (ULONGEST target_insn)
2050 {
2051   struct record_full_entry *p = NULL;
2052
2053   for (p = &record_full_first; p != NULL; p = p->next)
2054     if (p->type == record_full_end && p->u.end.insn_num == target_insn)
2055       break;
2056
2057   record_full_goto_entry (p);
2058 }
2059
2060 /* The "record_stop_replaying" target method.  */
2061
2062 void
2063 record_full_base_target::record_stop_replaying ()
2064 {
2065   goto_record_end ();
2066 }
2067
2068 /* "resume" method for prec over corefile.  */
2069
2070 void
2071 record_full_core_target::resume (ptid_t ptid, int step,
2072                                  enum gdb_signal signal)
2073 {
2074   record_full_resume_step = step;
2075   record_full_resumed = 1;
2076   record_full_execution_dir = ::execution_direction;
2077
2078   /* We are about to start executing the inferior (or simulate it),
2079      let's register it with the event loop.  */
2080   if (target_can_async_p ())
2081     target_async (1);
2082 }
2083
2084 /* "kill" method for prec over corefile.  */
2085
2086 void
2087 record_full_core_target::kill ()
2088 {
2089   if (record_debug)
2090     fprintf_unfiltered (gdb_stdlog, "Process record: record_full_core_kill\n");
2091
2092   unpush_target (this);
2093 }
2094
2095 /* "fetch_registers" method for prec over corefile.  */
2096
2097 void
2098 record_full_core_target::fetch_registers (struct regcache *regcache,
2099                                           int regno)
2100 {
2101   if (regno < 0)
2102     {
2103       int num = gdbarch_num_regs (regcache->arch ());
2104       int i;
2105
2106       for (i = 0; i < num; i ++)
2107         regcache->raw_supply (i, *record_full_core_regbuf);
2108     }
2109   else
2110     regcache->raw_supply (regno, *record_full_core_regbuf);
2111 }
2112
2113 /* "prepare_to_store" method for prec over corefile.  */
2114
2115 void
2116 record_full_core_target::prepare_to_store (struct regcache *regcache)
2117 {
2118 }
2119
2120 /* "store_registers" method for prec over corefile.  */
2121
2122 void
2123 record_full_core_target::store_registers (struct regcache *regcache,
2124                                           int regno)
2125 {
2126   if (record_full_gdb_operation_disable)
2127     record_full_core_regbuf->raw_supply (regno, *regcache);
2128   else
2129     error (_("You can't do that without a process to debug."));
2130 }
2131
2132 /* "xfer_partial" method for prec over corefile.  */
2133
2134 enum target_xfer_status
2135 record_full_core_target::xfer_partial (enum target_object object,
2136                                        const char *annex, gdb_byte *readbuf,
2137                                        const gdb_byte *writebuf, ULONGEST offset,
2138                                        ULONGEST len, ULONGEST *xfered_len)
2139 {
2140   if (object == TARGET_OBJECT_MEMORY)
2141     {
2142       if (record_full_gdb_operation_disable || !writebuf)
2143         {
2144           struct target_section *p;
2145
2146           for (p = record_full_core_start; p < record_full_core_end; p++)
2147             {
2148               if (offset >= p->addr)
2149                 {
2150                   struct record_full_core_buf_entry *entry;
2151                   ULONGEST sec_offset;
2152
2153                   if (offset >= p->endaddr)
2154                     continue;
2155
2156                   if (offset + len > p->endaddr)
2157                     len = p->endaddr - offset;
2158
2159                   sec_offset = offset - p->addr;
2160
2161                   /* Read readbuf or write writebuf p, offset, len.  */
2162                   /* Check flags.  */
2163                   if (p->the_bfd_section->flags & SEC_CONSTRUCTOR
2164                       || (p->the_bfd_section->flags & SEC_HAS_CONTENTS) == 0)
2165                     {
2166                       if (readbuf)
2167                         memset (readbuf, 0, len);
2168
2169                       *xfered_len = len;
2170                       return TARGET_XFER_OK;
2171                     }
2172                   /* Get record_full_core_buf_entry.  */
2173                   for (entry = record_full_core_buf_list; entry;
2174                        entry = entry->prev)
2175                     if (entry->p == p)
2176                       break;
2177                   if (writebuf)
2178                     {
2179                       if (!entry)
2180                         {
2181                           /* Add a new entry.  */
2182                           entry = XNEW (struct record_full_core_buf_entry);
2183                           entry->p = p;
2184                           if (!bfd_malloc_and_get_section
2185                                 (p->the_bfd_section->owner,
2186                                  p->the_bfd_section,
2187                                  &entry->buf))
2188                             {
2189                               xfree (entry);
2190                               return TARGET_XFER_EOF;
2191                             }
2192                           entry->prev = record_full_core_buf_list;
2193                           record_full_core_buf_list = entry;
2194                         }
2195
2196                       memcpy (entry->buf + sec_offset, writebuf,
2197                               (size_t) len);
2198                     }
2199                   else
2200                     {
2201                       if (!entry)
2202                         return this->beneath ()->xfer_partial (object, annex,
2203                                                                readbuf, writebuf,
2204                                                                offset, len,
2205                                                                xfered_len);
2206
2207                       memcpy (readbuf, entry->buf + sec_offset,
2208                               (size_t) len);
2209                     }
2210
2211                   *xfered_len = len;
2212                   return TARGET_XFER_OK;
2213                 }
2214             }
2215
2216           return TARGET_XFER_E_IO;
2217         }
2218       else
2219         error (_("You can't do that without a process to debug."));
2220     }
2221
2222   return this->beneath ()->xfer_partial (object, annex,
2223                                          readbuf, writebuf, offset, len,
2224                                          xfered_len);
2225 }
2226
2227 /* "insert_breakpoint" method for prec over corefile.  */
2228
2229 int
2230 record_full_core_target::insert_breakpoint (struct gdbarch *gdbarch,
2231                                             struct bp_target_info *bp_tgt)
2232 {
2233   return 0;
2234 }
2235
2236 /* "remove_breakpoint" method for prec over corefile.  */
2237
2238 int
2239 record_full_core_target::remove_breakpoint (struct gdbarch *gdbarch,
2240                                             struct bp_target_info *bp_tgt,
2241                                             enum remove_bp_reason reason)
2242 {
2243   return 0;
2244 }
2245
2246 /* "has_execution" method for prec over corefile.  */
2247
2248 bool
2249 record_full_core_target::has_execution (ptid_t the_ptid)
2250 {
2251   return true;
2252 }
2253
2254 /* Record log save-file format
2255    Version 1 (never released)
2256
2257    Header:
2258      4 bytes: magic number htonl(0x20090829).
2259        NOTE: be sure to change whenever this file format changes!
2260
2261    Records:
2262      record_full_end:
2263        1 byte:  record type (record_full_end, see enum record_full_type).
2264      record_full_reg:
2265        1 byte:  record type (record_full_reg, see enum record_full_type).
2266        8 bytes: register id (network byte order).
2267        MAX_REGISTER_SIZE bytes: register value.
2268      record_full_mem:
2269        1 byte:  record type (record_full_mem, see enum record_full_type).
2270        8 bytes: memory length (network byte order).
2271        8 bytes: memory address (network byte order).
2272        n bytes: memory value (n == memory length).
2273
2274    Version 2
2275      4 bytes: magic number netorder32(0x20091016).
2276        NOTE: be sure to change whenever this file format changes!
2277
2278    Records:
2279      record_full_end:
2280        1 byte:  record type (record_full_end, see enum record_full_type).
2281        4 bytes: signal
2282        4 bytes: instruction count
2283      record_full_reg:
2284        1 byte:  record type (record_full_reg, see enum record_full_type).
2285        4 bytes: register id (network byte order).
2286        n bytes: register value (n == actual register size).
2287                 (eg. 4 bytes for x86 general registers).
2288      record_full_mem:
2289        1 byte:  record type (record_full_mem, see enum record_full_type).
2290        4 bytes: memory length (network byte order).
2291        8 bytes: memory address (network byte order).
2292        n bytes: memory value (n == memory length).
2293
2294 */
2295
2296 /* bfdcore_read -- read bytes from a core file section.  */
2297
2298 static inline void
2299 bfdcore_read (bfd *obfd, asection *osec, void *buf, int len, int *offset)
2300 {
2301   int ret = bfd_get_section_contents (obfd, osec, buf, *offset, len);
2302
2303   if (ret)
2304     *offset += len;
2305   else
2306     error (_("Failed to read %d bytes from core file %s ('%s')."),
2307            len, bfd_get_filename (obfd),
2308            bfd_errmsg (bfd_get_error ()));
2309 }
2310
2311 static inline uint64_t
2312 netorder64 (uint64_t input)
2313 {
2314   uint64_t ret;
2315
2316   store_unsigned_integer ((gdb_byte *) &ret, sizeof (ret), 
2317                           BFD_ENDIAN_BIG, input);
2318   return ret;
2319 }
2320
2321 static inline uint32_t
2322 netorder32 (uint32_t input)
2323 {
2324   uint32_t ret;
2325
2326   store_unsigned_integer ((gdb_byte *) &ret, sizeof (ret), 
2327                           BFD_ENDIAN_BIG, input);
2328   return ret;
2329 }
2330
2331 /* Restore the execution log from a core_bfd file.  */
2332 static void
2333 record_full_restore (void)
2334 {
2335   uint32_t magic;
2336   struct record_full_entry *rec;
2337   asection *osec;
2338   uint32_t osec_size;
2339   int bfd_offset = 0;
2340   struct regcache *regcache;
2341
2342   /* We restore the execution log from the open core bfd,
2343      if there is one.  */
2344   if (core_bfd == NULL)
2345     return;
2346
2347   /* "record_full_restore" can only be called when record list is empty.  */
2348   gdb_assert (record_full_first.next == NULL);
2349  
2350   if (record_debug)
2351     fprintf_unfiltered (gdb_stdlog, "Restoring recording from core file.\n");
2352
2353   /* Now need to find our special note section.  */
2354   osec = bfd_get_section_by_name (core_bfd, "null0");
2355   if (record_debug)
2356     fprintf_unfiltered (gdb_stdlog, "Find precord section %s.\n",
2357                         osec ? "succeeded" : "failed");
2358   if (osec == NULL)
2359     return;
2360   osec_size = bfd_section_size (core_bfd, osec);
2361   if (record_debug)
2362     fprintf_unfiltered (gdb_stdlog, "%s", bfd_section_name (core_bfd, osec));
2363
2364   /* Check the magic code.  */
2365   bfdcore_read (core_bfd, osec, &magic, sizeof (magic), &bfd_offset);
2366   if (magic != RECORD_FULL_FILE_MAGIC)
2367     error (_("Version mis-match or file format error in core file %s."),
2368            bfd_get_filename (core_bfd));
2369   if (record_debug)
2370     fprintf_unfiltered (gdb_stdlog,
2371                         "  Reading 4-byte magic cookie "
2372                         "RECORD_FULL_FILE_MAGIC (0x%s)\n",
2373                         phex_nz (netorder32 (magic), 4));
2374
2375   /* Restore the entries in recfd into record_full_arch_list_head and
2376      record_full_arch_list_tail.  */
2377   record_full_arch_list_head = NULL;
2378   record_full_arch_list_tail = NULL;
2379   record_full_insn_num = 0;
2380
2381   TRY
2382     {
2383       regcache = get_current_regcache ();
2384
2385       while (1)
2386         {
2387           uint8_t rectype;
2388           uint32_t regnum, len, signal, count;
2389           uint64_t addr;
2390
2391           /* We are finished when offset reaches osec_size.  */
2392           if (bfd_offset >= osec_size)
2393             break;
2394           bfdcore_read (core_bfd, osec, &rectype, sizeof (rectype), &bfd_offset);
2395
2396           switch (rectype)
2397             {
2398             case record_full_reg: /* reg */
2399               /* Get register number to regnum.  */
2400               bfdcore_read (core_bfd, osec, &regnum,
2401                             sizeof (regnum), &bfd_offset);
2402               regnum = netorder32 (regnum);
2403
2404               rec = record_full_reg_alloc (regcache, regnum);
2405
2406               /* Get val.  */
2407               bfdcore_read (core_bfd, osec, record_full_get_loc (rec),
2408                             rec->u.reg.len, &bfd_offset);
2409
2410               if (record_debug)
2411                 fprintf_unfiltered (gdb_stdlog,
2412                                     "  Reading register %d (1 "
2413                                     "plus %lu plus %d bytes)\n",
2414                                     rec->u.reg.num,
2415                                     (unsigned long) sizeof (regnum),
2416                                     rec->u.reg.len);
2417               break;
2418
2419             case record_full_mem: /* mem */
2420               /* Get len.  */
2421               bfdcore_read (core_bfd, osec, &len,
2422                             sizeof (len), &bfd_offset);
2423               len = netorder32 (len);
2424
2425               /* Get addr.  */
2426               bfdcore_read (core_bfd, osec, &addr,
2427                             sizeof (addr), &bfd_offset);
2428               addr = netorder64 (addr);
2429
2430               rec = record_full_mem_alloc (addr, len);
2431
2432               /* Get val.  */
2433               bfdcore_read (core_bfd, osec, record_full_get_loc (rec),
2434                             rec->u.mem.len, &bfd_offset);
2435
2436               if (record_debug)
2437                 fprintf_unfiltered (gdb_stdlog,
2438                                     "  Reading memory %s (1 plus "
2439                                     "%lu plus %lu plus %d bytes)\n",
2440                                     paddress (get_current_arch (),
2441                                               rec->u.mem.addr),
2442                                     (unsigned long) sizeof (addr),
2443                                     (unsigned long) sizeof (len),
2444                                     rec->u.mem.len);
2445               break;
2446
2447             case record_full_end: /* end */
2448               rec = record_full_end_alloc ();
2449               record_full_insn_num ++;
2450
2451               /* Get signal value.  */
2452               bfdcore_read (core_bfd, osec, &signal,
2453                             sizeof (signal), &bfd_offset);
2454               signal = netorder32 (signal);
2455               rec->u.end.sigval = (enum gdb_signal) signal;
2456
2457               /* Get insn count.  */
2458               bfdcore_read (core_bfd, osec, &count,
2459                             sizeof (count), &bfd_offset);
2460               count = netorder32 (count);
2461               rec->u.end.insn_num = count;
2462               record_full_insn_count = count + 1;
2463               if (record_debug)
2464                 fprintf_unfiltered (gdb_stdlog,
2465                                     "  Reading record_full_end (1 + "
2466                                     "%lu + %lu bytes), offset == %s\n",
2467                                     (unsigned long) sizeof (signal),
2468                                     (unsigned long) sizeof (count),
2469                                     paddress (get_current_arch (),
2470                                               bfd_offset));
2471               break;
2472
2473             default:
2474               error (_("Bad entry type in core file %s."),
2475                      bfd_get_filename (core_bfd));
2476               break;
2477             }
2478
2479           /* Add rec to record arch list.  */
2480           record_full_arch_list_add (rec);
2481         }
2482     }
2483   CATCH (ex, RETURN_MASK_ALL)
2484     {
2485       record_full_list_release (record_full_arch_list_tail);
2486       throw_exception (ex);
2487     }
2488   END_CATCH
2489
2490   /* Add record_full_arch_list_head to the end of record list.  */
2491   record_full_first.next = record_full_arch_list_head;
2492   record_full_arch_list_head->prev = &record_full_first;
2493   record_full_arch_list_tail->next = NULL;
2494   record_full_list = &record_full_first;
2495
2496   /* Update record_full_insn_max_num.  */
2497   if (record_full_insn_num > record_full_insn_max_num)
2498     {
2499       record_full_insn_max_num = record_full_insn_num;
2500       warning (_("Auto increase record/replay buffer limit to %u."),
2501                record_full_insn_max_num);
2502     }
2503
2504   /* Succeeded.  */
2505   printf_filtered (_("Restored records from core file %s.\n"),
2506                    bfd_get_filename (core_bfd));
2507
2508   print_stack_frame (get_selected_frame (NULL), 1, SRC_AND_LOC, 1);
2509 }
2510
2511 /* bfdcore_write -- write bytes into a core file section.  */
2512
2513 static inline void
2514 bfdcore_write (bfd *obfd, asection *osec, void *buf, int len, int *offset)
2515 {
2516   int ret = bfd_set_section_contents (obfd, osec, buf, *offset, len);
2517
2518   if (ret)
2519     *offset += len;
2520   else
2521     error (_("Failed to write %d bytes to core file %s ('%s')."),
2522            len, bfd_get_filename (obfd),
2523            bfd_errmsg (bfd_get_error ()));
2524 }
2525
2526 /* Restore the execution log from a file.  We use a modified elf
2527    corefile format, with an extra section for our data.  */
2528
2529 static void
2530 cmd_record_full_restore (const char *args, int from_tty)
2531 {
2532   core_file_command (args, from_tty);
2533   record_full_open (args, from_tty);
2534 }
2535
2536 /* Save the execution log to a file.  We use a modified elf corefile
2537    format, with an extra section for our data.  */
2538
2539 void
2540 record_full_base_target::save_record (const char *recfilename)
2541 {
2542   struct record_full_entry *cur_record_full_list;
2543   uint32_t magic;
2544   struct regcache *regcache;
2545   struct gdbarch *gdbarch;
2546   int save_size = 0;
2547   asection *osec = NULL;
2548   int bfd_offset = 0;
2549
2550   /* Open the save file.  */
2551   if (record_debug)
2552     fprintf_unfiltered (gdb_stdlog, "Saving execution log to core file '%s'\n",
2553                         recfilename);
2554
2555   /* Open the output file.  */
2556   gdb_bfd_ref_ptr obfd (create_gcore_bfd (recfilename));
2557
2558   /* Arrange to remove the output file on failure.  */
2559   gdb::unlinker unlink_file (recfilename);
2560
2561   /* Save the current record entry to "cur_record_full_list".  */
2562   cur_record_full_list = record_full_list;
2563
2564   /* Get the values of regcache and gdbarch.  */
2565   regcache = get_current_regcache ();
2566   gdbarch = regcache->arch ();
2567
2568   /* Disable the GDB operation record.  */
2569   scoped_restore restore_operation_disable
2570     = record_full_gdb_operation_disable_set ();
2571
2572   /* Reverse execute to the begin of record list.  */
2573   while (1)
2574     {
2575       /* Check for beginning and end of log.  */
2576       if (record_full_list == &record_full_first)
2577         break;
2578
2579       record_full_exec_insn (regcache, gdbarch, record_full_list);
2580
2581       if (record_full_list->prev)
2582         record_full_list = record_full_list->prev;
2583     }
2584
2585   /* Compute the size needed for the extra bfd section.  */
2586   save_size = 4;        /* magic cookie */
2587   for (record_full_list = record_full_first.next; record_full_list;
2588        record_full_list = record_full_list->next)
2589     switch (record_full_list->type)
2590       {
2591       case record_full_end:
2592         save_size += 1 + 4 + 4;
2593         break;
2594       case record_full_reg:
2595         save_size += 1 + 4 + record_full_list->u.reg.len;
2596         break;
2597       case record_full_mem:
2598         save_size += 1 + 4 + 8 + record_full_list->u.mem.len;
2599         break;
2600       }
2601
2602   /* Make the new bfd section.  */
2603   osec = bfd_make_section_anyway_with_flags (obfd.get (), "precord",
2604                                              SEC_HAS_CONTENTS
2605                                              | SEC_READONLY);
2606   if (osec == NULL)
2607     error (_("Failed to create 'precord' section for corefile %s: %s"),
2608            recfilename,
2609            bfd_errmsg (bfd_get_error ()));
2610   bfd_set_section_size (obfd.get (), osec, save_size);
2611   bfd_set_section_vma (obfd.get (), osec, 0);
2612   bfd_set_section_alignment (obfd.get (), osec, 0);
2613   bfd_section_lma (obfd.get (), osec) = 0;
2614
2615   /* Save corefile state.  */
2616   write_gcore_file (obfd.get ());
2617
2618   /* Write out the record log.  */
2619   /* Write the magic code.  */
2620   magic = RECORD_FULL_FILE_MAGIC;
2621   if (record_debug)
2622     fprintf_unfiltered (gdb_stdlog,
2623                         "  Writing 4-byte magic cookie "
2624                         "RECORD_FULL_FILE_MAGIC (0x%s)\n",
2625                       phex_nz (magic, 4));
2626   bfdcore_write (obfd.get (), osec, &magic, sizeof (magic), &bfd_offset);
2627
2628   /* Save the entries to recfd and forward execute to the end of
2629      record list.  */
2630   record_full_list = &record_full_first;
2631   while (1)
2632     {
2633       /* Save entry.  */
2634       if (record_full_list != &record_full_first)
2635         {
2636           uint8_t type;
2637           uint32_t regnum, len, signal, count;
2638           uint64_t addr;
2639
2640           type = record_full_list->type;
2641           bfdcore_write (obfd.get (), osec, &type, sizeof (type), &bfd_offset);
2642
2643           switch (record_full_list->type)
2644             {
2645             case record_full_reg: /* reg */
2646               if (record_debug)
2647                 fprintf_unfiltered (gdb_stdlog,
2648                                     "  Writing register %d (1 "
2649                                     "plus %lu plus %d bytes)\n",
2650                                     record_full_list->u.reg.num,
2651                                     (unsigned long) sizeof (regnum),
2652                                     record_full_list->u.reg.len);
2653
2654               /* Write regnum.  */
2655               regnum = netorder32 (record_full_list->u.reg.num);
2656               bfdcore_write (obfd.get (), osec, &regnum,
2657                              sizeof (regnum), &bfd_offset);
2658
2659               /* Write regval.  */
2660               bfdcore_write (obfd.get (), osec,
2661                              record_full_get_loc (record_full_list),
2662                              record_full_list->u.reg.len, &bfd_offset);
2663               break;
2664
2665             case record_full_mem: /* mem */
2666               if (record_debug)
2667                 fprintf_unfiltered (gdb_stdlog,
2668                                     "  Writing memory %s (1 plus "
2669                                     "%lu plus %lu plus %d bytes)\n",
2670                                     paddress (gdbarch,
2671                                               record_full_list->u.mem.addr),
2672                                     (unsigned long) sizeof (addr),
2673                                     (unsigned long) sizeof (len),
2674                                     record_full_list->u.mem.len);
2675
2676               /* Write memlen.  */
2677               len = netorder32 (record_full_list->u.mem.len);
2678               bfdcore_write (obfd.get (), osec, &len, sizeof (len),
2679                              &bfd_offset);
2680
2681               /* Write memaddr.  */
2682               addr = netorder64 (record_full_list->u.mem.addr);
2683               bfdcore_write (obfd.get (), osec, &addr, 
2684                              sizeof (addr), &bfd_offset);
2685
2686               /* Write memval.  */
2687               bfdcore_write (obfd.get (), osec,
2688                              record_full_get_loc (record_full_list),
2689                              record_full_list->u.mem.len, &bfd_offset);
2690               break;
2691
2692               case record_full_end:
2693                 if (record_debug)
2694                   fprintf_unfiltered (gdb_stdlog,
2695                                       "  Writing record_full_end (1 + "
2696                                       "%lu + %lu bytes)\n", 
2697                                       (unsigned long) sizeof (signal),
2698                                       (unsigned long) sizeof (count));
2699                 /* Write signal value.  */
2700                 signal = netorder32 (record_full_list->u.end.sigval);
2701                 bfdcore_write (obfd.get (), osec, &signal,
2702                                sizeof (signal), &bfd_offset);
2703
2704                 /* Write insn count.  */
2705                 count = netorder32 (record_full_list->u.end.insn_num);
2706                 bfdcore_write (obfd.get (), osec, &count,
2707                                sizeof (count), &bfd_offset);
2708                 break;
2709             }
2710         }
2711
2712       /* Execute entry.  */
2713       record_full_exec_insn (regcache, gdbarch, record_full_list);
2714
2715       if (record_full_list->next)
2716         record_full_list = record_full_list->next;
2717       else
2718         break;
2719     }
2720
2721   /* Reverse execute to cur_record_full_list.  */
2722   while (1)
2723     {
2724       /* Check for beginning and end of log.  */
2725       if (record_full_list == cur_record_full_list)
2726         break;
2727
2728       record_full_exec_insn (regcache, gdbarch, record_full_list);
2729
2730       if (record_full_list->prev)
2731         record_full_list = record_full_list->prev;
2732     }
2733
2734   unlink_file.keep ();
2735
2736   /* Succeeded.  */
2737   printf_filtered (_("Saved core file %s with execution log.\n"),
2738                    recfilename);
2739 }
2740
2741 /* record_full_goto_insn -- rewind the record log (forward or backward,
2742    depending on DIR) to the given entry, changing the program state
2743    correspondingly.  */
2744
2745 static void
2746 record_full_goto_insn (struct record_full_entry *entry,
2747                        enum exec_direction_kind dir)
2748 {
2749   scoped_restore restore_operation_disable
2750     = record_full_gdb_operation_disable_set ();
2751   struct regcache *regcache = get_current_regcache ();
2752   struct gdbarch *gdbarch = regcache->arch ();
2753
2754   /* Assume everything is valid: we will hit the entry,
2755      and we will not hit the end of the recording.  */
2756
2757   if (dir == EXEC_FORWARD)
2758     record_full_list = record_full_list->next;
2759
2760   do
2761     {
2762       record_full_exec_insn (regcache, gdbarch, record_full_list);
2763       if (dir == EXEC_REVERSE)
2764         record_full_list = record_full_list->prev;
2765       else
2766         record_full_list = record_full_list->next;
2767     } while (record_full_list != entry);
2768 }
2769
2770 /* Alias for "target record-full".  */
2771
2772 static void
2773 cmd_record_full_start (const char *args, int from_tty)
2774 {
2775   execute_command ("target record-full", from_tty);
2776 }
2777
2778 static void
2779 set_record_full_insn_max_num (const char *args, int from_tty,
2780                               struct cmd_list_element *c)
2781 {
2782   if (record_full_insn_num > record_full_insn_max_num)
2783     {
2784       /* Count down record_full_insn_num while releasing records from list.  */
2785       while (record_full_insn_num > record_full_insn_max_num)
2786        {
2787          record_full_list_release_first ();
2788          record_full_insn_num--;
2789        }
2790     }
2791 }
2792
2793 /* The "set record full" command.  */
2794
2795 static void
2796 set_record_full_command (const char *args, int from_tty)
2797 {
2798   printf_unfiltered (_("\"set record full\" must be followed "
2799                        "by an appropriate subcommand.\n"));
2800   help_list (set_record_full_cmdlist, "set record full ", all_commands,
2801              gdb_stdout);
2802 }
2803
2804 /* The "show record full" command.  */
2805
2806 static void
2807 show_record_full_command (const char *args, int from_tty)
2808 {
2809   cmd_show_list (show_record_full_cmdlist, from_tty, "");
2810 }
2811
2812 void
2813 _initialize_record_full (void)
2814 {
2815   struct cmd_list_element *c;
2816
2817   /* Init record_full_first.  */
2818   record_full_first.prev = NULL;
2819   record_full_first.next = NULL;
2820   record_full_first.type = record_full_end;
2821
2822   add_target (record_full_target_info, record_full_open);
2823   add_deprecated_target_alias (record_full_target_info, "record");
2824   add_target (record_full_core_target_info, record_full_open);
2825
2826   add_prefix_cmd ("full", class_obscure, cmd_record_full_start,
2827                   _("Start full execution recording."), &record_full_cmdlist,
2828                   "record full ", 0, &record_cmdlist);
2829
2830   c = add_cmd ("restore", class_obscure, cmd_record_full_restore,
2831                _("Restore the execution log from a file.\n\
2832 Argument is filename.  File must be created with 'record save'."),
2833                &record_full_cmdlist);
2834   set_cmd_completer (c, filename_completer);
2835
2836   /* Deprecate the old version without "full" prefix.  */
2837   c = add_alias_cmd ("restore", "full restore", class_obscure, 1,
2838                      &record_cmdlist);
2839   set_cmd_completer (c, filename_completer);
2840   deprecate_cmd (c, "record full restore");
2841
2842   add_prefix_cmd ("full", class_support, set_record_full_command,
2843                   _("Set record options"), &set_record_full_cmdlist,
2844                   "set record full ", 0, &set_record_cmdlist);
2845
2846   add_prefix_cmd ("full", class_support, show_record_full_command,
2847                   _("Show record options"), &show_record_full_cmdlist,
2848                   "show record full ", 0, &show_record_cmdlist);
2849
2850   /* Record instructions number limit command.  */
2851   add_setshow_boolean_cmd ("stop-at-limit", no_class,
2852                            &record_full_stop_at_limit, _("\
2853 Set whether record/replay stops when record/replay buffer becomes full."), _("\
2854 Show whether record/replay stops when record/replay buffer becomes full."),
2855                            _("Default is ON.\n\
2856 When ON, if the record/replay buffer becomes full, ask user what to do.\n\
2857 When OFF, if the record/replay buffer becomes full,\n\
2858 delete the oldest recorded instruction to make room for each new one."),
2859                            NULL, NULL,
2860                            &set_record_full_cmdlist, &show_record_full_cmdlist);
2861
2862   c = add_alias_cmd ("stop-at-limit", "full stop-at-limit", no_class, 1,
2863                      &set_record_cmdlist);
2864   deprecate_cmd (c, "set record full stop-at-limit");
2865
2866   c = add_alias_cmd ("stop-at-limit", "full stop-at-limit", no_class, 1,
2867                      &show_record_cmdlist);
2868   deprecate_cmd (c, "show record full stop-at-limit");
2869
2870   add_setshow_uinteger_cmd ("insn-number-max", no_class,
2871                             &record_full_insn_max_num,
2872                             _("Set record/replay buffer limit."),
2873                             _("Show record/replay buffer limit."), _("\
2874 Set the maximum number of instructions to be stored in the\n\
2875 record/replay buffer.  A value of either \"unlimited\" or zero means no\n\
2876 limit.  Default is 200000."),
2877                             set_record_full_insn_max_num,
2878                             NULL, &set_record_full_cmdlist,
2879                             &show_record_full_cmdlist);
2880
2881   c = add_alias_cmd ("insn-number-max", "full insn-number-max", no_class, 1,
2882                      &set_record_cmdlist);
2883   deprecate_cmd (c, "set record full insn-number-max");
2884
2885   c = add_alias_cmd ("insn-number-max", "full insn-number-max", no_class, 1,
2886                      &show_record_cmdlist);
2887   deprecate_cmd (c, "show record full insn-number-max");
2888
2889   add_setshow_boolean_cmd ("memory-query", no_class,
2890                            &record_full_memory_query, _("\
2891 Set whether query if PREC cannot record memory change of next instruction."),
2892                            _("\
2893 Show whether query if PREC cannot record memory change of next instruction."),
2894                            _("\
2895 Default is OFF.\n\
2896 When ON, query if PREC cannot record memory change of next instruction."),
2897                            NULL, NULL,
2898                            &set_record_full_cmdlist,
2899                            &show_record_full_cmdlist);
2900
2901   c = add_alias_cmd ("memory-query", "full memory-query", no_class, 1,
2902                      &set_record_cmdlist);
2903   deprecate_cmd (c, "set record full memory-query");
2904
2905   c = add_alias_cmd ("memory-query", "full memory-query", no_class, 1,
2906                      &show_record_cmdlist);
2907   deprecate_cmd (c, "show record full memory-query");
2908 }