1 //===-- GDBRemoteCommunicationHistory.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 liblldb_GDBRemoteCommunicationHistory_h_
10 #define liblldb_GDBRemoteCommunicationHistory_h_
11 
12 #include <string>
13 #include <vector>
14 
15 #include "lldb/Utility/GDBRemote.h"
16 #include "lldb/lldb-public.h"
17 #include "llvm/Support/YAMLTraits.h"
18 #include "llvm/Support/raw_ostream.h"
19 
20 namespace lldb_private {
21 namespace process_gdb_remote {
22 
23 /// The history keeps a circular buffer of GDB remote packets. The history is
24 /// used for logging and replaying GDB remote packets.
25 class GDBRemoteCommunicationHistory {
26 public:
27   friend llvm::yaml::MappingTraits<GDBRemoteCommunicationHistory>;
28 
29   GDBRemoteCommunicationHistory(uint32_t size = 0);
30 
31   ~GDBRemoteCommunicationHistory();
32 
33   // For single char packets for ack, nack and /x03
34   void AddPacket(char packet_char, GDBRemotePacket::Type type,
35                  uint32_t bytes_transmitted);
36 
37   void AddPacket(const std::string &src, uint32_t src_len,
38                  GDBRemotePacket::Type type, uint32_t bytes_transmitted);
39 
40   void Dump(Stream &strm) const;
41   void Dump(Log *log) const;
42   bool DidDumpToLog() const { return m_dumped_to_log; }
43 
44   void SetStream(llvm::raw_ostream *strm) { m_stream = strm; }
45 
46 private:
47   uint32_t GetFirstSavedPacketIndex() const {
48     if (m_total_packet_count < m_packets.size())
49       return 0;
50     else
51       return m_curr_idx + 1;
52   }
53 
54   uint32_t GetNumPacketsInHistory() const {
55     if (m_total_packet_count < m_packets.size())
56       return m_total_packet_count;
57     else
58       return (uint32_t)m_packets.size();
59   }
60 
61   uint32_t GetNextIndex() {
62     ++m_total_packet_count;
63     const uint32_t idx = m_curr_idx;
64     m_curr_idx = NormalizeIndex(idx + 1);
65     return idx;
66   }
67 
68   uint32_t NormalizeIndex(uint32_t i) const {
69     return m_packets.empty() ? 0 : i % m_packets.size();
70   }
71 
72   std::vector<GDBRemotePacket> m_packets;
73   uint32_t m_curr_idx;
74   uint32_t m_total_packet_count;
75   mutable bool m_dumped_to_log;
76   llvm::raw_ostream *m_stream = nullptr;
77 };
78 
79 } // namespace process_gdb_remote
80 } // namespace lldb_private
81 
82 #endif // liblldb_GDBRemoteCommunicationHistory_h_
83