Limit the number of PeerConnections created in one process to 500.

Bug: webrtc:8571
Change-Id: If96ef0e8a8c137afbc62766215f70307e2713c53
Reviewed-on: https://chromium-review.googlesource.com/838380
Commit-Queue: Harald Alvestrand <hta@chromium.org>
Reviewed-by: Tommi <tommi@chromium.org>
Reviewed-by: Kentaro Hara <haraken@chromium.org>
Cr-Original-Commit-Position: refs/heads/master@{#525704}
Cr-Mirrored-From: https://chromium.googlesource.com/chromium/src
Cr-Mirrored-Commit: 87fd6420466bab9e3cf9958db08ad64818d837b8
diff --git a/WebKit/Source/modules/peerconnection/RTCPeerConnection.cpp b/WebKit/Source/modules/peerconnection/RTCPeerConnection.cpp
index dca61cf..a34a959 100644
--- a/WebKit/Source/modules/peerconnection/RTCPeerConnection.cpp
+++ b/WebKit/Source/modules/peerconnection/RTCPeerConnection.cpp
@@ -83,6 +83,7 @@
 #include "modules/peerconnection/RTCVoidRequestImpl.h"
 #include "modules/peerconnection/RTCVoidRequestPromiseImpl.h"
 #include "modules/peerconnection/testing/InternalsRTCPeerConnection.h"
+#include "platform/InstanceCounters.h"
 #include "platform/bindings/Microtask.h"
 #include "platform/bindings/ScriptState.h"
 #include "platform/bindings/V8ThrowException.h"
@@ -116,8 +117,8 @@
 const char kSignalingStateClosedMessage[] =
     "The RTCPeerConnection's signalingState is 'closed'.";
 
-// For testing: Keep track of number of existing PeerConnections.
-int g_peer_connection_counter = 0;
+// The maximum number of PeerConnections that can exist simultaneously.
+const long kMaxPeerConnections = 500;
 
 bool ThrowExceptionIfSignalingStateClosed(
     RTCPeerConnection::SignalingState state,
@@ -508,7 +509,14 @@
   // If we fail, set |m_closed| and |m_stopped| to true, to avoid hitting the
   // assert in the destructor.
 
-  g_peer_connection_counter++;
+  if (InstanceCounters::CounterValue(
+          InstanceCounters::kRTCPeerConnectionCounter) >= kMaxPeerConnections) {
+    exception_state.ThrowDOMException(kUnknownError,
+                                      "Cannot create so many PeerConnections");
+    return;
+  }
+  InstanceCounters::IncrementCounter(
+      InstanceCounters::kRTCPeerConnectionCounter);
   if (!document->GetFrame()) {
     closed_ = true;
     stopped_ = true;
@@ -549,7 +557,8 @@
   // We are assuming that a wrapper is always created when RTCPeerConnection is
   // created.
   DCHECK(closed_ || stopped_);
-  g_peer_connection_counter--;
+  InstanceCounters::DecrementCounter(
+      InstanceCounters::kRTCPeerConnectionCounter);
 }
 
 void RTCPeerConnection::Dispose() {
@@ -1786,7 +1795,12 @@
 }
 
 int RTCPeerConnection::PeerConnectionCount() {
-  return g_peer_connection_counter;
+  return InstanceCounters::CounterValue(
+      InstanceCounters::kRTCPeerConnectionCounter);
+}
+
+int RTCPeerConnection::PeerConnectionCountLimit() {
+  return kMaxPeerConnections;
 }
 
 }  // namespace blink