Refactor svr4_create_solib_event_breakpoints
[external/binutils.git] / gdb / memattr.c
1 /* Memory attributes support, for GDB.
2
3    Copyright (C) 2001-2019 Free Software Foundation, Inc.
4
5    This file is part of GDB.
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
19
20 #include "defs.h"
21 #include "command.h"
22 #include "gdbcmd.h"
23 #include "memattr.h"
24 #include "target.h"
25 #include "target-dcache.h"
26 #include "value.h"
27 #include "language.h"
28 #include "gdbsupport/vec.h"
29 #include "breakpoint.h"
30 #include "cli/cli-utils.h"
31 #include <algorithm>
32 #include "gdbarch.h"
33
34 static std::vector<mem_region> user_mem_region_list, target_mem_region_list;
35 static std::vector<mem_region> *mem_region_list = &target_mem_region_list;
36 static int mem_number = 0;
37
38 /* If this flag is set, the memory region list should be automatically
39    updated from the target.  If it is clear, the list is user-controlled
40    and should be left alone.  */
41
42 static bool
43 mem_use_target ()
44 {
45   return mem_region_list == &target_mem_region_list;
46 }
47
48 /* If this flag is set, we have tried to fetch the target memory regions
49    since the last time it was invalidated.  If that list is still
50    empty, then the target can't supply memory regions.  */
51 static bool target_mem_regions_valid;
52
53 /* If this flag is set, gdb will assume that memory ranges not
54    specified by the memory map have type MEM_NONE, and will
55    emit errors on all accesses to that memory.  */
56 static int inaccessible_by_default = 1;
57
58 static void
59 show_inaccessible_by_default (struct ui_file *file, int from_tty,
60                               struct cmd_list_element *c,
61                               const char *value)
62 {
63   if (inaccessible_by_default)
64     fprintf_filtered (file, _("Unknown memory addresses will "
65                               "be treated as inaccessible.\n"));
66   else
67     fprintf_filtered (file, _("Unknown memory addresses "
68                               "will be treated as RAM.\n"));          
69 }
70
71 /* This function should be called before any command which would
72    modify the memory region list.  It will handle switching from
73    a target-provided list to a local list, if necessary.  */
74
75 static void
76 require_user_regions (int from_tty)
77 {
78   /* If we're already using a user-provided list, nothing to do.  */
79   if (!mem_use_target ())
80     return;
81
82   /* Switch to a user-provided list (possibly a copy of the current
83      one).  */
84   mem_region_list = &user_mem_region_list;
85
86   /* If we don't have a target-provided region list yet, then
87      no need to warn.  */
88   if (target_mem_region_list.empty ())
89     return;
90
91   /* Otherwise, let the user know how to get back.  */
92   if (from_tty)
93     warning (_("Switching to manual control of memory regions; use "
94                "\"mem auto\" to fetch regions from the target again."));
95
96   /* And create a new list (copy of the target-supplied regions) for the user
97      to modify.  */
98   user_mem_region_list = target_mem_region_list;
99 }
100
101 /* This function should be called before any command which would
102    read the memory region list, other than those which call
103    require_user_regions.  It will handle fetching the
104    target-provided list, if necessary.  */
105
106 static void
107 require_target_regions (void)
108 {
109   if (mem_use_target () && !target_mem_regions_valid)
110     {
111       target_mem_regions_valid = true;
112       target_mem_region_list = target_memory_map ();
113     }
114 }
115
116 /* Create a new user-defined memory region.  */
117
118 static void
119 create_user_mem_region (CORE_ADDR lo, CORE_ADDR hi,
120                         const mem_attrib &attrib)
121 {
122   /* lo == hi is a useless empty region.  */
123   if (lo >= hi && hi != 0)
124     {
125       printf_unfiltered (_("invalid memory region: low >= high\n"));
126       return;
127     }
128
129   mem_region newobj (lo, hi, attrib);
130
131   auto it = std::lower_bound (user_mem_region_list.begin (),
132                               user_mem_region_list.end (),
133                               newobj);
134   int ix = std::distance (user_mem_region_list.begin (), it);
135
136   /* Check for an overlapping memory region.  We only need to check
137      in the vicinity - at most one before and one after the
138      insertion point.  */
139   for (int i = ix - 1; i < ix + 1; i++)
140     {
141       if (i < 0)
142         continue;
143       if (i >= user_mem_region_list.size ())
144         continue;
145
146       mem_region &n = user_mem_region_list[i];
147
148       if ((lo >= n.lo && (lo < n.hi || n.hi == 0))
149           || (hi > n.lo && (hi <= n.hi || n.hi == 0))
150           || (lo <= n.lo && ((hi >= n.hi && n.hi != 0) || hi == 0)))
151         {
152           printf_unfiltered (_("overlapping memory region\n"));
153           return;
154         }
155     }
156
157   newobj.number = ++mem_number;
158   user_mem_region_list.insert (it, newobj);
159 }
160
161 /* Look up the memory region corresponding to ADDR.  */
162
163 struct mem_region *
164 lookup_mem_region (CORE_ADDR addr)
165 {
166   static struct mem_region region (0, 0);
167   CORE_ADDR lo;
168   CORE_ADDR hi;
169
170   require_target_regions ();
171
172   /* First we initialize LO and HI so that they describe the entire
173      memory space.  As we process the memory region chain, they are
174      redefined to describe the minimal region containing ADDR.  LO
175      and HI are used in the case where no memory region is defined
176      that contains ADDR.  If a memory region is disabled, it is
177      treated as if it does not exist.  The initial values for LO
178      and HI represent the bottom and top of memory.  */
179
180   lo = 0;
181   hi = 0;
182
183   /* Either find memory range containing ADDR, or set LO and HI
184      to the nearest boundaries of an existing memory range.
185      
186      If we ever want to support a huge list of memory regions, this
187      check should be replaced with a binary search (probably using
188      VEC_lower_bound).  */
189   for (mem_region &m : *mem_region_list)
190     {
191       if (m.enabled_p == 1)
192         {
193           /* If the address is in the memory region, return that
194              memory range.  */
195           if (addr >= m.lo && (addr < m.hi || m.hi == 0))
196             return &m;
197
198           /* This (correctly) won't match if m->hi == 0, representing
199              the top of the address space, because CORE_ADDR is unsigned;
200              no value of LO is less than zero.  */
201           if (addr >= m.hi && lo < m.hi)
202             lo = m.hi;
203
204           /* This will never set HI to zero; if we're here and ADDR
205              is at or below M, and the region starts at zero, then ADDR
206              would have been in the region.  */
207           if (addr <= m.lo && (hi == 0 || hi > m.lo))
208             hi = m.lo;
209         }
210     }
211
212   /* Because no region was found, we must cons up one based on what
213      was learned above.  */
214   region.lo = lo;
215   region.hi = hi;
216
217   /* When no memory map is defined at all, we always return 
218      'default_mem_attrib', so that we do not make all memory 
219      inaccessible for targets that don't provide a memory map.  */
220   if (inaccessible_by_default && !mem_region_list->empty ())
221     region.attrib = mem_attrib::unknown ();
222   else
223     region.attrib = mem_attrib ();
224
225   return &region;
226 }
227
228 /* Invalidate any memory regions fetched from the target.  */
229
230 void
231 invalidate_target_mem_regions (void)
232 {
233   if (!target_mem_regions_valid)
234     return;
235
236   target_mem_regions_valid = false;
237   target_mem_region_list.clear ();
238 }
239
240 /* Clear user-defined memory region list.  */
241
242 static void
243 user_mem_clear (void)
244 {
245   user_mem_region_list.clear ();
246 }
247 \f
248
249 static void
250 mem_command (const char *args, int from_tty)
251 {
252   CORE_ADDR lo, hi;
253
254   if (!args)
255     error_no_arg (_("No mem"));
256
257   /* For "mem auto", switch back to using a target provided list.  */
258   if (strcmp (args, "auto") == 0)
259     {
260       if (mem_use_target ())
261         return;
262
263       user_mem_clear ();
264       mem_region_list = &target_mem_region_list;
265
266       return;
267     }
268
269   require_user_regions (from_tty);
270
271   std::string tok = extract_arg (&args);
272   if (tok == "")
273     error (_("no lo address"));
274   lo = parse_and_eval_address (tok.c_str ());
275
276   tok = extract_arg (&args);
277   if (tok == "")
278     error (_("no hi address"));
279   hi = parse_and_eval_address (tok.c_str ());
280
281   mem_attrib attrib;
282   while ((tok = extract_arg (&args)) != "")
283     {
284       if (tok == "rw")
285         attrib.mode = MEM_RW;
286       else if (tok == "ro")
287         attrib.mode = MEM_RO;
288       else if (tok == "wo")
289         attrib.mode = MEM_WO;
290
291       else if (tok == "8")
292         attrib.width = MEM_WIDTH_8;
293       else if (tok == "16")
294         {
295           if ((lo % 2 != 0) || (hi % 2 != 0))
296             error (_("region bounds not 16 bit aligned"));
297           attrib.width = MEM_WIDTH_16;
298         }
299       else if (tok == "32")
300         {
301           if ((lo % 4 != 0) || (hi % 4 != 0))
302             error (_("region bounds not 32 bit aligned"));
303           attrib.width = MEM_WIDTH_32;
304         }
305       else if (tok == "64")
306         {
307           if ((lo % 8 != 0) || (hi % 8 != 0))
308             error (_("region bounds not 64 bit aligned"));
309           attrib.width = MEM_WIDTH_64;
310         }
311
312 #if 0
313       else if (tok == "hwbreak")
314         attrib.hwbreak = 1;
315       else if (tok == "swbreak")
316         attrib.hwbreak = 0;
317 #endif
318
319       else if (tok == "cache")
320         attrib.cache = 1;
321       else if (tok == "nocache")
322         attrib.cache = 0;
323
324 #if 0
325       else if (tok == "verify")
326         attrib.verify = 1;
327       else if (tok == "noverify")
328         attrib.verify = 0;
329 #endif
330
331       else
332         error (_("unknown attribute: %s"), tok.c_str ());
333     }
334
335   create_user_mem_region (lo, hi, attrib);
336 }
337 \f
338
339 static void
340 info_mem_command (const char *args, int from_tty)
341 {
342   if (mem_use_target ())
343     printf_filtered (_("Using memory regions provided by the target.\n"));
344   else
345     printf_filtered (_("Using user-defined memory regions.\n"));
346
347   require_target_regions ();
348
349   if (mem_region_list->empty ())
350     {
351       printf_unfiltered (_("There are no memory regions defined.\n"));
352       return;
353     }
354
355   printf_filtered ("Num ");
356   printf_filtered ("Enb ");
357   printf_filtered ("Low Addr   ");
358   if (gdbarch_addr_bit (target_gdbarch ()) > 32)
359     printf_filtered ("        ");
360   printf_filtered ("High Addr  ");
361   if (gdbarch_addr_bit (target_gdbarch ()) > 32)
362     printf_filtered ("        ");
363   printf_filtered ("Attrs ");
364   printf_filtered ("\n");
365
366   for (const mem_region &m : *mem_region_list)
367     {
368       const char *tmp;
369
370       printf_filtered ("%-3d %-3c\t",
371                        m.number,
372                        m.enabled_p ? 'y' : 'n');
373       if (gdbarch_addr_bit (target_gdbarch ()) <= 32)
374         tmp = hex_string_custom (m.lo, 8);
375       else
376         tmp = hex_string_custom (m.lo, 16);
377       
378       printf_filtered ("%s ", tmp);
379
380       if (gdbarch_addr_bit (target_gdbarch ()) <= 32)
381         {
382           if (m.hi == 0)
383             tmp = "0x100000000";
384           else
385             tmp = hex_string_custom (m.hi, 8);
386         }
387       else
388         {
389           if (m.hi == 0)
390             tmp = "0x10000000000000000";
391           else
392             tmp = hex_string_custom (m.hi, 16);
393         }
394
395       printf_filtered ("%s ", tmp);
396
397       /* Print a token for each attribute.
398
399        * FIXME: Should we output a comma after each token?  It may
400        * make it easier for users to read, but we'd lose the ability
401        * to cut-and-paste the list of attributes when defining a new
402        * region.  Perhaps that is not important.
403        *
404        * FIXME: If more attributes are added to GDB, the output may
405        * become cluttered and difficult for users to read.  At that
406        * time, we may want to consider printing tokens only if they
407        * are different from the default attribute.  */
408
409       switch (m.attrib.mode)
410         {
411         case MEM_RW:
412           printf_filtered ("rw ");
413           break;
414         case MEM_RO:
415           printf_filtered ("ro ");
416           break;
417         case MEM_WO:
418           printf_filtered ("wo ");
419           break;
420         case MEM_FLASH:
421           printf_filtered ("flash blocksize 0x%x ", m.attrib.blocksize);
422           break;
423         }
424
425       switch (m.attrib.width)
426         {
427         case MEM_WIDTH_8:
428           printf_filtered ("8 ");
429           break;
430         case MEM_WIDTH_16:
431           printf_filtered ("16 ");
432           break;
433         case MEM_WIDTH_32:
434           printf_filtered ("32 ");
435           break;
436         case MEM_WIDTH_64:
437           printf_filtered ("64 ");
438           break;
439         case MEM_WIDTH_UNSPECIFIED:
440           break;
441         }
442
443 #if 0
444       if (attrib->hwbreak)
445         printf_filtered ("hwbreak");
446       else
447         printf_filtered ("swbreak");
448 #endif
449
450       if (m.attrib.cache)
451         printf_filtered ("cache ");
452       else
453         printf_filtered ("nocache ");
454
455 #if 0
456       if (attrib->verify)
457         printf_filtered ("verify ");
458       else
459         printf_filtered ("noverify ");
460 #endif
461
462       printf_filtered ("\n");
463     }
464 }
465 \f
466
467 /* Enable the memory region number NUM.  */
468
469 static void
470 mem_enable (int num)
471 {
472   for (mem_region &m : *mem_region_list)
473     if (m.number == num)
474       {
475         m.enabled_p = 1;
476         return;
477       }
478   printf_unfiltered (_("No memory region number %d.\n"), num);
479 }
480
481 static void
482 enable_mem_command (const char *args, int from_tty)
483 {
484   require_user_regions (from_tty);
485
486   target_dcache_invalidate ();
487
488   if (args == NULL || *args == '\0')
489     { /* Enable all mem regions.  */
490       for (mem_region &m : *mem_region_list)
491         m.enabled_p = 1;
492     }
493   else
494     {
495       number_or_range_parser parser (args);
496       while (!parser.finished ())
497         {
498           int num = parser.get_number ();
499           mem_enable (num);
500         }
501     }
502 }
503 \f
504
505 /* Disable the memory region number NUM.  */
506
507 static void
508 mem_disable (int num)
509 {
510   for (mem_region &m : *mem_region_list)
511     if (m.number == num)
512       {
513         m.enabled_p = 0;
514         return;
515       }
516   printf_unfiltered (_("No memory region number %d.\n"), num);
517 }
518
519 static void
520 disable_mem_command (const char *args, int from_tty)
521 {
522   require_user_regions (from_tty);
523
524   target_dcache_invalidate ();
525
526   if (args == NULL || *args == '\0')
527     {
528       for (mem_region &m : *mem_region_list)
529         m.enabled_p = false;
530     }
531   else
532     {
533       number_or_range_parser parser (args);
534       while (!parser.finished ())
535         {
536           int num = parser.get_number ();
537           mem_disable (num);
538         }
539     }
540 }
541
542 /* Delete the memory region number NUM.  */
543
544 static void
545 mem_delete (int num)
546 {
547   if (!mem_region_list)
548     {
549       printf_unfiltered (_("No memory region number %d.\n"), num);
550       return;
551     }
552
553   auto it = std::remove_if (mem_region_list->begin (), mem_region_list->end (),
554                             [num] (const mem_region &m)
555     {
556       return m.number == num;
557     });
558
559   if (it != mem_region_list->end ())
560     mem_region_list->erase (it);
561   else
562     printf_unfiltered (_("No memory region number %d.\n"), num);
563 }
564
565 static void
566 delete_mem_command (const char *args, int from_tty)
567 {
568   require_user_regions (from_tty);
569
570   target_dcache_invalidate ();
571
572   if (args == NULL || *args == '\0')
573     {
574       if (query (_("Delete all memory regions? ")))
575         user_mem_clear ();
576       dont_repeat ();
577       return;
578     }
579
580   number_or_range_parser parser (args);
581   while (!parser.finished ())
582     {
583       int num = parser.get_number ();
584       mem_delete (num);
585     }
586
587   dont_repeat ();
588 }
589
590 static void
591 dummy_cmd (const char *args, int from_tty)
592 {
593 }
594
595 static struct cmd_list_element *mem_set_cmdlist;
596 static struct cmd_list_element *mem_show_cmdlist;
597
598 void
599 _initialize_mem (void)
600 {
601   add_com ("mem", class_vars, mem_command, _("\
602 Define attributes for memory region or reset memory region handling to "
603 "target-based.\n\
604 Usage: mem auto\n\
605        mem LOW HIGH [MODE WIDTH CACHE],\n\
606 where MODE  may be rw (read/write), ro (read-only) or wo (write-only),\n\
607       WIDTH may be 8, 16, 32, or 64, and\n\
608       CACHE may be cache or nocache"));
609
610   add_cmd ("mem", class_vars, enable_mem_command, _("\
611 Enable memory region.\n\
612 Arguments are the IDs of the memory regions to enable.\n\
613 Usage: enable mem [ID]...\n\
614 Do \"info mem\" to see current list of IDs."), &enablelist);
615
616   add_cmd ("mem", class_vars, disable_mem_command, _("\
617 Disable memory region.\n\
618 Arguments are the IDs of the memory regions to disable.\n\
619 Usage: disable mem [ID]...\n\
620 Do \"info mem\" to see current list of IDs."), &disablelist);
621
622   add_cmd ("mem", class_vars, delete_mem_command, _("\
623 Delete memory region.\n\
624 Arguments are the IDs of the memory regions to delete.\n\
625 Usage: delete mem [ID]...\n\
626 Do \"info mem\" to see current list of IDs."), &deletelist);
627
628   add_info ("mem", info_mem_command,
629             _("Memory region attributes."));
630
631   add_prefix_cmd ("mem", class_vars, dummy_cmd, _("\
632 Memory regions settings."),
633                   &mem_set_cmdlist, "set mem ",
634                   0/* allow-unknown */, &setlist);
635   add_prefix_cmd ("mem", class_vars, dummy_cmd, _("\
636 Memory regions settings."),
637                   &mem_show_cmdlist, "show mem  ",
638                   0/* allow-unknown */, &showlist);
639
640   add_setshow_boolean_cmd ("inaccessible-by-default", no_class,
641                                   &inaccessible_by_default, _("\
642 Set handling of unknown memory regions."), _("\
643 Show handling of unknown memory regions."), _("\
644 If on, and some memory map is defined, debugger will emit errors on\n\
645 accesses to memory not defined in the memory map. If off, accesses to all\n\
646 memory addresses will be allowed."),
647                                 NULL,
648                                 show_inaccessible_by_default,
649                                 &mem_set_cmdlist,
650                                 &mem_show_cmdlist);
651 }