@@ -788,9 +788,14 @@ GDBRemoteCommunication::CheckForPacket(const uint8_t *src, size_t src_len,
788788
789789 // Copy the packet from m_bytes to packet_str expanding the run-length
790790 // encoding in the process.
791- std ::string packet_str =
791+ auto maybe_packet_str =
792792 ExpandRLE (m_bytes.substr (content_start, content_end - content_start));
793- packet = StringExtractorGDBRemote (packet_str);
793+ if (!maybe_packet_str) {
794+ m_bytes.erase (0 , total_length);
795+ packet.Clear ();
796+ return GDBRemoteCommunication::PacketType::Invalid;
797+ }
798+ packet = StringExtractorGDBRemote (*maybe_packet_str);
794799
795800 if (m_bytes[0 ] == ' $' || m_bytes[0 ] == ' %' ) {
796801 assert (checksum_idx < m_bytes.size ());
@@ -1311,25 +1316,32 @@ void llvm::format_provider<GDBRemoteCommunication::PacketResult>::format(
13111316 }
13121317}
13131318
1314- std::string GDBRemoteCommunication::ExpandRLE (std::string packet) {
1319+ std::optional<std::string>
1320+ GDBRemoteCommunication::ExpandRLE (std::string packet) {
13151321 // Reserve enough byte for the most common case (no RLE used).
13161322 std::string decoded;
13171323 decoded.reserve (packet.size ());
13181324 for (std::string::const_iterator c = packet.begin (); c != packet.end (); ++c) {
13191325 if (*c == ' *' ) {
1326+ if (decoded.empty ())
1327+ return std::nullopt ;
13201328 // '*' indicates RLE. Next character will give us the repeat count and
13211329 // previous character is what is to be repeated.
13221330 char char_to_repeat = decoded.back ();
13231331 // Number of time the previous character is repeated.
1324- int repeat_count = *++c + 3 - ' ' ;
1332+ if (++c == packet.end ())
1333+ return std::nullopt ;
1334+ int repeat_count = *c + 3 - ' ' ;
13251335 // We have the char_to_repeat and repeat_count. Now push it in the
13261336 // packet.
13271337 for (int i = 0 ; i < repeat_count; ++i)
13281338 decoded.push_back (char_to_repeat);
13291339 } else if (*c == 0x7d ) {
13301340 // 0x7d is the escape character. The next character is to be XOR'd with
13311341 // 0x20.
1332- char escapee = *++c ^ 0x20 ;
1342+ if (++c == packet.end ())
1343+ return std::nullopt ;
1344+ char escapee = *c ^ 0x20 ;
13331345 decoded.push_back (escapee);
13341346 } else {
13351347 decoded.push_back (*c);
0 commit comments