Upstream version 5.34.92.0
[platform/framework/web/crosswalk.git] / src / mojo / system / local_data_pipe.cc
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.
4
5 // TODO(vtl): I currently potentially overflow in doing index calculations.
6 // E.g., |start_index_| and |current_num_bytes_| fit into a |uint32_t|, but
7 // their sum may not. This is bad and poses a security risk. (We're currently
8 // saved by the limit on capacity -- the maximum size of the buffer, checked in
9 // |DataPipe::ValidateOptions()|, is currently sufficiently small.
10
11 #include "mojo/system/local_data_pipe.h"
12
13 #include <string.h>
14
15 #include <algorithm>
16
17 #include "base/logging.h"
18 #include "mojo/system/constants.h"
19
20 namespace mojo {
21 namespace system {
22
23 LocalDataPipe::LocalDataPipe(const MojoCreateDataPipeOptions& options)
24     : DataPipe(true, true, options),
25       start_index_(0),
26       current_num_bytes_(0) {
27   // Note: |buffer_| is lazily allocated, since a common case will be that one
28   // of the handles is immediately passed off to another process.
29 }
30
31 LocalDataPipe::~LocalDataPipe() {
32 }
33
34 void LocalDataPipe::ProducerCloseImplNoLock() {
35   // If the consumer is still open and we still have data, we have to keep the
36   // buffer around. Currently, we won't free it even if it empties later. (We
37   // could do this -- requiring a check on every read -- but that seems to be
38   // optimizing for the uncommon case.)
39   if (!consumer_open_no_lock() || !current_num_bytes_) {
40     // Note: There can only be a two-phase *read* (by the consumer) if we still
41     // have data.
42     DCHECK(!consumer_in_two_phase_read_no_lock());
43     DestroyBufferNoLock();
44   }
45 }
46
47 MojoResult LocalDataPipe::ProducerWriteDataImplNoLock(const void* elements,
48                                                       uint32_t* num_bytes,
49                                                       bool all_or_none) {
50   DCHECK_EQ(*num_bytes % element_num_bytes(), 0u);
51   DCHECK_GT(*num_bytes, 0u);
52   DCHECK(consumer_open_no_lock());
53
54   size_t num_bytes_to_write = 0;
55   if (may_discard()) {
56     if (all_or_none && *num_bytes > capacity_num_bytes())
57       return MOJO_RESULT_OUT_OF_RANGE;
58
59     num_bytes_to_write = std::min(static_cast<size_t>(*num_bytes),
60                                   capacity_num_bytes());
61     if (num_bytes_to_write > capacity_num_bytes() - current_num_bytes_) {
62       // Discard as much as needed (discard oldest first).
63       MarkDataAsConsumedNoLock(
64           num_bytes_to_write - (capacity_num_bytes() - current_num_bytes_));
65       // No need to wake up write waiters, since we're definitely going to leave
66       // the buffer full.
67     }
68   } else {
69     if (all_or_none && *num_bytes > capacity_num_bytes() - current_num_bytes_) {
70       // Don't return "should wait" since you can't wait for a specified amount
71       // of data.
72       return MOJO_RESULT_OUT_OF_RANGE;
73     }
74
75     num_bytes_to_write = std::min(static_cast<size_t>(*num_bytes),
76                                   capacity_num_bytes() - current_num_bytes_);
77   }
78   if (num_bytes_to_write == 0)
79     return MOJO_RESULT_SHOULD_WAIT;
80
81   // The amount we can write in our first |memcpy()|.
82   size_t num_bytes_to_write_first =
83       std::min(num_bytes_to_write, GetMaxNumBytesToWriteNoLock());
84   // Do the first (and possibly only) |memcpy()|.
85   size_t first_write_index =
86       (start_index_ + current_num_bytes_) % capacity_num_bytes();
87   EnsureBufferNoLock();
88   memcpy(buffer_.get() + first_write_index, elements, num_bytes_to_write_first);
89
90   if (num_bytes_to_write_first < num_bytes_to_write) {
91     // The "second write index" is zero.
92     memcpy(buffer_.get(),
93            static_cast<const char*>(elements) + num_bytes_to_write_first,
94            num_bytes_to_write - num_bytes_to_write_first);
95   }
96
97   current_num_bytes_ += num_bytes_to_write;
98   DCHECK_LE(current_num_bytes_, capacity_num_bytes());
99   *num_bytes = static_cast<uint32_t>(num_bytes_to_write);
100   return MOJO_RESULT_OK;
101 }
102
103 MojoResult LocalDataPipe::ProducerBeginWriteDataImplNoLock(
104     void** buffer,
105     uint32_t* buffer_num_bytes,
106     bool all_or_none) {
107   DCHECK(consumer_open_no_lock());
108
109   // The index we need to start writing at.
110   size_t write_index =
111       (start_index_ + current_num_bytes_) % capacity_num_bytes();
112
113   size_t max_num_bytes_to_write = GetMaxNumBytesToWriteNoLock();
114   if (all_or_none && *buffer_num_bytes > max_num_bytes_to_write) {
115     // In "may discard" mode, we can always write from the write index to the
116     // end of the buffer.
117     if (may_discard() &&
118         *buffer_num_bytes <= capacity_num_bytes() - write_index) {
119       // To do so, we need to discard an appropriate amount of data.
120       // We should only reach here if the start index is after the write index!
121       DCHECK_GE(start_index_, write_index);
122       DCHECK_GT(*buffer_num_bytes - max_num_bytes_to_write, 0u);
123       MarkDataAsConsumedNoLock(*buffer_num_bytes - max_num_bytes_to_write);
124       max_num_bytes_to_write = *buffer_num_bytes;
125     } else {
126       // Don't return "should wait" since you can't wait for a specified amount
127       // of data.
128       return MOJO_RESULT_OUT_OF_RANGE;
129     }
130   }
131
132   // Don't go into a two-phase write if there's no room.
133   if (max_num_bytes_to_write == 0)
134     return MOJO_RESULT_SHOULD_WAIT;
135
136   EnsureBufferNoLock();
137   *buffer = buffer_.get() + write_index;
138   *buffer_num_bytes = static_cast<uint32_t>(max_num_bytes_to_write);
139   set_producer_two_phase_max_num_bytes_written_no_lock(
140       static_cast<uint32_t>(max_num_bytes_to_write));
141   return MOJO_RESULT_OK;
142 }
143
144 MojoResult LocalDataPipe::ProducerEndWriteDataImplNoLock(
145     uint32_t num_bytes_written) {
146   DCHECK_LE(num_bytes_written,
147             producer_two_phase_max_num_bytes_written_no_lock());
148   current_num_bytes_ += num_bytes_written;
149   DCHECK_LE(current_num_bytes_, capacity_num_bytes());
150   set_producer_two_phase_max_num_bytes_written_no_lock(0);
151   return MOJO_RESULT_OK;
152 }
153
154 MojoWaitFlags LocalDataPipe::ProducerSatisfiedFlagsNoLock() {
155   MojoWaitFlags rv = MOJO_WAIT_FLAG_NONE;
156   if (consumer_open_no_lock() &&
157       (may_discard() || current_num_bytes_ < capacity_num_bytes()) &&
158       !producer_in_two_phase_write_no_lock())
159     rv |= MOJO_WAIT_FLAG_WRITABLE;
160   return rv;
161 }
162
163 MojoWaitFlags LocalDataPipe::ProducerSatisfiableFlagsNoLock() {
164   MojoWaitFlags rv = MOJO_WAIT_FLAG_NONE;
165   if (consumer_open_no_lock())
166     rv |= MOJO_WAIT_FLAG_WRITABLE;
167   return rv;
168 }
169
170 void LocalDataPipe::ConsumerCloseImplNoLock() {
171   // If the producer is around and in a two-phase write, we have to keep the
172   // buffer around. (We then don't free it until the producer is closed. This
173   // could be rectified, but again seems like optimizing for the uncommon case.)
174   if (!producer_open_no_lock() || !producer_in_two_phase_write_no_lock())
175     DestroyBufferNoLock();
176   current_num_bytes_ = 0;
177 }
178
179 MojoResult LocalDataPipe::ConsumerReadDataImplNoLock(void* elements,
180                                                      uint32_t* num_bytes,
181                                                      bool all_or_none) {
182   DCHECK_EQ(*num_bytes % element_num_bytes(), 0u);
183   DCHECK_GT(*num_bytes, 0u);
184
185   if (all_or_none && *num_bytes > current_num_bytes_) {
186     // Don't return "should wait" since you can't wait for a specified amount of
187     // data.
188     return producer_open_no_lock() ? MOJO_RESULT_OUT_OF_RANGE :
189                                      MOJO_RESULT_FAILED_PRECONDITION;
190   }
191
192   size_t num_bytes_to_read =
193       std::min(static_cast<size_t>(*num_bytes), current_num_bytes_);
194   if (num_bytes_to_read == 0) {
195     return producer_open_no_lock() ? MOJO_RESULT_SHOULD_WAIT :
196                                      MOJO_RESULT_FAILED_PRECONDITION;
197   }
198
199   // The amount we can read in our first |memcpy()|.
200   size_t num_bytes_to_read_first =
201       std::min(num_bytes_to_read, GetMaxNumBytesToReadNoLock());
202   memcpy(elements, buffer_.get() + start_index_, num_bytes_to_read_first);
203
204   if (num_bytes_to_read_first < num_bytes_to_read) {
205     // The "second read index" is zero.
206     memcpy(static_cast<char*>(elements) + num_bytes_to_read_first,
207            buffer_.get(),
208            num_bytes_to_read - num_bytes_to_read_first);
209   }
210
211   MarkDataAsConsumedNoLock(num_bytes_to_read);
212   *num_bytes = static_cast<uint32_t>(num_bytes_to_read);
213   return MOJO_RESULT_OK;
214 }
215
216 MojoResult LocalDataPipe::ConsumerDiscardDataImplNoLock(uint32_t* num_bytes,
217                                                         bool all_or_none) {
218   DCHECK_EQ(*num_bytes % element_num_bytes(), 0u);
219   DCHECK_GT(*num_bytes, 0u);
220
221   if (all_or_none && *num_bytes > current_num_bytes_) {
222     // Don't return "should wait" since you can't wait for a specified amount of
223     // data.
224     return producer_open_no_lock() ? MOJO_RESULT_OUT_OF_RANGE :
225                                      MOJO_RESULT_FAILED_PRECONDITION;
226   }
227
228   // Be consistent with other operations; error if no data available.
229   if (current_num_bytes_ == 0) {
230     return producer_open_no_lock() ? MOJO_RESULT_SHOULD_WAIT :
231                                      MOJO_RESULT_FAILED_PRECONDITION;
232   }
233
234   size_t num_bytes_to_discard =
235       std::min(static_cast<size_t>(*num_bytes), current_num_bytes_);
236   MarkDataAsConsumedNoLock(num_bytes_to_discard);
237   *num_bytes = static_cast<uint32_t>(num_bytes_to_discard);
238   return MOJO_RESULT_OK;
239 }
240
241 MojoResult LocalDataPipe::ConsumerQueryDataImplNoLock(uint32_t* num_bytes) {
242   // Note: This cast is safe, since the capacity fits into a |uint32_t|.
243   *num_bytes = static_cast<uint32_t>(current_num_bytes_);
244   return MOJO_RESULT_OK;
245 }
246
247 MojoResult LocalDataPipe::ConsumerBeginReadDataImplNoLock(
248     const void** buffer,
249     uint32_t* buffer_num_bytes,
250     bool all_or_none) {
251   size_t max_num_bytes_to_read = GetMaxNumBytesToReadNoLock();
252   if (all_or_none && *buffer_num_bytes > max_num_bytes_to_read) {
253     // Don't return "should wait" since you can't wait for a specified amount of
254     // data.
255     return producer_open_no_lock() ? MOJO_RESULT_OUT_OF_RANGE :
256                                      MOJO_RESULT_FAILED_PRECONDITION;
257   }
258
259   // Don't go into a two-phase read if there's no data.
260   if (max_num_bytes_to_read == 0) {
261     return producer_open_no_lock() ? MOJO_RESULT_SHOULD_WAIT :
262                                      MOJO_RESULT_FAILED_PRECONDITION;
263   }
264
265   *buffer = buffer_.get() + start_index_;
266   *buffer_num_bytes = static_cast<uint32_t>(max_num_bytes_to_read);
267   set_consumer_two_phase_max_num_bytes_read_no_lock(
268       static_cast<uint32_t>(max_num_bytes_to_read));
269   return MOJO_RESULT_OK;
270 }
271
272 MojoResult LocalDataPipe::ConsumerEndReadDataImplNoLock(
273     uint32_t num_bytes_read) {
274   DCHECK_LE(num_bytes_read, consumer_two_phase_max_num_bytes_read_no_lock());
275   DCHECK_LE(start_index_ + num_bytes_read, capacity_num_bytes());
276   MarkDataAsConsumedNoLock(num_bytes_read);
277   set_consumer_two_phase_max_num_bytes_read_no_lock(0);
278   return MOJO_RESULT_OK;
279 }
280
281 MojoWaitFlags LocalDataPipe::ConsumerSatisfiedFlagsNoLock() {
282   MojoWaitFlags rv = MOJO_WAIT_FLAG_NONE;
283   if (current_num_bytes_ > 0 && !consumer_in_two_phase_read_no_lock())
284     rv |= MOJO_WAIT_FLAG_READABLE;
285   return rv;
286 }
287
288 MojoWaitFlags LocalDataPipe::ConsumerSatisfiableFlagsNoLock() {
289   MojoWaitFlags rv = MOJO_WAIT_FLAG_NONE;
290   if (current_num_bytes_ > 0 || producer_open_no_lock())
291     rv |= MOJO_WAIT_FLAG_READABLE;
292   return rv;
293 }
294
295 void LocalDataPipe::EnsureBufferNoLock() {
296   DCHECK(producer_open_no_lock());
297   if (buffer_.get())
298     return;
299   buffer_.reset(static_cast<char*>(
300       base::AlignedAlloc(capacity_num_bytes(), kDataPipeBufferAlignmentBytes)));
301 }
302
303 void LocalDataPipe::DestroyBufferNoLock() {
304 #ifndef NDEBUG
305   // Scribble on the buffer to help detect use-after-frees. (This also helps the
306   // unit test detect certain bugs without needing ASAN or similar.)
307   if (buffer_.get())
308     memset(buffer_.get(), 0xcd, capacity_num_bytes());
309 #endif
310   buffer_.reset();
311 }
312
313 size_t LocalDataPipe::GetMaxNumBytesToWriteNoLock() {
314   size_t next_index = start_index_ + current_num_bytes_;
315   if (next_index >= capacity_num_bytes()) {
316     next_index %= capacity_num_bytes();
317     DCHECK_GE(start_index_, next_index);
318     DCHECK_EQ(start_index_ - next_index,
319               capacity_num_bytes() - current_num_bytes_);
320     return start_index_ - next_index;
321   }
322   return capacity_num_bytes() - next_index;
323 }
324
325 size_t LocalDataPipe::GetMaxNumBytesToReadNoLock() {
326   if (start_index_ + current_num_bytes_ > capacity_num_bytes())
327     return capacity_num_bytes() - start_index_;
328   return current_num_bytes_;
329 }
330
331 void LocalDataPipe::MarkDataAsConsumedNoLock(size_t num_bytes) {
332   DCHECK_LE(num_bytes, current_num_bytes_);
333   start_index_ += num_bytes;
334   start_index_ %= capacity_num_bytes();
335   current_num_bytes_ -= num_bytes;
336 }
337
338 }  // namespace system
339 }  // namespace mojo