Fix WindowAndroid leak in Android WebView
[chromium-blink-merge.git] / ui / gl / gl_image_shared_memory.cc
blobd9e31a73ae5f80b1ca28c835be83af190392b59e
1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "ui/gl/gl_image_shared_memory.h"
7 #include "base/logging.h"
8 #include "base/numerics/safe_math.h"
9 #include "base/process/process_handle.h"
11 namespace gfx {
12 namespace {
14 // Returns true if the size is valid and false otherwise.
15 bool SizeInBytes(const gfx::Size& size,
16 gfx::GpuMemoryBuffer::Format format,
17 size_t* size_in_bytes) {
18 if (size.IsEmpty())
19 return false;
21 size_t stride_in_bytes = 0;
22 if (!GLImageMemory::StrideInBytes(size.width(), format, &stride_in_bytes))
23 return false;
24 base::CheckedNumeric<size_t> s = stride_in_bytes;
25 s *= size.height();
26 if (!s.IsValid())
27 return false;
28 *size_in_bytes = s.ValueOrDie();
29 return true;
32 } // namespace
34 GLImageSharedMemory::GLImageSharedMemory(const gfx::Size& size,
35 unsigned internalformat)
36 : GLImageMemory(size, internalformat) {
39 GLImageSharedMemory::~GLImageSharedMemory() {
40 DCHECK(!shared_memory_);
43 bool GLImageSharedMemory::Initialize(const gfx::GpuMemoryBufferHandle& handle,
44 gfx::GpuMemoryBuffer::Format format) {
45 size_t size_in_bytes;
46 if (!SizeInBytes(GetSize(), format, &size_in_bytes))
47 return false;
49 if (!base::SharedMemory::IsHandleValid(handle.handle))
50 return false;
52 base::SharedMemory shared_memory(handle.handle, true);
54 // Duplicate the handle.
55 base::SharedMemoryHandle duped_shared_memory_handle;
56 if (!shared_memory.ShareToProcess(base::GetCurrentProcessHandle(),
57 &duped_shared_memory_handle)) {
58 DVLOG(0) << "Failed to duplicate shared memory handle.";
59 return false;
62 scoped_ptr<base::SharedMemory> duped_shared_memory(
63 new base::SharedMemory(duped_shared_memory_handle, true));
64 if (!duped_shared_memory->Map(size_in_bytes)) {
65 DVLOG(0) << "Failed to map shared memory.";
66 return false;
69 if (!GLImageMemory::Initialize(
70 static_cast<unsigned char*>(duped_shared_memory->memory()), format)) {
71 return false;
74 DCHECK(!shared_memory_);
75 shared_memory_ = duped_shared_memory.Pass();
76 return true;
79 void GLImageSharedMemory::Destroy(bool have_context) {
80 GLImageMemory::Destroy(have_context);
81 shared_memory_.reset();
84 } // namespace gfx