1 // Copyright 2015 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 "base/memory/shared_memory_handle.h"
9 #include "base/posix/eintr_wrapper.h"
13 static_assert(sizeof(SharedMemoryHandle::Type
) <=
14 sizeof(SharedMemoryHandle::TypeWireFormat
),
15 "Size of enum SharedMemoryHandle::Type exceeds size of type "
16 "transmitted over wire.");
18 SharedMemoryHandle::SharedMemoryHandle() : type_(POSIX
), file_descriptor_() {
21 SharedMemoryHandle::SharedMemoryHandle(
22 const base::FileDescriptor
& file_descriptor
)
23 : type_(POSIX
), file_descriptor_(file_descriptor
) {
26 SharedMemoryHandle::SharedMemoryHandle(int fd
, bool auto_close
)
27 : type_(POSIX
), file_descriptor_(fd
, auto_close
) {
30 SharedMemoryHandle::SharedMemoryHandle(const SharedMemoryHandle
& handle
)
31 : type_(handle
.type_
), file_descriptor_(handle
.file_descriptor_
) {
34 SharedMemoryHandle
& SharedMemoryHandle::operator=(
35 const SharedMemoryHandle
& handle
) {
40 file_descriptor_
= handle
.file_descriptor_
;
44 bool SharedMemoryHandle::operator==(const SharedMemoryHandle
& handle
) const {
45 // Invalid handles are always equal, even if they have different types.
46 if (!IsValid() && !handle
.IsValid())
49 return type_
== handle
.type_
&& file_descriptor_
== handle
.file_descriptor_
;
52 bool SharedMemoryHandle::operator!=(const SharedMemoryHandle
& handle
) const {
53 return !(*this == handle
);
56 SharedMemoryHandle::Type
SharedMemoryHandle::GetType() const {
60 bool SharedMemoryHandle::IsValid() const {
63 return file_descriptor_
.fd
>= 0;
69 void SharedMemoryHandle::SetFileHandle(int fd
, bool auto_close
) {
70 DCHECK_EQ(type_
, POSIX
);
71 file_descriptor_
.fd
= fd
;
72 file_descriptor_
.auto_close
= auto_close
;
75 const FileDescriptor
SharedMemoryHandle::GetFileDescriptor() const {
76 DCHECK_EQ(type_
, POSIX
);
77 return file_descriptor_
;
80 SharedMemoryHandle
SharedMemoryHandle::Duplicate() const {
81 DCHECK_EQ(type_
, POSIX
);
82 int duped_handle
= HANDLE_EINTR(dup(file_descriptor_
.fd
));
84 return SharedMemoryHandle();
85 return SharedMemoryHandle(duped_handle
, true);