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 "FileDescriptorUtils.h"
7 #include "nsIEventTarget.h"
12 #include "nsServiceManagerUtils.h"
13 #include "nsThreadUtils.h"
15 #include "private/pprio.h"
24 using mozilla::ipc::CloseFileRunnable
;
28 CloseFileRunnable::CloseFileRunnable(const FileDescriptor
& aFileDescriptor
)
29 : mFileDescriptor(aFileDescriptor
)
31 MOZ_ASSERT(aFileDescriptor
.IsValid());
36 CloseFileRunnable::~CloseFileRunnable()
38 if (mFileDescriptor
.IsValid()) {
39 // It's probably safer to take the main thread IO hit here rather than leak
40 // the file descriptor.
45 NS_IMPL_ISUPPORTS(CloseFileRunnable
, nsIRunnable
)
48 CloseFileRunnable::Dispatch()
50 nsCOMPtr
<nsIEventTarget
> eventTarget
=
51 do_GetService(NS_STREAMTRANSPORTSERVICE_CONTRACTID
);
52 NS_ENSURE_TRUE_VOID(eventTarget
);
54 nsresult rv
= eventTarget
->Dispatch(this, NS_DISPATCH_NORMAL
);
55 NS_ENSURE_SUCCESS_VOID(rv
);
59 CloseFileRunnable::CloseFile()
61 // It's possible for this to happen on the main thread if the dispatch to the
62 // stream service fails so we can't assert the thread on which we're running.
64 MOZ_ASSERT(mFileDescriptor
.IsValid());
67 PR_ImportFile(PROsfd(mFileDescriptor
.PlatformHandle()));
68 NS_WARN_IF_FALSE(fd
, "Failed to import file handle!");
70 mFileDescriptor
= FileDescriptor();
79 CloseFileRunnable::Run()
81 MOZ_ASSERT(!NS_IsMainThread());
91 FileDescriptorToFILE(const FileDescriptor
& aDesc
,
92 const char* aOpenMode
)
94 // Debug builds check whether the handle was "used", even if it's
95 // invalid, so that needs to happen first.
96 FileDescriptor::PlatformHandleType handle
= aDesc
.PlatformHandle();
97 if (!aDesc
.IsValid()) {
102 int fd
= _open_osfhandle(reinterpret_cast<intptr_t>(handle
), 0);
110 FILE* file
= fdopen(fd
, aOpenMode
);
112 int saved_errno
= errno
;
120 FILEToFileDescriptor(FILE* aStream
)
124 return FileDescriptor();
127 int fd
= _fileno(aStream
);
129 return FileDescriptor();
131 return FileDescriptor(reinterpret_cast<HANDLE
>(_get_osfhandle(fd
)));
133 return FileDescriptor(fileno(aStream
));
138 } // namespace mozilla