Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(143)

Side by Side Diff: chrome/nacl/nacl_ipc_adapter.cc

Issue 9863005: Initial implementation of an IPC adapter to expose Chrome IPC to Native Client. (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src
Patch Set: Created 8 years, 9 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
OLDNEW
(Empty)
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 "chrome/nacl/nacl_ipc_adapter.h"
6
7 #include <limits.h>
8 #include <string.h>
9
10 #include "base/basictypes.h"
11 #include "base/bind.h"
12 #include "base/location.h"
13 #include "base/memory/scoped_ptr.h"
14 #include "build/build_config.h"
15
16 namespace {
17
18 // The NaCl message header type is always like Posix. So when we're compiling
19 // on Posix platforms, we can check that our header is correct.
20 #if defined(OS_POSIX)
21 COMPILE_ASSERT(sizeof(NaClIPCAdapter::NaClMessageHeader) ==
22 sizeof(IPC::Message::Header),
23 PosixHeaderSizesDontMatch);
24 #endif
25
26 enum BufferSizeStatus {
27 // The buffer contains a full message with no extra bytes.
28 MESSAGE_IS_COMPLETE,
29
30 // The message doesn't fit and the buffer contains only some of it.
31 MESSAGE_IS_TRUNCATED,
32
33 // The buffer contains a full message + extra data.
34 BUFFER_UNDERFLOW
bbudge 2012/03/27 18:38:37 This name seems counterintuitive to me. Perhaps so
35 };
36
37 BufferSizeStatus GetBufferStatus(const char* data, size_t len) {
38 if (len < sizeof(NaClIPCAdapter::NaClMessageHeader))
39 return MESSAGE_IS_TRUNCATED;
40
41 const NaClIPCAdapter::NaClMessageHeader* header =
42 reinterpret_cast<const NaClIPCAdapter::NaClMessageHeader*>(data);
43 uint32 message_size =
44 sizeof(NaClIPCAdapter::NaClMessageHeader) + header->payload_size;
45
46 if (len == message_size)
47 return MESSAGE_IS_COMPLETE;
48 if (len > message_size)
49 return BUFFER_UNDERFLOW;
50 return MESSAGE_IS_TRUNCATED;
51 }
52
53 } // namespace
54
55 class NaClIPCAdapter::RewrittenMessage
56 : public base::RefCounted<RewrittenMessage> {
57 public:
58 RewrittenMessage();
59
60 bool is_consumed() const { return data_read_cursor_ == data_len_; }
61
62 void SetData(const NaClIPCAdapter::NaClMessageHeader& header,
63 const void* payload, size_t payload_length);
64
65 int Read(char* dest_buffer, int dest_buffer_size);
66
67 private:
68 scoped_array<char> data_;
69 int data_len_;
70
71 // Offset into data where the next read will happen. This will be equal to
72 // data_len_ when all data has been consumed.
73 int data_read_cursor_;
74 };
75
76 NaClIPCAdapter::RewrittenMessage::RewrittenMessage()
77 : data_len_(0),
78 data_read_cursor_(0) {
79 }
80
81 void NaClIPCAdapter::RewrittenMessage::SetData(
82 const NaClIPCAdapter::NaClMessageHeader& header,
83 const void* payload,
84 size_t payload_length) {
85 DCHECK(!data_.get() && data_len_ == 0);
86 int header_len = sizeof(NaClIPCAdapter::NaClMessageHeader);
87 data_len_ = header_len + static_cast<int>(payload_length);
88 data_.reset(new char[data_len_]);
89
90 memcpy(data_.get(), &header, sizeof(NaClIPCAdapter::NaClMessageHeader));
91 memcpy(&data_[header_len], payload, payload_length);
92 }
93
94 int NaClIPCAdapter::RewrittenMessage::Read(char* dest_buffer,
95 int dest_buffer_size) {
96 int bytes_to_write = std::min(dest_buffer_size,
97 data_len_ - data_read_cursor_);
98 if (bytes_to_write == 0)
99 return 0;
100
101 memcpy(dest_buffer, &data_[data_read_cursor_], bytes_to_write);
102 data_read_cursor_ += bytes_to_write;
103 return bytes_to_write;
104 }
105
106 NaClIPCAdapter::LockedData::LockedData() : channel_closed_(false) {
107 }
108
109 NaClIPCAdapter::IOThreadData::IOThreadData() {
110 }
111
112 NaClIPCAdapter::NaClIPCAdapter(const IPC::ChannelHandle& handle,
113 base::TaskRunner* runner)
114 : lock_(),
115 cond_var_(&lock_),
116 task_runner_(runner),
117 locked_data_() {
118 io_thread_data_.channel_.reset(
119 new IPC::Channel(handle, IPC::Channel::MODE_SERVER, this));
120 }
121
122 NaClIPCAdapter::NaClIPCAdapter(scoped_ptr<IPC::Channel> channel,
123 base::TaskRunner* runner)
124 : lock_(),
125 cond_var_(&lock_),
126 task_runner_(runner),
127 locked_data_() {
128 io_thread_data_.channel_ = channel.Pass();
129 }
130
131 NaClIPCAdapter::~NaClIPCAdapter() {
132 }
133
134 // Note that this message is controlled by the untrusted code. So we should be
135 // skeptical of anything it contains and quick to give up if anything is fishy.
136 int NaClIPCAdapter::Send(const char* input_data, size_t input_data_len) {
137 base::AutoLock lock(lock_);
138
139 if (input_data_len > IPC::Channel::kMaximumMessageSize) {
140 ClearToBeSent();
141 return -1;
142 }
143
144 // current_message[_len] refers to the total input data received so far.
145 const char* current_message;
146 size_t current_message_len;
147 bool did_append_input_data;
148 if (locked_data_.to_be_sent_.empty()) {
149 // No accumulated data, we can avoid a copy by referring to the input
150 // buffer (the entire message fitting in one call is the common case).
151 current_message = input_data;
152 current_message_len = input_data_len;
153 did_append_input_data = false;
154 } else {
155 // We've already accumulated some data, accumulate this new data and
156 // point to the beginning of the buffer.
157
158 // Make sure our accumulated message size doesn't overflow our max. Since
159 // we know that data_len < max size (checked above) and our current
160 // accumulated value is also < max size, we just need to make sure that
161 // 2x max size can never overflow.
162 COMPILE_ASSERT(IPC::Channel::kMaximumMessageSize < (UINT_MAX / 2),
163 MaximumMessageSizeWillOverflow);
164 size_t new_size = locked_data_.to_be_sent_.size() + input_data_len;
165 if (new_size > IPC::Channel::kMaximumMessageSize) {
166 ClearToBeSent();
167 return -1;
168 }
169
170 locked_data_.to_be_sent_.append(input_data, input_data_len);
171 current_message = &locked_data_.to_be_sent_[0];
172 current_message_len = locked_data_.to_be_sent_.size();
173 did_append_input_data = true;
174 }
175
176 // Check the total data we've accumulated so far to see if it contains a full
177 // message.
178 switch (GetBufferStatus(current_message, current_message_len)) {
179 case MESSAGE_IS_COMPLETE: {
180 // Got a complete message, can send it out. This will be the common case.
181 bool success = SendCompleteMessage(current_message, current_message_len);
182 ClearToBeSent();
183 return success ? input_data_len : -1;
184 }
185 case MESSAGE_IS_TRUNCATED:
186 // For truncated messages, just accumulate the new data (if we didn't
187 // already do so above) and go back to waiting for more.
188 if (!did_append_input_data)
189 locked_data_.to_be_sent_.append(input_data, input_data_len);
190 return input_data_len;
191 case BUFFER_UNDERFLOW:
192 default:
193 // When the plugin gives us too much data, it's an error.
194 ClearToBeSent();
195 return -1;
196 }
197 }
198
199 int NaClIPCAdapter::BlockingReceive(char* output_buffer,
200 int output_buffer_size) {
201 int retval = 0;
202 {
203 base::AutoLock lock(lock_);
204 while (locked_data_.to_be_received_.empty() &&
205 !locked_data_.channel_closed_)
206 cond_var_.Wait();
207 if (locked_data_.channel_closed_) {
208 retval = -1;
209 } else {
210 retval = LockedReceive(output_buffer, output_buffer_size);
211 DCHECK(retval > 0);
212 }
213 }
214 cond_var_.Signal();
215 return retval;
216 }
217
218 void NaClIPCAdapter::CloseChannel() {
219 {
220 base::AutoLock lock(lock_);
221 locked_data_.channel_closed_ = true;
222 }
223 cond_var_.Signal();
224
225 task_runner_->PostTask(FROM_HERE,
226 base::Bind(&NaClIPCAdapter::CloseChannelOnIOThread, this));
227 }
228
229 bool NaClIPCAdapter::OnMessageReceived(const IPC::Message& message) {
230 {
231 base::AutoLock lock(lock_);
232
233 // There is some padding in this structure (the "padding" member is 16
234 // bits but this then gets padded to 32 bits). We want to be sure not to
235 // leak data to the untrusted plugin, so zero everything out first.
236 NaClMessageHeader header;
237 memset(&header, 0, sizeof(NaClMessageHeader));
238
239 header.payload_size = message.payload_size();
240 header.routing = message.routing_id();
241 header.type = message.type();
242 header.flags = message.flags();
243 header.num_fds = 0; // TODO(brettw) hook this up.
244
245 scoped_refptr<RewrittenMessage> dest(new RewrittenMessage);
246 dest->SetData(header, message.payload(), message.payload_size());
247 locked_data_.to_be_received_.push(dest);
248 }
249 cond_var_.Signal();
250 return true;
251 }
252
253 void NaClIPCAdapter::OnChannelConnected(int32 peer_pid) {
254 }
255
256 void NaClIPCAdapter::OnChannelError() {
257 CloseChannel();
258 }
259
260 int NaClIPCAdapter::LockedReceive(char* output_buffer, int output_buffer_size) {
261 lock_.AssertAcquired();
262
263 if (locked_data_.to_be_received_.empty())
264 return 0;
265 scoped_refptr<RewrittenMessage> current =
266 locked_data_.to_be_received_.front();
267
268 int retval = current->Read(output_buffer, output_buffer_size);
269
270 // When a message is entirely consumed, remove if from the waiting queue.
271 if (current->is_consumed())
272 locked_data_.to_be_received_.pop();
273 return retval;
274 }
275
276 bool NaClIPCAdapter::SendCompleteMessage(const char* buffer,
277 size_t buffer_len) {
278
bbudge 2012/03/27 18:38:37 Extra line?
279 // The message will have already been validated, so we know it's large enough
280 // for our header.
281 const NaClMessageHeader* header =
282 reinterpret_cast<const NaClMessageHeader*>(buffer);
283
284 // Length of the message not including the body. The data passed to us by the
285 // plugin should match that in the message header. This should have already
286 // been validated by GetBufferStatus.
287 int body_len = buffer_len - sizeof(NaClMessageHeader);
288 DCHECK(body_len == static_cast<int>(header->payload_size));
289
290 // We actually discard the flags and only copy the ones we care about. This
291 // is just because message doesn't have a constructor that takes raw flags.
292 scoped_ptr<IPC::Message> msg(
293 new IPC::Message(header->routing, header->type,
294 IPC::Message::PRIORITY_NORMAL));
295 if (header->flags & IPC::Message::SYNC_BIT)
296 msg->set_sync();
297 if (header->flags & IPC::Message::REPLY_BIT)
298 msg->set_reply();
299 if (header->flags & IPC::Message::REPLY_ERROR_BIT)
300 msg->set_reply_error();
301 if (header->flags & IPC::Message::UNBLOCK_BIT)
302 msg->set_unblock(true);
303
304 msg->WriteBytes(&buffer[sizeof(NaClMessageHeader)], body_len);
305
306 // Technically we didn't have to do any of the previous work in the lock. But
307 // sometimes our buffer will point to the to_be_sent_ string which is
308 // protected by the lock, and it's messier to factor Send() such that it can
309 // unlock for us. Holding the lock for the message construction, which is
310 // just some memcpys, shouldn't be a big deal.
311 lock_.AssertAcquired();
312 if (locked_data_.channel_closed_)
313 return false; // TODO(brettw) clean up handles here when we add support!
314
315 // Actual send must be done on the I/O thread.
316 task_runner_->PostTask(FROM_HERE,
317 base::Bind(&NaClIPCAdapter::SendMessageOnIOThread, this,
318 base::Passed(&msg)));
319 return true;
320 }
321
322 void NaClIPCAdapter::CloseChannelOnIOThread() {
323 io_thread_data_.channel_->Close();
324 }
325
326 void NaClIPCAdapter::SendMessageOnIOThread(scoped_ptr<IPC::Message> message) {
327 io_thread_data_.channel_->Send(message.release());
328 }
329
330 void NaClIPCAdapter::ClearToBeSent() {
331 lock_.AssertAcquired();
332
333 // Don't let the string keep its buffer behind our back.
334 std::string empty;
335 locked_data_.to_be_sent_.swap(empty);
336 }
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698