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