[lldb/test] s/add_no_ack_remote_stream/do_handshake

These two functions are doing the same thing, only one of them is
sending the packets immediately and the other "queues" them to be sent
later. The first one is better as in case of errors, the backtrace will
point straight to the place that caused them.

Modify the first method to avoid duplication, and ten standardize on it.

GitOrigin-RevId: 872b1da6ad276515ccfb1481009d23b129c72cac
diff --git a/packages/Python/lldbsuite/test/tools/lldb-server/gdbremote_testcase.py b/packages/Python/lldbsuite/test/tools/lldb-server/gdbremote_testcase.py
index 5964b24..5451877 100644
--- a/packages/Python/lldbsuite/test/tools/lldb-server/gdbremote_testcase.py
+++ b/packages/Python/lldbsuite/test/tools/lldb-server/gdbremote_testcase.py
@@ -521,8 +521,9 @@
         server = self.connect_to_debug_monitor(attach_pid=attach_pid)
         self.assertIsNotNone(server)
 
+        self.do_handshake()
+
         # Build the expected protocol stream
-        self.add_no_ack_remote_stream()
         if inferior_env:
             for name, value in inferior_env.items():
                 self.add_set_environment_packets(name, value)
@@ -531,60 +532,13 @@
 
         return {"inferior": inferior, "server": server}
 
-    def expect_socket_recv(
-            self,
-            sock,
-            expected_content_regex
-            ):
-        response = ""
-        timeout_time = time.time() + self.DEFAULT_TIMEOUT
-
-        while not expected_content_regex.match(
-                response) and time.time() < timeout_time:
-            can_read, _, _ = select.select([sock], [], [], self.DEFAULT_TIMEOUT)
-            if can_read and sock in can_read:
-                recv_bytes = sock.recv(4096)
-                if recv_bytes:
-                    response += seven.bitcast_to_string(recv_bytes)
-
-        self.assertTrue(expected_content_regex.match(response))
-
-    def expect_socket_send(self, sock, content):
-        request_bytes_remaining = content
-        timeout_time = time.time() + self.DEFAULT_TIMEOUT
-
-        while len(request_bytes_remaining) > 0 and time.time() < timeout_time:
-            _, can_write, _ = select.select([], [sock], [], self.DEFAULT_TIMEOUT)
-            if can_write and sock in can_write:
-                written_byte_count = sock.send(request_bytes_remaining.encode())
-                request_bytes_remaining = request_bytes_remaining[
-                    written_byte_count:]
-        self.assertEqual(len(request_bytes_remaining), 0)
-
-    def do_handshake(self, stub_socket):
-        # Write the ack.
-        self.expect_socket_send(stub_socket, "+")
-
-        # Send the start no ack mode packet.
-        NO_ACK_MODE_REQUEST = "$QStartNoAckMode#b0"
-        bytes_sent = stub_socket.send(NO_ACK_MODE_REQUEST.encode())
-        self.assertEqual(bytes_sent, len(NO_ACK_MODE_REQUEST))
-
-        # Receive the ack and "OK"
-        self.expect_socket_recv(stub_socket, re.compile(
-            r"^\+\$OK#[0-9a-fA-F]{2}$"))
-
-        # Send the final ack.
-        self.expect_socket_send(stub_socket, "+")
-
-    def add_no_ack_remote_stream(self):
-        self.test_sequence.add_log_lines(
-            ["read packet: +",
-             "read packet: $QStartNoAckMode#b0",
-             "send packet: +",
-             "send packet: $OK#9a",
-             "read packet: +"],
-            True)
+    def do_handshake(self):
+        server = self._server
+        server.send_ack()
+        server.send_packet(b"QStartNoAckMode")
+        self.assertEqual(server.get_normal_packet(), b"+")
+        self.assertEqual(server.get_normal_packet(), b"OK")
+        server.send_ack()
 
     def add_verified_launch_packets(self, launch_args):
         self.test_sequence.add_log_lines(
diff --git a/packages/Python/lldbsuite/test/tools/lldb-server/lldbgdbserverutils.py b/packages/Python/lldbsuite/test/tools/lldb-server/lldbgdbserverutils.py
index eba6f32..a769cb1 100644
--- a/packages/Python/lldbsuite/test/tools/lldb-server/lldbgdbserverutils.py
+++ b/packages/Python/lldbsuite/test/tools/lldb-server/lldbgdbserverutils.py
@@ -912,6 +912,19 @@
     def send_raw(self, frame):
         self._sock.sendall(frame)
 
+    def send_ack(self):
+        self.send_raw(b"+")
+
+    def send_packet(self, packet):
+        self.send_raw(b'$%s#%02x'%(packet, self._checksum(packet)))
+
+    @staticmethod
+    def _checksum(packet):
+        checksum = 0
+        for c in six.iterbytes(packet):
+            checksum += c
+        return checksum % 256
+
     def _read(self, q):
         while not q:
             new_bytes = self._sock.recv(4096)
@@ -962,6 +975,19 @@
     def get_raw_normal_packet(self):
         return self._read(self._normal_queue)
 
+    @staticmethod
+    def _get_payload(frame):
+        payload = frame[1:-3]
+        checksum = int(frame[-2:], 16)
+        if checksum != Server._checksum(payload):
+            raise ChecksumMismatch
+        return payload
+
+    def get_normal_packet(self):
+        frame = self.get_raw_normal_packet()
+        if frame == b"+": return frame
+        return self._get_payload(frame)
+
     def get_accumulated_output(self):
         return self._accumulated_output
 
diff --git a/test/API/tools/lldb-server/TestAppleSimulatorOSType.py b/test/API/tools/lldb-server/TestAppleSimulatorOSType.py
index 467e6cd..dc5785f 100644
--- a/test/API/tools/lldb-server/TestAppleSimulatorOSType.py
+++ b/test/API/tools/lldb-server/TestAppleSimulatorOSType.py
@@ -94,7 +94,7 @@
         server = self.connect_to_debug_monitor(attach_pid=pid)
 
         # Setup packet sequences
-        self.add_no_ack_remote_stream()
+        self.do_handshake()
         self.add_process_info_collection_packets()
         self.test_sequence.add_log_lines(
             ["read packet: " +
diff --git a/test/API/tools/lldb-server/TestGdbRemoteAttachOrWait.py b/test/API/tools/lldb-server/TestGdbRemoteAttachOrWait.py
index c91e94b..dd71e50 100644
--- a/test/API/tools/lldb-server/TestGdbRemoteAttachOrWait.py
+++ b/test/API/tools/lldb-server/TestGdbRemoteAttachOrWait.py
@@ -65,7 +65,7 @@
         server = self.connect_to_debug_monitor()
         self.assertIsNotNone(server)
 
-        self.add_no_ack_remote_stream()
+        self.do_handshake()
         self.test_sequence.add_log_lines([
             # Do the attach.
             "read packet: $vAttachOrWait;{}#00".format(lldbgdbserverutils.gdbremote_hex_encode_string(exe)),
diff --git a/test/API/tools/lldb-server/TestGdbRemoteAttachWait.py b/test/API/tools/lldb-server/TestGdbRemoteAttachWait.py
index d2ba674..deb82ed 100644
--- a/test/API/tools/lldb-server/TestGdbRemoteAttachWait.py
+++ b/test/API/tools/lldb-server/TestGdbRemoteAttachWait.py
@@ -36,7 +36,7 @@
         # Launch the first inferior (we shouldn't attach to this one).
         launch_inferior()
         
-        self.add_no_ack_remote_stream()
+        self.do_handshake()
         self.test_sequence.add_log_lines([
             # Do the attach.
             "read packet: $vAttachWait;{}#00".format(lldbgdbserverutils.gdbremote_hex_encode_string(exe)),
diff --git a/test/API/tools/lldb-server/TestGdbRemoteCompletion.py b/test/API/tools/lldb-server/TestGdbRemoteCompletion.py
index 22af21d..064aefe 100644
--- a/test/API/tools/lldb-server/TestGdbRemoteCompletion.py
+++ b/test/API/tools/lldb-server/TestGdbRemoteCompletion.py
@@ -29,7 +29,7 @@
         self.sock = self.create_socket()
         self._server = Server(self.sock, server)
 
-        self.add_no_ack_remote_stream()
+        self.do_handshake()
 
     def generate_hex_path(self, target):
         return str(os.path.join(self.getBuildDir(), target)).encode().hex()
diff --git a/test/API/tools/lldb-server/TestGdbRemoteHostInfo.py b/test/API/tools/lldb-server/TestGdbRemoteHostInfo.py
index 6a4bdc1..01c2a38 100644
--- a/test/API/tools/lldb-server/TestGdbRemoteHostInfo.py
+++ b/test/API/tools/lldb-server/TestGdbRemoteHostInfo.py
@@ -77,7 +77,7 @@
         # Launch the debug monitor stub, attaching to the inferior.
         server = self.connect_to_debug_monitor()
         self.assertIsNotNone(server)
-        self.add_no_ack_remote_stream()
+        self.do_handshake()
 
         # Request qHostInfo and get response
         self.add_host_info_collection_packets()
diff --git a/test/API/tools/lldb-server/TestLldbGdbServer.py b/test/API/tools/lldb-server/TestLldbGdbServer.py
index 7090abf..02bd363 100644
--- a/test/API/tools/lldb-server/TestLldbGdbServer.py
+++ b/test/API/tools/lldb-server/TestLldbGdbServer.py
@@ -28,7 +28,7 @@
         server = self.connect_to_debug_monitor()
         self.assertIsNotNone(server)
 
-        self.add_no_ack_remote_stream()
+        self.do_handshake()
         self.test_sequence.add_log_lines(
             ["lldb-server <  26> read packet: $QThreadSuffixSupported#e4",
              "lldb-server <   6> send packet: $OK#9a"],
@@ -41,7 +41,7 @@
         server = self.connect_to_debug_monitor()
         self.assertIsNotNone(server)
 
-        self.add_no_ack_remote_stream()
+        self.do_handshake()
         self.test_sequence.add_log_lines(
             ["lldb-server <  27> read packet: $QListThreadsInStopReply#21",
              "lldb-server <   6> send packet: $OK#9a"],
diff --git a/test/API/tools/lldb-server/commandline/TestGdbRemoteConnection.py b/test/API/tools/lldb-server/commandline/TestGdbRemoteConnection.py
index a82f4a8..514e553 100644
--- a/test/API/tools/lldb-server/commandline/TestGdbRemoteConnection.py
+++ b/test/API/tools/lldb-server/commandline/TestGdbRemoteConnection.py
@@ -1,12 +1,13 @@
 from __future__ import print_function
 
 import gdbremote_testcase
+import random
 import select
 import socket
 from lldbsuite.test.decorators import *
 from lldbsuite.test.lldbtest import *
+from lldbgdbserverutils import Server
 import lldbsuite.test.lldbplatformutil
-import random
 
 if lldbplatformutil.getHostPlatform() == "windows":
     import ctypes
@@ -132,7 +133,7 @@
         # Reverse connect is the default connection method.
         self.connect_to_debug_monitor()
         # Verify we can do the handshake.  If that works, we'll call it good.
-        self.do_handshake(self.sock)
+        self.do_handshake()
 
     @skipIfRemote
     def test_named_pipe(self):
@@ -165,6 +166,7 @@
         # Trim null byte, convert to int
         addr = (addr[0], int(port[:-1]))
         self.sock.connect(addr)
+        self._server = Server(self.sock, server)
 
         # Verify we can do the handshake.  If that works, we'll call it good.
-        self.do_handshake(self.sock)
+        self.do_handshake()