1 /* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
5 #include "FileDescriptor.h"
7 #include "mozilla/Assertions.h"
13 #define INVALID_HANDLE INVALID_HANDLE_VALUE
23 #include "base/eintr_wrapper.h"
24 #define INVALID_HANDLE -1
28 using mozilla::ipc::FileDescriptor
;
30 FileDescriptor::FileDescriptor()
31 : mHandle(INVALID_HANDLE
), mHandleCreatedByOtherProcess(false),
32 mHandleCreatedByOtherProcessWasUsed(false)
35 FileDescriptor::FileDescriptor(PlatformHandleType aHandle
)
36 : mHandle(INVALID_HANDLE
), mHandleCreatedByOtherProcess(false),
37 mHandleCreatedByOtherProcessWasUsed(false)
39 DuplicateInCurrentProcess(aHandle
);
43 FileDescriptor::DuplicateInCurrentProcess(PlatformHandleType aHandle
)
45 MOZ_ASSERT_IF(mHandleCreatedByOtherProcess
,
46 mHandleCreatedByOtherProcessWasUsed
);
48 if (IsValid(aHandle
)) {
49 PlatformHandleType newHandle
;
51 if (DuplicateHandle(GetCurrentProcess(), aHandle
, GetCurrentProcess(),
52 &newHandle
, 0, FALSE
, DUPLICATE_SAME_ACCESS
)) {
54 if ((newHandle
= dup(aHandle
)) != INVALID_HANDLE
) {
59 NS_WARNING("Failed to duplicate file handle for current process!");
62 mHandle
= INVALID_HANDLE
;
66 FileDescriptor::CloseCurrentProcessHandle()
68 MOZ_ASSERT_IF(mHandleCreatedByOtherProcess
,
69 mHandleCreatedByOtherProcessWasUsed
);
71 // Don't actually close handles created by another process.
72 if (mHandleCreatedByOtherProcess
) {
78 if (!CloseHandle(mHandle
)) {
79 NS_WARNING("Failed to close file handle for current process!");
82 HANDLE_EINTR(close(mHandle
));
84 mHandle
= INVALID_HANDLE
;
88 FileDescriptor::PickleType
89 FileDescriptor::ShareTo(const FileDescriptor::IPDLPrivate
&,
90 FileDescriptor::ProcessHandle aOtherProcess
) const
92 PlatformHandleType newHandle
;
95 if (DuplicateHandle(GetCurrentProcess(), mHandle
, aOtherProcess
,
96 &newHandle
, 0, FALSE
, DUPLICATE_SAME_ACCESS
)) {
99 NS_WARNING("Failed to duplicate file handle for other process!");
101 return INVALID_HANDLE
;
104 newHandle
= dup(mHandle
);
105 if (IsValid(newHandle
)) {
106 return base::FileDescriptor(newHandle
, /* auto_close */ true);
108 NS_WARNING("Failed to duplicate file handle for other process!");
110 return base::FileDescriptor();
113 MOZ_CRASH("Must not get here!");
118 FileDescriptor::IsValid(PlatformHandleType aHandle
)
120 return aHandle
!= INVALID_HANDLE
;