Fix the Chrome crash caused by RtcEventLog

Stop the RtcEventLog when the PeerConnection is closed so that Chrome
will not crash because of creating too many threads.

BUG=chromium:687553

Review-Url: https://codereview.webrtc.org/2682433005
Cr-Commit-Position: refs/heads/master@{#16482}
diff --git a/webrtc/pc/peerconnection.cc b/webrtc/pc/peerconnection.cc
index ee04d8e..96e2b33 100644
--- a/webrtc/pc/peerconnection.cc
+++ b/webrtc/pc/peerconnection.cc
@@ -1558,6 +1558,7 @@
   stats_->UpdateStats(kStatsOutputLevelStandard);
 
   session_->Close();
+  event_log_.reset();
 }
 
 void PeerConnection::OnSessionStateChange(WebRtcSession* /*session*/,
@@ -2573,10 +2574,15 @@
 
 bool PeerConnection::StartRtcEventLog_w(rtc::PlatformFile file,
                                         int64_t max_size_bytes) {
+  if (!event_log_) {
+    return false;
+  }
   return event_log_->StartLogging(file, max_size_bytes);
 }
 
 void PeerConnection::StopRtcEventLog_w() {
-  event_log_->StopLogging();
+  if (event_log_) {
+    event_log_->StopLogging();
+  }
 }
 }  // namespace webrtc
diff --git a/webrtc/pc/peerconnectioninterface_unittest.cc b/webrtc/pc/peerconnectioninterface_unittest.cc
index 90f4854..f7d4777 100644
--- a/webrtc/pc/peerconnectioninterface_unittest.cc
+++ b/webrtc/pc/peerconnectioninterface_unittest.cc
@@ -3100,6 +3100,20 @@
   EXPECT_EQ(local_answer, pc_->current_local_description());
 }
 
+// Tests that it won't crash when calling StartRtcEventLog or StopRtcEventLog
+// after the PeerConnection is closed.
+TEST_F(PeerConnectionInterfaceTest,
+       StartAndStopLoggingAfterPeerConnectionClosed) {
+  CreatePeerConnection();
+  // The RtcEventLog will be reset when the PeerConnection is closed.
+  pc_->Close();
+
+  rtc::PlatformFile file = 0;
+  int64_t max_size_bytes = 1024;
+  EXPECT_FALSE(pc_->StartRtcEventLog(file, max_size_bytes));
+  pc_->StopRtcEventLog();
+}
+
 class PeerConnectionMediaConfigTest : public testing::Test {
  protected:
   void SetUp() override {