1 // Copyright (c) 2012 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 "sandbox/win/src/win2k_threadpool.h"
6 
7 #include <stddef.h>
8 
9 #include "sandbox/win/src/win_utils.h"
10 
11 namespace sandbox {
12 
Win2kThreadPool()13 Win2kThreadPool::Win2kThreadPool() {
14   ::InitializeCriticalSection(&lock_);
15 }
16 
RegisterWait(const void * cookie,HANDLE waitable_object,CrossCallIPCCallback callback,void * context)17 bool Win2kThreadPool::RegisterWait(const void* cookie,
18                                    HANDLE waitable_object,
19                                    CrossCallIPCCallback callback,
20                                    void* context) {
21   if (0 == cookie) {
22     return false;
23   }
24   HANDLE pool_object = nullptr;
25   // create a wait for a kernel object, with no timeout
26   if (!::RegisterWaitForSingleObject(&pool_object, waitable_object, callback,
27                                      context, INFINITE, WT_EXECUTEDEFAULT)) {
28     return false;
29   }
30   PoolObject pool_obj = {cookie, pool_object};
31   AutoLock lock(&lock_);
32   pool_objects_.push_back(pool_obj);
33   return true;
34 }
35 
UnRegisterWaits(void * cookie)36 bool Win2kThreadPool::UnRegisterWaits(void* cookie) {
37   if (0 == cookie) {
38     return false;
39   }
40   AutoLock lock(&lock_);
41   bool success = true;
42   PoolObjects::iterator it = pool_objects_.begin();
43   while (it != pool_objects_.end()) {
44     if (it->cookie == cookie) {
45       HANDLE wait = it->wait;
46       it = pool_objects_.erase(it);
47       success &= (::UnregisterWaitEx(wait, INVALID_HANDLE_VALUE) != 0);
48     } else {
49       ++it;
50     }
51   }
52   return success;
53 }
54 
OutstandingWaits()55 size_t Win2kThreadPool::OutstandingWaits() {
56   AutoLock lock(&lock_);
57   return pool_objects_.size();
58 }
59 
~Win2kThreadPool()60 Win2kThreadPool::~Win2kThreadPool() {
61   // Here we used to unregister all the pool wait handles. Now, following the
62   // rest of the code we avoid lengthy or blocking calls given that the process
63   // is being torn down.
64   ::DeleteCriticalSection(&lock_);
65 }
66 
67 }  // namespace sandbox
68