1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
|
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "mozilla/Services.h"
#include "nsCOMPtr.h"
#include "nsIObserverService.h"
#include "nsNamedPipeService.h"
#include "nsNetCID.h"
#include "nsThreadUtils.h"
#include "mozilla/ClearOnShutdown.h"
#include "mozilla/Logging.h"
namespace mozilla {
namespace net {
static mozilla::LazyLogModule gNamedPipeServiceLog("NamedPipeWin");
#define LOG_NPS_DEBUG(...) \
MOZ_LOG(gNamedPipeServiceLog, mozilla::LogLevel::Debug, (__VA_ARGS__))
#define LOG_NPS_ERROR(...) \
MOZ_LOG(gNamedPipeServiceLog, mozilla::LogLevel::Error, (__VA_ARGS__))
StaticRefPtr<NamedPipeService> NamedPipeService::gSingleton;
NS_IMPL_ISUPPORTS(NamedPipeService, nsINamedPipeService, nsIObserver,
nsIRunnable)
NamedPipeService::NamedPipeService()
: mIocp(nullptr), mIsShutdown(false), mLock("NamedPipeServiceLock") {}
nsresult NamedPipeService::Init() {
MOZ_ASSERT(!mIsShutdown);
nsresult rv;
// nsIObserverService must be accessed in main thread.
// register shutdown event to stop NamedPipeSrv thread.
nsCOMPtr<nsIObserver> self(this);
nsCOMPtr<nsIRunnable> r = NS_NewRunnableFunction(
"NamedPipeService::Init", [self = std::move(self)]() -> void {
MOZ_ASSERT(NS_IsMainThread());
nsCOMPtr<nsIObserverService> svc =
mozilla::services::GetObserverService();
if (NS_WARN_IF(!svc)) {
return;
}
if (NS_WARN_IF(NS_FAILED(svc->AddObserver(
self, NS_XPCOM_SHUTDOWN_OBSERVER_ID, false)))) {
return;
}
});
if (NS_IsMainThread()) {
rv = r->Run();
} else {
rv = NS_DispatchToMainThread(r);
}
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
}
mIocp = CreateIoCompletionPort(INVALID_HANDLE_VALUE, nullptr, 0, 1);
if (NS_WARN_IF(!mIocp || mIocp == INVALID_HANDLE_VALUE)) {
Shutdown();
return NS_ERROR_FAILURE;
}
rv = NS_NewNamedThread("NamedPipeSrv", getter_AddRefs(mThread));
if (NS_WARN_IF(NS_FAILED(rv))) {
Shutdown();
return rv;
}
return NS_OK;
}
// static
already_AddRefed<nsINamedPipeService> NamedPipeService::GetOrCreate() {
MOZ_ASSERT(NS_IsMainThread());
RefPtr<NamedPipeService> inst;
if (gSingleton) {
inst = gSingleton;
} else {
inst = new NamedPipeService();
nsresult rv = inst->Init();
NS_ENSURE_SUCCESS(rv, nullptr);
gSingleton = inst;
ClearOnShutdown(&gSingleton);
}
return inst.forget();
}
void NamedPipeService::Shutdown() {
MOZ_ASSERT(NS_IsMainThread());
// remove observer
nsCOMPtr<nsIObserverService> obs = mozilla::services::GetObserverService();
if (obs) {
obs->RemoveObserver(this, NS_XPCOM_SHUTDOWN_OBSERVER_ID);
}
// stop thread
if (mThread && !mIsShutdown) {
mIsShutdown = true;
// invoke ERROR_ABANDONED_WAIT_0 to |GetQueuedCompletionStatus|
CloseHandle(mIocp);
mIocp = nullptr;
mThread->Shutdown();
}
// close I/O Completion Port
if (mIocp && mIocp != INVALID_HANDLE_VALUE) {
CloseHandle(mIocp);
mIocp = nullptr;
}
}
void NamedPipeService::RemoveRetiredObjects() {
MOZ_ASSERT(NS_GetCurrentThread() == mThread);
mLock.AssertCurrentThreadOwns();
if (!mRetiredHandles.IsEmpty()) {
for (auto& handle : mRetiredHandles) {
CloseHandle(handle);
}
mRetiredHandles.Clear();
}
mRetiredObservers.Clear();
}
/**
* Implement nsINamedPipeService
*/
NS_IMETHODIMP
NamedPipeService::AddDataObserver(void* aHandle,
nsINamedPipeDataObserver* aObserver) {
if (!aHandle || aHandle == INVALID_HANDLE_VALUE || !aObserver) {
return NS_ERROR_ILLEGAL_VALUE;
}
nsresult rv;
HANDLE h = CreateIoCompletionPort(aHandle, mIocp,
reinterpret_cast<ULONG_PTR>(aObserver), 1);
if (NS_WARN_IF(!h)) {
LOG_NPS_ERROR("CreateIoCompletionPort error (%lu)", GetLastError());
return NS_ERROR_FAILURE;
}
if (NS_WARN_IF(h != mIocp)) {
LOG_NPS_ERROR(
"CreateIoCompletionPort got unexpected value %p (should be %p)", h,
mIocp);
CloseHandle(h);
return NS_ERROR_FAILURE;
}
{
MutexAutoLock lock(mLock);
MOZ_ASSERT(!mObservers.Contains(aObserver));
mObservers.AppendElement(aObserver);
// start event loop
if (mObservers.Length() == 1) {
rv = mThread->Dispatch(this, NS_DISPATCH_NORMAL);
if (NS_WARN_IF(NS_FAILED(rv))) {
LOG_NPS_ERROR("Dispatch to thread failed (%08x)", uint32_t(rv));
mObservers.Clear();
return rv;
}
}
}
return NS_OK;
}
NS_IMETHODIMP
NamedPipeService::RemoveDataObserver(void* aHandle,
nsINamedPipeDataObserver* aObserver) {
MutexAutoLock lock(mLock);
mObservers.RemoveElement(aObserver);
mRetiredHandles.AppendElement(aHandle);
mRetiredObservers.AppendElement(aObserver);
return NS_OK;
}
NS_IMETHODIMP
NamedPipeService::IsOnCurrentThread(bool* aRetVal) {
MOZ_ASSERT(mThread);
MOZ_ASSERT(aRetVal);
if (!mThread) {
*aRetVal = false;
return NS_OK;
}
return mThread->IsOnCurrentThread(aRetVal);
}
/**
* Implement nsIObserver
*/
NS_IMETHODIMP
NamedPipeService::Observe(nsISupports* aSubject, const char* aTopic,
const char16_t* aData) {
MOZ_ASSERT(NS_IsMainThread());
if (!strcmp(NS_XPCOM_SHUTDOWN_OBSERVER_ID, aTopic)) {
Shutdown();
}
return NS_OK;
}
/**
* Implement nsIRunnable
*/
NS_IMETHODIMP
NamedPipeService::Run() {
MOZ_ASSERT(NS_GetCurrentThread() == mThread);
MOZ_ASSERT(mIocp && mIocp != INVALID_HANDLE_VALUE);
while (!mIsShutdown) {
{
MutexAutoLock lock(mLock);
if (mObservers.IsEmpty()) {
LOG_NPS_DEBUG("no observer, stop loop");
break;
}
RemoveRetiredObjects();
}
DWORD bytesTransferred = 0;
ULONG_PTR key = 0;
LPOVERLAPPED overlapped = nullptr;
BOOL success =
GetQueuedCompletionStatus(mIocp, &bytesTransferred, &key, &overlapped,
1000); // timeout, 1s
auto err = GetLastError();
if (!success) {
if (err == WAIT_TIMEOUT) {
continue;
} else if (err == ERROR_ABANDONED_WAIT_0) { // mIocp was closed
break;
} else if (!overlapped) {
/**
* Did not dequeue a completion packet from the completion port, and
* bytesTransferred/key are meaningless.
* See remarks of |GetQueuedCompletionStatus| API.
*/
LOG_NPS_ERROR("invalid overlapped (%lu)", err);
continue;
}
MOZ_ASSERT(key);
}
/**
* Windows doesn't provide a method to remove created I/O Completion Port,
* all we can do is just close the handle we monitored before.
* In some cases, there's race condition that the monitored handle has an
* I/O status after the observer is being removed and destroyed.
* To avoid changing the ref-count of a dangling pointer, don't use nsCOMPtr
* here.
*/
nsINamedPipeDataObserver* target =
reinterpret_cast<nsINamedPipeDataObserver*>(key);
nsCOMPtr<nsINamedPipeDataObserver> obs;
{
MutexAutoLock lock(mLock);
auto idx = mObservers.IndexOf(target);
if (idx == decltype(mObservers)::NoIndex) {
LOG_NPS_ERROR("observer %p not found", target);
continue;
}
obs = target;
}
MOZ_ASSERT(obs.get());
if (success) {
LOG_NPS_DEBUG("OnDataAvailable: obs=%p, bytes=%lu", obs.get(),
bytesTransferred);
obs->OnDataAvailable(bytesTransferred, overlapped);
} else {
LOG_NPS_ERROR("GetQueuedCompletionStatus %p failed, error=%lu", obs.get(),
err);
obs->OnError(err, overlapped);
}
}
{
MutexAutoLock lock(mLock);
RemoveRetiredObjects();
}
return NS_OK;
}
} // namespace net
} // namespace mozilla
|