tuple: update to make use of C++11
[chromium-blink-merge.git] / mojo / edk / system / channel.h
blob227d202229a49f236d5a1d93db1ccf6b284a5774
1 // Copyright 2013 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.
5 #ifndef MOJO_EDK_SYSTEM_CHANNEL_H_
6 #define MOJO_EDK_SYSTEM_CHANNEL_H_
8 #include <stdint.h>
10 #include "base/containers/hash_tables.h"
11 #include "base/macros.h"
12 #include "base/memory/ref_counted.h"
13 #include "base/memory/scoped_ptr.h"
14 #include "base/strings/string_piece.h"
15 #include "base/synchronization/lock.h"
16 #include "base/threading/thread_checker.h"
17 #include "mojo/edk/embedder/scoped_platform_handle.h"
18 #include "mojo/edk/system/channel_endpoint.h"
19 #include "mojo/edk/system/channel_endpoint_id.h"
20 #include "mojo/edk/system/message_in_transit.h"
21 #include "mojo/edk/system/message_pipe.h"
22 #include "mojo/edk/system/raw_channel.h"
23 #include "mojo/edk/system/system_impl_export.h"
24 #include "mojo/public/c/system/types.h"
26 namespace mojo {
28 namespace embedder {
29 class PlatformSupport;
32 namespace system {
34 class ChannelEndpoint;
35 class ChannelManager;
37 // This class is mostly thread-safe. It must be created on an I/O thread.
38 // |Init()| must be called on that same thread before it becomes thread-safe (in
39 // particular, before references are given to any other thread) and |Shutdown()|
40 // must be called on that same thread before destruction. Its public methods are
41 // otherwise thread-safe. (Many private methods are restricted to the creation
42 // thread.) It may be destroyed on any thread, in the sense that the last
43 // reference to it may be released on any thread, with the proviso that
44 // |Shutdown()| must have been called first (so the pattern is that a "main"
45 // reference is kept on its creation thread and is released after |Shutdown()|
46 // is called, but other threads may have temporarily "dangling" references).
48 // Note the lock order (in order of allowable acquisition): |MessagePipe|,
49 // |ChannelEndpoint|, |Channel|. Thus |Channel| may not call into
50 // |ChannelEndpoint| with |Channel|'s lock held.
51 class MOJO_SYSTEM_IMPL_EXPORT Channel
52 : public base::RefCountedThreadSafe<Channel>,
53 public RawChannel::Delegate {
54 public:
55 // |platform_support| (typically owned by |Core|) must remain alive until
56 // after |Shutdown()| is called.
57 explicit Channel(embedder::PlatformSupport* platform_support);
59 // This must be called on the creation thread before any other methods are
60 // called, and before references to this object are given to any other
61 // threads. |raw_channel| should be uninitialized. Returns true on success. On
62 // failure, no other methods should be called (including |Shutdown()|).
63 bool Init(scoped_ptr<RawChannel> raw_channel);
65 // Sets the channel manager associated with this channel. This should be set
66 // at most once and only called before |WillShutdownSoon()| (and
67 // |Shutdown()|).
68 void SetChannelManager(ChannelManager* channel_manager);
70 // This must be called on the creation thread before destruction (which can
71 // happen on any thread).
72 void Shutdown();
74 // Signals that |Shutdown()| will be called soon (this may be called from any
75 // thread, unlike |Shutdown()|). Warnings will be issued if, e.g., messages
76 // are written after this is called; other warnings may be suppressed. (This
77 // may be called multiple times, or not at all.)
79 // If set, the channel manager associated with this channel will be reset.
80 void WillShutdownSoon();
82 // Attaches the given endpoint to this channel and runs it. |is_bootstrap|
83 // should be set if and only if it is the first endpoint on the channel. This
84 // assigns the endpoint both local and remote IDs. If |is_bootstrap| is set,
85 // both are the bootstrap ID (given by |ChannelEndpointId::GetBootstrap()|);
86 // if not, it will also send a |kSubtypeChannelAttachAndRunEndpoint| message
87 // to the remote side to tell it to create an endpoint as well.
89 // (Bootstrapping is symmetric: Both sides attach and run endpoints with
90 // |is_bootstrap| set, which establishes the first message pipe across a
91 // channel.)
93 // This returns the *remote* ID (which will be the bootstrap ID in the
94 // bootstrap case, and a "remote ID", i.e., one for which |is_remote()|
95 // returns true, otherwise).
97 // TODO(vtl): Maybe limit the number of attached message pipes.
98 ChannelEndpointId AttachAndRunEndpoint(
99 scoped_refptr<ChannelEndpoint> endpoint,
100 bool is_bootstrap);
102 // This forwards |message| verbatim to |raw_channel_|.
103 bool WriteMessage(scoped_ptr<MessageInTransit> message);
105 // See |RawChannel::IsWriteBufferEmpty()|.
106 // TODO(vtl): Maybe we shouldn't expose this, and instead have a
107 // |FlushWriteBufferAndShutdown()| or something like that.
108 bool IsWriteBufferEmpty();
110 // Removes the given endpoint from this channel (|local_id| and |remote_id|
111 // are specified as an optimization; the latter should be an invalid
112 // |ChannelEndpointId| if the endpoint is not yet running). Note: If this is
113 // called, the |Channel| will *not* call
114 // |ChannelEndpoint::DetachFromChannel()|.
115 void DetachEndpoint(ChannelEndpoint* endpoint,
116 ChannelEndpointId local_id,
117 ChannelEndpointId remote_id);
119 // Takes ownership of an incoming message pipe (i.e., one that was created via
120 // a |kSubtypeChannelAttachAndRunEndpoint| message).
121 scoped_refptr<MessagePipe> PassIncomingMessagePipe(
122 ChannelEndpointId local_id);
124 // See |RawChannel::GetSerializedPlatformHandleSize()|.
125 size_t GetSerializedPlatformHandleSize() const;
127 embedder::PlatformSupport* platform_support() const {
128 return platform_support_;
131 private:
132 friend class base::RefCountedThreadSafe<Channel>;
133 ~Channel() override;
135 // |RawChannel::Delegate| implementation (only called on the creation thread):
136 void OnReadMessage(
137 const MessageInTransit::View& message_view,
138 embedder::ScopedPlatformHandleVectorPtr platform_handles) override;
139 void OnError(Error error) override;
141 // Helpers for |OnReadMessage| (only called on the creation thread):
142 void OnReadMessageForEndpoint(
143 const MessageInTransit::View& message_view,
144 embedder::ScopedPlatformHandleVectorPtr platform_handles);
145 void OnReadMessageForChannel(
146 const MessageInTransit::View& message_view,
147 embedder::ScopedPlatformHandleVectorPtr platform_handles);
149 // Handles "attach and run endpoint" messages.
150 bool OnAttachAndRunEndpoint(ChannelEndpointId local_id,
151 ChannelEndpointId remote_id);
152 // Handles "remove message pipe endpoint" messages.
153 bool OnRemoveMessagePipeEndpoint(ChannelEndpointId local_id,
154 ChannelEndpointId remote_id);
155 // Handles "remove message pipe endpoint ack" messages.
156 bool OnRemoveMessagePipeEndpointAck(ChannelEndpointId local_id);
158 // Handles errors (e.g., invalid messages) from the remote side. Callable from
159 // any thread.
160 void HandleRemoteError(const base::StringPiece& error_message);
161 // Handles internal errors/failures from the local side. Callable from any
162 // thread.
163 void HandleLocalError(const base::StringPiece& error_message);
165 // Helper to send channel control messages. Returns true on success. Should be
166 // called *without* |lock_| held. Callable from any thread.
167 bool SendControlMessage(MessageInTransit::Subtype subtype,
168 ChannelEndpointId source_id,
169 ChannelEndpointId destination_id);
171 base::ThreadChecker creation_thread_checker_;
173 embedder::PlatformSupport* const platform_support_;
175 // Note: |MessagePipe|s MUST NOT be used under |lock_|. I.e., |lock_| can only
176 // be acquired after |MessagePipe::lock_|, never before. Thus to call into a
177 // |MessagePipe|, a reference to the |MessagePipe| should be acquired from
178 // |local_id_to_endpoint_map_| under |lock_| and then the lock released.
179 base::Lock lock_; // Protects the members below.
181 scoped_ptr<RawChannel> raw_channel_;
182 bool is_running_;
183 // Set when |WillShutdownSoon()| is called.
184 bool is_shutting_down_;
186 // Has a reference to us.
187 ChannelManager* channel_manager_;
189 typedef base::hash_map<ChannelEndpointId, scoped_refptr<ChannelEndpoint>>
190 IdToEndpointMap;
191 // Map from local IDs to endpoints. If the endpoint is null, this means that
192 // we're just waiting for the remove ack before removing the entry.
193 IdToEndpointMap local_id_to_endpoint_map_;
194 // Note: The IDs generated by this should be checked for existence before use.
195 LocalChannelEndpointIdGenerator local_id_generator_;
197 typedef base::hash_map<ChannelEndpointId, scoped_refptr<MessagePipe>>
198 IdToMessagePipeMap;
199 // Map from local IDs to pending/incoming message pipes (i.e., those which do
200 // not yet have a dispatcher attached).
201 // TODO(vtl): This is a layering violation, since |Channel| shouldn't know
202 // about |MessagePipe|. However, we can't just hang on to |ChannelEndpoint|s
203 // (even if they have a reference to the |MessagePipe|) since their lifetimes
204 // are tied to the "remote" side. When |ChannelEndpoint::DetachFromChannel()|
205 // (eventually) results in |ChannelEndpoint::DetachFromClient()| being called.
206 // We really need to hang on to the "local" side of the message pipe, to which
207 // dispatchers will be "attached".
208 IdToMessagePipeMap incoming_message_pipes_;
209 // TODO(vtl): We need to keep track of remote IDs (so that we don't collide
210 // if/when we wrap).
211 RemoteChannelEndpointIdGenerator remote_id_generator_;
213 DISALLOW_COPY_AND_ASSIGN(Channel);
216 } // namespace system
217 } // namespace mojo
219 #endif // MOJO_EDK_SYSTEM_CHANNEL_H_