Upstream version 11.40.277.0
[platform/framework/web/crosswalk.git] / src / third_party / WebKit / Source / platform / SharedBuffer.cpp
1 /*
2  * Copyright (C) 2006, 2008 Apple Inc. All rights reserved.
3  * Copyright (C) Research In Motion Limited 2009-2010. All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
15  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
17  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
18  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
19  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
20  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
21  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
22  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
24  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  */
26
27 #include "config.h"
28 #include "platform/SharedBuffer.h"
29
30 #include "wtf/unicode/Unicode.h"
31 #include "wtf/unicode/UTF8.h"
32
33 #undef SHARED_BUFFER_STATS
34
35 #ifdef SHARED_BUFFER_STATS
36 #include "wtf/DataLog.h"
37 #include "wtf/MainThread.h"
38 #endif
39
40 namespace blink {
41
42 static const unsigned segmentSize = 0x1000;
43 static const unsigned segmentPositionMask = 0x0FFF;
44
45 static inline unsigned segmentIndex(unsigned position)
46 {
47     return position / segmentSize;
48 }
49
50 static inline unsigned offsetInSegment(unsigned position)
51 {
52     return position & segmentPositionMask;
53 }
54
55 static inline char* allocateSegment()
56 {
57     return static_cast<char*>(fastMalloc(segmentSize));
58 }
59
60 static inline void freeSegment(char* p)
61 {
62     fastFree(p);
63 }
64
65 #ifdef SHARED_BUFFER_STATS
66
67 static Mutex& statsMutex()
68 {
69     DEFINE_STATIC_LOCAL(Mutex, mutex, ());
70     return mutex;
71 }
72
73 static HashSet<SharedBuffer*>& liveBuffers()
74 {
75     DEFINE_STATIC_LOCAL(HashSet<SharedBuffer*>, buffers, ());
76     return buffers;
77 }
78
79 static bool sizeComparator(SharedBuffer* a, SharedBuffer* b)
80 {
81     return a->size() > b->size();
82 }
83
84 static CString snippetForBuffer(SharedBuffer* sharedBuffer)
85 {
86     const unsigned kMaxSnippetLength = 64;
87     char* snippet = 0;
88     unsigned snippetLength = std::min(sharedBuffer->size(), kMaxSnippetLength);
89     CString result = CString::newUninitialized(snippetLength, snippet);
90
91     const char* segment;
92     unsigned offset = 0;
93     while (unsigned segmentLength = sharedBuffer->getSomeData(segment, offset)) {
94         unsigned length = std::min(segmentLength, snippetLength - offset);
95         memcpy(snippet + offset, segment, length);
96         offset += segmentLength;
97         if (offset >= snippetLength)
98             break;
99     }
100
101     for (unsigned i = 0; i < snippetLength; ++i) {
102         if (!isASCIIPrintable(snippet[i]))
103             snippet[i] = '?';
104     }
105
106     return result;
107 }
108
109 static void printStats(void*)
110 {
111     MutexLocker locker(statsMutex());
112     Vector<SharedBuffer*> buffers;
113     for (HashSet<SharedBuffer*>::const_iterator iter = liveBuffers().begin(); iter != liveBuffers().end(); ++iter)
114         buffers.append(*iter);
115     std::sort(buffers.begin(), buffers.end(), sizeComparator);
116
117     dataLogF("---- Shared Buffer Stats ----\n");
118     for (size_t i = 0; i < buffers.size() && i < 64; ++i) {
119         CString snippet = snippetForBuffer(buffers[i]);
120         dataLogF("Buffer size=%8u %s\n", buffers[i]->size(), snippet.data());
121     }
122 }
123
124 static void didCreateSharedBuffer(SharedBuffer* buffer)
125 {
126     MutexLocker locker(statsMutex());
127     liveBuffers().add(buffer);
128
129     callOnMainThread(printStats, 0);
130 }
131
132 static void willDestroySharedBuffer(SharedBuffer* buffer)
133 {
134     MutexLocker locker(statsMutex());
135     liveBuffers().remove(buffer);
136 }
137
138 #endif
139
140 SharedBuffer::SharedBuffer()
141     : m_size(0)
142     , m_buffer(PurgeableVector::NotPurgeable)
143 {
144 #ifdef SHARED_BUFFER_STATS
145     didCreateSharedBuffer(this);
146 #endif
147 }
148
149 SharedBuffer::SharedBuffer(size_t size)
150     : m_size(size)
151     , m_buffer(PurgeableVector::NotPurgeable)
152 {
153     m_buffer.reserveCapacity(size);
154     m_buffer.grow(size);
155 #ifdef SHARED_BUFFER_STATS
156     didCreateSharedBuffer(this);
157 #endif
158 }
159
160 SharedBuffer::SharedBuffer(const char* data, int size)
161     : m_size(0)
162     , m_buffer(PurgeableVector::NotPurgeable)
163 {
164     // FIXME: Use unsigned consistently, and check for invalid casts when calling into SharedBuffer from other code.
165     if (size < 0)
166         CRASH();
167
168     append(data, size);
169
170 #ifdef SHARED_BUFFER_STATS
171     didCreateSharedBuffer(this);
172 #endif
173 }
174
175 SharedBuffer::SharedBuffer(const char* data, unsigned size, PurgeableVector::PurgeableOption purgeable)
176     : m_size(0)
177     , m_buffer(purgeable)
178 {
179     append(data, size);
180
181 #ifdef SHARED_BUFFER_STATS
182     didCreateSharedBuffer(this);
183 #endif
184 }
185
186 SharedBuffer::SharedBuffer(const unsigned char* data, int size)
187     : m_size(0)
188     , m_buffer(PurgeableVector::NotPurgeable)
189 {
190     // FIXME: Use unsigned consistently, and check for invalid casts when calling into SharedBuffer from other code.
191     if (size < 0)
192         CRASH();
193
194     append(reinterpret_cast<const char*>(data), size);
195
196 #ifdef SHARED_BUFFER_STATS
197     didCreateSharedBuffer(this);
198 #endif
199 }
200
201 SharedBuffer::~SharedBuffer()
202 {
203     clear();
204
205 #ifdef SHARED_BUFFER_STATS
206     willDestroySharedBuffer(this);
207 #endif
208 }
209
210 PassRefPtr<SharedBuffer> SharedBuffer::adoptVector(Vector<char>& vector)
211 {
212     RefPtr<SharedBuffer> buffer = create();
213     buffer->m_buffer.adopt(vector);
214     buffer->m_size = buffer->m_buffer.size();
215     return buffer.release();
216 }
217
218 unsigned SharedBuffer::size() const
219 {
220     return m_size;
221 }
222
223 const char* SharedBuffer::data() const
224 {
225     mergeSegmentsIntoBuffer();
226     return m_buffer.data();
227 }
228
229 void SharedBuffer::append(PassRefPtr<SharedBuffer> data)
230 {
231     const char* segment;
232     size_t position = 0;
233     while (size_t length = data->getSomeData(segment, position)) {
234         append(segment, length);
235         position += length;
236     }
237 }
238
239 void SharedBuffer::append(const char* data, unsigned length)
240 {
241     ASSERT(isLocked());
242     if (!length)
243         return;
244
245     ASSERT(m_size >= m_buffer.size());
246     unsigned positionInSegment = offsetInSegment(m_size - m_buffer.size());
247     m_size += length;
248
249     if (m_size <= segmentSize) {
250         // No need to use segments for small resource data.
251         m_buffer.append(data, length);
252         return;
253     }
254
255     char* segment;
256     if (!positionInSegment) {
257         segment = allocateSegment();
258         m_segments.append(segment);
259     } else
260         segment = m_segments.last() + positionInSegment;
261
262     unsigned segmentFreeSpace = segmentSize - positionInSegment;
263     unsigned bytesToCopy = std::min(length, segmentFreeSpace);
264
265     for (;;) {
266         memcpy(segment, data, bytesToCopy);
267         if (static_cast<unsigned>(length) == bytesToCopy)
268             break;
269
270         length -= bytesToCopy;
271         data += bytesToCopy;
272         segment = allocateSegment();
273         m_segments.append(segment);
274         bytesToCopy = std::min(length, segmentSize);
275     }
276 }
277
278 void SharedBuffer::append(const Vector<char>& data)
279 {
280     append(data.data(), data.size());
281 }
282
283 void SharedBuffer::clear()
284 {
285     for (unsigned i = 0; i < m_segments.size(); ++i)
286         freeSegment(m_segments[i]);
287
288     m_segments.clear();
289     m_size = 0;
290     m_buffer.clear();
291 }
292
293 PassRefPtr<SharedBuffer> SharedBuffer::copy() const
294 {
295     RefPtr<SharedBuffer> clone(adoptRef(new SharedBuffer));
296     clone->m_size = m_size;
297     clone->m_buffer.reserveCapacity(m_size);
298     clone->m_buffer.append(m_buffer.data(), m_buffer.size());
299     if (!m_segments.isEmpty()) {
300         const char* segment = 0;
301         unsigned position = m_buffer.size();
302         while (unsigned segmentSize = getSomeData(segment, position)) {
303             clone->m_buffer.append(segment, segmentSize);
304             position += segmentSize;
305         }
306         ASSERT(position == clone->size());
307     }
308     return clone.release();
309 }
310
311 void SharedBuffer::mergeSegmentsIntoBuffer() const
312 {
313     unsigned bufferSize = m_buffer.size();
314     if (m_size > bufferSize) {
315         m_buffer.reserveCapacity(m_size);
316         unsigned bytesLeft = m_size - bufferSize;
317         for (unsigned i = 0; i < m_segments.size(); ++i) {
318             unsigned bytesToCopy = std::min(bytesLeft, segmentSize);
319             m_buffer.append(m_segments[i], bytesToCopy);
320             bytesLeft -= bytesToCopy;
321             freeSegment(m_segments[i]);
322         }
323         m_segments.clear();
324     }
325 }
326
327 unsigned SharedBuffer::getSomeData(const char*& someData, unsigned position) const
328 {
329     ASSERT(isLocked());
330     unsigned totalSize = size();
331     if (position >= totalSize) {
332         someData = 0;
333         return 0;
334     }
335
336     ASSERT_WITH_SECURITY_IMPLICATION(position < m_size);
337     unsigned consecutiveSize = m_buffer.size();
338     if (position < consecutiveSize) {
339         someData = m_buffer.data() + position;
340         return consecutiveSize - position;
341     }
342
343     position -= consecutiveSize;
344     unsigned segments = m_segments.size();
345     unsigned maxSegmentedSize = segments * segmentSize;
346     unsigned segment = segmentIndex(position);
347     if (segment < segments) {
348         unsigned bytesLeft = totalSize - consecutiveSize;
349         unsigned segmentedSize = std::min(maxSegmentedSize, bytesLeft);
350
351         unsigned positionInSegment = offsetInSegment(position);
352         someData = m_segments[segment] + positionInSegment;
353         return segment == segments - 1 ? segmentedSize - position : segmentSize - positionInSegment;
354     }
355     ASSERT_NOT_REACHED();
356     return 0;
357 }
358
359 PassRefPtr<ArrayBuffer> SharedBuffer::getAsArrayBuffer() const
360 {
361     RefPtr<ArrayBuffer> arrayBuffer = ArrayBuffer::createUninitialized(static_cast<unsigned>(size()), 1);
362
363     if (!arrayBuffer)
364         return nullptr;
365
366     const char* segment = 0;
367     unsigned position = 0;
368     while (unsigned segmentSize = getSomeData(segment, position)) {
369         memcpy(static_cast<char*>(arrayBuffer->data()) + position, segment, segmentSize);
370         position += segmentSize;
371     }
372
373     if (position != arrayBuffer->byteLength()) {
374         ASSERT_NOT_REACHED();
375         // Don't return the incomplete ArrayBuffer.
376         return nullptr;
377     }
378
379     return arrayBuffer;
380 }
381
382 PassRefPtr<SkData> SharedBuffer::getAsSkData() const
383 {
384     unsigned bufferLength = size();
385     SkData* data = SkData::NewUninitialized(bufferLength);
386     char* buffer = static_cast<char*>(data->writable_data());
387     const char* segment = 0;
388     unsigned position = 0;
389     while (unsigned segmentSize = getSomeData(segment, position)) {
390         memcpy(buffer + position, segment, segmentSize);
391         position += segmentSize;
392     }
393
394     if (position != bufferLength) {
395         ASSERT_NOT_REACHED();
396         // Don't return the incomplete SkData.
397         return nullptr;
398     }
399     return adoptRef(data);
400 }
401
402 bool SharedBuffer::lock()
403 {
404     return m_buffer.lock();
405 }
406
407 void SharedBuffer::unlock()
408 {
409     mergeSegmentsIntoBuffer();
410     m_buffer.unlock();
411 }
412
413 bool SharedBuffer::isLocked() const
414 {
415     return m_buffer.isLocked();
416 }
417
418 } // namespace blink