| 1 |
""" |
| 2 |
Base class for gdb-remote test cases. |
| 3 |
""" |
| 4 |
|
| 5 |
import errno |
| 6 |
import os |
| 7 |
import os.path |
| 8 |
import random |
| 9 |
import re |
| 10 |
import select |
| 11 |
import socket |
| 12 |
import subprocess |
| 13 |
import sys |
| 14 |
import tempfile |
| 15 |
import time |
| 16 |
from lldbsuite.test import configuration |
| 17 |
from lldbsuite.test.lldbtest import * |
| 18 |
from lldbsuite.support import seven |
| 19 |
from lldbgdbserverutils import * |
| 20 |
import logging |
| 21 |
|
| 22 |
|
| 23 |
class _ConnectionRefused(IOError): |
| 24 |
pass |
| 25 |
|
| 26 |
|
| 27 |
class GdbRemoteTestCaseFactory(type): |
| 28 |
def __new__(cls, name, bases, attrs): |
| 29 |
newattrs = {} |
| 30 |
for attrname, attrvalue in attrs.items(): |
| 31 |
if not attrname.startswith("test"): |
| 32 |
newattrs[attrname] = attrvalue |
| 33 |
continue |
| 34 |
|
| 35 |
# If any debug server categories were explicitly tagged, assume |
| 36 |
# that list to be authoritative. If none were specified, try |
| 37 |
# all of them. |
| 38 |
all_categories = set(["debugserver", "llgs"]) |
| 39 |
categories = set(getattr(attrvalue, "categories", [])) & all_categories |
| 40 |
if not categories: |
| 41 |
categories = all_categories |
| 42 |
|
| 43 |
for cat in categories: |
| 44 |
|
| 45 |
@decorators.add_test_categories([cat]) |
| 46 |
@wraps(attrvalue) |
| 47 |
def test_method(self, attrvalue=attrvalue): |
| 48 |
return attrvalue(self) |
| 49 |
|
| 50 |
method_name = attrname + "_" + cat |
| 51 |
test_method.__name__ = method_name |
| 52 |
test_method.debug_server = cat |
| 53 |
newattrs[method_name] = test_method |
| 54 |
|
| 55 |
return super(GdbRemoteTestCaseFactory, cls).__new__(cls, name, bases, newattrs) |
| 56 |
|
| 57 |
|
| 58 |
class GdbRemoteTestCaseBase(Base, metaclass=GdbRemoteTestCaseFactory): |
| 59 |
# Default time out in seconds. The timeout is increased tenfold under Asan. |
| 60 |
DEFAULT_TIMEOUT = 20 * (10 if ("ASAN_OPTIONS" in os.environ) else 1) |
| 61 |
# Default sleep time in seconds. The sleep time is doubled under Asan. |
| 62 |
DEFAULT_SLEEP = 5 * (2 if ("ASAN_OPTIONS" in os.environ) else 1) |
| 63 |
|
| 64 |
_GDBREMOTE_KILL_PACKET = b"$k#6b" |
| 65 |
|
| 66 |
# Start the inferior separately, attach to the inferior on the stub |
| 67 |
# command line. |
| 68 |
_STARTUP_ATTACH = "attach" |
| 69 |
# Start the inferior separately, start the stub without attaching, allow |
| 70 |
# the test to attach to the inferior however it wants (e.g. $vAttach;pid). |
| 71 |
_STARTUP_ATTACH_MANUALLY = "attach_manually" |
| 72 |
# Start the stub, and launch the inferior with an $A packet via the |
| 73 |
# initial packet stream. |
| 74 |
_STARTUP_LAUNCH = "launch" |
| 75 |
|
| 76 |
# GDB Signal numbers that are not target-specific used for common |
| 77 |
# exceptions |
| 78 |
TARGET_EXC_BAD_ACCESS = 0x91 |
| 79 |
TARGET_EXC_BAD_INSTRUCTION = 0x92 |
| 80 |
TARGET_EXC_ARITHMETIC = 0x93 |
| 81 |
TARGET_EXC_EMULATION = 0x94 |
| 82 |
TARGET_EXC_SOFTWARE = 0x95 |
| 83 |
TARGET_EXC_BREAKPOINT = 0x96 |
| 84 |
|
| 85 |
_verbose_log_handler = None |
| 86 |
_log_formatter = logging.Formatter(fmt="%(asctime)-15s %(levelname)-8s %(message)s") |
| 87 |
|
| 88 |
def setUpBaseLogging(self): |
| 89 |
self.logger = logging.getLogger(__name__) |
| 90 |
|
| 91 |
if len(self.logger.handlers) > 0: |
| 92 |
return # We have set up this handler already |
| 93 |
|
| 94 |
self.logger.propagate = False |
| 95 |
self.logger.setLevel(logging.DEBUG) |
| 96 |
|
| 97 |
# log all warnings to stderr |
| 98 |
handler = logging.StreamHandler() |
| 99 |
handler.setLevel(logging.WARNING) |
| 100 |
handler.setFormatter(self._log_formatter) |
| 101 |
self.logger.addHandler(handler) |
| 102 |
|
| 103 |
def isVerboseLoggingRequested(self): |
| 104 |
# We will report our detailed logs if the user requested that the "gdb-remote" channel is |
| 105 |
# logged. |
| 106 |
return any(("gdb-remote" in channel) for channel in lldbtest_config.channels) |
| 107 |
|
| 108 |
def getDebugServer(self): |
| 109 |
method = getattr(self, self.testMethodName) |
| 110 |
return getattr(method, "debug_server", None) |
| 111 |
|
| 112 |
def setUp(self): |
| 113 |
super(GdbRemoteTestCaseBase, self).setUp() |
| 114 |
|
| 115 |
self.setUpBaseLogging() |
| 116 |
self.debug_monitor_extra_args = [] |
| 117 |
|
| 118 |
if self.isVerboseLoggingRequested(): |
| 119 |
# If requested, full logs go to a log file |
| 120 |
self._verbose_log_handler = logging.FileHandler( |
| 121 |
self.getLogBasenameForCurrentTest() + "-host.log" |
| 122 |
) |
| 123 |
self._verbose_log_handler.setFormatter(self._log_formatter) |
| 124 |
self._verbose_log_handler.setLevel(logging.DEBUG) |
| 125 |
self.logger.addHandler(self._verbose_log_handler) |
| 126 |
|
| 127 |
self.test_sequence = GdbRemoteTestSequence(self.logger) |
| 128 |
self.set_inferior_startup_launch() |
| 129 |
self.port = self.get_next_port() |
| 130 |
self.stub_sends_two_stop_notifications_on_kill = False |
| 131 |
if configuration.lldb_platform_url: |
| 132 |
if configuration.lldb_platform_url.startswith("unix-"): |
| 133 |
url_pattern = r"(.+)://\[?(.+?)\]?/.*" |
| 134 |
else: |
| 135 |
url_pattern = r"(.+)://(.+):\d+" |
| 136 |
scheme, host = re.match( |
| 137 |
url_pattern, configuration.lldb_platform_url |
| 138 |
).groups() |
| 139 |
if ( |
| 140 |
configuration.lldb_platform_name == "remote-android" |
| 141 |
and host != "localhost" |
| 142 |
): |
| 143 |
self.stub_device = host |
| 144 |
self.stub_hostname = "localhost" |
| 145 |
else: |
| 146 |
self.stub_device = None |
| 147 |
self.stub_hostname = host |
| 148 |
else: |
| 149 |
self.stub_hostname = "localhost" |
| 150 |
|
| 151 |
debug_server = self.getDebugServer() |
| 152 |
if debug_server == "debugserver": |
| 153 |
self._init_debugserver_test() |
| 154 |
else: |
| 155 |
self._init_llgs_test() |
| 156 |
|
| 157 |
def tearDown(self): |
| 158 |
self.logger.removeHandler(self._verbose_log_handler) |
| 159 |
self._verbose_log_handler = None |
| 160 |
TestBase.tearDown(self) |
| 161 |
|
| 162 |
def getLocalServerLogFile(self): |
| 163 |
return self.getLogBasenameForCurrentTest() + "-server.log" |
| 164 |
|
| 165 |
def setUpServerLogging(self, is_llgs): |
| 166 |
if len(lldbtest_config.channels) == 0: |
| 167 |
return # No logging requested |
| 168 |
|
| 169 |
if lldb.remote_platform: |
| 170 |
log_file = lldbutil.join_remote_paths( |
| 171 |
lldb.remote_platform.GetWorkingDirectory(), "server.log" |
| 172 |
) |
| 173 |
else: |
| 174 |
log_file = self.getLocalServerLogFile() |
| 175 |
|
| 176 |
if is_llgs: |
| 177 |
self.debug_monitor_extra_args.append("--log-file=" + log_file) |
| 178 |
self.debug_monitor_extra_args.append( |
| 179 |
"--log-channels={}".format(":".join(lldbtest_config.channels)) |
| 180 |
) |
| 181 |
else: |
| 182 |
self.debug_monitor_extra_args = [ |
| 183 |
"--log-file=" + log_file, |
| 184 |
"--log-flags=0x800000", |
| 185 |
] |
| 186 |
|
| 187 |
def get_next_port(self): |
| 188 |
return 12000 + random.randint(0, 3999) |
| 189 |
|
| 190 |
def reset_test_sequence(self): |
| 191 |
self.test_sequence = GdbRemoteTestSequence(self.logger) |
| 192 |
|
| 193 |
def _init_llgs_test(self): |
| 194 |
reverse_connect = True |
| 195 |
if lldb.remote_platform: |
| 196 |
# Reverse connections may be tricky due to firewalls/NATs. |
| 197 |
reverse_connect = False |
| 198 |
|
| 199 |
# FIXME: This is extremely linux-oriented |
| 200 |
|
| 201 |
# Grab the ppid from /proc/[shell pid]/stat |
| 202 |
err, retcode, shell_stat = self.run_platform_command("cat /proc/$$/stat") |
| 203 |
self.assertTrue( |
| 204 |
err.Success() and retcode == 0, |
| 205 |
"Failed to read file /proc/$$/stat: %s, retcode: %d" |
| 206 |
% (err.GetCString(), retcode), |
| 207 |
) |
| 208 |
|
| 209 |
# [pid] ([executable]) [state] [*ppid*] |
| 210 |
pid = re.match(r"^\d+ \(.+\) . (\d+)", shell_stat).group(1) |
| 211 |
err, retcode, ls_output = self.run_platform_command( |
| 212 |
"ls -l /proc/%s/exe" % pid |
| 213 |
) |
| 214 |
self.assertTrue( |
| 215 |
err.Success() and retcode == 0, |
| 216 |
"Failed to read file /proc/%s/exe: %s, retcode: %d" |
| 217 |
% (pid, err.GetCString(), retcode), |
| 218 |
) |
| 219 |
exe = ls_output.split()[-1] |
| 220 |
|
| 221 |
# If the binary has been deleted, the link name has " (deleted)" appended. |
| 222 |
# Remove if it's there. |
| 223 |
self.debug_monitor_exe = re.sub(r" \(deleted\)$", "", exe) |
| 224 |
else: |
| 225 |
self.debug_monitor_exe = get_lldb_server_exe() |
| 226 |
|
| 227 |
self.debug_monitor_extra_args = ["gdbserver"] |
| 228 |
self.setUpServerLogging(is_llgs=True) |
| 229 |
|
| 230 |
self.reverse_connect = reverse_connect |
| 231 |
|
| 232 |
def _init_debugserver_test(self): |
| 233 |
self.debug_monitor_exe = get_debugserver_exe() |
| 234 |
self.setUpServerLogging(is_llgs=False) |
| 235 |
self.reverse_connect = True |
| 236 |
|
| 237 |
# The debugserver stub has a race on handling the 'k' command, so it sends an X09 right away, then sends the real X notification |
| 238 |
# when the process truly dies. |
| 239 |
self.stub_sends_two_stop_notifications_on_kill = True |
| 240 |
|
| 241 |
def forward_adb_port(self, source, target, direction, device): |
| 242 |
adb = ["adb"] + (["-s", device] if device else []) + [direction] |
| 243 |
|
| 244 |
def remove_port_forward(): |
| 245 |
subprocess.call(adb + ["--remove", "tcp:%d" % source]) |
| 246 |
|
| 247 |
subprocess.call(adb + ["tcp:%d" % source, "tcp:%d" % target]) |
| 248 |
self.addTearDownHook(remove_port_forward) |
| 249 |
|
| 250 |
def _verify_socket(self, sock): |
| 251 |
# Normally, when the remote stub is not ready, we will get ECONNREFUSED during the |
| 252 |
# connect() attempt. However, due to the way how ADB forwarding works, on android targets |
| 253 |
# the connect() will always be successful, but the connection will be immediately dropped |
| 254 |
# if ADB could not connect on the remote side. This function tries to detect this |
| 255 |
# situation, and report it as "connection refused" so that the upper layers attempt the |
| 256 |
# connection again. |
| 257 |
triple = self.dbg.GetSelectedPlatform().GetTriple() |
| 258 |
if not re.match(".*-.*-.*-android", triple): |
| 259 |
return # Not android. |
| 260 |
can_read, _, _ = select.select([sock], [], [], 0.1) |
| 261 |
if sock not in can_read: |
| 262 |
return # Data is not available, but the connection is alive. |
| 263 |
if len(sock.recv(1, socket.MSG_PEEK)) == 0: |
| 264 |
raise _ConnectionRefused() # Got EOF, connection dropped. |
| 265 |
|
| 266 |
def create_socket(self): |
| 267 |
try: |
| 268 |
sock = socket.socket(family=socket.AF_INET) |
| 269 |
except OSError as e: |
| 270 |
if e.errno != errno.EAFNOSUPPORT: |
| 271 |
raise |
| 272 |
sock = socket.socket(family=socket.AF_INET6) |
| 273 |
|
| 274 |
logger = self.logger |
| 275 |
|
| 276 |
triple = self.dbg.GetSelectedPlatform().GetTriple() |
| 277 |
if re.match(".*-.*-.*-android", triple): |
| 278 |
self.forward_adb_port(self.port, self.port, "forward", self.stub_device) |
| 279 |
|
| 280 |
logger.info( |
| 281 |
"Connecting to debug monitor on %s:%d", self.stub_hostname, self.port |
| 282 |
) |
| 283 |
connect_info = (self.stub_hostname, self.port) |
| 284 |
try: |
| 285 |
sock.connect(connect_info) |
| 286 |
except socket.error as serr: |
| 287 |
if serr.errno == errno.ECONNREFUSED: |
| 288 |
raise _ConnectionRefused() |
| 289 |
raise serr |
| 290 |
|
| 291 |
def shutdown_socket(): |
| 292 |
if sock: |
| 293 |
try: |
| 294 |
# send the kill packet so lldb-server shuts down gracefully |
| 295 |
sock.sendall(GdbRemoteTestCaseBase._GDBREMOTE_KILL_PACKET) |
| 296 |
except: |
| 297 |
logger.warning( |
| 298 |
"failed to send kill packet to debug monitor: {}; ignoring".format( |
| 299 |
sys.exc_info()[0] |
| 300 |
) |
| 301 |
) |
| 302 |
|
| 303 |
try: |
| 304 |
sock.close() |
| 305 |
except: |
| 306 |
logger.warning( |
| 307 |
"failed to close socket to debug monitor: {}; ignoring".format( |
| 308 |
sys.exc_info()[0] |
| 309 |
) |
| 310 |
) |
| 311 |
|
| 312 |
self.addTearDownHook(shutdown_socket) |
| 313 |
|
| 314 |
self._verify_socket(sock) |
| 315 |
|
| 316 |
return sock |
| 317 |
|
| 318 |
def set_inferior_startup_launch(self): |
| 319 |
self._inferior_startup = self._STARTUP_LAUNCH |
| 320 |
|
| 321 |
def set_inferior_startup_attach(self): |
| 322 |
self._inferior_startup = self._STARTUP_ATTACH |
| 323 |
|
| 324 |
def set_inferior_startup_attach_manually(self): |
| 325 |
self._inferior_startup = self._STARTUP_ATTACH_MANUALLY |
| 326 |
|
| 327 |
def get_debug_monitor_command_line_args(self, attach_pid=None): |
| 328 |
commandline_args = self.debug_monitor_extra_args |
| 329 |
if attach_pid: |
| 330 |
commandline_args += ["--attach=%d" % attach_pid] |
| 331 |
if self.reverse_connect: |
| 332 |
commandline_args += ["--reverse-connect", self.connect_address] |
| 333 |
else: |
| 334 |
if lldb.remote_platform: |
| 335 |
commandline_args += ["*:{}".format(self.port)] |
| 336 |
else: |
| 337 |
commandline_args += ["localhost:{}".format(self.port)] |
| 338 |
|
| 339 |
return commandline_args |
| 340 |
|
| 341 |
def get_target_byte_order(self): |
| 342 |
inferior_exe_path = self.getBuildArtifact("a.out") |
| 343 |
target = self.dbg.CreateTarget(inferior_exe_path) |
| 344 |
return target.GetByteOrder() |
| 345 |
|
| 346 |
def launch_debug_monitor(self, attach_pid=None, logfile=None): |
| 347 |
if self.reverse_connect: |
| 348 |
family, type, proto, _, addr = socket.getaddrinfo( |
| 349 |
"localhost", 0, proto=socket.IPPROTO_TCP |
| 350 |
)[0] |
| 351 |
sock = socket.socket(family, type, proto) |
| 352 |
sock.settimeout(self.DEFAULT_TIMEOUT) |
| 353 |
|
| 354 |
sock.bind(addr) |
| 355 |
sock.listen(1) |
| 356 |
addr = sock.getsockname() |
| 357 |
self.connect_address = "[{}]:{}".format(*addr) |
| 358 |
|
| 359 |
# Create the command line. |
| 360 |
commandline_args = self.get_debug_monitor_command_line_args( |
| 361 |
attach_pid=attach_pid |
| 362 |
) |
| 363 |
|
| 364 |
# Start the server. |
| 365 |
server = self.spawnSubprocess( |
| 366 |
self.debug_monitor_exe, commandline_args, install_remote=False |
| 367 |
) |
| 368 |
self.assertIsNotNone(server) |
| 369 |
|
| 370 |
if self.reverse_connect: |
| 371 |
self.sock = sock.accept()[0] |
| 372 |
self.sock.settimeout(self.DEFAULT_TIMEOUT) |
| 373 |
|
| 374 |
return server |
| 375 |
|
| 376 |
def connect_to_debug_monitor(self, attach_pid=None): |
| 377 |
if self.reverse_connect: |
| 378 |
# Create the stub. |
| 379 |
server = self.launch_debug_monitor(attach_pid=attach_pid) |
| 380 |
self.assertIsNotNone(server) |
| 381 |
|
| 382 |
# Schedule debug monitor to be shut down during teardown. |
| 383 |
logger = self.logger |
| 384 |
|
| 385 |
self._server = Server(self.sock, server) |
| 386 |
return server |
| 387 |
|
| 388 |
# We're using a random port algorithm to try not to collide with other ports, |
| 389 |
# and retry a max # times. |
| 390 |
attempts = 0 |
| 391 |
MAX_ATTEMPTS = 20 |
| 392 |
|
| 393 |
while attempts < MAX_ATTEMPTS: |
| 394 |
server = self.launch_debug_monitor(attach_pid=attach_pid) |
| 395 |
|
| 396 |
# Schedule debug monitor to be shut down during teardown. |
| 397 |
logger = self.logger |
| 398 |
|
| 399 |
connect_attemps = 0 |
| 400 |
MAX_CONNECT_ATTEMPTS = 10 |
| 401 |
|
| 402 |
while connect_attemps < MAX_CONNECT_ATTEMPTS: |
| 403 |
# Create a socket to talk to the server |
| 404 |
try: |
| 405 |
logger.info("Connect attempt %d", connect_attemps + 1) |
| 406 |
self.sock = self.create_socket() |
| 407 |
self._server = Server(self.sock, server) |
| 408 |
return server |
| 409 |
except _ConnectionRefused as serr: |
| 410 |
# Ignore, and try again. |
| 411 |
pass |
| 412 |
time.sleep(0.5) |
| 413 |
connect_attemps += 1 |
| 414 |
|
| 415 |
# We should close the server here to be safe. |
| 416 |
server.terminate() |
| 417 |
|
| 418 |
# Increment attempts. |
| 419 |
print( |
| 420 |
"connect to debug monitor on port %d failed, attempt #%d of %d" |
| 421 |
% (self.port, attempts + 1, MAX_ATTEMPTS) |
| 422 |
) |
| 423 |
attempts += 1 |
| 424 |
|
| 425 |
# And wait a random length of time before next attempt, to avoid |
| 426 |
# collisions. |
| 427 |
time.sleep(random.randint(1, 5)) |
| 428 |
|
| 429 |
# Now grab a new port number. |
| 430 |
self.port = self.get_next_port() |
| 431 |
|
| 432 |
raise Exception( |
| 433 |
"failed to create a socket to the launched debug monitor after %d tries" |
| 434 |
% attempts |
| 435 |
) |
| 436 |
|
| 437 |
def launch_process_for_attach( |
| 438 |
self, inferior_args=None, sleep_seconds=3, exe_path=None |
| 439 |
): |
| 440 |
# We're going to start a child process that the debug monitor stub can later attach to. |
| 441 |
# This process needs to be started so that it just hangs around for a while. We'll |
| 442 |
# have it sleep. |
| 443 |
if not exe_path: |
| 444 |
exe_path = self.getBuildArtifact("a.out") |
| 445 |
|
| 446 |
args = [] |
| 447 |
if inferior_args: |
| 448 |
args.extend(inferior_args) |
| 449 |
if sleep_seconds: |
| 450 |
args.append("sleep:%d" % sleep_seconds) |
| 451 |
|
| 452 |
return self.spawnSubprocess(exe_path, args) |
| 453 |
|
| 454 |
def prep_debug_monitor_and_inferior( |
| 455 |
self, |
| 456 |
inferior_args=None, |
| 457 |
inferior_sleep_seconds=3, |
| 458 |
inferior_exe_path=None, |
| 459 |
inferior_env=None, |
| 460 |
): |
| 461 |
"""Prep the debug monitor, the inferior, and the expected packet stream. |
| 462 |
|
| 463 |
Handle the separate cases of using the debug monitor in attach-to-inferior mode |
| 464 |
and in launch-inferior mode. |
| 465 |
|
| 466 |
For attach-to-inferior mode, the inferior process is first started, then |
| 467 |
the debug monitor is started in attach to pid mode (using --attach on the |
| 468 |
stub command line), and the no-ack-mode setup is appended to the packet |
| 469 |
stream. The packet stream is not yet executed, ready to have more expected |
| 470 |
packet entries added to it. |
| 471 |
|
| 472 |
For launch-inferior mode, the stub is first started, then no ack mode is |
| 473 |
setup on the expected packet stream, then the verified launch packets are added |
| 474 |
to the expected socket stream. The packet stream is not yet executed, ready |
| 475 |
to have more expected packet entries added to it. |
| 476 |
|
| 477 |
The return value is: |
| 478 |
{inferior:<inferior>, server:<server>} |
| 479 |
""" |
| 480 |
inferior = None |
| 481 |
attach_pid = None |
| 482 |
|
| 483 |
if ( |
| 484 |
self._inferior_startup == self._STARTUP_ATTACH |
| 485 |
or self._inferior_startup == self._STARTUP_ATTACH_MANUALLY |
| 486 |
): |
| 487 |
# Launch the process that we'll use as the inferior. |
| 488 |
inferior = self.launch_process_for_attach( |
| 489 |
inferior_args=inferior_args, |
| 490 |
sleep_seconds=inferior_sleep_seconds, |
| 491 |
exe_path=inferior_exe_path, |
| 492 |
) |
| 493 |
self.assertIsNotNone(inferior) |
| 494 |
self.assertTrue(inferior.pid > 0) |
| 495 |
if self._inferior_startup == self._STARTUP_ATTACH: |
| 496 |
# In this case, we want the stub to attach via the command |
| 497 |
# line, so set the command line attach pid here. |
| 498 |
attach_pid = inferior.pid |
| 499 |
|
| 500 |
if self._inferior_startup == self._STARTUP_LAUNCH: |
| 501 |
# Build launch args |
| 502 |
if not inferior_exe_path: |
| 503 |
inferior_exe_path = self.getBuildArtifact("a.out") |
| 504 |
|
| 505 |
if lldb.remote_platform: |
| 506 |
remote_path = lldbutil.append_to_process_working_directory( |
| 507 |
self, os.path.basename(inferior_exe_path) |
| 508 |
) |
| 509 |
remote_file_spec = lldb.SBFileSpec(remote_path, False) |
| 510 |
err = lldb.remote_platform.Install( |
| 511 |
lldb.SBFileSpec(inferior_exe_path, True), remote_file_spec |
| 512 |
) |
| 513 |
if err.Fail(): |
| 514 |
raise Exception( |
| 515 |
"remote_platform.Install('%s', '%s') failed: %s" |
| 516 |
% (inferior_exe_path, remote_path, err) |
| 517 |
) |
| 518 |
inferior_exe_path = remote_path |
| 519 |
|
| 520 |
launch_args = [inferior_exe_path] |
| 521 |
if inferior_args: |
| 522 |
launch_args.extend(inferior_args) |
| 523 |
|
| 524 |
# Launch the debug monitor stub, attaching to the inferior. |
| 525 |
server = self.connect_to_debug_monitor(attach_pid=attach_pid) |
| 526 |
self.assertIsNotNone(server) |
| 527 |
|
| 528 |
self.do_handshake() |
| 529 |
|
| 530 |
# Build the expected protocol stream |
| 531 |
if inferior_env: |
| 532 |
for name, value in inferior_env.items(): |
| 533 |
self.add_set_environment_packets(name, value) |
| 534 |
if self._inferior_startup == self._STARTUP_LAUNCH: |
| 535 |
self.add_verified_launch_packets(launch_args) |
| 536 |
|
| 537 |
return {"inferior": inferior, "server": server} |
| 538 |
|
| 539 |
def do_handshake(self): |
| 540 |
server = self._server |
| 541 |
server.send_ack() |
| 542 |
server.send_packet(b"QStartNoAckMode") |
| 543 |
self.assertEqual(server.get_normal_packet(), b"+") |
| 544 |
self.assertEqual(server.get_normal_packet(), b"OK") |
| 545 |
server.send_ack() |
| 546 |
|
| 547 |
def add_verified_launch_packets(self, launch_args): |
| 548 |
self.test_sequence.add_log_lines( |
| 549 |
[ |
| 550 |
"read packet: %s" % build_gdbremote_A_packet(launch_args), |
| 551 |
"send packet: $OK#00", |
| 552 |
"read packet: $qLaunchSuccess#a5", |
| 553 |
"send packet: $OK#00", |
| 554 |
], |
| 555 |
True, |
| 556 |
) |
| 557 |
|
| 558 |
def add_thread_suffix_request_packets(self): |
| 559 |
self.test_sequence.add_log_lines( |
| 560 |
[ |
| 561 |
"read packet: $QThreadSuffixSupported#e4", |
| 562 |
"send packet: $OK#00", |
| 563 |
], |
| 564 |
True, |
| 565 |
) |
| 566 |
|
| 567 |
def add_process_info_collection_packets(self): |
| 568 |
self.test_sequence.add_log_lines( |
| 569 |
[ |
| 570 |
"read packet: $qProcessInfo#dc", |
| 571 |
{ |
| 572 |
"direction": "send", |
| 573 |
"regex": r"^\$(.+)#[0-9a-fA-F]{2}$", |
| 574 |
"capture": {1: "process_info_raw"}, |
| 575 |
}, |
| 576 |
], |
| 577 |
True, |
| 578 |
) |
| 579 |
|
| 580 |
def add_set_environment_packets(self, name, value): |
| 581 |
self.test_sequence.add_log_lines( |
| 582 |
[ |
| 583 |
"read packet: $QEnvironment:" + name + "=" + value + "#00", |
| 584 |
"send packet: $OK#00", |
| 585 |
], |
| 586 |
True, |
| 587 |
) |
| 588 |
|
| 589 |
_KNOWN_PROCESS_INFO_KEYS = [ |
| 590 |
"pid", |
| 591 |
"parent-pid", |
| 592 |
"real-uid", |
| 593 |
"real-gid", |
| 594 |
"effective-uid", |
| 595 |
"effective-gid", |
| 596 |
"cputype", |
| 597 |
"cpusubtype", |
| 598 |
"ostype", |
| 599 |
"triple", |
| 600 |
"vendor", |
| 601 |
"endian", |
| 602 |
"elf_abi", |
| 603 |
"ptrsize", |
| 604 |
] |
| 605 |
|
| 606 |
def parse_process_info_response(self, context): |
| 607 |
# Ensure we have a process info response. |
| 608 |
self.assertIsNotNone(context) |
| 609 |
process_info_raw = context.get("process_info_raw") |
| 610 |
self.assertIsNotNone(process_info_raw) |
| 611 |
|
| 612 |
# Pull out key:value; pairs. |
| 613 |
process_info_dict = { |
| 614 |
match.group(1): match.group(2) |
| 615 |
for match in re.finditer(r"([^:]+):([^;]+);", process_info_raw) |
| 616 |
} |
| 617 |
|
| 618 |
# Validate keys are known. |
| 619 |
for key, val in list(process_info_dict.items()): |
| 620 |
self.assertTrue(key in self._KNOWN_PROCESS_INFO_KEYS) |
| 621 |
self.assertIsNotNone(val) |
| 622 |
|
| 623 |
return process_info_dict |
| 624 |
|
| 625 |
def add_register_info_collection_packets(self): |
| 626 |
self.test_sequence.add_log_lines( |
| 627 |
[ |
| 628 |
{ |
| 629 |
"type": "multi_response", |
| 630 |
"query": "qRegisterInfo", |
| 631 |
"append_iteration_suffix": True, |
| 632 |
"end_regex": re.compile(r"^\$(E\d+)?#[0-9a-fA-F]{2}$"), |
| 633 |
"save_key": "reg_info_responses", |
| 634 |
} |
| 635 |
], |
| 636 |
True, |
| 637 |
) |
| 638 |
|
| 639 |
def parse_register_info_packets(self, context): |
| 640 |
"""Return an array of register info dictionaries, one per register info.""" |
| 641 |
reg_info_responses = context.get("reg_info_responses") |
| 642 |
self.assertIsNotNone(reg_info_responses) |
| 643 |
|
| 644 |
# Parse register infos. |
| 645 |
return [ |
| 646 |
parse_reg_info_response(reg_info_response) |
| 647 |
for reg_info_response in reg_info_responses |
| 648 |
] |
| 649 |
|
| 650 |
def expect_gdbremote_sequence(self): |
| 651 |
return expect_lldb_gdbserver_replay( |
| 652 |
self, |
| 653 |
self._server, |
| 654 |
self.test_sequence, |
| 655 |
self.DEFAULT_TIMEOUT * len(self.test_sequence), |
| 656 |
self.logger, |
| 657 |
) |
| 658 |
|
| 659 |
_KNOWN_REGINFO_KEYS = [ |
| 660 |
"name", |
| 661 |
"alt-name", |
| 662 |
"bitsize", |
| 663 |
"offset", |
| 664 |
"encoding", |
| 665 |
"format", |
| 666 |
"set", |
| 667 |
"gcc", |
| 668 |
"ehframe", |
| 669 |
"dwarf", |
| 670 |
"generic", |
| 671 |
"container-regs", |
| 672 |
"invalidate-regs", |
| 673 |
"dynamic_size_dwarf_expr_bytes", |
| 674 |
"dynamic_size_dwarf_len", |
| 675 |
] |
| 676 |
|
| 677 |
def assert_valid_reg_info(self, reg_info): |
| 678 |
# Assert we know about all the reginfo keys parsed. |
| 679 |
for key in reg_info: |
| 680 |
self.assertTrue(key in self._KNOWN_REGINFO_KEYS) |
| 681 |
|
| 682 |
# Check the bare-minimum expected set of register info keys. |
| 683 |
self.assertTrue("name" in reg_info) |
| 684 |
self.assertTrue("bitsize" in reg_info) |
| 685 |
|
| 686 |
if not self.getArchitecture() == "aarch64": |
| 687 |
self.assertTrue("offset" in reg_info) |
| 688 |
|
| 689 |
self.assertTrue("encoding" in reg_info) |
| 690 |
self.assertTrue("format" in reg_info) |
| 691 |
|
| 692 |
def find_pc_reg_info(self, reg_infos): |
| 693 |
lldb_reg_index = 0 |
| 694 |
for reg_info in reg_infos: |
| 695 |
if ("generic" in reg_info) and (reg_info["generic"] == "pc"): |
| 696 |
return (lldb_reg_index, reg_info) |
| 697 |
lldb_reg_index += 1 |
| 698 |
|
| 699 |
return (None, None) |
| 700 |
|
| 701 |
def add_lldb_register_index(self, reg_infos): |
| 702 |
"""Add a "lldb_register_index" key containing the 0-baed index of each reg_infos entry. |
| 703 |
|
| 704 |
We'll use this when we want to call packets like P/p with a register index but do so |
| 705 |
on only a subset of the full register info set. |
| 706 |
""" |
| 707 |
self.assertIsNotNone(reg_infos) |
| 708 |
|
| 709 |
reg_index = 0 |
| 710 |
for reg_info in reg_infos: |
| 711 |
reg_info["lldb_register_index"] = reg_index |
| 712 |
reg_index += 1 |
| 713 |
|
| 714 |
def add_query_memory_region_packets(self, address): |
| 715 |
self.test_sequence.add_log_lines( |
| 716 |
[ |
| 717 |
"read packet: $qMemoryRegionInfo:{0:x}#00".format(address), |
| 718 |
{ |
| 719 |
"direction": "send", |
| 720 |
"regex": r"^\$(.+)#[0-9a-fA-F]{2}$", |
| 721 |
"capture": {1: "memory_region_response"}, |
| 722 |
}, |
| 723 |
], |
| 724 |
True, |
| 725 |
) |
| 726 |
|
| 727 |
def parse_key_val_dict(self, key_val_text, allow_dupes=True): |
| 728 |
self.assertIsNotNone(key_val_text) |
| 729 |
kv_dict = {} |
| 730 |
for match in re.finditer(r";?([^:]+):([^;]+)", key_val_text): |
| 731 |
key = match.group(1) |
| 732 |
val = match.group(2) |
| 733 |
if key in kv_dict: |
| 734 |
if allow_dupes: |
| 735 |
if isinstance(kv_dict[key], list): |
| 736 |
kv_dict[key].append(val) |
| 737 |
else: |
| 738 |
# Promote to list |
| 739 |
kv_dict[key] = [kv_dict[key], val] |
| 740 |
else: |
| 741 |
self.fail( |
| 742 |
"key '{}' already present when attempting to add value '{}' (text='{}', dict={})".format( |
| 743 |
key, val, key_val_text, kv_dict |
| 744 |
) |
| 745 |
) |
| 746 |
else: |
| 747 |
kv_dict[key] = val |
| 748 |
return kv_dict |
| 749 |
|
| 750 |
def parse_memory_region_packet(self, context): |
| 751 |
# Ensure we have a context. |
| 752 |
self.assertIsNotNone(context.get("memory_region_response")) |
| 753 |
|
| 754 |
# Pull out key:value; pairs. |
| 755 |
mem_region_dict = self.parse_key_val_dict(context.get("memory_region_response")) |
| 756 |
|
| 757 |
# Validate keys are known. |
| 758 |
for key, val in list(mem_region_dict.items()): |
| 759 |
self.assertIn( |
| 760 |
key, |
| 761 |
[ |
| 762 |
"start", |
| 763 |
"size", |
| 764 |
"permissions", |
| 765 |
"flags", |
| 766 |
"name", |
| 767 |
"error", |
| 768 |
"dirty-pages", |
| 769 |
"type", |
| 770 |
], |
| 771 |
) |
| 772 |
self.assertIsNotNone(val) |
| 773 |
|
| 774 |
mem_region_dict["name"] = seven.unhexlify(mem_region_dict.get("name", "")) |
| 775 |
# Return the dictionary of key-value pairs for the memory region. |
| 776 |
return mem_region_dict |
| 777 |
|
| 778 |
def assert_address_within_memory_region(self, test_address, mem_region_dict): |
| 779 |
self.assertIsNotNone(mem_region_dict) |
| 780 |
self.assertTrue("start" in mem_region_dict) |
| 781 |
self.assertTrue("size" in mem_region_dict) |
| 782 |
|
| 783 |
range_start = int(mem_region_dict["start"], 16) |
| 784 |
range_size = int(mem_region_dict["size"], 16) |
| 785 |
range_end = range_start + range_size |
| 786 |
|
| 787 |
if test_address < range_start: |
| 788 |
self.fail( |
| 789 |
"address 0x{0:x} comes before range 0x{1:x} - 0x{2:x} (size 0x{3:x})".format( |
| 790 |
test_address, range_start, range_end, range_size |
| 791 |
) |
| 792 |
) |
| 793 |
elif test_address >= range_end: |
| 794 |
self.fail( |
| 795 |
"address 0x{0:x} comes after range 0x{1:x} - 0x{2:x} (size 0x{3:x})".format( |
| 796 |
test_address, range_start, range_end, range_size |
| 797 |
) |
| 798 |
) |
| 799 |
|
| 800 |
def add_threadinfo_collection_packets(self): |
| 801 |
self.test_sequence.add_log_lines( |
| 802 |
[ |
| 803 |
{ |
| 804 |
"type": "multi_response", |
| 805 |
"first_query": "qfThreadInfo", |
| 806 |
"next_query": "qsThreadInfo", |
| 807 |
"append_iteration_suffix": False, |
| 808 |
"end_regex": re.compile(r"^\$(l)?#[0-9a-fA-F]{2}$"), |
| 809 |
"save_key": "threadinfo_responses", |
| 810 |
} |
| 811 |
], |
| 812 |
True, |
| 813 |
) |
| 814 |
|
| 815 |
def parse_threadinfo_packets(self, context): |
| 816 |
"""Return an array of thread ids (decimal ints), one per thread.""" |
| 817 |
threadinfo_responses = context.get("threadinfo_responses") |
| 818 |
self.assertIsNotNone(threadinfo_responses) |
| 819 |
|
| 820 |
thread_ids = [] |
| 821 |
for threadinfo_response in threadinfo_responses: |
| 822 |
new_thread_infos = parse_threadinfo_response(threadinfo_response) |
| 823 |
thread_ids.extend(new_thread_infos) |
| 824 |
return thread_ids |
| 825 |
|
| 826 |
def launch_with_threads(self, thread_count): |
| 827 |
procs = self.prep_debug_monitor_and_inferior( |
| 828 |
inferior_args=["thread:new"] * (thread_count - 1) + ["trap"] |
| 829 |
) |
| 830 |
|
| 831 |
self.test_sequence.add_log_lines( |
| 832 |
[ |
| 833 |
"read packet: $c#00", |
| 834 |
{ |
| 835 |
"direction": "send", |
| 836 |
"regex": r"^\$T([0-9a-fA-F]{2})([^#]*)#..$", |
| 837 |
"capture": {1: "stop_signo", 2: "stop_reply_kv"}, |
| 838 |
}, |
| 839 |
], |
| 840 |
True, |
| 841 |
) |
| 842 |
self.add_threadinfo_collection_packets() |
| 843 |
context = self.expect_gdbremote_sequence() |
| 844 |
threads = self.parse_threadinfo_packets(context) |
| 845 |
self.assertGreaterEqual(len(threads), thread_count) |
| 846 |
return context, threads |
| 847 |
|
| 848 |
def add_set_breakpoint_packets( |
| 849 |
self, address, z_packet_type=0, do_continue=True, breakpoint_kind=1 |
| 850 |
): |
| 851 |
self.test_sequence.add_log_lines( |
| 852 |
[ # Set the breakpoint. |
| 853 |
"read packet: $Z{2},{0:x},{1}#00".format( |
| 854 |
address, breakpoint_kind, z_packet_type |
| 855 |
), |
| 856 |
# Verify the stub could set it. |
| 857 |
"send packet: $OK#00", |
| 858 |
], |
| 859 |
True, |
| 860 |
) |
| 861 |
|
| 862 |
if do_continue: |
| 863 |
self.test_sequence.add_log_lines( |
| 864 |
[ # Continue the inferior. |
| 865 |
"read packet: $c#63", |
| 866 |
# Expect a breakpoint stop report. |
| 867 |
{ |
| 868 |
"direction": "send", |
| 869 |
"regex": r"^\$T([0-9a-fA-F]{2})thread:([0-9a-fA-F]+);", |
| 870 |
"capture": {1: "stop_signo", 2: "stop_thread_id"}, |
| 871 |
}, |
| 872 |
], |
| 873 |
True, |
| 874 |
) |
| 875 |
|
| 876 |
def add_remove_breakpoint_packets( |
| 877 |
self, address, z_packet_type=0, breakpoint_kind=1 |
| 878 |
): |
| 879 |
self.test_sequence.add_log_lines( |
| 880 |
[ # Remove the breakpoint. |
| 881 |
"read packet: $z{2},{0:x},{1}#00".format( |
| 882 |
address, breakpoint_kind, z_packet_type |
| 883 |
), |
| 884 |
# Verify the stub could unset it. |
| 885 |
"send packet: $OK#00", |
| 886 |
], |
| 887 |
True, |
| 888 |
) |
| 889 |
|
| 890 |
def add_qSupported_packets(self, client_features=[]): |
| 891 |
features = "".join(";" + x for x in client_features) |
| 892 |
self.test_sequence.add_log_lines( |
| 893 |
[ |
| 894 |
"read packet: $qSupported{}#00".format(features), |
| 895 |
{ |
| 896 |
"direction": "send", |
| 897 |
"regex": r"^\$(.*)#[0-9a-fA-F]{2}", |
| 898 |
"capture": {1: "qSupported_response"}, |
| 899 |
}, |
| 900 |
], |
| 901 |
True, |
| 902 |
) |
| 903 |
|
| 904 |
_KNOWN_QSUPPORTED_STUB_FEATURES = [ |
| 905 |
"augmented-libraries-svr4-read", |
| 906 |
"PacketSize", |
| 907 |
"QStartNoAckMode", |
| 908 |
"QThreadSuffixSupported", |
| 909 |
"QListThreadsInStopReply", |
| 910 |
"qXfer:auxv:read", |
| 911 |
"qXfer:libraries:read", |
| 912 |
"qXfer:libraries-svr4:read", |
| 913 |
"qXfer:features:read", |
| 914 |
"qXfer:siginfo:read", |
| 915 |
"qEcho", |
| 916 |
"QPassSignals", |
| 917 |
"multiprocess", |
| 918 |
"fork-events", |
| 919 |
"vfork-events", |
| 920 |
"memory-tagging", |
| 921 |
"qSaveCore", |
| 922 |
"native-signals", |
| 923 |
"QNonStop", |
| 924 |
"SupportedWatchpointTypes", |
| 925 |
"SupportedCompressions", |
| 926 |
] |
| 927 |
|
| 928 |
def parse_qSupported_response(self, context): |
| 929 |
self.assertIsNotNone(context) |
| 930 |
|
| 931 |
raw_response = context.get("qSupported_response") |
| 932 |
self.assertIsNotNone(raw_response) |
| 933 |
|
| 934 |
# For values with key=val, the dict key and vals are set as expected. For feature+, feature- and feature?, the |
| 935 |
# +,-,? is stripped from the key and set as the value. |
| 936 |
supported_dict = {} |
| 937 |
for match in re.finditer(r";?([^=;]+)(=([^;]+))?", raw_response): |
| 938 |
key = match.group(1) |
| 939 |
val = match.group(3) |
| 940 |
|
| 941 |
# key=val: store as is |
| 942 |
if val and len(val) > 0: |
| 943 |
supported_dict[key] = val |
| 944 |
else: |
| 945 |
if len(key) < 2: |
| 946 |
raise Exception( |
| 947 |
"singular stub feature is too short: must be stub_feature{+,-,?}" |
| 948 |
) |
| 949 |
supported_type = key[-1] |
| 950 |
key = key[:-1] |
| 951 |
if not supported_type in ["+", "-", "?"]: |
| 952 |
raise Exception( |
| 953 |
"malformed stub feature: final character {} not in expected set (+,-,?)".format( |
| 954 |
supported_type |
| 955 |
) |
| 956 |
) |
| 957 |
supported_dict[key] = supported_type |
| 958 |
# Ensure we know the supported element |
| 959 |
if key not in self._KNOWN_QSUPPORTED_STUB_FEATURES: |
| 960 |
raise Exception("unknown qSupported stub feature reported: %s" % key) |
| 961 |
|
| 962 |
return supported_dict |
| 963 |
|
| 964 |
def continue_process_and_wait_for_stop(self): |
| 965 |
self.test_sequence.add_log_lines( |
| 966 |
[ |
| 967 |
"read packet: $vCont;c#a8", |
| 968 |
{ |
| 969 |
"direction": "send", |
| 970 |
"regex": r"^\$T([0-9a-fA-F]{2})(.*)#[0-9a-fA-F]{2}$", |
| 971 |
"capture": {1: "stop_signo", 2: "stop_key_val_text"}, |
| 972 |
}, |
| 973 |
], |
| 974 |
True, |
| 975 |
) |
| 976 |
context = self.expect_gdbremote_sequence() |
| 977 |
self.assertIsNotNone(context) |
| 978 |
return self.parse_interrupt_packets(context) |
| 979 |
|
| 980 |
def select_modifiable_register(self, reg_infos): |
| 981 |
"""Find a register that can be read/written freely.""" |
| 982 |
PREFERRED_REGISTER_NAMES = set( |
| 983 |
[ |
| 984 |
"rax", |
| 985 |
] |
| 986 |
) |
| 987 |
|
| 988 |
# First check for the first register from the preferred register name |
| 989 |
# set. |
| 990 |
alternative_register_index = None |
| 991 |
|
| 992 |
self.assertIsNotNone(reg_infos) |
| 993 |
for reg_info in reg_infos: |
| 994 |
if ("name" in reg_info) and (reg_info["name"] in PREFERRED_REGISTER_NAMES): |
| 995 |
# We found a preferred register. Use it. |
| 996 |
return reg_info["lldb_register_index"] |
| 997 |
if ("generic" in reg_info) and ( |
| 998 |
reg_info["generic"] == "fp" or reg_info["generic"] == "arg1" |
| 999 |
): |
| 1000 |
# A frame pointer or first arg register will do as a |
| 1001 |
# register to modify temporarily. |
| 1002 |
alternative_register_index = reg_info["lldb_register_index"] |
| 1003 |
|
| 1004 |
# We didn't find a preferred register. Return whatever alternative register |
| 1005 |
# we found, if any. |
| 1006 |
return alternative_register_index |
| 1007 |
|
| 1008 |
def extract_registers_from_stop_notification(self, stop_key_vals_text): |
| 1009 |
self.assertIsNotNone(stop_key_vals_text) |
| 1010 |
kv_dict = self.parse_key_val_dict(stop_key_vals_text) |
| 1011 |
|
| 1012 |
registers = {} |
| 1013 |
for key, val in list(kv_dict.items()): |
| 1014 |
if re.match(r"^[0-9a-fA-F]+$", key): |
| 1015 |
registers[int(key, 16)] = val |
| 1016 |
return registers |
| 1017 |
|
| 1018 |
def gather_register_infos(self): |
| 1019 |
self.reset_test_sequence() |
| 1020 |
self.add_register_info_collection_packets() |
| 1021 |
|
| 1022 |
context = self.expect_gdbremote_sequence() |
| 1023 |
self.assertIsNotNone(context) |
| 1024 |
|
| 1025 |
reg_infos = self.parse_register_info_packets(context) |
| 1026 |
self.assertIsNotNone(reg_infos) |
| 1027 |
self.add_lldb_register_index(reg_infos) |
| 1028 |
|
| 1029 |
return reg_infos |
| 1030 |
|
| 1031 |
def find_generic_register_with_name(self, reg_infos, generic_name): |
| 1032 |
self.assertIsNotNone(reg_infos) |
| 1033 |
for reg_info in reg_infos: |
| 1034 |
if ("generic" in reg_info) and (reg_info["generic"] == generic_name): |
| 1035 |
return reg_info |
| 1036 |
return None |
| 1037 |
|
| 1038 |
def find_register_with_name_and_dwarf_regnum(self, reg_infos, name, dwarf_num): |
| 1039 |
self.assertIsNotNone(reg_infos) |
| 1040 |
for reg_info in reg_infos: |
| 1041 |
if (reg_info["name"] == name) and (reg_info["dwarf"] == dwarf_num): |
| 1042 |
return reg_info |
| 1043 |
return None |
| 1044 |
|
| 1045 |
def decode_gdbremote_binary(self, encoded_bytes): |
| 1046 |
decoded_bytes = "" |
| 1047 |
i = 0 |
| 1048 |
while i < len(encoded_bytes): |
| 1049 |
if encoded_bytes[i] == "}": |
| 1050 |
# Handle escaped char. |
| 1051 |
self.assertTrue(i + 1 < len(encoded_bytes)) |
| 1052 |
decoded_bytes += chr(ord(encoded_bytes[i + 1]) ^ 0x20) |
| 1053 |
i += 2 |
| 1054 |
elif encoded_bytes[i] == "*": |
| 1055 |
# Handle run length encoding. |
| 1056 |
self.assertTrue(len(decoded_bytes) > 0) |
| 1057 |
self.assertTrue(i + 1 < len(encoded_bytes)) |
| 1058 |
repeat_count = ord(encoded_bytes[i + 1]) - 29 |
| 1059 |
decoded_bytes += decoded_bytes[-1] * repeat_count |
| 1060 |
i += 2 |
| 1061 |
else: |
| 1062 |
decoded_bytes += encoded_bytes[i] |
| 1063 |
i += 1 |
| 1064 |
return decoded_bytes |
| 1065 |
|
| 1066 |
def build_auxv_dict(self, endian, word_size, auxv_data): |
| 1067 |
self.assertIsNotNone(endian) |
| 1068 |
self.assertIsNotNone(word_size) |
| 1069 |
self.assertIsNotNone(auxv_data) |
| 1070 |
|
| 1071 |
auxv_dict = {} |
| 1072 |
|
| 1073 |
# PowerPC64le's auxvec has a special key that must be ignored. |
| 1074 |
# This special key may be used multiple times, resulting in |
| 1075 |
# multiple key/value pairs with the same key, which would otherwise |
| 1076 |
# break this test check for repeated keys. |
| 1077 |
# |
| 1078 |
# AT_IGNOREPPC = 22 |
| 1079 |
ignored_keys_for_arch = {"powerpc64le": [22]} |
| 1080 |
arch = self.getArchitecture() |
| 1081 |
ignore_keys = None |
| 1082 |
if arch in ignored_keys_for_arch: |
| 1083 |
ignore_keys = ignored_keys_for_arch[arch] |
| 1084 |
|
| 1085 |
while len(auxv_data) > 0: |
| 1086 |
# Chop off key. |
| 1087 |
raw_key = auxv_data[:word_size] |
| 1088 |
auxv_data = auxv_data[word_size:] |
| 1089 |
|
| 1090 |
# Chop of value. |
| 1091 |
raw_value = auxv_data[:word_size] |
| 1092 |
auxv_data = auxv_data[word_size:] |
| 1093 |
|
| 1094 |
# Convert raw text from target endian. |
| 1095 |
key = unpack_endian_binary_string(endian, raw_key) |
| 1096 |
value = unpack_endian_binary_string(endian, raw_value) |
| 1097 |
|
| 1098 |
if ignore_keys and key in ignore_keys: |
| 1099 |
continue |
| 1100 |
|
| 1101 |
# Handle ending entry. |
| 1102 |
if key == 0: |
| 1103 |
self.assertEqual(value, 0) |
| 1104 |
return auxv_dict |
| 1105 |
|
| 1106 |
# The key should not already be present. |
| 1107 |
self.assertFalse(key in auxv_dict) |
| 1108 |
auxv_dict[key] = value |
| 1109 |
|
| 1110 |
self.fail( |
| 1111 |
"should not reach here - implies required double zero entry not found" |
| 1112 |
) |
| 1113 |
return auxv_dict |
| 1114 |
|
| 1115 |
def read_binary_data_in_chunks(self, command_prefix, chunk_length): |
| 1116 |
"""Collect command_prefix{offset:x},{chunk_length:x} until a single 'l' or 'l' with data is returned.""" |
| 1117 |
offset = 0 |
| 1118 |
done = False |
| 1119 |
decoded_data = "" |
| 1120 |
|
| 1121 |
while not done: |
| 1122 |
# Grab the next iteration of data. |
| 1123 |
self.reset_test_sequence() |
| 1124 |
self.test_sequence.add_log_lines( |
| 1125 |
[ |
| 1126 |
"read packet: ${}{:x},{:x}:#00".format( |
| 1127 |
command_prefix, offset, chunk_length |
| 1128 |
), |
| 1129 |
{ |
| 1130 |
"direction": "send", |
| 1131 |
"regex": re.compile( |
| 1132 |
r"^\$([^E])(.*)#[0-9a-fA-F]{2}$", re.MULTILINE | re.DOTALL |
| 1133 |
), |
| 1134 |
"capture": {1: "response_type", 2: "content_raw"}, |
| 1135 |
}, |
| 1136 |
], |
| 1137 |
True, |
| 1138 |
) |
| 1139 |
|
| 1140 |
context = self.expect_gdbremote_sequence() |
| 1141 |
self.assertIsNotNone(context) |
| 1142 |
|
| 1143 |
response_type = context.get("response_type") |
| 1144 |
self.assertIsNotNone(response_type) |
| 1145 |
self.assertTrue(response_type in ["l", "m"]) |
| 1146 |
|
| 1147 |
# Move offset along. |
| 1148 |
offset += chunk_length |
| 1149 |
|
| 1150 |
# Figure out if we're done. We're done if the response type is l. |
| 1151 |
done = response_type == "l" |
| 1152 |
|
| 1153 |
# Decode binary data. |
| 1154 |
content_raw = context.get("content_raw") |
| 1155 |
if content_raw and len(content_raw) > 0: |
| 1156 |
self.assertIsNotNone(content_raw) |
| 1157 |
decoded_data += self.decode_gdbremote_binary(content_raw) |
| 1158 |
return decoded_data |
| 1159 |
|
| 1160 |
def add_interrupt_packets(self): |
| 1161 |
self.test_sequence.add_log_lines( |
| 1162 |
[ |
| 1163 |
# Send the intterupt. |
| 1164 |
"read packet: {}".format(chr(3)), |
| 1165 |
# And wait for the stop notification. |
| 1166 |
{ |
| 1167 |
"direction": "send", |
| 1168 |
"regex": r"^\$T([0-9a-fA-F]{2})(.*)#[0-9a-fA-F]{2}$", |
| 1169 |
"capture": {1: "stop_signo", 2: "stop_key_val_text"}, |
| 1170 |
}, |
| 1171 |
], |
| 1172 |
True, |
| 1173 |
) |
| 1174 |
|
| 1175 |
def parse_interrupt_packets(self, context): |
| 1176 |
self.assertIsNotNone(context.get("stop_signo")) |
| 1177 |
self.assertIsNotNone(context.get("stop_key_val_text")) |
| 1178 |
return ( |
| 1179 |
int(context["stop_signo"], 16), |
| 1180 |
self.parse_key_val_dict(context["stop_key_val_text"]), |
| 1181 |
) |
| 1182 |
|
| 1183 |
def add_QSaveRegisterState_packets(self, thread_id): |
| 1184 |
if thread_id: |
| 1185 |
# Use the thread suffix form. |
| 1186 |
request = "read packet: $QSaveRegisterState;thread:{:x}#00".format( |
| 1187 |
thread_id |
| 1188 |
) |
| 1189 |
else: |
| 1190 |
request = "read packet: $QSaveRegisterState#00" |
| 1191 |
|
| 1192 |
self.test_sequence.add_log_lines( |
| 1193 |
[ |
| 1194 |
request, |
| 1195 |
{ |
| 1196 |
"direction": "send", |
| 1197 |
"regex": r"^\$(E?.*)#[0-9a-fA-F]{2}$", |
| 1198 |
"capture": {1: "save_response"}, |
| 1199 |
}, |
| 1200 |
], |
| 1201 |
True, |
| 1202 |
) |
| 1203 |
|
| 1204 |
def parse_QSaveRegisterState_response(self, context): |
| 1205 |
self.assertIsNotNone(context) |
| 1206 |
|
| 1207 |
save_response = context.get("save_response") |
| 1208 |
self.assertIsNotNone(save_response) |
| 1209 |
|
| 1210 |
if len(save_response) < 1 or save_response[0] == "E": |
| 1211 |
# error received |
| 1212 |
return (False, None) |
| 1213 |
else: |
| 1214 |
return (True, int(save_response)) |
| 1215 |
|
| 1216 |
def add_QRestoreRegisterState_packets(self, save_id, thread_id=None): |
| 1217 |
if thread_id: |
| 1218 |
# Use the thread suffix form. |
| 1219 |
request = "read packet: $QRestoreRegisterState:{};thread:{:x}#00".format( |
| 1220 |
save_id, thread_id |
| 1221 |
) |
| 1222 |
else: |
| 1223 |
request = "read packet: $QRestoreRegisterState:{}#00".format(save_id) |
| 1224 |
|
| 1225 |
self.test_sequence.add_log_lines([request, "send packet: $OK#00"], True) |
| 1226 |
|
| 1227 |
def flip_all_bits_in_each_register_value(self, reg_infos, endian, thread_id=None): |
| 1228 |
self.assertIsNotNone(reg_infos) |
| 1229 |
|
| 1230 |
successful_writes = 0 |
| 1231 |
failed_writes = 0 |
| 1232 |
|
| 1233 |
for reg_info in reg_infos: |
| 1234 |
# Use the lldb register index added to the reg info. We're not necessarily |
| 1235 |
# working off a full set of register infos, so an inferred register |
| 1236 |
# index could be wrong. |
| 1237 |
reg_index = reg_info["lldb_register_index"] |
| 1238 |
self.assertIsNotNone(reg_index) |
| 1239 |
|
| 1240 |
reg_byte_size = int(reg_info["bitsize"]) // 8 |
| 1241 |
self.assertTrue(reg_byte_size > 0) |
| 1242 |
|
| 1243 |
# Handle thread suffix. |
| 1244 |
if thread_id: |
| 1245 |
p_request = "read packet: $p{:x};thread:{:x}#00".format( |
| 1246 |
reg_index, thread_id |
| 1247 |
) |
| 1248 |
else: |
| 1249 |
p_request = "read packet: $p{:x}#00".format(reg_index) |
| 1250 |
|
| 1251 |
# Read the existing value. |
| 1252 |
self.reset_test_sequence() |
| 1253 |
self.test_sequence.add_log_lines( |
| 1254 |
[ |
| 1255 |
p_request, |
| 1256 |
{ |
| 1257 |
"direction": "send", |
| 1258 |
"regex": r"^\$([0-9a-fA-F]+)#", |
| 1259 |
"capture": {1: "p_response"}, |
| 1260 |
}, |
| 1261 |
], |
| 1262 |
True, |
| 1263 |
) |
| 1264 |
context = self.expect_gdbremote_sequence() |
| 1265 |
self.assertIsNotNone(context) |
| 1266 |
|
| 1267 |
# Verify the response length. |
| 1268 |
p_response = context.get("p_response") |
| 1269 |
self.assertIsNotNone(p_response) |
| 1270 |
initial_reg_value = unpack_register_hex_unsigned(endian, p_response) |
| 1271 |
|
| 1272 |
# Flip the value by xoring with all 1s |
| 1273 |
all_one_bits_raw = "ff" * (int(reg_info["bitsize"]) // 8) |
| 1274 |
flipped_bits_int = initial_reg_value ^ int(all_one_bits_raw, 16) |
| 1275 |
# print("reg (index={}, name={}): val={}, flipped bits (int={}, hex={:x})".format(reg_index, reg_info["name"], initial_reg_value, flipped_bits_int, flipped_bits_int)) |
| 1276 |
|
| 1277 |
# Handle thread suffix for P. |
| 1278 |
if thread_id: |
| 1279 |
P_request = "read packet: $P{:x}={};thread:{:x}#00".format( |
| 1280 |
reg_index, |
| 1281 |
pack_register_hex( |
| 1282 |
endian, flipped_bits_int, byte_size=reg_byte_size |
| 1283 |
), |
| 1284 |
thread_id, |
| 1285 |
) |
| 1286 |
else: |
| 1287 |
P_request = "read packet: $P{:x}={}#00".format( |
| 1288 |
reg_index, |
| 1289 |
pack_register_hex( |
| 1290 |
endian, flipped_bits_int, byte_size=reg_byte_size |
| 1291 |
), |
| 1292 |
) |
| 1293 |
|
| 1294 |
# Write the flipped value to the register. |
| 1295 |
self.reset_test_sequence() |
| 1296 |
self.test_sequence.add_log_lines( |
| 1297 |
[ |
| 1298 |
P_request, |
| 1299 |
{ |
| 1300 |
"direction": "send", |
| 1301 |
"regex": r"^\$(OK|E[0-9a-fA-F]+)#[0-9a-fA-F]{2}", |
| 1302 |
"capture": {1: "P_response"}, |
| 1303 |
}, |
| 1304 |
], |
| 1305 |
True, |
| 1306 |
) |
| 1307 |
context = self.expect_gdbremote_sequence() |
| 1308 |
self.assertIsNotNone(context) |
| 1309 |
|
| 1310 |
# Determine if the write succeeded. There are a handful of registers that can fail, or partially fail |
| 1311 |
# (e.g. flags, segment selectors, etc.) due to register value restrictions. Don't worry about them |
| 1312 |
# all flipping perfectly. |
| 1313 |
P_response = context.get("P_response") |
| 1314 |
self.assertIsNotNone(P_response) |
| 1315 |
if P_response == "OK": |
| 1316 |
successful_writes += 1 |
| 1317 |
else: |
| 1318 |
failed_writes += 1 |
| 1319 |
# print("reg (index={}, name={}) write FAILED (error: {})".format(reg_index, reg_info["name"], P_response)) |
| 1320 |
|
| 1321 |
# Read back the register value, ensure it matches the flipped |
| 1322 |
# value. |
| 1323 |
if P_response == "OK": |
| 1324 |
self.reset_test_sequence() |
| 1325 |
self.test_sequence.add_log_lines( |
| 1326 |
[ |
| 1327 |
p_request, |
| 1328 |
{ |
| 1329 |
"direction": "send", |
| 1330 |
"regex": r"^\$([0-9a-fA-F]+)#", |
| 1331 |
"capture": {1: "p_response"}, |
| 1332 |
}, |
| 1333 |
], |
| 1334 |
True, |
| 1335 |
) |
| 1336 |
context = self.expect_gdbremote_sequence() |
| 1337 |
self.assertIsNotNone(context) |
| 1338 |
|
| 1339 |
verify_p_response_raw = context.get("p_response") |
| 1340 |
self.assertIsNotNone(verify_p_response_raw) |
| 1341 |
verify_bits = unpack_register_hex_unsigned( |
| 1342 |
endian, verify_p_response_raw |
| 1343 |
) |
| 1344 |
|
| 1345 |
if verify_bits != flipped_bits_int: |
| 1346 |
# Some registers, like mxcsrmask and others, will permute what's written. Adjust succeed/fail counts. |
| 1347 |
# print("reg (index={}, name={}): read verify FAILED: wrote {:x}, verify read back {:x}".format(reg_index, reg_info["name"], flipped_bits_int, verify_bits)) |
| 1348 |
successful_writes -= 1 |
| 1349 |
failed_writes += 1 |
| 1350 |
|
| 1351 |
return (successful_writes, failed_writes) |
| 1352 |
|
| 1353 |
def is_bit_flippable_register(self, reg_info): |
| 1354 |
if not reg_info: |
| 1355 |
return False |
| 1356 |
if not "set" in reg_info: |
| 1357 |
return False |
| 1358 |
if reg_info["set"] != "General Purpose Registers": |
| 1359 |
return False |
| 1360 |
if ("container-regs" in reg_info) and (len(reg_info["container-regs"]) > 0): |
| 1361 |
# Don't try to bit flip registers contained in another register. |
| 1362 |
return False |
| 1363 |
if re.match("^.s$", reg_info["name"]): |
| 1364 |
# This is a 2-letter register name that ends in "s", like a segment register. |
| 1365 |
# Don't try to bit flip these. |
| 1366 |
return False |
| 1367 |
if re.match("^(c|)psr$", reg_info["name"]): |
| 1368 |
# This is an ARM program status register; don't flip it. |
| 1369 |
return False |
| 1370 |
# Okay, this looks fine-enough. |
| 1371 |
return True |
| 1372 |
|
| 1373 |
def read_register_values(self, reg_infos, endian, thread_id=None): |
| 1374 |
self.assertIsNotNone(reg_infos) |
| 1375 |
values = {} |
| 1376 |
|
| 1377 |
for reg_info in reg_infos: |
| 1378 |
# We append a register index when load reg infos so we can work |
| 1379 |
# with subsets. |
| 1380 |
reg_index = reg_info.get("lldb_register_index") |
| 1381 |
self.assertIsNotNone(reg_index) |
| 1382 |
|
| 1383 |
# Handle thread suffix. |
| 1384 |
if thread_id: |
| 1385 |
p_request = "read packet: $p{:x};thread:{:x}#00".format( |
| 1386 |
reg_index, thread_id |
| 1387 |
) |
| 1388 |
else: |
| 1389 |
p_request = "read packet: $p{:x}#00".format(reg_index) |
| 1390 |
|
| 1391 |
# Read it with p. |
| 1392 |
self.reset_test_sequence() |
| 1393 |
self.test_sequence.add_log_lines( |
| 1394 |
[ |
| 1395 |
p_request, |
| 1396 |
{ |
| 1397 |
"direction": "send", |
| 1398 |
"regex": r"^\$([0-9a-fA-F]+)#", |
| 1399 |
"capture": {1: "p_response"}, |
| 1400 |
}, |
| 1401 |
], |
| 1402 |
True, |
| 1403 |
) |
| 1404 |
context = self.expect_gdbremote_sequence() |
| 1405 |
self.assertIsNotNone(context) |
| 1406 |
|
| 1407 |
# Convert value from target endian to integral. |
| 1408 |
p_response = context.get("p_response") |
| 1409 |
self.assertIsNotNone(p_response) |
| 1410 |
self.assertTrue(len(p_response) > 0) |
| 1411 |
self.assertFalse(p_response[0] == "E") |
| 1412 |
|
| 1413 |
values[reg_index] = unpack_register_hex_unsigned(endian, p_response) |
| 1414 |
|
| 1415 |
return values |
| 1416 |
|
| 1417 |
def add_vCont_query_packets(self): |
| 1418 |
self.test_sequence.add_log_lines( |
| 1419 |
[ |
| 1420 |
"read packet: $vCont?#49", |
| 1421 |
{ |
| 1422 |
"direction": "send", |
| 1423 |
"regex": r"^\$(vCont)?(.*)#[0-9a-fA-F]{2}$", |
| 1424 |
"capture": {2: "vCont_query_response"}, |
| 1425 |
}, |
| 1426 |
], |
| 1427 |
True, |
| 1428 |
) |
| 1429 |
|
| 1430 |
def parse_vCont_query_response(self, context): |
| 1431 |
self.assertIsNotNone(context) |
| 1432 |
vCont_query_response = context.get("vCont_query_response") |
| 1433 |
|
| 1434 |
# Handle case of no vCont support at all - in which case the capture |
| 1435 |
# group will be none or zero length. |
| 1436 |
if not vCont_query_response or len(vCont_query_response) == 0: |
| 1437 |
return {} |
| 1438 |
|
| 1439 |
return { |
| 1440 |
key: 1 for key in vCont_query_response.split(";") if key and len(key) > 0 |
| 1441 |
} |
| 1442 |
|
| 1443 |
def count_single_steps_until_true( |
| 1444 |
self, |
| 1445 |
thread_id, |
| 1446 |
predicate, |
| 1447 |
args, |
| 1448 |
max_step_count=100, |
| 1449 |
use_Hc_packet=True, |
| 1450 |
step_instruction="s", |
| 1451 |
): |
| 1452 |
"""Used by single step test that appears in a few different contexts.""" |
| 1453 |
single_step_count = 0 |
| 1454 |
|
| 1455 |
while single_step_count < max_step_count: |
| 1456 |
self.assertIsNotNone(thread_id) |
| 1457 |
|
| 1458 |
# Build the packet for the single step instruction. We replace |
| 1459 |
# {thread}, if present, with the thread_id. |
| 1460 |
step_packet = "read packet: ${}#00".format( |
| 1461 |
re.sub(r"{thread}", "{:x}".format(thread_id), step_instruction) |
| 1462 |
) |
| 1463 |
# print("\nstep_packet created: {}\n".format(step_packet)) |
| 1464 |
|
| 1465 |
# Single step. |
| 1466 |
self.reset_test_sequence() |
| 1467 |
if use_Hc_packet: |
| 1468 |
self.test_sequence.add_log_lines( |
| 1469 |
[ # Set the continue thread. |
| 1470 |
"read packet: $Hc{0:x}#00".format(thread_id), |
| 1471 |
"send packet: $OK#00", |
| 1472 |
], |
| 1473 |
True, |
| 1474 |
) |
| 1475 |
self.test_sequence.add_log_lines( |
| 1476 |
[ |
| 1477 |
# Single step. |
| 1478 |
step_packet, |
| 1479 |
# "read packet: $vCont;s:{0:x}#00".format(thread_id), |
| 1480 |
# Expect a breakpoint stop report. |
| 1481 |
{ |
| 1482 |
"direction": "send", |
| 1483 |
"regex": r"^\$T([0-9a-fA-F]{2})thread:([0-9a-fA-F]+);", |
| 1484 |
"capture": {1: "stop_signo", 2: "stop_thread_id"}, |
| 1485 |
}, |
| 1486 |
], |
| 1487 |
True, |
| 1488 |
) |
| 1489 |
context = self.expect_gdbremote_sequence() |
| 1490 |
self.assertIsNotNone(context) |
| 1491 |
self.assertIsNotNone(context.get("stop_signo")) |
| 1492 |
self.assertEqual( |
| 1493 |
int(context.get("stop_signo"), 16), |
| 1494 |
lldbutil.get_signal_number("SIGTRAP"), |
| 1495 |
) |
| 1496 |
|
| 1497 |
single_step_count += 1 |
| 1498 |
|
| 1499 |
# See if the predicate is true. If so, we're done. |
| 1500 |
if predicate(args): |
| 1501 |
return (True, single_step_count) |
| 1502 |
|
| 1503 |
# The predicate didn't return true within the runaway step count. |
| 1504 |
return (False, single_step_count) |
| 1505 |
|
| 1506 |
def g_c1_c2_contents_are(self, args): |
| 1507 |
"""Used by single step test that appears in a few different contexts.""" |
| 1508 |
g_c1_address = args["g_c1_address"] |
| 1509 |
g_c2_address = args["g_c2_address"] |
| 1510 |
expected_g_c1 = args["expected_g_c1"] |
| 1511 |
expected_g_c2 = args["expected_g_c2"] |
| 1512 |
|
| 1513 |
# Read g_c1 and g_c2 contents. |
| 1514 |
self.reset_test_sequence() |
| 1515 |
self.test_sequence.add_log_lines( |
| 1516 |
[ |
| 1517 |
"read packet: $m{0:x},{1:x}#00".format(g_c1_address, 1), |
| 1518 |
{ |
| 1519 |
"direction": "send", |
| 1520 |
"regex": r"^\$(.+)#[0-9a-fA-F]{2}$", |
| 1521 |
"capture": {1: "g_c1_contents"}, |
| 1522 |
}, |
| 1523 |
"read packet: $m{0:x},{1:x}#00".format(g_c2_address, 1), |
| 1524 |
{ |
| 1525 |
"direction": "send", |
| 1526 |
"regex": r"^\$(.+)#[0-9a-fA-F]{2}$", |
| 1527 |
"capture": {1: "g_c2_contents"}, |
| 1528 |
}, |
| 1529 |
], |
| 1530 |
True, |
| 1531 |
) |
| 1532 |
|
| 1533 |
# Run the packet stream. |
| 1534 |
context = self.expect_gdbremote_sequence() |
| 1535 |
self.assertIsNotNone(context) |
| 1536 |
|
| 1537 |
# Check if what we read from inferior memory is what we are expecting. |
| 1538 |
self.assertIsNotNone(context.get("g_c1_contents")) |
| 1539 |
self.assertIsNotNone(context.get("g_c2_contents")) |
| 1540 |
|
| 1541 |
return (seven.unhexlify(context.get("g_c1_contents")) == expected_g_c1) and ( |
| 1542 |
seven.unhexlify(context.get("g_c2_contents")) == expected_g_c2 |
| 1543 |
) |
| 1544 |
|
| 1545 |
def single_step_only_steps_one_instruction( |
| 1546 |
self, use_Hc_packet=True, step_instruction="s" |
| 1547 |
): |
| 1548 |
"""Used by single step test that appears in a few different contexts.""" |
| 1549 |
# Start up the inferior. |
| 1550 |
procs = self.prep_debug_monitor_and_inferior( |
| 1551 |
inferior_args=[ |
| 1552 |
"get-code-address-hex:swap_chars", |
| 1553 |
"get-data-address-hex:g_c1", |
| 1554 |
"get-data-address-hex:g_c2", |
| 1555 |
"sleep:1", |
| 1556 |
"call-function:swap_chars", |
| 1557 |
"sleep:5", |
| 1558 |
] |
| 1559 |
) |
| 1560 |
|
| 1561 |
# Run the process |
| 1562 |
self.test_sequence.add_log_lines( |
| 1563 |
[ # Start running after initial stop. |
| 1564 |
"read packet: $c#63", |
| 1565 |
# Match output line that prints the memory address of the function call entry point. |
| 1566 |
# Note we require launch-only testing so we can get inferior otuput. |
| 1567 |
{ |
| 1568 |
"type": "output_match", |
| 1569 |
"regex": r"^code address: 0x([0-9a-fA-F]+)\r\ndata address: 0x([0-9a-fA-F]+)\r\ndata address: 0x([0-9a-fA-F]+)\r\n$", |
| 1570 |
"capture": { |
| 1571 |
1: "function_address", |
| 1572 |
2: "g_c1_address", |
| 1573 |
3: "g_c2_address", |
| 1574 |
}, |
| 1575 |
}, |
| 1576 |
# Now stop the inferior. |
| 1577 |
"read packet: {}".format(chr(3)), |
| 1578 |
# And wait for the stop notification. |
| 1579 |
{ |
| 1580 |
"direction": "send", |
| 1581 |
"regex": r"^\$T([0-9a-fA-F]{2})thread:([0-9a-fA-F]+);", |
| 1582 |
"capture": {1: "stop_signo", 2: "stop_thread_id"}, |
| 1583 |
}, |
| 1584 |
], |
| 1585 |
True, |
| 1586 |
) |
| 1587 |
|
| 1588 |
# Run the packet stream. |
| 1589 |
context = self.expect_gdbremote_sequence() |
| 1590 |
self.assertIsNotNone(context) |
| 1591 |
|
| 1592 |
# Grab the main thread id. |
| 1593 |
self.assertIsNotNone(context.get("stop_thread_id")) |
| 1594 |
main_thread_id = int(context.get("stop_thread_id"), 16) |
| 1595 |
|
| 1596 |
# Grab the function address. |
| 1597 |
self.assertIsNotNone(context.get("function_address")) |
| 1598 |
function_address = int(context.get("function_address"), 16) |
| 1599 |
|
| 1600 |
# Grab the data addresses. |
| 1601 |
self.assertIsNotNone(context.get("g_c1_address")) |
| 1602 |
g_c1_address = int(context.get("g_c1_address"), 16) |
| 1603 |
|
| 1604 |
self.assertIsNotNone(context.get("g_c2_address")) |
| 1605 |
g_c2_address = int(context.get("g_c2_address"), 16) |
| 1606 |
|
| 1607 |
# Set a breakpoint at the given address. |
| 1608 |
if self.getArchitecture().startswith("arm"): |
| 1609 |
# TODO: Handle case when setting breakpoint in thumb code |
| 1610 |
BREAKPOINT_KIND = 4 |
| 1611 |
else: |
| 1612 |
BREAKPOINT_KIND = 1 |
| 1613 |
self.reset_test_sequence() |
| 1614 |
self.add_set_breakpoint_packets( |
| 1615 |
function_address, do_continue=True, breakpoint_kind=BREAKPOINT_KIND |
| 1616 |
) |
| 1617 |
context = self.expect_gdbremote_sequence() |
| 1618 |
self.assertIsNotNone(context) |
| 1619 |
|
| 1620 |
# Remove the breakpoint. |
| 1621 |
self.reset_test_sequence() |
| 1622 |
self.add_remove_breakpoint_packets( |
| 1623 |
function_address, breakpoint_kind=BREAKPOINT_KIND |
| 1624 |
) |
| 1625 |
context = self.expect_gdbremote_sequence() |
| 1626 |
self.assertIsNotNone(context) |
| 1627 |
|
| 1628 |
# Verify g_c1 and g_c2 match expected initial state. |
| 1629 |
args = {} |
| 1630 |
args["g_c1_address"] = g_c1_address |
| 1631 |
args["g_c2_address"] = g_c2_address |
| 1632 |
args["expected_g_c1"] = "0" |
| 1633 |
args["expected_g_c2"] = "1" |
| 1634 |
|
| 1635 |
self.assertTrue(self.g_c1_c2_contents_are(args)) |
| 1636 |
|
| 1637 |
# Verify we take only a small number of steps to hit the first state. |
| 1638 |
# Might need to work through function entry prologue code. |
| 1639 |
args["expected_g_c1"] = "1" |
| 1640 |
args["expected_g_c2"] = "1" |
| 1641 |
(state_reached, step_count) = self.count_single_steps_until_true( |
| 1642 |
main_thread_id, |
| 1643 |
self.g_c1_c2_contents_are, |
| 1644 |
args, |
| 1645 |
max_step_count=25, |
| 1646 |
use_Hc_packet=use_Hc_packet, |
| 1647 |
step_instruction=step_instruction, |
| 1648 |
) |
| 1649 |
self.assertTrue(state_reached) |
| 1650 |
|
| 1651 |
# Verify we hit the next state. |
| 1652 |
args["expected_g_c1"] = "1" |
| 1653 |
args["expected_g_c2"] = "0" |
| 1654 |
(state_reached, step_count) = self.count_single_steps_until_true( |
| 1655 |
main_thread_id, |
| 1656 |
self.g_c1_c2_contents_are, |
| 1657 |
args, |
| 1658 |
max_step_count=5, |
| 1659 |
use_Hc_packet=use_Hc_packet, |
| 1660 |
step_instruction=step_instruction, |
| 1661 |
) |
| 1662 |
self.assertTrue(state_reached) |
| 1663 |
expected_step_count = 1 |
| 1664 |
arch = self.getArchitecture() |
| 1665 |
|
| 1666 |
# MIPS required "3" (ADDIU, SB, LD) machine instructions for updation |
| 1667 |
# of variable value |
| 1668 |
if re.match("mips", arch): |
| 1669 |
expected_step_count = 3 |
| 1670 |
# S390X requires "2" (LARL, MVI) machine instructions for updation of |
| 1671 |
# variable value |
| 1672 |
if re.match("s390x", arch): |
| 1673 |
expected_step_count = 2 |
| 1674 |
# ARM64 requires "4" instructions: 2 to compute the address (adrp, |
| 1675 |
# add), one to materialize the constant (mov) and the store. Once |
| 1676 |
# addresses and constants are materialized, only one instruction is |
| 1677 |
# needed. |
| 1678 |
if re.match("arm64", arch): |
| 1679 |
before_materialization_step_count = 4 |
| 1680 |
after_matrialization_step_count = 1 |
| 1681 |
self.assertIn( |
| 1682 |
step_count, |
| 1683 |
[before_materialization_step_count, after_matrialization_step_count], |
| 1684 |
) |
| 1685 |
expected_step_count = after_matrialization_step_count |
| 1686 |
else: |
| 1687 |
self.assertEqual(step_count, expected_step_count) |
| 1688 |
|
| 1689 |
# Verify we hit the next state. |
| 1690 |
args["expected_g_c1"] = "0" |
| 1691 |
args["expected_g_c2"] = "0" |
| 1692 |
(state_reached, step_count) = self.count_single_steps_until_true( |
| 1693 |
main_thread_id, |
| 1694 |
self.g_c1_c2_contents_are, |
| 1695 |
args, |
| 1696 |
max_step_count=5, |
| 1697 |
use_Hc_packet=use_Hc_packet, |
| 1698 |
step_instruction=step_instruction, |
| 1699 |
) |
| 1700 |
self.assertTrue(state_reached) |
| 1701 |
self.assertEqual(step_count, expected_step_count) |
| 1702 |
|
| 1703 |
# Verify we hit the next state. |
| 1704 |
args["expected_g_c1"] = "0" |
| 1705 |
args["expected_g_c2"] = "1" |
| 1706 |
(state_reached, step_count) = self.count_single_steps_until_true( |
| 1707 |
main_thread_id, |
| 1708 |
self.g_c1_c2_contents_are, |
| 1709 |
args, |
| 1710 |
max_step_count=5, |
| 1711 |
use_Hc_packet=use_Hc_packet, |
| 1712 |
step_instruction=step_instruction, |
| 1713 |
) |
| 1714 |
self.assertTrue(state_reached) |
| 1715 |
self.assertEqual(step_count, expected_step_count) |
| 1716 |
|
| 1717 |
def maybe_strict_output_regex(self, regex): |
| 1718 |
return ( |
| 1719 |
".*" + regex + ".*" |
| 1720 |
if lldbplatformutil.hasChattyStderr(self) |
| 1721 |
else "^" + regex + "$" |
| 1722 |
) |
| 1723 |
|
| 1724 |
def install_and_create_launch_args(self): |
| 1725 |
exe_path = self.getBuildArtifact("a.out") |
| 1726 |
if not lldb.remote_platform: |
| 1727 |
return [exe_path] |
| 1728 |
remote_path = lldbutil.append_to_process_working_directory( |
| 1729 |
self, os.path.basename(exe_path) |
| 1730 |
) |
| 1731 |
remote_file_spec = lldb.SBFileSpec(remote_path, False) |
| 1732 |
err = lldb.remote_platform.Install( |
| 1733 |
lldb.SBFileSpec(exe_path, True), remote_file_spec |
| 1734 |
) |
| 1735 |
if err.Fail(): |
| 1736 |
raise Exception( |
| 1737 |
"remote_platform.Install('%s', '%s') failed: %s" |
| 1738 |
% (exe_path, remote_path, err) |
| 1739 |
) |
| 1740 |
return [remote_path] |