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"
14 // Returns true if the size is valid and false otherwise.
15 bool SizeInBytes(const gfx::Size
& size
,
16 gfx::BufferFormat format
,
17 size_t* size_in_bytes
) {
21 size_t stride_in_bytes
= 0;
22 if (!GLImageMemory::StrideInBytes(size
.width(), format
, &stride_in_bytes
))
24 base::CheckedNumeric
<size_t> s
= stride_in_bytes
;
28 *size_in_bytes
= s
.ValueOrDie();
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::BufferFormat format
) {
46 if (!SizeInBytes(GetSize(), format
, &size_in_bytes
))
49 if (!base::SharedMemory::IsHandleValid(handle
.handle
))
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.";
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.";
69 if (!GLImageMemory::Initialize(
70 static_cast<unsigned char*>(duped_shared_memory
->memory()), format
)) {
74 DCHECK(!shared_memory_
);
75 shared_memory_
= duped_shared_memory
.Pass();
76 shared_memory_id_
= handle
.id
;
80 void GLImageSharedMemory::Destroy(bool have_context
) {
81 GLImageMemory::Destroy(have_context
);
82 shared_memory_
.reset();
85 void GLImageSharedMemory::OnMemoryDump(
86 base::trace_event::ProcessMemoryDump
* pmd
,
87 uint64_t process_tracing_id
,
88 const std::string
& dump_name
) {
89 size_t size_in_bytes
= 0;
92 bool result
= SizeInBytes(GetSize(), format(), &size_in_bytes
);
96 base::trace_event::MemoryAllocatorDump
* dump
=
97 pmd
->CreateAllocatorDump(dump_name
);
98 dump
->AddScalar(base::trace_event::MemoryAllocatorDump::kNameSize
,
99 base::trace_event::MemoryAllocatorDump::kUnitsBytes
,
100 static_cast<uint64_t>(size_in_bytes
));
102 auto guid
= gfx::GetGenericSharedMemoryGUIDForTracing(process_tracing_id
,
104 pmd
->CreateSharedGlobalAllocatorDump(guid
);
105 pmd
->AddOwnershipEdge(dump
->guid(), guid
);