1 // Copyright 2014 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 #ifndef MOJO_PUBLIC_CPP_SYSTEM_HANDLE_H_
6 #define MOJO_PUBLIC_CPP_SYSTEM_HANDLE_H_
7
8 #include <stdint.h>
9 #include <limits>
10
11 #include "base/compiler_specific.h"
12 #include "base/logging.h"
13 #include "base/macros.h"
14 #include "mojo/public/c/system/functions.h"
15 #include "mojo/public/c/system/types.h"
16 #include "mojo/public/cpp/system/handle_signals_state.h"
17
18 namespace mojo {
19
20 // OVERVIEW
21 //
22 // |Handle| and |...Handle|:
23 //
24 // |Handle| is a simple, copyable wrapper for the C type |MojoHandle| (which is
25 // just an integer). Its purpose is to increase type-safety, not provide
26 // lifetime management. For the same purpose, we have trivial *subclasses* of
27 // |Handle|, e.g., |MessagePipeHandle| and |DataPipeProducerHandle|. |Handle|
28 // and its subclasses impose *no* extra overhead over using |MojoHandle|s
29 // directly.
30 //
31 // Note that though we provide constructors for |Handle|/|...Handle| from a
32 // |MojoHandle|, we do not provide, e.g., a constructor for |MessagePipeHandle|
33 // from a |Handle|. This is for type safety: If we did, you'd then be able to
34 // construct a |MessagePipeHandle| from, e.g., a |DataPipeProducerHandle| (since
35 // it's a |Handle|).
36 //
37 // |ScopedHandleBase| and |Scoped...Handle|:
38 //
39 // |ScopedHandleBase<HandleType>| is a templated scoped wrapper, for the handle
40 // types above (in the same sense that a C++11 |unique_ptr<T>| is a scoped
41 // wrapper for a |T*|). It provides lifetime management, closing its owned
42 // handle on destruction. It also provides move semantics, again along the lines
43 // of C++11's |unique_ptr|. A moved-from |ScopedHandleBase<HandleType>| sets its
44 // handle value to MOJO_HANDLE_INVALID.
45 //
46 // |ScopedHandle| is just (a typedef of) a |ScopedHandleBase<Handle>|.
47 // Similarly, |ScopedMessagePipeHandle| is just a
48 // |ScopedHandleBase<MessagePipeHandle>|. Etc. Note that a
49 // |ScopedMessagePipeHandle| is *not* a (subclass of) |ScopedHandle|.
50 //
51 // Wrapper functions:
52 //
53 // We provide simple wrappers for the |Mojo...()| functions (in
54 // mojo/public/c/system/core.h -- see that file for details on individual
55 // functions).
56 //
57 // The general guideline is functions that imply ownership transfer of a handle
58 // should take (or produce) an appropriate |Scoped...Handle|, while those that
59 // don't take a |...Handle|. For example, |CreateMessagePipe()| has two
60 // |ScopedMessagePipe| "out" parameters, whereas |Wait()| and |WaitMany()| take
61 // |Handle| parameters. Some, have both: e.g., |DuplicatedBuffer()| takes a
62 // suitable (unscoped) handle (e.g., |SharedBufferHandle|) "in" parameter and
63 // produces a suitable scoped handle (e.g., |ScopedSharedBufferHandle| a.k.a.
64 // |ScopedHandleBase<SharedBufferHandle>|) as an "out" parameter.
65 //
66 // An exception are some of the |...Raw()| functions. E.g., |CloseRaw()| takes a
67 // |Handle|, leaving the user to discard the wrapper.
68 //
69 // ScopedHandleBase ------------------------------------------------------------
70
71 // Scoper for the actual handle types defined further below. It's move-only,
72 // like the C++11 |unique_ptr|.
73 template <class HandleType>
74 class ScopedHandleBase {
75 public:
76 using RawHandleType = HandleType;
77
ScopedHandleBase()78 ScopedHandleBase() {}
ScopedHandleBase(HandleType handle)79 explicit ScopedHandleBase(HandleType handle) : handle_(handle) {}
~ScopedHandleBase()80 ~ScopedHandleBase() { CloseIfNecessary(); }
81
82 template <class CompatibleHandleType>
ScopedHandleBase(ScopedHandleBase<CompatibleHandleType> other)83 explicit ScopedHandleBase(ScopedHandleBase<CompatibleHandleType> other)
84 : handle_(other.release()) {}
85
86 // Move-only constructor and operator=.
ScopedHandleBase(ScopedHandleBase && other)87 ScopedHandleBase(ScopedHandleBase&& other) noexcept
88 : handle_(other.release()) {}
89 ScopedHandleBase& operator=(ScopedHandleBase&& other) noexcept {
90 if (&other != this) {
91 CloseIfNecessary();
92 handle_ = other.release();
93 }
94 return *this;
95 }
96
get()97 const HandleType& get() const { return handle_; }
98 const HandleType* operator->() const {
99 DCHECK(handle_.is_valid());
100 return &handle_;
101 }
102
103 template <typename PassedHandleType>
From(ScopedHandleBase<PassedHandleType> other)104 static ScopedHandleBase<HandleType> From(
105 ScopedHandleBase<PassedHandleType> other) {
106 static_assert(
107 sizeof(static_cast<PassedHandleType*>(static_cast<HandleType*>(0))),
108 "HandleType is not a subtype of PassedHandleType");
109 return ScopedHandleBase<HandleType>(
110 static_cast<HandleType>(other.release().value()));
111 }
112
swap(ScopedHandleBase & other)113 void swap(ScopedHandleBase& other) { handle_.swap(other.handle_); }
114
release()115 HandleType release() WARN_UNUSED_RESULT {
116 HandleType rv;
117 rv.swap(handle_);
118 return rv;
119 }
120
121 void reset(HandleType handle = HandleType()) {
122 CloseIfNecessary();
123 handle_ = handle;
124 }
125
is_valid()126 bool is_valid() const { return handle_.is_valid(); }
127
128 explicit operator bool() const { return handle_; }
129
130 bool operator==(const ScopedHandleBase& other) const {
131 return handle_.value() == other.get().value();
132 }
133
134 private:
CloseIfNecessary()135 void CloseIfNecessary() {
136 if (handle_.is_valid())
137 handle_.Close();
138 }
139
140 HandleType handle_;
141
142 DISALLOW_COPY_AND_ASSIGN(ScopedHandleBase);
143 };
144
145 template <typename HandleType>
MakeScopedHandle(HandleType handle)146 inline ScopedHandleBase<HandleType> MakeScopedHandle(HandleType handle) {
147 return ScopedHandleBase<HandleType>(handle);
148 }
149
150 // Handle ----------------------------------------------------------------------
151
152 const MojoHandle kInvalidHandleValue = MOJO_HANDLE_INVALID;
153
154 // Wrapper base class for |MojoHandle|.
155 class Handle {
156 public:
Handle()157 Handle() : value_(kInvalidHandleValue) {}
Handle(MojoHandle value)158 explicit Handle(MojoHandle value) : value_(value) {}
~Handle()159 ~Handle() {}
160
swap(Handle & other)161 void swap(Handle& other) {
162 MojoHandle temp = value_;
163 value_ = other.value_;
164 other.value_ = temp;
165 }
166
is_valid()167 bool is_valid() const { return value_ != kInvalidHandleValue; }
168
169 explicit operator bool() const { return value_ != kInvalidHandleValue; }
170
value()171 const MojoHandle& value() const { return value_; }
mutable_value()172 MojoHandle* mutable_value() { return &value_; }
set_value(MojoHandle value)173 void set_value(MojoHandle value) { value_ = value; }
174
Close()175 void Close() {
176 DCHECK(is_valid());
177 MojoResult result = MojoClose(value_);
178 ALLOW_UNUSED_LOCAL(result);
179 DCHECK_EQ(MOJO_RESULT_OK, result);
180 }
181
QuerySignalsState()182 HandleSignalsState QuerySignalsState() const {
183 HandleSignalsState signals_state;
184 MojoResult result = MojoQueryHandleSignalsState(
185 value_, static_cast<MojoHandleSignalsState*>(&signals_state));
186 DCHECK_EQ(MOJO_RESULT_OK, result);
187 return signals_state;
188 }
189
190 private:
191 MojoHandle value_;
192
193 // Copying and assignment allowed.
194 };
195
196 // Should have zero overhead.
197 static_assert(sizeof(Handle) == sizeof(MojoHandle), "Bad size for C++ Handle");
198
199 // The scoper should also impose no more overhead.
200 typedef ScopedHandleBase<Handle> ScopedHandle;
201 static_assert(sizeof(ScopedHandle) == sizeof(Handle),
202 "Bad size for C++ ScopedHandle");
203
204 // |Close()| takes ownership of the handle, since it'll invalidate it.
205 // Note: There's nothing to do, since the argument will be destroyed when it
206 // goes out of scope.
207 template <class HandleType>
Close(ScopedHandleBase<HandleType>)208 inline void Close(ScopedHandleBase<HandleType> /*handle*/) {
209 }
210
211 // Most users should typically use |Close()| (above) instead.
CloseRaw(Handle handle)212 inline MojoResult CloseRaw(Handle handle) {
213 return MojoClose(handle.value());
214 }
215
216 // Strict weak ordering, so that |Handle|s can be used as keys in |std::map|s,
217 inline bool operator<(const Handle a, const Handle b) {
218 return a.value() < b.value();
219 }
220
221 // Comparison, so that |Handle|s can be used as keys in hash maps.
222 inline bool operator==(const Handle a, const Handle b) {
223 return a.value() == b.value();
224 }
225
226 } // namespace mojo
227
228 #endif // MOJO_PUBLIC_CPP_SYSTEM_HANDLE_H_
229