WireServer: check buffer exists before sending the map callback

The client might have asked for the buffer to be destroyed, but the
reference to the buffer is still alive because it is internally
referenced by Dawn.

BUG=chromium:918254

Change-Id: Id7d2de891eba98e3cf15e77730f66f64d9a3b9f9
Reviewed-on: https://dawn-review.googlesource.com/c/3622
Reviewed-by: Austin Eng <enga@chromium.org>
Reviewed-by: Kai Ninomiya <kainino@chromium.org>
Commit-Queue: Corentin Wallez <cwallez@chromium.org>
diff --git a/generator/templates/dawn_wire/WireServer.cpp b/generator/templates/dawn_wire/WireServer.cpp
index 1f4c090..99d91d6 100644
--- a/generator/templates/dawn_wire/WireServer.cpp
+++ b/generator/templates/dawn_wire/WireServer.cpp
@@ -326,6 +326,12 @@
                 {% endfor %}
 
                 void OnMapReadAsyncCallback(dawnBufferMapAsyncStatus status, const void* ptr, MapUserdata* data) {
+                    // Skip sending the callback if the buffer has already been destroyed.
+                    auto* bufferData = mKnownBuffer.Get(data->bufferId);
+                    if (bufferData == nullptr || bufferData->serial != data->bufferSerial) {
+                        return;
+                    }
+
                     ReturnBufferMapReadAsyncCallbackCmd cmd;
                     cmd.bufferId = data->bufferId;
                     cmd.bufferSerial = data->bufferSerial;
@@ -347,6 +353,12 @@
                 }
 
                 void OnMapWriteAsyncCallback(dawnBufferMapAsyncStatus status, void* ptr, MapUserdata* data) {
+                    // Skip sending the callback if the buffer has already been destroyed.
+                    auto* bufferData = mKnownBuffer.Get(data->bufferId);
+                    if (bufferData == nullptr || bufferData->serial != data->bufferSerial) {
+                        return;
+                    }
+
                     ReturnBufferMapWriteAsyncCallbackCmd cmd;
                     cmd.bufferId = data->bufferId;
                     cmd.bufferSerial = data->bufferSerial;
@@ -357,11 +369,8 @@
                     *allocCmd = cmd;
 
                     if (status == DAWN_BUFFER_MAP_ASYNC_STATUS_SUCCESS) {
-                        auto* selfData = mKnownBuffer.Get(data->bufferId);
-                        ASSERT(selfData != nullptr);
-
-                        selfData->mappedData = ptr;
-                        selfData->mappedDataSize = data->size;
+                        bufferData->mappedData = ptr;
+                        bufferData->mappedDataSize = data->size;
                     }
 
                     delete data;