Use std::unique_ptr in reg_buffer
[external/binutils.git] / gdb / regcache.c
1 /* Cache and manage the values of registers for GDB, the GNU debugger.
2
3    Copyright (C) 1986-2018 Free Software Foundation, Inc.
4
5    This file is part of GDB.
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
19
20 #include "defs.h"
21 #include "inferior.h"
22 #include "target.h"
23 #include "gdbarch.h"
24 #include "gdbcmd.h"
25 #include "regcache.h"
26 #include "reggroups.h"
27 #include "observable.h"
28 #include "regset.h"
29 #include <forward_list>
30
31 /*
32  * DATA STRUCTURE
33  *
34  * Here is the actual register cache.
35  */
36
37 /* Per-architecture object describing the layout of a register cache.
38    Computed once when the architecture is created.  */
39
40 struct gdbarch_data *regcache_descr_handle;
41
42 struct regcache_descr
43 {
44   /* The architecture this descriptor belongs to.  */
45   struct gdbarch *gdbarch;
46
47   /* The raw register cache.  Each raw (or hard) register is supplied
48      by the target interface.  The raw cache should not contain
49      redundant information - if the PC is constructed from two
50      registers then those registers and not the PC lives in the raw
51      cache.  */
52   long sizeof_raw_registers;
53
54   /* The cooked register space.  Each cooked register in the range
55      [0..NR_RAW_REGISTERS) is direct-mapped onto the corresponding raw
56      register.  The remaining [NR_RAW_REGISTERS
57      .. NR_COOKED_REGISTERS) (a.k.a. pseudo registers) are mapped onto
58      both raw registers and memory by the architecture methods
59      gdbarch_pseudo_register_read and gdbarch_pseudo_register_write.  */
60   int nr_cooked_registers;
61   long sizeof_cooked_registers;
62
63   /* Offset and size (in 8 bit bytes), of each register in the
64      register cache.  All registers (including those in the range
65      [NR_RAW_REGISTERS .. NR_COOKED_REGISTERS) are given an
66      offset.  */
67   long *register_offset;
68   long *sizeof_register;
69
70   /* Cached table containing the type of each register.  */
71   struct type **register_type;
72 };
73
74 static void *
75 init_regcache_descr (struct gdbarch *gdbarch)
76 {
77   int i;
78   struct regcache_descr *descr;
79   gdb_assert (gdbarch != NULL);
80
81   /* Create an initial, zero filled, table.  */
82   descr = GDBARCH_OBSTACK_ZALLOC (gdbarch, struct regcache_descr);
83   descr->gdbarch = gdbarch;
84
85   /* Total size of the register space.  The raw registers are mapped
86      directly onto the raw register cache while the pseudo's are
87      either mapped onto raw-registers or memory.  */
88   descr->nr_cooked_registers = gdbarch_num_regs (gdbarch)
89                                + gdbarch_num_pseudo_regs (gdbarch);
90
91   /* Fill in a table of register types.  */
92   descr->register_type
93     = GDBARCH_OBSTACK_CALLOC (gdbarch, descr->nr_cooked_registers,
94                               struct type *);
95   for (i = 0; i < descr->nr_cooked_registers; i++)
96     descr->register_type[i] = gdbarch_register_type (gdbarch, i);
97
98   /* Construct a strictly RAW register cache.  Don't allow pseudo's
99      into the register cache.  */
100
101   /* Lay out the register cache.
102
103      NOTE: cagney/2002-05-22: Only register_type() is used when
104      constructing the register cache.  It is assumed that the
105      register's raw size, virtual size and type length are all the
106      same.  */
107
108   {
109     long offset = 0;
110
111     descr->sizeof_register
112       = GDBARCH_OBSTACK_CALLOC (gdbarch, descr->nr_cooked_registers, long);
113     descr->register_offset
114       = GDBARCH_OBSTACK_CALLOC (gdbarch, descr->nr_cooked_registers, long);
115     for (i = 0; i < gdbarch_num_regs (gdbarch); i++)
116       {
117         descr->sizeof_register[i] = TYPE_LENGTH (descr->register_type[i]);
118         descr->register_offset[i] = offset;
119         offset += descr->sizeof_register[i];
120       }
121     /* Set the real size of the raw register cache buffer.  */
122     descr->sizeof_raw_registers = offset;
123
124     for (; i < descr->nr_cooked_registers; i++)
125       {
126         descr->sizeof_register[i] = TYPE_LENGTH (descr->register_type[i]);
127         descr->register_offset[i] = offset;
128         offset += descr->sizeof_register[i];
129       }
130     /* Set the real size of the readonly register cache buffer.  */
131     descr->sizeof_cooked_registers = offset;
132   }
133
134   return descr;
135 }
136
137 static struct regcache_descr *
138 regcache_descr (struct gdbarch *gdbarch)
139 {
140   return (struct regcache_descr *) gdbarch_data (gdbarch,
141                                                  regcache_descr_handle);
142 }
143
144 /* Utility functions returning useful register attributes stored in
145    the regcache descr.  */
146
147 struct type *
148 register_type (struct gdbarch *gdbarch, int regnum)
149 {
150   struct regcache_descr *descr = regcache_descr (gdbarch);
151
152   gdb_assert (regnum >= 0 && regnum < descr->nr_cooked_registers);
153   return descr->register_type[regnum];
154 }
155
156 /* Utility functions returning useful register attributes stored in
157    the regcache descr.  */
158
159 int
160 register_size (struct gdbarch *gdbarch, int regnum)
161 {
162   struct regcache_descr *descr = regcache_descr (gdbarch);
163   int size;
164
165   gdb_assert (regnum >= 0
166               && regnum < (gdbarch_num_regs (gdbarch)
167                            + gdbarch_num_pseudo_regs (gdbarch)));
168   size = descr->sizeof_register[regnum];
169   return size;
170 }
171
172 /* See common/common-regcache.h.  */
173
174 int
175 regcache_register_size (const struct regcache *regcache, int n)
176 {
177   return register_size (regcache->arch (), n);
178 }
179
180 reg_buffer::reg_buffer (gdbarch *gdbarch, bool has_pseudo)
181   : m_has_pseudo (has_pseudo)
182 {
183   gdb_assert (gdbarch != NULL);
184   m_descr = regcache_descr (gdbarch);
185
186   if (has_pseudo)
187     {
188       m_registers.reset (new gdb_byte[m_descr->sizeof_cooked_registers] ());
189       m_register_status.reset
190         (new register_status[m_descr->nr_cooked_registers] ());
191     }
192   else
193     {
194       m_registers.reset (new gdb_byte[m_descr->sizeof_raw_registers] ());
195       m_register_status.reset
196         (new register_status[gdbarch_num_regs (gdbarch)] ());
197     }
198 }
199
200 regcache::regcache (gdbarch *gdbarch, const address_space *aspace_)
201 /* The register buffers.  A read/write register cache can only hold
202    [0 .. gdbarch_num_regs).  */
203   : detached_regcache (gdbarch, false), m_aspace (aspace_)
204 {
205   m_ptid = minus_one_ptid;
206 }
207
208 static enum register_status
209 do_cooked_read (void *src, int regnum, gdb_byte *buf)
210 {
211   struct regcache *regcache = (struct regcache *) src;
212
213   return regcache->cooked_read (regnum, buf);
214 }
215
216 readonly_detached_regcache::readonly_detached_regcache (const regcache &src)
217   : readonly_detached_regcache (src.arch (), do_cooked_read, (void *) &src)
218 {
219 }
220
221 gdbarch *
222 reg_buffer::arch () const
223 {
224   return m_descr->gdbarch;
225 }
226
227 /* Cleanup class for invalidating a register.  */
228
229 class regcache_invalidator
230 {
231 public:
232
233   regcache_invalidator (struct regcache *regcache, int regnum)
234     : m_regcache (regcache),
235       m_regnum (regnum)
236   {
237   }
238
239   ~regcache_invalidator ()
240   {
241     if (m_regcache != nullptr)
242       m_regcache->invalidate (m_regnum);
243   }
244
245   DISABLE_COPY_AND_ASSIGN (regcache_invalidator);
246
247   void release ()
248   {
249     m_regcache = nullptr;
250   }
251
252 private:
253
254   struct regcache *m_regcache;
255   int m_regnum;
256 };
257
258 /* Return  a pointer to register REGNUM's buffer cache.  */
259
260 gdb_byte *
261 reg_buffer::register_buffer (int regnum) const
262 {
263   return m_registers.get () + m_descr->register_offset[regnum];
264 }
265
266 void
267 reg_buffer::save (regcache_cooked_read_ftype *cooked_read,
268                   void *src)
269 {
270   struct gdbarch *gdbarch = m_descr->gdbarch;
271   int regnum;
272
273   /* It should have pseudo registers.  */
274   gdb_assert (m_has_pseudo);
275   /* Clear the dest.  */
276   memset (m_registers.get (), 0, m_descr->sizeof_cooked_registers);
277   memset (m_register_status.get (), REG_UNKNOWN, m_descr->nr_cooked_registers);
278   /* Copy over any registers (identified by their membership in the
279      save_reggroup) and mark them as valid.  The full [0 .. gdbarch_num_regs +
280      gdbarch_num_pseudo_regs) range is checked since some architectures need
281      to save/restore `cooked' registers that live in memory.  */
282   for (regnum = 0; regnum < m_descr->nr_cooked_registers; regnum++)
283     {
284       if (gdbarch_register_reggroup_p (gdbarch, regnum, save_reggroup))
285         {
286           gdb_byte *dst_buf = register_buffer (regnum);
287           enum register_status status = cooked_read (src, regnum, dst_buf);
288
289           gdb_assert (status != REG_UNKNOWN);
290
291           if (status != REG_VALID)
292             memset (dst_buf, 0, register_size (gdbarch, regnum));
293
294           m_register_status[regnum] = status;
295         }
296     }
297 }
298
299 void
300 regcache::restore (readonly_detached_regcache *src)
301 {
302   struct gdbarch *gdbarch = m_descr->gdbarch;
303   int regnum;
304
305   gdb_assert (src != NULL);
306   gdb_assert (src->m_has_pseudo);
307
308   gdb_assert (gdbarch == src->arch ());
309
310   /* Copy over any registers, being careful to only restore those that
311      were both saved and need to be restored.  The full [0 .. gdbarch_num_regs
312      + gdbarch_num_pseudo_regs) range is checked since some architectures need
313      to save/restore `cooked' registers that live in memory.  */
314   for (regnum = 0; regnum < m_descr->nr_cooked_registers; regnum++)
315     {
316       if (gdbarch_register_reggroup_p (gdbarch, regnum, restore_reggroup))
317         {
318           if (src->m_register_status[regnum] == REG_VALID)
319             cooked_write (regnum, src->register_buffer (regnum));
320         }
321     }
322 }
323
324 enum register_status
325 reg_buffer::get_register_status (int regnum) const
326 {
327   assert_regnum (regnum);
328
329   return m_register_status[regnum];
330 }
331
332 void
333 detached_regcache::invalidate (int regnum)
334 {
335   assert_regnum (regnum);
336   m_register_status[regnum] = REG_UNKNOWN;
337 }
338
339 void
340 reg_buffer::assert_regnum (int regnum) const
341 {
342   gdb_assert (regnum >= 0);
343   if (m_has_pseudo)
344     gdb_assert (regnum < m_descr->nr_cooked_registers);
345   else
346     gdb_assert (regnum < gdbarch_num_regs (arch ()));
347 }
348
349 /* Global structure containing the current regcache.  */
350
351 /* NOTE: this is a write-through cache.  There is no "dirty" bit for
352    recording if the register values have been changed (eg. by the
353    user).  Therefore all registers must be written back to the
354    target when appropriate.  */
355 std::forward_list<regcache *> regcache::current_regcache;
356
357 struct regcache *
358 get_thread_arch_aspace_regcache (ptid_t ptid, struct gdbarch *gdbarch,
359                                  struct address_space *aspace)
360 {
361   for (const auto &regcache : regcache::current_regcache)
362     if (ptid_equal (regcache->ptid (), ptid) && regcache->arch () == gdbarch)
363       return regcache;
364
365   regcache *new_regcache = new regcache (gdbarch, aspace);
366
367   regcache::current_regcache.push_front (new_regcache);
368   new_regcache->set_ptid (ptid);
369
370   return new_regcache;
371 }
372
373 struct regcache *
374 get_thread_arch_regcache (ptid_t ptid, struct gdbarch *gdbarch)
375 {
376   address_space *aspace = target_thread_address_space (ptid);
377
378   return get_thread_arch_aspace_regcache  (ptid, gdbarch, aspace);
379 }
380
381 static ptid_t current_thread_ptid;
382 static struct gdbarch *current_thread_arch;
383
384 struct regcache *
385 get_thread_regcache (ptid_t ptid)
386 {
387   if (!current_thread_arch || !ptid_equal (current_thread_ptid, ptid))
388     {
389       current_thread_ptid = ptid;
390       current_thread_arch = target_thread_architecture (ptid);
391     }
392
393   return get_thread_arch_regcache (ptid, current_thread_arch);
394 }
395
396 struct regcache *
397 get_current_regcache (void)
398 {
399   return get_thread_regcache (inferior_ptid);
400 }
401
402 /* See common/common-regcache.h.  */
403
404 struct regcache *
405 get_thread_regcache_for_ptid (ptid_t ptid)
406 {
407   return get_thread_regcache (ptid);
408 }
409
410 /* Observer for the target_changed event.  */
411
412 static void
413 regcache_observer_target_changed (struct target_ops *target)
414 {
415   registers_changed ();
416 }
417
418 /* Update global variables old ptids to hold NEW_PTID if they were
419    holding OLD_PTID.  */
420 void
421 regcache::regcache_thread_ptid_changed (ptid_t old_ptid, ptid_t new_ptid)
422 {
423   for (auto &regcache : regcache::current_regcache)
424     {
425       if (ptid_equal (regcache->ptid (), old_ptid))
426         regcache->set_ptid (new_ptid);
427     }
428 }
429
430 /* Low level examining and depositing of registers.
431
432    The caller is responsible for making sure that the inferior is
433    stopped before calling the fetching routines, or it will get
434    garbage.  (a change from GDB version 3, in which the caller got the
435    value from the last stop).  */
436
437 /* REGISTERS_CHANGED ()
438
439    Indicate that registers may have changed, so invalidate the cache.  */
440
441 void
442 registers_changed_ptid (ptid_t ptid)
443 {
444   for (auto oit = regcache::current_regcache.before_begin (),
445          it = std::next (oit);
446        it != regcache::current_regcache.end ();
447        )
448     {
449       if (ptid_match ((*it)->ptid (), ptid))
450         {
451           delete *it;
452           it = regcache::current_regcache.erase_after (oit);
453         }
454       else
455         oit = it++;
456     }
457
458   if (ptid_match (current_thread_ptid, ptid))
459     {
460       current_thread_ptid = null_ptid;
461       current_thread_arch = NULL;
462     }
463
464   if (ptid_match (inferior_ptid, ptid))
465     {
466       /* We just deleted the regcache of the current thread.  Need to
467          forget about any frames we have cached, too.  */
468       reinit_frame_cache ();
469     }
470 }
471
472 void
473 registers_changed (void)
474 {
475   registers_changed_ptid (minus_one_ptid);
476
477   /* Force cleanup of any alloca areas if using C alloca instead of
478      a builtin alloca.  This particular call is used to clean up
479      areas allocated by low level target code which may build up
480      during lengthy interactions between gdb and the target before
481      gdb gives control to the user (ie watchpoints).  */
482   alloca (0);
483 }
484
485 void
486 regcache::raw_update (int regnum)
487 {
488   assert_regnum (regnum);
489
490   /* Make certain that the register cache is up-to-date with respect
491      to the current thread.  This switching shouldn't be necessary
492      only there is still only one target side register cache.  Sigh!
493      On the bright side, at least there is a regcache object.  */
494
495   if (get_register_status (regnum) == REG_UNKNOWN)
496     {
497       target_fetch_registers (this, regnum);
498
499       /* A number of targets can't access the whole set of raw
500          registers (because the debug API provides no means to get at
501          them).  */
502       if (m_register_status[regnum] == REG_UNKNOWN)
503         m_register_status[regnum] = REG_UNAVAILABLE;
504     }
505 }
506
507 enum register_status
508 readable_regcache::raw_read (int regnum, gdb_byte *buf)
509 {
510   gdb_assert (buf != NULL);
511   raw_update (regnum);
512
513   if (m_register_status[regnum] != REG_VALID)
514     memset (buf, 0, m_descr->sizeof_register[regnum]);
515   else
516     memcpy (buf, register_buffer (regnum),
517             m_descr->sizeof_register[regnum]);
518
519   return m_register_status[regnum];
520 }
521
522 enum register_status
523 regcache_raw_read_signed (struct regcache *regcache, int regnum, LONGEST *val)
524 {
525   gdb_assert (regcache != NULL);
526   return regcache->raw_read (regnum, val);
527 }
528
529 template<typename T, typename>
530 enum register_status
531 readable_regcache::raw_read (int regnum, T *val)
532 {
533   gdb_byte *buf;
534   enum register_status status;
535
536   assert_regnum (regnum);
537   buf = (gdb_byte *) alloca (m_descr->sizeof_register[regnum]);
538   status = raw_read (regnum, buf);
539   if (status == REG_VALID)
540     *val = extract_integer<T> (buf,
541                                m_descr->sizeof_register[regnum],
542                                gdbarch_byte_order (m_descr->gdbarch));
543   else
544     *val = 0;
545   return status;
546 }
547
548 enum register_status
549 regcache_raw_read_unsigned (struct regcache *regcache, int regnum,
550                             ULONGEST *val)
551 {
552   gdb_assert (regcache != NULL);
553   return regcache->raw_read (regnum, val);
554 }
555
556 void
557 regcache_raw_write_signed (struct regcache *regcache, int regnum, LONGEST val)
558 {
559   gdb_assert (regcache != NULL);
560   regcache->raw_write (regnum, val);
561 }
562
563 template<typename T, typename>
564 void
565 regcache::raw_write (int regnum, T val)
566 {
567   gdb_byte *buf;
568
569   assert_regnum (regnum);
570   buf = (gdb_byte *) alloca (m_descr->sizeof_register[regnum]);
571   store_integer (buf, m_descr->sizeof_register[regnum],
572                  gdbarch_byte_order (m_descr->gdbarch), val);
573   raw_write (regnum, buf);
574 }
575
576 void
577 regcache_raw_write_unsigned (struct regcache *regcache, int regnum,
578                              ULONGEST val)
579 {
580   gdb_assert (regcache != NULL);
581   regcache->raw_write (regnum, val);
582 }
583
584 LONGEST
585 regcache_raw_get_signed (struct regcache *regcache, int regnum)
586 {
587   LONGEST value;
588   enum register_status status;
589
590   status = regcache_raw_read_signed (regcache, regnum, &value);
591   if (status == REG_UNAVAILABLE)
592     throw_error (NOT_AVAILABLE_ERROR,
593                  _("Register %d is not available"), regnum);
594   return value;
595 }
596
597 enum register_status
598 readable_regcache::cooked_read (int regnum, gdb_byte *buf)
599 {
600   gdb_assert (regnum >= 0);
601   gdb_assert (regnum < m_descr->nr_cooked_registers);
602   if (regnum < num_raw_registers ())
603     return raw_read (regnum, buf);
604   else if (m_has_pseudo
605            && m_register_status[regnum] != REG_UNKNOWN)
606     {
607       if (m_register_status[regnum] == REG_VALID)
608         memcpy (buf, register_buffer (regnum),
609                 m_descr->sizeof_register[regnum]);
610       else
611         memset (buf, 0, m_descr->sizeof_register[regnum]);
612
613       return m_register_status[regnum];
614     }
615   else if (gdbarch_pseudo_register_read_value_p (m_descr->gdbarch))
616     {
617       struct value *mark, *computed;
618       enum register_status result = REG_VALID;
619
620       mark = value_mark ();
621
622       computed = gdbarch_pseudo_register_read_value (m_descr->gdbarch,
623                                                      this, regnum);
624       if (value_entirely_available (computed))
625         memcpy (buf, value_contents_raw (computed),
626                 m_descr->sizeof_register[regnum]);
627       else
628         {
629           memset (buf, 0, m_descr->sizeof_register[regnum]);
630           result = REG_UNAVAILABLE;
631         }
632
633       value_free_to_mark (mark);
634
635       return result;
636     }
637   else
638     return gdbarch_pseudo_register_read (m_descr->gdbarch, this,
639                                          regnum, buf);
640 }
641
642 struct value *
643 readable_regcache::cooked_read_value (int regnum)
644 {
645   gdb_assert (regnum >= 0);
646   gdb_assert (regnum < m_descr->nr_cooked_registers);
647
648   if (regnum < num_raw_registers ()
649       || (m_has_pseudo && m_register_status[regnum] != REG_UNKNOWN)
650       || !gdbarch_pseudo_register_read_value_p (m_descr->gdbarch))
651     {
652       struct value *result;
653
654       result = allocate_value (register_type (m_descr->gdbarch, regnum));
655       VALUE_LVAL (result) = lval_register;
656       VALUE_REGNUM (result) = regnum;
657
658       /* It is more efficient in general to do this delegation in this
659          direction than in the other one, even though the value-based
660          API is preferred.  */
661       if (cooked_read (regnum,
662                        value_contents_raw (result)) == REG_UNAVAILABLE)
663         mark_value_bytes_unavailable (result, 0,
664                                       TYPE_LENGTH (value_type (result)));
665
666       return result;
667     }
668   else
669     return gdbarch_pseudo_register_read_value (m_descr->gdbarch,
670                                                this, regnum);
671 }
672
673 enum register_status
674 regcache_cooked_read_signed (struct regcache *regcache, int regnum,
675                              LONGEST *val)
676 {
677   gdb_assert (regcache != NULL);
678   return regcache->cooked_read (regnum, val);
679 }
680
681 template<typename T, typename>
682 enum register_status
683 readable_regcache::cooked_read (int regnum, T *val)
684 {
685   enum register_status status;
686   gdb_byte *buf;
687
688   gdb_assert (regnum >= 0 && regnum < m_descr->nr_cooked_registers);
689   buf = (gdb_byte *) alloca (m_descr->sizeof_register[regnum]);
690   status = cooked_read (regnum, buf);
691   if (status == REG_VALID)
692     *val = extract_integer<T> (buf, m_descr->sizeof_register[regnum],
693                                gdbarch_byte_order (m_descr->gdbarch));
694   else
695     *val = 0;
696   return status;
697 }
698
699 enum register_status
700 regcache_cooked_read_unsigned (struct regcache *regcache, int regnum,
701                                ULONGEST *val)
702 {
703   gdb_assert (regcache != NULL);
704   return regcache->cooked_read (regnum, val);
705 }
706
707 void
708 regcache_cooked_write_signed (struct regcache *regcache, int regnum,
709                               LONGEST val)
710 {
711   gdb_assert (regcache != NULL);
712   regcache->cooked_write (regnum, val);
713 }
714
715 template<typename T, typename>
716 void
717 regcache::cooked_write (int regnum, T val)
718 {
719   gdb_byte *buf;
720
721   gdb_assert (regnum >=0 && regnum < m_descr->nr_cooked_registers);
722   buf = (gdb_byte *) alloca (m_descr->sizeof_register[regnum]);
723   store_integer (buf, m_descr->sizeof_register[regnum],
724                  gdbarch_byte_order (m_descr->gdbarch), val);
725   cooked_write (regnum, buf);
726 }
727
728 void
729 regcache_cooked_write_unsigned (struct regcache *regcache, int regnum,
730                                 ULONGEST val)
731 {
732   gdb_assert (regcache != NULL);
733   regcache->cooked_write (regnum, val);
734 }
735
736 void
737 regcache::raw_write (int regnum, const gdb_byte *buf)
738 {
739
740   gdb_assert (buf != NULL);
741   assert_regnum (regnum);
742
743   /* On the sparc, writing %g0 is a no-op, so we don't even want to
744      change the registers array if something writes to this register.  */
745   if (gdbarch_cannot_store_register (arch (), regnum))
746     return;
747
748   /* If we have a valid copy of the register, and new value == old
749      value, then don't bother doing the actual store.  */
750   if (get_register_status (regnum) == REG_VALID
751       && (memcmp (register_buffer (regnum), buf,
752                   m_descr->sizeof_register[regnum]) == 0))
753     return;
754
755   target_prepare_to_store (this);
756   raw_supply (regnum, buf);
757
758   /* Invalidate the register after it is written, in case of a
759      failure.  */
760   regcache_invalidator invalidator (this, regnum);
761
762   target_store_registers (this, regnum);
763
764   /* The target did not throw an error so we can discard invalidating
765      the register.  */
766   invalidator.release ();
767 }
768
769 void
770 regcache::cooked_write (int regnum, const gdb_byte *buf)
771 {
772   gdb_assert (regnum >= 0);
773   gdb_assert (regnum < m_descr->nr_cooked_registers);
774   if (regnum < num_raw_registers ())
775     raw_write (regnum, buf);
776   else
777     gdbarch_pseudo_register_write (m_descr->gdbarch, this,
778                                    regnum, buf);
779 }
780
781 /* Perform a partial register transfer using a read, modify, write
782    operation.  */
783
784 enum register_status
785 readable_regcache::read_part (int regnum, int offset, int len, void *in,
786                               bool is_raw)
787 {
788   struct gdbarch *gdbarch = arch ();
789   gdb_byte *reg = (gdb_byte *) alloca (register_size (gdbarch, regnum));
790
791   gdb_assert (in != NULL);
792   gdb_assert (offset >= 0 && offset <= m_descr->sizeof_register[regnum]);
793   gdb_assert (len >= 0 && offset + len <= m_descr->sizeof_register[regnum]);
794   /* Something to do?  */
795   if (offset + len == 0)
796     return REG_VALID;
797   /* Read (when needed) ...  */
798   enum register_status status;
799
800   if (is_raw)
801     status = raw_read (regnum, reg);
802   else
803     status = cooked_read (regnum, reg);
804   if (status != REG_VALID)
805     return status;
806
807   /* ... modify ...  */
808   memcpy (in, reg + offset, len);
809
810   return REG_VALID;
811 }
812
813 enum register_status
814 regcache::write_part (int regnum, int offset, int len,
815                      const void *out, bool is_raw)
816 {
817   struct gdbarch *gdbarch = arch ();
818   gdb_byte *reg = (gdb_byte *) alloca (register_size (gdbarch, regnum));
819
820   gdb_assert (out != NULL);
821   gdb_assert (offset >= 0 && offset <= m_descr->sizeof_register[regnum]);
822   gdb_assert (len >= 0 && offset + len <= m_descr->sizeof_register[regnum]);
823   /* Something to do?  */
824   if (offset + len == 0)
825     return REG_VALID;
826   /* Read (when needed) ...  */
827   if (offset > 0
828       || offset + len < m_descr->sizeof_register[regnum])
829     {
830       enum register_status status;
831
832       if (is_raw)
833         status = raw_read (regnum, reg);
834       else
835         status = cooked_read (regnum, reg);
836       if (status != REG_VALID)
837         return status;
838     }
839
840   memcpy (reg + offset, out, len);
841   /* ... write (when needed).  */
842   if (is_raw)
843     raw_write (regnum, reg);
844   else
845     cooked_write (regnum, reg);
846
847   return REG_VALID;
848 }
849
850 enum register_status
851 readable_regcache::raw_read_part (int regnum, int offset, int len, gdb_byte *buf)
852 {
853   assert_regnum (regnum);
854   return read_part (regnum, offset, len, buf, true);
855 }
856
857 /* See regcache.h.  */
858
859 void
860 regcache::raw_write_part (int regnum, int offset, int len,
861                           const gdb_byte *buf)
862 {
863   assert_regnum (regnum);
864   write_part (regnum, offset, len, buf, true);
865 }
866
867 enum register_status
868 readable_regcache::cooked_read_part (int regnum, int offset, int len,
869                                      gdb_byte *buf)
870 {
871   gdb_assert (regnum >= 0 && regnum < m_descr->nr_cooked_registers);
872   return read_part (regnum, offset, len, buf, false);
873 }
874
875 void
876 regcache::cooked_write_part (int regnum, int offset, int len,
877                              const gdb_byte *buf)
878 {
879   gdb_assert (regnum >= 0 && regnum < m_descr->nr_cooked_registers);
880   write_part (regnum, offset, len, buf, false);
881 }
882
883 void
884 detached_regcache::raw_supply (int regnum, const void *buf)
885 {
886   void *regbuf;
887   size_t size;
888
889   assert_regnum (regnum);
890
891   regbuf = register_buffer (regnum);
892   size = m_descr->sizeof_register[regnum];
893
894   if (buf)
895     {
896       memcpy (regbuf, buf, size);
897       m_register_status[regnum] = REG_VALID;
898     }
899   else
900     {
901       /* This memset not strictly necessary, but better than garbage
902          in case the register value manages to escape somewhere (due
903          to a bug, no less).  */
904       memset (regbuf, 0, size);
905       m_register_status[regnum] = REG_UNAVAILABLE;
906     }
907 }
908
909 /* Supply register REGNUM to REGCACHE.  Value to supply is an integer stored at
910    address ADDR, in target endian, with length ADDR_LEN and sign IS_SIGNED.  If
911    the register size is greater than ADDR_LEN, then the integer will be sign or
912    zero extended.  If the register size is smaller than the integer, then the
913    most significant bytes of the integer will be truncated.  */
914
915 void
916 detached_regcache::raw_supply_integer (int regnum, const gdb_byte *addr,
917                                    int addr_len, bool is_signed)
918 {
919   enum bfd_endian byte_order = gdbarch_byte_order (m_descr->gdbarch);
920   gdb_byte *regbuf;
921   size_t regsize;
922
923   assert_regnum (regnum);
924
925   regbuf = register_buffer (regnum);
926   regsize = m_descr->sizeof_register[regnum];
927
928   copy_integer_to_size (regbuf, regsize, addr, addr_len, is_signed,
929                         byte_order);
930   m_register_status[regnum] = REG_VALID;
931 }
932
933 /* Supply register REGNUM with zeroed value to REGCACHE.  This is not the same
934    as calling raw_supply with NULL (which will set the state to
935    unavailable).  */
936
937 void
938 detached_regcache::raw_supply_zeroed (int regnum)
939 {
940   void *regbuf;
941   size_t size;
942
943   assert_regnum (regnum);
944
945   regbuf = register_buffer (regnum);
946   size = m_descr->sizeof_register[regnum];
947
948   memset (regbuf, 0, size);
949   m_register_status[regnum] = REG_VALID;
950 }
951
952 void
953 regcache::raw_collect (int regnum, void *buf) const
954 {
955   const void *regbuf;
956   size_t size;
957
958   gdb_assert (buf != NULL);
959   assert_regnum (regnum);
960
961   regbuf = register_buffer (regnum);
962   size = m_descr->sizeof_register[regnum];
963   memcpy (buf, regbuf, size);
964 }
965
966 /* Transfer a single or all registers belonging to a certain register
967    set to or from a buffer.  This is the main worker function for
968    regcache_supply_regset and regcache_collect_regset.  */
969
970 /* Collect register REGNUM from REGCACHE.  Store collected value as an integer
971    at address ADDR, in target endian, with length ADDR_LEN and sign IS_SIGNED.
972    If ADDR_LEN is greater than the register size, then the integer will be sign
973    or zero extended.  If ADDR_LEN is smaller than the register size, then the
974    most significant bytes of the integer will be truncated.  */
975
976 void
977 regcache::raw_collect_integer (int regnum, gdb_byte *addr, int addr_len,
978                                bool is_signed) const
979 {
980   enum bfd_endian byte_order = gdbarch_byte_order (m_descr->gdbarch);
981   const gdb_byte *regbuf;
982   size_t regsize;
983
984   assert_regnum (regnum);
985
986   regbuf = register_buffer (regnum);
987   regsize = m_descr->sizeof_register[regnum];
988
989   copy_integer_to_size (addr, addr_len, regbuf, regsize, is_signed,
990                         byte_order);
991 }
992
993 void
994 regcache::transfer_regset (const struct regset *regset,
995                            struct regcache *out_regcache,
996                            int regnum, const void *in_buf,
997                            void *out_buf, size_t size) const
998 {
999   const struct regcache_map_entry *map;
1000   int offs = 0, count;
1001
1002   for (map = (const struct regcache_map_entry *) regset->regmap;
1003        (count = map->count) != 0;
1004        map++)
1005     {
1006       int regno = map->regno;
1007       int slot_size = map->size;
1008
1009       if (slot_size == 0 && regno != REGCACHE_MAP_SKIP)
1010         slot_size = m_descr->sizeof_register[regno];
1011
1012       if (regno == REGCACHE_MAP_SKIP
1013           || (regnum != -1
1014               && (regnum < regno || regnum >= regno + count)))
1015           offs += count * slot_size;
1016
1017       else if (regnum == -1)
1018         for (; count--; regno++, offs += slot_size)
1019           {
1020             if (offs + slot_size > size)
1021               break;
1022
1023             if (out_buf)
1024               raw_collect (regno, (gdb_byte *) out_buf + offs);
1025             else
1026               out_regcache->raw_supply (regno, in_buf
1027                                         ? (const gdb_byte *) in_buf + offs
1028                                         : NULL);
1029           }
1030       else
1031         {
1032           /* Transfer a single register and return.  */
1033           offs += (regnum - regno) * slot_size;
1034           if (offs + slot_size > size)
1035             return;
1036
1037           if (out_buf)
1038             raw_collect (regnum, (gdb_byte *) out_buf + offs);
1039           else
1040             out_regcache->raw_supply (regnum, in_buf
1041                                       ? (const gdb_byte *) in_buf + offs
1042                                       : NULL);
1043           return;
1044         }
1045     }
1046 }
1047
1048 /* Supply register REGNUM from BUF to REGCACHE, using the register map
1049    in REGSET.  If REGNUM is -1, do this for all registers in REGSET.
1050    If BUF is NULL, set the register(s) to "unavailable" status. */
1051
1052 void
1053 regcache_supply_regset (const struct regset *regset,
1054                         struct regcache *regcache,
1055                         int regnum, const void *buf, size_t size)
1056 {
1057   regcache->supply_regset (regset, regnum, buf, size);
1058 }
1059
1060 void
1061 regcache::supply_regset (const struct regset *regset,
1062                          int regnum, const void *buf, size_t size)
1063 {
1064   transfer_regset (regset, this, regnum, buf, NULL, size);
1065 }
1066
1067 /* Collect register REGNUM from REGCACHE to BUF, using the register
1068    map in REGSET.  If REGNUM is -1, do this for all registers in
1069    REGSET.  */
1070
1071 void
1072 regcache_collect_regset (const struct regset *regset,
1073                          const struct regcache *regcache,
1074                          int regnum, void *buf, size_t size)
1075 {
1076   regcache->collect_regset (regset, regnum, buf, size);
1077 }
1078
1079 void
1080 regcache::collect_regset (const struct regset *regset,
1081                          int regnum, void *buf, size_t size) const
1082 {
1083   transfer_regset (regset, NULL, regnum, NULL, buf, size);
1084 }
1085
1086
1087 /* Special handling for register PC.  */
1088
1089 CORE_ADDR
1090 regcache_read_pc (struct regcache *regcache)
1091 {
1092   struct gdbarch *gdbarch = regcache->arch ();
1093
1094   CORE_ADDR pc_val;
1095
1096   if (gdbarch_read_pc_p (gdbarch))
1097     pc_val = gdbarch_read_pc (gdbarch, regcache);
1098   /* Else use per-frame method on get_current_frame.  */
1099   else if (gdbarch_pc_regnum (gdbarch) >= 0)
1100     {
1101       ULONGEST raw_val;
1102
1103       if (regcache_cooked_read_unsigned (regcache,
1104                                          gdbarch_pc_regnum (gdbarch),
1105                                          &raw_val) == REG_UNAVAILABLE)
1106         throw_error (NOT_AVAILABLE_ERROR, _("PC register is not available"));
1107
1108       pc_val = gdbarch_addr_bits_remove (gdbarch, raw_val);
1109     }
1110   else
1111     internal_error (__FILE__, __LINE__,
1112                     _("regcache_read_pc: Unable to find PC"));
1113   return pc_val;
1114 }
1115
1116 void
1117 regcache_write_pc (struct regcache *regcache, CORE_ADDR pc)
1118 {
1119   struct gdbarch *gdbarch = regcache->arch ();
1120
1121   if (gdbarch_write_pc_p (gdbarch))
1122     gdbarch_write_pc (gdbarch, regcache, pc);
1123   else if (gdbarch_pc_regnum (gdbarch) >= 0)
1124     regcache_cooked_write_unsigned (regcache,
1125                                     gdbarch_pc_regnum (gdbarch), pc);
1126   else
1127     internal_error (__FILE__, __LINE__,
1128                     _("regcache_write_pc: Unable to update PC"));
1129
1130   /* Writing the PC (for instance, from "load") invalidates the
1131      current frame.  */
1132   reinit_frame_cache ();
1133 }
1134
1135 int
1136 reg_buffer::num_raw_registers () const
1137 {
1138   return gdbarch_num_regs (arch ());
1139 }
1140
1141 void
1142 regcache::debug_print_register (const char *func,  int regno)
1143 {
1144   struct gdbarch *gdbarch = arch ();
1145
1146   fprintf_unfiltered (gdb_stdlog, "%s ", func);
1147   if (regno >= 0 && regno < gdbarch_num_regs (gdbarch)
1148       && gdbarch_register_name (gdbarch, regno) != NULL
1149       && gdbarch_register_name (gdbarch, regno)[0] != '\0')
1150     fprintf_unfiltered (gdb_stdlog, "(%s)",
1151                         gdbarch_register_name (gdbarch, regno));
1152   else
1153     fprintf_unfiltered (gdb_stdlog, "(%d)", regno);
1154   if (regno >= 0 && regno < gdbarch_num_regs (gdbarch))
1155     {
1156       enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
1157       int size = register_size (gdbarch, regno);
1158       gdb_byte *buf = register_buffer (regno);
1159
1160       fprintf_unfiltered (gdb_stdlog, " = ");
1161       for (int i = 0; i < size; i++)
1162         {
1163           fprintf_unfiltered (gdb_stdlog, "%02x", buf[i]);
1164         }
1165       if (size <= sizeof (LONGEST))
1166         {
1167           ULONGEST val = extract_unsigned_integer (buf, size, byte_order);
1168
1169           fprintf_unfiltered (gdb_stdlog, " %s %s",
1170                               core_addr_to_string_nz (val), plongest (val));
1171         }
1172     }
1173   fprintf_unfiltered (gdb_stdlog, "\n");
1174 }
1175
1176 static void
1177 reg_flush_command (const char *command, int from_tty)
1178 {
1179   /* Force-flush the register cache.  */
1180   registers_changed ();
1181   if (from_tty)
1182     printf_filtered (_("Register cache flushed.\n"));
1183 }
1184
1185 void
1186 register_dump::dump (ui_file *file)
1187 {
1188   auto descr = regcache_descr (m_gdbarch);
1189   int regnum;
1190   int footnote_nr = 0;
1191   int footnote_register_offset = 0;
1192   int footnote_register_type_name_null = 0;
1193   long register_offset = 0;
1194
1195   gdb_assert (descr->nr_cooked_registers
1196               == (gdbarch_num_regs (m_gdbarch)
1197                   + gdbarch_num_pseudo_regs (m_gdbarch)));
1198
1199   for (regnum = -1; regnum < descr->nr_cooked_registers; regnum++)
1200     {
1201       /* Name.  */
1202       if (regnum < 0)
1203         fprintf_unfiltered (file, " %-10s", "Name");
1204       else
1205         {
1206           const char *p = gdbarch_register_name (m_gdbarch, regnum);
1207
1208           if (p == NULL)
1209             p = "";
1210           else if (p[0] == '\0')
1211             p = "''";
1212           fprintf_unfiltered (file, " %-10s", p);
1213         }
1214
1215       /* Number.  */
1216       if (regnum < 0)
1217         fprintf_unfiltered (file, " %4s", "Nr");
1218       else
1219         fprintf_unfiltered (file, " %4d", regnum);
1220
1221       /* Relative number.  */
1222       if (regnum < 0)
1223         fprintf_unfiltered (file, " %4s", "Rel");
1224       else if (regnum < gdbarch_num_regs (m_gdbarch))
1225         fprintf_unfiltered (file, " %4d", regnum);
1226       else
1227         fprintf_unfiltered (file, " %4d",
1228                             (regnum - gdbarch_num_regs (m_gdbarch)));
1229
1230       /* Offset.  */
1231       if (regnum < 0)
1232         fprintf_unfiltered (file, " %6s  ", "Offset");
1233       else
1234         {
1235           fprintf_unfiltered (file, " %6ld",
1236                               descr->register_offset[regnum]);
1237           if (register_offset != descr->register_offset[regnum]
1238               || (regnum > 0
1239                   && (descr->register_offset[regnum]
1240                       != (descr->register_offset[regnum - 1]
1241                           + descr->sizeof_register[regnum - 1])))
1242               )
1243             {
1244               if (!footnote_register_offset)
1245                 footnote_register_offset = ++footnote_nr;
1246               fprintf_unfiltered (file, "*%d", footnote_register_offset);
1247             }
1248           else
1249             fprintf_unfiltered (file, "  ");
1250           register_offset = (descr->register_offset[regnum]
1251                              + descr->sizeof_register[regnum]);
1252         }
1253
1254       /* Size.  */
1255       if (regnum < 0)
1256         fprintf_unfiltered (file, " %5s ", "Size");
1257       else
1258         fprintf_unfiltered (file, " %5ld", descr->sizeof_register[regnum]);
1259
1260       /* Type.  */
1261       {
1262         const char *t;
1263         std::string name_holder;
1264
1265         if (regnum < 0)
1266           t = "Type";
1267         else
1268           {
1269             static const char blt[] = "builtin_type";
1270
1271             t = TYPE_NAME (register_type (m_gdbarch, regnum));
1272             if (t == NULL)
1273               {
1274                 if (!footnote_register_type_name_null)
1275                   footnote_register_type_name_null = ++footnote_nr;
1276                 name_holder = string_printf ("*%d",
1277                                              footnote_register_type_name_null);
1278                 t = name_holder.c_str ();
1279               }
1280             /* Chop a leading builtin_type.  */
1281             if (startswith (t, blt))
1282               t += strlen (blt);
1283           }
1284         fprintf_unfiltered (file, " %-15s", t);
1285       }
1286
1287       /* Leading space always present.  */
1288       fprintf_unfiltered (file, " ");
1289
1290       dump_reg (file, regnum);
1291
1292       fprintf_unfiltered (file, "\n");
1293     }
1294
1295   if (footnote_register_offset)
1296     fprintf_unfiltered (file, "*%d: Inconsistent register offsets.\n",
1297                         footnote_register_offset);
1298   if (footnote_register_type_name_null)
1299     fprintf_unfiltered (file,
1300                         "*%d: Register type's name NULL.\n",
1301                         footnote_register_type_name_null);
1302 }
1303
1304 #if GDB_SELF_TEST
1305 #include "selftest.h"
1306 #include "selftest-arch.h"
1307 #include "gdbthread.h"
1308 #include "target-float.h"
1309
1310 namespace selftests {
1311
1312 class regcache_access : public regcache
1313 {
1314 public:
1315
1316   /* Return the number of elements in current_regcache.  */
1317
1318   static size_t
1319   current_regcache_size ()
1320   {
1321     return std::distance (regcache::current_regcache.begin (),
1322                           regcache::current_regcache.end ());
1323   }
1324 };
1325
1326 static void
1327 current_regcache_test (void)
1328 {
1329   /* It is empty at the start.  */
1330   SELF_CHECK (regcache_access::current_regcache_size () == 0);
1331
1332   ptid_t ptid1 (1), ptid2 (2), ptid3 (3);
1333
1334   /* Get regcache from ptid1, a new regcache is added to
1335      current_regcache.  */
1336   regcache *regcache = get_thread_arch_aspace_regcache (ptid1,
1337                                                         target_gdbarch (),
1338                                                         NULL);
1339
1340   SELF_CHECK (regcache != NULL);
1341   SELF_CHECK (regcache->ptid () == ptid1);
1342   SELF_CHECK (regcache_access::current_regcache_size () == 1);
1343
1344   /* Get regcache from ptid2, a new regcache is added to
1345      current_regcache.  */
1346   regcache = get_thread_arch_aspace_regcache (ptid2,
1347                                               target_gdbarch (),
1348                                               NULL);
1349   SELF_CHECK (regcache != NULL);
1350   SELF_CHECK (regcache->ptid () == ptid2);
1351   SELF_CHECK (regcache_access::current_regcache_size () == 2);
1352
1353   /* Get regcache from ptid3, a new regcache is added to
1354      current_regcache.  */
1355   regcache = get_thread_arch_aspace_regcache (ptid3,
1356                                               target_gdbarch (),
1357                                               NULL);
1358   SELF_CHECK (regcache != NULL);
1359   SELF_CHECK (regcache->ptid () == ptid3);
1360   SELF_CHECK (regcache_access::current_regcache_size () == 3);
1361
1362   /* Get regcache from ptid2 again, nothing is added to
1363      current_regcache.  */
1364   regcache = get_thread_arch_aspace_regcache (ptid2,
1365                                               target_gdbarch (),
1366                                               NULL);
1367   SELF_CHECK (regcache != NULL);
1368   SELF_CHECK (regcache->ptid () == ptid2);
1369   SELF_CHECK (regcache_access::current_regcache_size () == 3);
1370
1371   /* Mark ptid2 is changed, so regcache of ptid2 should be removed from
1372      current_regcache.  */
1373   registers_changed_ptid (ptid2);
1374   SELF_CHECK (regcache_access::current_regcache_size () == 2);
1375 }
1376
1377 class target_ops_no_register : public test_target_ops
1378 {
1379 public:
1380   target_ops_no_register ()
1381     : test_target_ops {}
1382   {}
1383
1384   void reset ()
1385   {
1386     fetch_registers_called = 0;
1387     store_registers_called = 0;
1388     xfer_partial_called = 0;
1389   }
1390
1391   void fetch_registers (regcache *regs, int regno) override;
1392   void store_registers (regcache *regs, int regno) override;
1393
1394   enum target_xfer_status xfer_partial (enum target_object object,
1395                                         const char *annex, gdb_byte *readbuf,
1396                                         const gdb_byte *writebuf,
1397                                         ULONGEST offset, ULONGEST len,
1398                                         ULONGEST *xfered_len) override;
1399
1400   unsigned int fetch_registers_called = 0;
1401   unsigned int store_registers_called = 0;
1402   unsigned int xfer_partial_called = 0;
1403 };
1404
1405 void
1406 target_ops_no_register::fetch_registers (regcache *regs, int regno)
1407 {
1408   /* Mark register available.  */
1409   regs->raw_supply_zeroed (regno);
1410   this->fetch_registers_called++;
1411 }
1412
1413 void
1414 target_ops_no_register::store_registers (regcache *regs, int regno)
1415 {
1416   this->store_registers_called++;
1417 }
1418
1419 enum target_xfer_status
1420 target_ops_no_register::xfer_partial (enum target_object object,
1421                                       const char *annex, gdb_byte *readbuf,
1422                                       const gdb_byte *writebuf,
1423                                       ULONGEST offset, ULONGEST len,
1424                                       ULONGEST *xfered_len)
1425 {
1426   this->xfer_partial_called++;
1427
1428   *xfered_len = len;
1429   return TARGET_XFER_OK;
1430 }
1431
1432 class readwrite_regcache : public regcache
1433 {
1434 public:
1435   readwrite_regcache (struct gdbarch *gdbarch)
1436     : regcache (gdbarch, nullptr)
1437   {}
1438 };
1439
1440 /* Test regcache::cooked_read gets registers from raw registers and
1441    memory instead of target to_{fetch,store}_registers.  */
1442
1443 static void
1444 cooked_read_test (struct gdbarch *gdbarch)
1445 {
1446   /* Error out if debugging something, because we're going to push the
1447      test target, which would pop any existing target.  */
1448   if (current_top_target ()->to_stratum >= process_stratum)
1449     error (_("target already pushed"));
1450
1451   /* Create a mock environment.  An inferior with a thread, with a
1452      process_stratum target pushed.  */
1453
1454   target_ops_no_register mock_target;
1455   ptid_t mock_ptid (1, 1);
1456   inferior mock_inferior (mock_ptid.pid ());
1457   address_space mock_aspace {};
1458   mock_inferior.gdbarch = gdbarch;
1459   mock_inferior.aspace = &mock_aspace;
1460   thread_info mock_thread (&mock_inferior, mock_ptid);
1461
1462   scoped_restore restore_thread_list
1463     = make_scoped_restore (&thread_list, &mock_thread);
1464
1465   /* Add the mock inferior to the inferior list so that look ups by
1466      target+ptid can find it.  */
1467   scoped_restore restore_inferior_list
1468     = make_scoped_restore (&inferior_list);
1469   inferior_list = &mock_inferior;
1470
1471   /* Switch to the mock inferior.  */
1472   scoped_restore_current_inferior restore_current_inferior;
1473   set_current_inferior (&mock_inferior);
1474
1475   /* Push the process_stratum target so we can mock accessing
1476      registers.  */
1477   push_target (&mock_target);
1478
1479   /* Pop it again on exit (return/exception).  */
1480   struct on_exit
1481   {
1482     ~on_exit ()
1483     {
1484       pop_all_targets_at_and_above (process_stratum);
1485     }
1486   } pop_targets;
1487
1488   /* Switch to the mock thread.  */
1489   scoped_restore restore_inferior_ptid
1490     = make_scoped_restore (&inferior_ptid, mock_ptid);
1491
1492   /* Test that read one raw register from regcache_no_target will go
1493      to the target layer.  */
1494   int regnum;
1495
1496   /* Find a raw register which size isn't zero.  */
1497   for (regnum = 0; regnum < gdbarch_num_regs (gdbarch); regnum++)
1498     {
1499       if (register_size (gdbarch, regnum) != 0)
1500         break;
1501     }
1502
1503   readwrite_regcache readwrite (gdbarch);
1504   gdb::def_vector<gdb_byte> buf (register_size (gdbarch, regnum));
1505
1506   readwrite.raw_read (regnum, buf.data ());
1507
1508   /* raw_read calls target_fetch_registers.  */
1509   SELF_CHECK (mock_target.fetch_registers_called > 0);
1510   mock_target.reset ();
1511
1512   /* Mark all raw registers valid, so the following raw registers
1513      accesses won't go to target.  */
1514   for (auto i = 0; i < gdbarch_num_regs (gdbarch); i++)
1515     readwrite.raw_update (i);
1516
1517   mock_target.reset ();
1518   /* Then, read all raw and pseudo registers, and don't expect calling
1519      to_{fetch,store}_registers.  */
1520   for (int regnum = 0;
1521        regnum < gdbarch_num_regs (gdbarch) + gdbarch_num_pseudo_regs (gdbarch);
1522        regnum++)
1523     {
1524       if (register_size (gdbarch, regnum) == 0)
1525         continue;
1526
1527       gdb::def_vector<gdb_byte> buf (register_size (gdbarch, regnum));
1528
1529       SELF_CHECK (REG_VALID == readwrite.cooked_read (regnum, buf.data ()));
1530
1531       SELF_CHECK (mock_target.fetch_registers_called == 0);
1532       SELF_CHECK (mock_target.store_registers_called == 0);
1533
1534       /* Some SPU pseudo registers are got via TARGET_OBJECT_SPU.  */
1535       if (gdbarch_bfd_arch_info (gdbarch)->arch != bfd_arch_spu)
1536         SELF_CHECK (mock_target.xfer_partial_called == 0);
1537
1538       mock_target.reset ();
1539     }
1540
1541   readonly_detached_regcache readonly (readwrite);
1542
1543   /* GDB may go to target layer to fetch all registers and memory for
1544      readonly regcache.  */
1545   mock_target.reset ();
1546
1547   for (int regnum = 0;
1548        regnum < gdbarch_num_regs (gdbarch) + gdbarch_num_pseudo_regs (gdbarch);
1549        regnum++)
1550     {
1551       if (register_size (gdbarch, regnum) == 0)
1552         continue;
1553
1554       gdb::def_vector<gdb_byte> buf (register_size (gdbarch, regnum));
1555       enum register_status status = readonly.cooked_read (regnum,
1556                                                           buf.data ());
1557
1558       if (regnum < gdbarch_num_regs (gdbarch))
1559         {
1560           auto bfd_arch = gdbarch_bfd_arch_info (gdbarch)->arch;
1561
1562           if (bfd_arch == bfd_arch_frv || bfd_arch == bfd_arch_h8300
1563               || bfd_arch == bfd_arch_m32c || bfd_arch == bfd_arch_sh
1564               || bfd_arch == bfd_arch_alpha || bfd_arch == bfd_arch_v850
1565               || bfd_arch == bfd_arch_msp430 || bfd_arch == bfd_arch_mep
1566               || bfd_arch == bfd_arch_mips || bfd_arch == bfd_arch_v850_rh850
1567               || bfd_arch == bfd_arch_tic6x || bfd_arch == bfd_arch_mn10300
1568               || bfd_arch == bfd_arch_rl78 || bfd_arch == bfd_arch_score
1569               || bfd_arch == bfd_arch_riscv)
1570             {
1571               /* Raw registers.  If raw registers are not in save_reggroup,
1572                  their status are unknown.  */
1573               if (gdbarch_register_reggroup_p (gdbarch, regnum, save_reggroup))
1574                 SELF_CHECK (status == REG_VALID);
1575               else
1576                 SELF_CHECK (status == REG_UNKNOWN);
1577             }
1578           else
1579             SELF_CHECK (status == REG_VALID);
1580         }
1581       else
1582         {
1583           if (gdbarch_register_reggroup_p (gdbarch, regnum, save_reggroup))
1584             SELF_CHECK (status == REG_VALID);
1585           else
1586             {
1587               /* If pseudo registers are not in save_reggroup, some of
1588                  them can be computed from saved raw registers, but some
1589                  of them are unknown.  */
1590               auto bfd_arch = gdbarch_bfd_arch_info (gdbarch)->arch;
1591
1592               if (bfd_arch == bfd_arch_frv
1593                   || bfd_arch == bfd_arch_m32c
1594                   || bfd_arch == bfd_arch_mep
1595                   || bfd_arch == bfd_arch_sh)
1596                 SELF_CHECK (status == REG_VALID || status == REG_UNKNOWN);
1597               else if (bfd_arch == bfd_arch_mips
1598                        || bfd_arch == bfd_arch_h8300)
1599                 SELF_CHECK (status == REG_UNKNOWN);
1600               else
1601                 SELF_CHECK (status == REG_VALID);
1602             }
1603         }
1604
1605       SELF_CHECK (mock_target.fetch_registers_called == 0);
1606       SELF_CHECK (mock_target.store_registers_called == 0);
1607       SELF_CHECK (mock_target.xfer_partial_called == 0);
1608
1609       mock_target.reset ();
1610     }
1611 }
1612
1613 /* Test regcache::cooked_write by writing some expected contents to
1614    registers, and checking that contents read from registers and the
1615    expected contents are the same.  */
1616
1617 static void
1618 cooked_write_test (struct gdbarch *gdbarch)
1619 {
1620   /* Error out if debugging something, because we're going to push the
1621      test target, which would pop any existing target.  */
1622   if (current_top_target ()->to_stratum >= process_stratum)
1623     error (_("target already pushed"));
1624
1625   /* Create a mock environment.  A process_stratum target pushed.  */
1626
1627   target_ops_no_register mock_target;
1628
1629   /* Push the process_stratum target so we can mock accessing
1630      registers.  */
1631   push_target (&mock_target);
1632
1633   /* Pop it again on exit (return/exception).  */
1634   struct on_exit
1635   {
1636     ~on_exit ()
1637     {
1638       pop_all_targets_at_and_above (process_stratum);
1639     }
1640   } pop_targets;
1641
1642   readwrite_regcache readwrite (gdbarch);
1643
1644   const int num_regs = (gdbarch_num_regs (gdbarch)
1645                         + gdbarch_num_pseudo_regs (gdbarch));
1646
1647   for (auto regnum = 0; regnum < num_regs; regnum++)
1648     {
1649       if (register_size (gdbarch, regnum) == 0
1650           || gdbarch_cannot_store_register (gdbarch, regnum))
1651         continue;
1652
1653       auto bfd_arch = gdbarch_bfd_arch_info (gdbarch)->arch;
1654
1655       if ((bfd_arch == bfd_arch_sparc
1656            /* SPARC64_CWP_REGNUM, SPARC64_PSTATE_REGNUM,
1657               SPARC64_ASI_REGNUM and SPARC64_CCR_REGNUM are hard to test.  */
1658            && gdbarch_ptr_bit (gdbarch) == 64
1659            && (regnum >= gdbarch_num_regs (gdbarch)
1660                && regnum <= gdbarch_num_regs (gdbarch) + 4))
1661           || (bfd_arch == bfd_arch_spu
1662               /* SPU pseudo registers except SPU_SP_REGNUM are got by
1663                  TARGET_OBJECT_SPU.  */
1664               && regnum >= gdbarch_num_regs (gdbarch) && regnum != 130))
1665         continue;
1666
1667       std::vector<gdb_byte> expected (register_size (gdbarch, regnum), 0);
1668       std::vector<gdb_byte> buf (register_size (gdbarch, regnum), 0);
1669       const auto type = register_type (gdbarch, regnum);
1670
1671       if (TYPE_CODE (type) == TYPE_CODE_FLT
1672           || TYPE_CODE (type) == TYPE_CODE_DECFLOAT)
1673         {
1674           /* Generate valid float format.  */
1675           target_float_from_string (expected.data (), type, "1.25");
1676         }
1677       else if (TYPE_CODE (type) == TYPE_CODE_INT
1678                || TYPE_CODE (type) == TYPE_CODE_ARRAY
1679                || TYPE_CODE (type) == TYPE_CODE_PTR
1680                || TYPE_CODE (type) == TYPE_CODE_UNION
1681                || TYPE_CODE (type) == TYPE_CODE_STRUCT)
1682         {
1683           if (bfd_arch == bfd_arch_ia64
1684               || (regnum >= gdbarch_num_regs (gdbarch)
1685                   && (bfd_arch == bfd_arch_xtensa
1686                       || bfd_arch == bfd_arch_bfin
1687                       || bfd_arch == bfd_arch_m32c
1688                       /* m68hc11 pseudo registers are in memory.  */
1689                       || bfd_arch == bfd_arch_m68hc11
1690                       || bfd_arch == bfd_arch_m68hc12
1691                       || bfd_arch == bfd_arch_s390))
1692               || (bfd_arch == bfd_arch_frv
1693                   /* FRV pseudo registers except iacc0.  */
1694                   && regnum > gdbarch_num_regs (gdbarch)))
1695             {
1696               /* Skip setting the expected values for some architecture
1697                  registers.  */
1698             }
1699           else if (bfd_arch == bfd_arch_rl78 && regnum == 40)
1700             {
1701               /* RL78_PC_REGNUM */
1702               for (auto j = 0; j < register_size (gdbarch, regnum) - 1; j++)
1703                 expected[j] = j;
1704             }
1705           else
1706             {
1707               for (auto j = 0; j < register_size (gdbarch, regnum); j++)
1708                 expected[j] = j;
1709             }
1710         }
1711       else if (TYPE_CODE (type) == TYPE_CODE_FLAGS)
1712         {
1713           /* No idea how to test flags.  */
1714           continue;
1715         }
1716       else
1717         {
1718           /* If we don't know how to create the expected value for the
1719              this type, make it fail.  */
1720           SELF_CHECK (0);
1721         }
1722
1723       readwrite.cooked_write (regnum, expected.data ());
1724
1725       SELF_CHECK (readwrite.cooked_read (regnum, buf.data ()) == REG_VALID);
1726       SELF_CHECK (expected == buf);
1727     }
1728 }
1729
1730 } // namespace selftests
1731 #endif /* GDB_SELF_TEST */
1732
1733 void
1734 _initialize_regcache (void)
1735 {
1736   regcache_descr_handle
1737     = gdbarch_data_register_post_init (init_regcache_descr);
1738
1739   gdb::observers::target_changed.attach (regcache_observer_target_changed);
1740   gdb::observers::thread_ptid_changed.attach
1741     (regcache::regcache_thread_ptid_changed);
1742
1743   add_com ("flushregs", class_maintenance, reg_flush_command,
1744            _("Force gdb to flush its register cache (maintainer command)"));
1745
1746 #if GDB_SELF_TEST
1747   selftests::register_test ("current_regcache", selftests::current_regcache_test);
1748
1749   selftests::register_test_foreach_arch ("regcache::cooked_read_test",
1750                                          selftests::cooked_read_test);
1751   selftests::register_test_foreach_arch ("regcache::cooked_write_test",
1752                                          selftests::cooked_write_test);
1753 #endif
1754 }