1 // Copyright 2017 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.
4
5 #include "base/memory/shared_memory_handle.h"
6
7 #include <unistd.h>
8
9 #include "base/logging.h"
10 #include "base/posix/eintr_wrapper.h"
11 #include "base/unguessable_token.h"
12
13 namespace base {
14
15 SharedMemoryHandle::SharedMemoryHandle() = default;
16
SharedMemoryHandle(const base::FileDescriptor & file_descriptor,size_t size,const base::UnguessableToken & guid)17 SharedMemoryHandle::SharedMemoryHandle(
18 const base::FileDescriptor& file_descriptor,
19 size_t size,
20 const base::UnguessableToken& guid)
21 : file_descriptor_(file_descriptor), guid_(guid), size_(size) {}
22
23 // static
ImportHandle(int fd,size_t size)24 SharedMemoryHandle SharedMemoryHandle::ImportHandle(int fd, size_t size) {
25 SharedMemoryHandle handle;
26 handle.file_descriptor_.fd = fd;
27 handle.file_descriptor_.auto_close = false;
28 handle.guid_ = UnguessableToken::Create();
29 handle.size_ = size;
30 return handle;
31 }
32
GetHandle() const33 int SharedMemoryHandle::GetHandle() const {
34 return file_descriptor_.fd;
35 }
36
IsValid() const37 bool SharedMemoryHandle::IsValid() const {
38 return file_descriptor_.fd >= 0;
39 }
40
Close() const41 void SharedMemoryHandle::Close() const {
42 if (IGNORE_EINTR(close(file_descriptor_.fd)) < 0)
43 PLOG(ERROR) << "close";
44 }
45
Release()46 int SharedMemoryHandle::Release() {
47 int old_fd = file_descriptor_.fd;
48 file_descriptor_.fd = -1;
49 return old_fd;
50 }
51
Duplicate() const52 SharedMemoryHandle SharedMemoryHandle::Duplicate() const {
53 if (!IsValid())
54 return SharedMemoryHandle();
55
56 int duped_handle = HANDLE_EINTR(dup(file_descriptor_.fd));
57 if (duped_handle < 0)
58 return SharedMemoryHandle();
59 return SharedMemoryHandle(FileDescriptor(duped_handle, true), GetSize(),
60 GetGUID());
61 }
62
SetOwnershipPassesToIPC(bool ownership_passes)63 void SharedMemoryHandle::SetOwnershipPassesToIPC(bool ownership_passes) {
64 file_descriptor_.auto_close = ownership_passes;
65 }
66
OwnershipPassesToIPC() const67 bool SharedMemoryHandle::OwnershipPassesToIPC() const {
68 return file_descriptor_.auto_close;
69 }
70
71 } // namespace base
72