1 /* Memory ranges 2 3 Copyright (C) 2010-2017 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 "memrange.h" 22 #include <algorithm> 23 24 int 25 mem_ranges_overlap (CORE_ADDR start1, int len1, 26 CORE_ADDR start2, int len2) 27 { 28 ULONGEST h, l; 29 30 l = std::max (start1, start2); 31 h = std::min (start1 + len1, start2 + len2); 32 return (l < h); 33 } 34 35 /* See memrange.h. */ 36 37 int 38 address_in_mem_range (CORE_ADDR address, const struct mem_range *r) 39 { 40 return (r->start <= address 41 && (address - r->start) < r->length); 42 } 43 44 /* qsort comparison function, that compares mem_ranges. Ranges are 45 sorted in ascending START order. */ 46 47 static int 48 compare_mem_ranges (const void *ap, const void *bp) 49 { 50 const struct mem_range *r1 = (const struct mem_range *) ap; 51 const struct mem_range *r2 = (const struct mem_range *) bp; 52 53 if (r1->start > r2->start) 54 return 1; 55 else if (r1->start < r2->start) 56 return -1; 57 else 58 return 0; 59 } 60 61 void 62 normalize_mem_ranges (VEC(mem_range_s) *ranges) 63 { 64 /* This function must not use any VEC operation on RANGES that 65 reallocates the memory block as that invalidates the RANGES 66 pointer, which callers expect to remain valid. */ 67 68 if (!VEC_empty (mem_range_s, ranges)) 69 { 70 struct mem_range *ra, *rb; 71 int a, b; 72 73 qsort (VEC_address (mem_range_s, ranges), 74 VEC_length (mem_range_s, ranges), 75 sizeof (mem_range_s), 76 compare_mem_ranges); 77 78 a = 0; 79 ra = VEC_index (mem_range_s, ranges, a); 80 for (b = 1; VEC_iterate (mem_range_s, ranges, b, rb); b++) 81 { 82 /* If mem_range B overlaps or is adjacent to mem_range A, 83 merge them. */ 84 if (rb->start <= ra->start + ra->length) 85 { 86 ra->length = std::max ((CORE_ADDR) ra->length, 87 (rb->start - ra->start) + rb->length); 88 continue; /* next b, same a */ 89 } 90 a++; /* next a */ 91 ra = VEC_index (mem_range_s, ranges, a); 92 93 if (a != b) 94 *ra = *rb; 95 } 96 VEC_truncate (mem_range_s, ranges, a + 1); 97 } 98 } 99