Add check to avoid doing illegal memory access from an invalid iterator from std::prev()

PiperOrigin-RevId: 573248334
This commit is contained in:
MediaPipe Team 2023-10-13 09:59:10 -07:00 committed by Copybara-Service
parent 652792ebaa
commit 8823046e4b

View File

@ -13,6 +13,7 @@
// limitations under the License. // limitations under the License.
#include <algorithm> #include <algorithm>
#include <iterator>
#include <memory> #include <memory>
#include <queue> #include <queue>
#include <set> #include <set>
@ -223,8 +224,8 @@ absl::Status SwitchDemuxCalculator::RecordPackets(CalculatorContext* cc) {
// Returns the channel index for a Timestamp. // Returns the channel index for a Timestamp.
int SwitchDemuxCalculator::ChannelIndex(Timestamp timestamp) { int SwitchDemuxCalculator::ChannelIndex(Timestamp timestamp) {
auto it = std::prev(channel_history_.upper_bound(timestamp)); auto it = channel_history_.upper_bound(timestamp);
return it->second; return it == channel_history_.begin() ? -1 : std::prev(it)->second;
} }
// Dispatches all queued input packets with known channels. // Dispatches all queued input packets with known channels.
@ -237,10 +238,12 @@ absl::Status SwitchDemuxCalculator::SendActivePackets(CalculatorContext* cc) {
auto& queue = input_queue_[input_id]; auto& queue = input_queue_[input_id];
while (!queue.empty() && queue.front().Timestamp() <= channel_settled) { while (!queue.empty() && queue.front().Timestamp() <= channel_settled) {
int channel_index = ChannelIndex(queue.front().Timestamp()); int channel_index = ChannelIndex(queue.front().Timestamp());
std::string output_tag = tool::ChannelTag(tag, channel_index); if (channel_index != -1) {
auto output_id = cc->Outputs().GetId(output_tag, index); std::string output_tag = tool::ChannelTag(tag, channel_index);
if (output_id.IsValid()) { auto output_id = cc->Outputs().GetId(output_tag, index);
cc->Outputs().Get(output_id).AddPacket(queue.front()); if (output_id.IsValid()) {
cc->Outputs().Get(output_id).AddPacket(queue.front());
}
} }
queue.pop(); queue.pop();
} }