Skip to content

Commit 147d7a6

Browse files
committed
[lldb] Add support for large watchpoints in lldb (#79962)
This patch is the next piece of work in my Large Watchpoint proposal, https://discourse.llvm.org/t/rfc-large-watchpoint-support-in-lldb/72116 This patch breaks a user's watchpoint into one or more WatchpointResources which reflect what the hardware registers can cover. This means we can watch objects larger than 8 bytes, and we can watched unaligned address ranges. On a typical 64-bit target with 4 watchpoint registers you can watch 32 bytes of memory if the start address is doubleword aligned. Additionally, if the remote stub implements AArch64 MASK style watchpoints (e.g. debugserver on Darwin), we can watch any power-of-2 size region of memory up to 2GB, aligned to that same size. I updated the Watchpoint constructor and CommandObjectWatchpoint to create a CompilerType of Array<UInt8> when the size of the watched region is greater than pointer-size and we don't have a variable type to use. For pointer-size and smaller, we can display the watched granule as an integer value; for larger-than-pointer-size we will display as an array of bytes. I have `watchpoint list` now print the WatchpointResources used to implement the watchpoint. I added a WatchpointAlgorithm class which has a top-level static method that takes an enum flag mask WatchpointHardwareFeature and a user address and size, and returns a vector of WatchpointResources covering the request. It does not take into account the number of watchpoint registers the target has, or the number still available for use. Right now there is only one algorithm, which monitors power-of-2 regions of memory. For up to pointer-size, this is what Intel hardware supports. AArch64 Byte Address Select watchpoints can watch any number of contiguous bytes in a pointer-size memory granule, that is not currently supported so if you ask to watch bytes 3-5, the algorithm will watch the entire doubleword (8 bytes). The newly default "modify" style means we will silently ignore modifications to bytes outside the watched range. I've temporarily skipped TestLargeWatchpoint.py for all targets. It was only run on Darwin when using the in-tree debugserver, which was a proxy for "debugserver supports MASK watchpoints". I'll be adding the aforementioned feature flag from the stub and enabling full mask watchpoints when a debugserver with that feature is enabled, and re-enable this test. I added a new TestUnalignedLargeWatchpoint.py which only has one test but it's a great one, watching a 22-byte range that is unaligned and requires four 8-byte watchpoints to cover. I also added a unit test, WatchpointAlgorithmsTests, which has a number of simple tests against WatchpointAlgorithms::PowerOf2Watchpoints. I think there's interesting possible different approaches to how we cover these; I note in the unit test that a user requesting a watch on address 0x12e0 of 120 bytes will be covered by two watchpoints today, a 128-bytes at 0x1280 and at 0x1300. But it could be done with a 16-byte watchpoint at 0x12e0 and a 128-byte at 0x1300, which would have fewer false positives/private stops. As we try refining this one, it's helpful to have a collection of tests to make sure things don't regress. I tested this on arm64 macOS, (genuine) x86_64 macOS, and AArch64 Ubuntu. I have not modifed the Windows process plugins yet, I might try that as a standalone patch, I'd be making the change blind, but the necessary changes (see ProcessGDBRemote::EnableWatchpoint) are pretty small so it might be obvious enough that I can change it and see what the Windows CI thinks. There isn't yet a packet (or a qSupported feature query) for the gdb remote serial protocol stub to communicate its watchpoint capabilities to lldb. I'll be doing that in a patch right after this is landed, having debugserver advertise its capability of AArch64 MASK watchpoints, and have ProcessGDBRemote add eWatchpointHardwareArmMASK to WatchpointAlgorithms so we can watch larger than 32-byte requests on Darwin. I haven't yet tackled WatchpointResource *sharing* by multiple Watchpoints. This is all part of the goal, especially when we may be watching a larger memory range than the user requested, if they then add another watchpoint next to their first request, it may be covered by the same WatchpointResource (hardware watchpoint register). Also one "read" watchpoint and one "write" watchpoint on the same memory granule need to be handled, making the WatchpointResource cover all requests. As WatchpointResources aren't shared among multiple Watchpoints yet, there's no handling of running the conditions/commands/etc on multiple Watchpoints when their shared WatchpointResource is hit. The goal beyond "large watchpoint" is to unify (much more) the Watchpoint and Breakpoint behavior and commands. I have a feeling I may be slowly chipping away at this for a while. Re-landing this patch after fixing two undefined behaviors in WatchpointAlgorithms found by UBSan and by failures on different CI bots. rdar://108234227
1 parent 0c36127 commit 147d7a6

File tree

18 files changed

+695
-40
lines changed

18 files changed

+695
-40
lines changed
Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
//===-- WatchpointAlgorithms.h ----------------------------------*- C++ -*-===//
2+
//
3+
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4+
// See https://llvm.org/LICENSE.txt for license information.
5+
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6+
//
7+
//===----------------------------------------------------------------------===//
8+
9+
#ifndef LLDB_BREAKPOINT_WATCHPOINTALGORITHMS_H
10+
#define LLDB_BREAKPOINT_WATCHPOINTALGORITHMS_H
11+
12+
#include "lldb/Breakpoint/WatchpointResource.h"
13+
#include "lldb/Utility/ArchSpec.h"
14+
#include "lldb/lldb-public.h"
15+
16+
#include <vector>
17+
18+
namespace lldb_private {
19+
20+
class WatchpointAlgorithms {
21+
22+
public:
23+
/// Convert a user's watchpoint request into an array of memory
24+
/// regions that can be watched by one hardware watchpoint register
25+
/// on the current target.
26+
///
27+
/// \param[in] addr
28+
/// The start address specified by the user.
29+
///
30+
/// \param[in] size
31+
/// The number of bytes the user wants to watch.
32+
///
33+
/// \param[in] read
34+
/// True if we are watching for read accesses.
35+
///
36+
/// \param[in] write
37+
/// True if we are watching for write accesses.
38+
/// \a read and \a write may both be true.
39+
/// There is no "modify" style for WatchpointResources -
40+
/// WatchpointResources are akin to the hardware watchpoint
41+
/// registers which are either in terms of read or write.
42+
/// "modify" distinction is done at the Watchpoint layer, where
43+
/// we check the actual range of bytes the user requested.
44+
///
45+
/// \param[in] supported_features
46+
/// The bit flags in this parameter are set depending on which
47+
/// WatchpointHardwareFeature enum values the current target supports.
48+
/// The eWatchpointHardwareFeatureUnknown bit may be set if we
49+
/// don't have specific information about what the remote stub
50+
/// can support, and a reasonablec default will be used.
51+
///
52+
/// \param[in] arch
53+
/// The ArchSpec of the current Target.
54+
///
55+
/// \return
56+
/// A vector of WatchpointResourceSP's, one per hardware watchpoint
57+
/// register needed. We may return more WatchpointResources than the
58+
/// target can watch at once; if all resources cannot be set, the
59+
/// watchpoint cannot be set.
60+
static std::vector<lldb::WatchpointResourceSP> AtomizeWatchpointRequest(
61+
lldb::addr_t addr, size_t size, bool read, bool write,
62+
lldb::WatchpointHardwareFeature supported_features, ArchSpec &arch);
63+
64+
struct Region {
65+
lldb::addr_t addr;
66+
size_t size;
67+
};
68+
69+
protected:
70+
/// Convert a user's watchpoint request into an array of addr+size that
71+
/// can be watched with power-of-2 style hardware watchpoints.
72+
///
73+
/// This is the default algorithm if we have no further information;
74+
/// most watchpoint implementations can be assumed to be able to watch up
75+
/// to pointer-size regions of memory in power-of-2 sizes and alingments.
76+
///
77+
/// \param[in] user_addr
78+
/// The user's start address.
79+
///
80+
/// \param[in] user_size
81+
/// The user's specified byte length.
82+
///
83+
/// \param[in] min_byte_size
84+
/// The minimum byte size supported on this target.
85+
/// In most cases, this will be 1. AArch64 MASK watchpoints can
86+
/// watch a minimum of 8 bytes (although Byte Address Select watchpoints
87+
/// can watch 1 to pointer-size bytes in a pointer-size aligned granule).
88+
///
89+
/// \param[in] max_byte_size
90+
/// The maximum byte size supported for one watchpoint on this target.
91+
///
92+
/// \param[in] address_byte_size
93+
/// The address byte size on this target.
94+
static std::vector<Region> PowerOf2Watchpoints(lldb::addr_t user_addr,
95+
size_t user_size,
96+
size_t min_byte_size,
97+
size_t max_byte_size,
98+
uint32_t address_byte_size);
99+
};
100+
101+
} // namespace lldb_private
102+
103+
#endif // LLDB_BREAKPOINT_WATCHPOINTALGORITHMS_H

lldb/include/lldb/lldb-enumerations.h

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -448,6 +448,32 @@ enum WatchpointWriteType {
448448
eWatchpointWriteTypeOnModify
449449
};
450450

451+
/// The hardware and native stub capabilities for a given target,
452+
/// for translating a user's watchpoint request into hardware
453+
/// capable watchpoint resources.
454+
FLAGS_ENUM(WatchpointHardwareFeature){
455+
/// lldb will fall back to a default that assumes the target
456+
/// can watch up to pointer-size power-of-2 regions, aligned to
457+
/// power-of-2.
458+
eWatchpointHardwareFeatureUnknown = (1u << 0),
459+
460+
/// Intel systems can watch 1, 2, 4, or 8 bytes (in 64-bit targets),
461+
/// aligned naturally.
462+
eWatchpointHardwareX86 = (1u << 1),
463+
464+
/// ARM systems with Byte Address Select watchpoints
465+
/// can watch any consecutive series of bytes up to the
466+
/// size of a pointer (4 or 8 bytes), at a pointer-size
467+
/// alignment.
468+
eWatchpointHardwareArmBAS = (1u << 2),
469+
470+
/// ARM systems with MASK watchpoints can watch any power-of-2
471+
/// sized region from 8 bytes to 2 gigabytes, aligned to that
472+
/// same power-of-2 alignment.
473+
eWatchpointHardwareArmMASK = (1u << 3),
474+
};
475+
LLDB_MARK_AS_BITMASK_ENUM(WatchpointHardwareFeature)
476+
451477
/// Programming language type.
452478
///
453479
/// These enumerations use the same language enumerations as the DWARF

lldb/packages/Python/lldbsuite/test/concurrent_base.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -166,7 +166,12 @@ def do_thread_actions(
166166

167167
# Initialize the (single) watchpoint on the global variable (g_watchme)
168168
if num_watchpoint_threads + num_delay_watchpoint_threads > 0:
169-
self.runCmd("watchpoint set variable g_watchme")
169+
# The concurrent tests have multiple threads modifying a variable
170+
# with the same value. The default "modify" style watchpoint will
171+
# only report this as 1 hit for all threads, because they all wrote
172+
# the same value. The testsuite needs "write" style watchpoints to
173+
# get the correct number of hits reported.
174+
self.runCmd("watchpoint set variable -w write g_watchme")
170175
for w in self.inferior_target.watchpoint_iter():
171176
self.thread_watchpoint = w
172177
self.assertTrue(

lldb/source/Breakpoint/CMakeLists.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ add_lldb_library(lldbBreakpoint NO_PLUGIN_DEPENDENCIES
2121
StoppointSite.cpp
2222
StopPointSiteList.cpp
2323
Watchpoint.cpp
24+
WatchpointAlgorithms.cpp
2425
WatchpointList.cpp
2526
WatchpointOptions.cpp
2627
WatchpointResource.cpp

lldb/source/Breakpoint/Watchpoint.cpp

Lines changed: 24 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -44,10 +44,16 @@ Watchpoint::Watchpoint(Target &target, lldb::addr_t addr, uint32_t size,
4444
LLDB_LOG_ERROR(GetLog(LLDBLog::Watchpoints), std::move(err),
4545
"Failed to set type: {0}");
4646
} else {
47-
if (auto ts = *type_system_or_err)
48-
m_type =
49-
ts->GetBuiltinTypeForEncodingAndBitSize(eEncodingUint, 8 * size);
50-
else
47+
if (auto ts = *type_system_or_err) {
48+
if (size <= target.GetArchitecture().GetAddressByteSize()) {
49+
m_type =
50+
ts->GetBuiltinTypeForEncodingAndBitSize(eEncodingUint, 8 * size);
51+
} else {
52+
CompilerType clang_uint8_type =
53+
ts->GetBuiltinTypeForEncodingAndBitSize(eEncodingUint, 8);
54+
m_type = clang_uint8_type.GetArrayType(size);
55+
}
56+
} else
5157
LLDB_LOG_ERROR(GetLog(LLDBLog::Watchpoints), std::move(err),
5258
"Failed to set type: Typesystem is no longer live: {0}");
5359
}
@@ -350,6 +356,20 @@ void Watchpoint::DumpWithLevel(Stream *s,
350356
s->Printf("\n declare @ '%s'", m_decl_str.c_str());
351357
if (!m_watch_spec_str.empty())
352358
s->Printf("\n watchpoint spec = '%s'", m_watch_spec_str.c_str());
359+
if (IsEnabled()) {
360+
if (ProcessSP process_sp = m_target.GetProcessSP()) {
361+
auto &resourcelist = process_sp->GetWatchpointResourceList();
362+
size_t idx = 0;
363+
s->Printf("\n watchpoint resources:");
364+
for (WatchpointResourceSP &wpres : resourcelist.Sites()) {
365+
if (wpres->ConstituentsContains(this)) {
366+
s->Printf("\n #%zu: ", idx);
367+
wpres->Dump(s);
368+
}
369+
idx++;
370+
}
371+
}
372+
}
353373

354374
// Dump the snapshots we have taken.
355375
DumpSnapshots(s, " ");
Lines changed: 159 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,159 @@
1+
//===-- WatchpointAlgorithms.cpp ------------------------------------------===//
2+
//
3+
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4+
// See https://llvm.org/LICENSE.txt for license information.
5+
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6+
//
7+
//===----------------------------------------------------------------------===//
8+
9+
#include "lldb/Breakpoint/WatchpointAlgorithms.h"
10+
#include "lldb/Breakpoint/WatchpointResource.h"
11+
#include "lldb/Target/Process.h"
12+
#include "lldb/Utility/ArchSpec.h"
13+
#include "lldb/Utility/LLDBLog.h"
14+
#include "lldb/Utility/Log.h"
15+
16+
#include <algorithm>
17+
#include <utility>
18+
#include <vector>
19+
20+
using namespace lldb;
21+
using namespace lldb_private;
22+
23+
std::vector<WatchpointResourceSP>
24+
WatchpointAlgorithms::AtomizeWatchpointRequest(
25+
addr_t addr, size_t size, bool read, bool write,
26+
WatchpointHardwareFeature supported_features, ArchSpec &arch) {
27+
28+
std::vector<Region> entries;
29+
30+
if (supported_features &
31+
WatchpointHardwareFeature::eWatchpointHardwareArmMASK) {
32+
entries =
33+
PowerOf2Watchpoints(addr, size,
34+
/*min_byte_size*/ 1,
35+
/*max_byte_size*/ INT32_MAX,
36+
/*address_byte_size*/ arch.GetAddressByteSize());
37+
} else {
38+
// As a fallback, assume we can watch any power-of-2
39+
// number of bytes up through the size of an address in the target.
40+
entries =
41+
PowerOf2Watchpoints(addr, size,
42+
/*min_byte_size*/ 1,
43+
/*max_byte_size*/ arch.GetAddressByteSize(),
44+
/*address_byte_size*/ arch.GetAddressByteSize());
45+
}
46+
47+
Log *log = GetLog(LLDBLog::Watchpoints);
48+
LLDB_LOGV(log, "AtomizeWatchpointRequest user request addr {0:x} size {1}",
49+
addr, size);
50+
std::vector<WatchpointResourceSP> resources;
51+
for (Region &ent : entries) {
52+
LLDB_LOGV(log, "AtomizeWatchpointRequest creating resource {0:x} size {1}",
53+
ent.addr, ent.size);
54+
WatchpointResourceSP wp_res_sp =
55+
std::make_shared<WatchpointResource>(ent.addr, ent.size, read, write);
56+
resources.push_back(wp_res_sp);
57+
}
58+
59+
return resources;
60+
}
61+
62+
// This should be `std::bit_ceil(aligned_size)` but
63+
// that requires C++20.
64+
// Calculates the smallest integral power of two that is not smaller than x.
65+
static uint64_t bit_ceil(uint64_t input) {
66+
if (input <= 1 || llvm::popcount(input) == 1)
67+
return input;
68+
69+
return 1ULL << (64 - llvm::countl_zero(input));
70+
}
71+
72+
/// Convert a user's watchpoint request (\a user_addr and \a user_size)
73+
/// into hardware watchpoints, for a target that can watch a power-of-2
74+
/// region of memory (1, 2, 4, 8, etc), aligned to that same power-of-2
75+
/// memory address.
76+
///
77+
/// If a user asks to watch 4 bytes at address 0x1002 (0x1002-0x1005
78+
/// inclusive) we can implement this with two 2-byte watchpoints
79+
/// (0x1002 and 0x1004) or with an 8-byte watchpoint at 0x1000.
80+
/// A 4-byte watchpoint at 0x1002 would not be properly 4 byte aligned.
81+
///
82+
/// If a user asks to watch 16 bytes at 0x1000, and this target supports
83+
/// 8-byte watchpoints, we can implement this with two 8-byte watchpoints
84+
/// at 0x1000 and 0x1008.
85+
std::vector<WatchpointAlgorithms::Region>
86+
WatchpointAlgorithms::PowerOf2Watchpoints(addr_t user_addr, size_t user_size,
87+
size_t min_byte_size,
88+
size_t max_byte_size,
89+
uint32_t address_byte_size) {
90+
91+
Log *log = GetLog(LLDBLog::Watchpoints);
92+
LLDB_LOGV(log,
93+
"AtomizeWatchpointRequest user request addr {0:x} size {1} "
94+
"min_byte_size {2}, max_byte_size {3}, address_byte_size {4}",
95+
user_addr, user_size, min_byte_size, max_byte_size,
96+
address_byte_size);
97+
98+
// Can't watch zero bytes.
99+
if (user_size == 0)
100+
return {};
101+
102+
size_t aligned_size = std::max(user_size, min_byte_size);
103+
/// Round up \a user_size to the next power-of-2 size
104+
/// user_size == 8 -> aligned_size == 8
105+
/// user_size == 9 -> aligned_size == 16
106+
aligned_size = bit_ceil(aligned_size);
107+
108+
addr_t aligned_start = user_addr & ~(aligned_size - 1);
109+
110+
// Does this power-of-2 memory range, aligned to power-of-2 that the
111+
// hardware can watch, completely cover the requested region.
112+
if (aligned_size <= max_byte_size &&
113+
aligned_start + aligned_size >= user_addr + user_size)
114+
return {{aligned_start, aligned_size}};
115+
116+
// If the maximum region we can watch is larger than the aligned
117+
// size, try increasing the region size by one power of 2 and see
118+
// if aligning to that amount can cover the requested region.
119+
//
120+
// Increasing the aligned_size repeatedly instead of splitting the
121+
// watchpoint can result in us watching large regions of memory
122+
// unintentionally when we could use small two watchpoints. e.g.
123+
// user_addr 0x3ff8 user_size 32
124+
// can be watched with four 8-byte watchpoints or if it's done with one
125+
// MASK watchpoint, it would need to be a 32KB watchpoint (a 16KB
126+
// watchpoint at 0x0 only covers 0x0000-0x4000). A user request
127+
// at the end of a power-of-2 region can lead to these undesirably
128+
// large watchpoints and many false positive hits to ignore.
129+
if (max_byte_size >= (aligned_size << 1)) {
130+
aligned_size <<= 1;
131+
aligned_start = user_addr & ~(aligned_size - 1);
132+
if (aligned_size <= max_byte_size &&
133+
aligned_start + aligned_size >= user_addr + user_size)
134+
return {{aligned_start, aligned_size}};
135+
136+
// Go back to our original aligned size, to try the multiple
137+
// watchpoint approach.
138+
aligned_size >>= 1;
139+
}
140+
141+
// We need to split the user's watchpoint into two or more watchpoints
142+
// that can be monitored by hardware, because of alignment and/or size
143+
// reasons.
144+
aligned_size = std::min(aligned_size, max_byte_size);
145+
aligned_start = user_addr & ~(aligned_size - 1);
146+
147+
std::vector<Region> result;
148+
addr_t current_address = aligned_start;
149+
const addr_t user_end_address = user_addr + user_size;
150+
while (current_address + aligned_size < user_end_address) {
151+
result.push_back({current_address, aligned_size});
152+
current_address += aligned_size;
153+
}
154+
155+
if (current_address < user_end_address)
156+
result.push_back({current_address, aligned_size});
157+
158+
return result;
159+
}

lldb/source/Breakpoint/WatchpointResource.cpp

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
#include <assert.h>
1010

1111
#include "lldb/Breakpoint/WatchpointResource.h"
12+
#include "lldb/Utility/Stream.h"
1213

1314
#include <algorithm>
1415

@@ -113,7 +114,8 @@ bool WatchpointResource::ShouldStop(StoppointCallbackContext *context) {
113114
}
114115

115116
void WatchpointResource::Dump(Stream *s) const {
116-
return; // LWP_TODO
117+
s->Printf("addr = 0x%8.8" PRIx64 " size = %zu", m_addr, m_size);
118+
return;
117119
}
118120

119121
wp_resource_id_t WatchpointResource::GetNextID() {

0 commit comments

Comments
 (0)