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