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