]> git.saurik.com Git - apple/javascriptcore.git/blob - runtime/JSArray.cpp
6bc316363ad3ee98dd6c969a4be1a7c32115579b
[apple/javascriptcore.git] / runtime / JSArray.cpp
1 /*
2 * Copyright (C) 1999-2000 Harri Porten (porten@kde.org)
3 * Copyright (C) 2003, 2007, 2008, 2009 Apple Inc. All rights reserved.
4 * Copyright (C) 2003 Peter Kelly (pmk@post.com)
5 * Copyright (C) 2006 Alexey Proskuryakov (ap@nypop.com)
6 *
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2 of the License, or (at your option) any later version.
11 *
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
16 *
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20 *
21 */
22
23 #include "config.h"
24 #include "JSArray.h"
25
26 #include "ArrayPrototype.h"
27 #include "CachedCall.h"
28 #include "Error.h"
29 #include "Executable.h"
30 #include "PropertyNameArray.h"
31 #include <wtf/AVLTree.h>
32 #include <wtf/Assertions.h>
33 #include <wtf/OwnPtr.h>
34 #include <Operations.h>
35
36 using namespace std;
37 using namespace WTF;
38
39 namespace JSC {
40
41 ASSERT_CLASS_FITS_IN_CELL(JSArray);
42
43 // Overview of JSArray
44 //
45 // Properties of JSArray objects may be stored in one of three locations:
46 // * The regular JSObject property map.
47 // * A storage vector.
48 // * A sparse map of array entries.
49 //
50 // Properties with non-numeric identifiers, with identifiers that are not representable
51 // as an unsigned integer, or where the value is greater than MAX_ARRAY_INDEX
52 // (specifically, this is only one property - the value 0xFFFFFFFFU as an unsigned 32-bit
53 // integer) are not considered array indices and will be stored in the JSObject property map.
54 //
55 // All properties with a numeric identifer, representable as an unsigned integer i,
56 // where (i <= MAX_ARRAY_INDEX), are an array index and will be stored in either the
57 // storage vector or the sparse map. An array index i will be handled in the following
58 // fashion:
59 //
60 // * Where (i < MIN_SPARSE_ARRAY_INDEX) the value will be stored in the storage vector.
61 // * Where (MIN_SPARSE_ARRAY_INDEX <= i <= MAX_STORAGE_VECTOR_INDEX) the value will either
62 // be stored in the storage vector or in the sparse array, depending on the density of
63 // data that would be stored in the vector (a vector being used where at least
64 // (1 / minDensityMultiplier) of the entries would be populated).
65 // * Where (MAX_STORAGE_VECTOR_INDEX < i <= MAX_ARRAY_INDEX) the value will always be stored
66 // in the sparse array.
67
68 // The definition of MAX_STORAGE_VECTOR_LENGTH is dependant on the definition storageSize
69 // function below - the MAX_STORAGE_VECTOR_LENGTH limit is defined such that the storage
70 // size calculation cannot overflow. (sizeof(ArrayStorage) - sizeof(JSValue)) +
71 // (vectorLength * sizeof(JSValue)) must be <= 0xFFFFFFFFU (which is maximum value of size_t).
72 #define MAX_STORAGE_VECTOR_LENGTH static_cast<unsigned>((0xFFFFFFFFU - (sizeof(ArrayStorage) - sizeof(JSValue))) / sizeof(JSValue))
73
74 // These values have to be macros to be used in max() and min() without introducing
75 // a PIC branch in Mach-O binaries, see <rdar://problem/5971391>.
76 #define MIN_SPARSE_ARRAY_INDEX 10000U
77 #define MAX_STORAGE_VECTOR_INDEX (MAX_STORAGE_VECTOR_LENGTH - 1)
78 // 0xFFFFFFFF is a bit weird -- is not an array index even though it's an integer.
79 #define MAX_ARRAY_INDEX 0xFFFFFFFEU
80
81 // The value BASE_VECTOR_LEN is the maximum number of vector elements we'll allocate
82 // for an array that was created with a sepcified length (e.g. a = new Array(123))
83 #define BASE_VECTOR_LEN 4U
84
85 // The upper bound to the size we'll grow a zero length array when the first element
86 // is added.
87 #define FIRST_VECTOR_GROW 4U
88
89 // Our policy for when to use a vector and when to use a sparse map.
90 // For all array indices under MIN_SPARSE_ARRAY_INDEX, we always use a vector.
91 // When indices greater than MIN_SPARSE_ARRAY_INDEX are involved, we use a vector
92 // as long as it is 1/8 full. If more sparse than that, we use a map.
93 static const unsigned minDensityMultiplier = 8;
94
95 const ClassInfo JSArray::s_info = {"Array", &JSNonFinalObject::s_info, 0, 0};
96
97 // We keep track of the size of the last array after it was grown. We use this
98 // as a simple heuristic for as the value to grow the next array from size 0.
99 // This value is capped by the constant FIRST_VECTOR_GROW defined above.
100 static unsigned lastArraySize = 0;
101
102 static inline size_t storageSize(unsigned vectorLength)
103 {
104 ASSERT(vectorLength <= MAX_STORAGE_VECTOR_LENGTH);
105
106 // MAX_STORAGE_VECTOR_LENGTH is defined such that provided (vectorLength <= MAX_STORAGE_VECTOR_LENGTH)
107 // - as asserted above - the following calculation cannot overflow.
108 size_t size = (sizeof(ArrayStorage) - sizeof(JSValue)) + (vectorLength * sizeof(JSValue));
109 // Assertion to detect integer overflow in previous calculation (should not be possible, provided that
110 // MAX_STORAGE_VECTOR_LENGTH is correctly defined).
111 ASSERT(((size - (sizeof(ArrayStorage) - sizeof(JSValue))) / sizeof(JSValue) == vectorLength) && (size >= (sizeof(ArrayStorage) - sizeof(JSValue))));
112
113 return size;
114 }
115
116 static inline bool isDenseEnoughForVector(unsigned length, unsigned numValues)
117 {
118 return length / minDensityMultiplier <= numValues;
119 }
120
121 #if !CHECK_ARRAY_CONSISTENCY
122
123 inline void JSArray::checkConsistency(ConsistencyCheckType)
124 {
125 }
126
127 #endif
128
129 JSArray::JSArray(VPtrStealingHackType)
130 : JSNonFinalObject(VPtrStealingHack)
131 {
132 }
133
134 JSArray::JSArray(JSGlobalData& globalData, Structure* structure)
135 : JSNonFinalObject(globalData, structure)
136 {
137 ASSERT(inherits(&s_info));
138
139 unsigned initialCapacity = 0;
140
141 m_storage = static_cast<ArrayStorage*>(fastZeroedMalloc(storageSize(initialCapacity)));
142 m_storage->m_allocBase = m_storage;
143 m_indexBias = 0;
144 m_vectorLength = initialCapacity;
145
146 checkConsistency();
147
148 Heap::heap(this)->reportExtraMemoryCost(storageSize(0));
149 }
150
151 JSArray::JSArray(JSGlobalData& globalData, Structure* structure, unsigned initialLength, ArrayCreationMode creationMode)
152 : JSNonFinalObject(globalData, structure)
153 {
154 ASSERT(inherits(&s_info));
155
156 unsigned initialCapacity;
157 if (creationMode == CreateCompact)
158 initialCapacity = initialLength;
159 else
160 initialCapacity = min(BASE_VECTOR_LEN, MIN_SPARSE_ARRAY_INDEX);
161
162 m_storage = static_cast<ArrayStorage*>(fastMalloc(storageSize(initialCapacity)));
163 m_storage->m_allocBase = m_storage;
164 m_storage->m_length = initialLength;
165 m_indexBias = 0;
166 m_vectorLength = initialCapacity;
167 m_storage->m_sparseValueMap = 0;
168 m_storage->subclassData = 0;
169 m_storage->reportedMapCapacity = 0;
170
171 if (creationMode == CreateCompact) {
172 #if CHECK_ARRAY_CONSISTENCY
173 m_storage->m_inCompactInitialization = !!initialCapacity;
174 #endif
175 m_storage->m_length = 0;
176 m_storage->m_numValuesInVector = initialCapacity;
177 } else {
178 #if CHECK_ARRAY_CONSISTENCY
179 storage->m_inCompactInitialization = false;
180 #endif
181 m_storage->m_length = initialLength;
182 m_storage->m_numValuesInVector = 0;
183 WriteBarrier<Unknown>* vector = m_storage->m_vector;
184 for (size_t i = 0; i < initialCapacity; ++i)
185 vector[i].clear();
186 }
187
188 checkConsistency();
189
190 Heap::heap(this)->reportExtraMemoryCost(storageSize(initialCapacity));
191 }
192
193 JSArray::JSArray(JSGlobalData& globalData, Structure* structure, const ArgList& list)
194 : JSNonFinalObject(globalData, structure)
195 {
196 ASSERT(inherits(&s_info));
197
198 unsigned initialCapacity = list.size();
199 unsigned initialStorage;
200
201 // If the ArgList is empty, allocate space for 3 entries. This value empirically
202 // works well for benchmarks.
203 if (!initialCapacity)
204 initialStorage = 3;
205 else
206 initialStorage = initialCapacity;
207
208 m_storage = static_cast<ArrayStorage*>(fastMalloc(storageSize(initialStorage)));
209 m_storage->m_allocBase = m_storage;
210 m_indexBias = 0;
211 m_storage->m_length = initialCapacity;
212 m_vectorLength = initialStorage;
213 m_storage->m_numValuesInVector = initialCapacity;
214 m_storage->m_sparseValueMap = 0;
215 m_storage->subclassData = 0;
216 m_storage->reportedMapCapacity = 0;
217 #if CHECK_ARRAY_CONSISTENCY
218 m_storage->m_inCompactInitialization = false;
219 #endif
220
221 size_t i = 0;
222 WriteBarrier<Unknown>* vector = m_storage->m_vector;
223 ArgList::const_iterator end = list.end();
224 for (ArgList::const_iterator it = list.begin(); it != end; ++it, ++i)
225 vector[i].set(globalData, this, *it);
226 for (; i < initialStorage; i++)
227 vector[i].clear();
228
229 checkConsistency();
230
231 Heap::heap(this)->reportExtraMemoryCost(storageSize(initialStorage));
232 }
233
234 JSArray::~JSArray()
235 {
236 ASSERT(vptr() == JSGlobalData::jsArrayVPtr);
237 checkConsistency(DestructorConsistencyCheck);
238
239 delete m_storage->m_sparseValueMap;
240 fastFree(m_storage->m_allocBase);
241 }
242
243 bool JSArray::getOwnPropertySlot(ExecState* exec, unsigned i, PropertySlot& slot)
244 {
245 ArrayStorage* storage = m_storage;
246
247 if (i >= storage->m_length) {
248 if (i > MAX_ARRAY_INDEX)
249 return getOwnPropertySlot(exec, Identifier::from(exec, i), slot);
250 return false;
251 }
252
253 if (i < m_vectorLength) {
254 JSValue value = storage->m_vector[i].get();
255 if (value) {
256 slot.setValue(value);
257 return true;
258 }
259 } else if (SparseArrayValueMap* map = storage->m_sparseValueMap) {
260 if (i >= MIN_SPARSE_ARRAY_INDEX) {
261 SparseArrayValueMap::iterator it = map->find(i);
262 if (it != map->end()) {
263 slot.setValue(it->second.get());
264 return true;
265 }
266 }
267 }
268
269 return JSObject::getOwnPropertySlot(exec, Identifier::from(exec, i), slot);
270 }
271
272 bool JSArray::getOwnPropertySlot(ExecState* exec, const Identifier& propertyName, PropertySlot& slot)
273 {
274 if (propertyName == exec->propertyNames().length) {
275 slot.setValue(jsNumber(length()));
276 return true;
277 }
278
279 bool isArrayIndex;
280 unsigned i = propertyName.toArrayIndex(isArrayIndex);
281 if (isArrayIndex)
282 return JSArray::getOwnPropertySlot(exec, i, slot);
283
284 return JSObject::getOwnPropertySlot(exec, propertyName, slot);
285 }
286
287 bool JSArray::getOwnPropertyDescriptor(ExecState* exec, const Identifier& propertyName, PropertyDescriptor& descriptor)
288 {
289 if (propertyName == exec->propertyNames().length) {
290 descriptor.setDescriptor(jsNumber(length()), DontDelete | DontEnum);
291 return true;
292 }
293
294 ArrayStorage* storage = m_storage;
295
296 bool isArrayIndex;
297 unsigned i = propertyName.toArrayIndex(isArrayIndex);
298 if (isArrayIndex) {
299 if (i >= storage->m_length)
300 return false;
301 if (i < m_vectorLength) {
302 WriteBarrier<Unknown>& value = storage->m_vector[i];
303 if (value) {
304 descriptor.setDescriptor(value.get(), 0);
305 return true;
306 }
307 } else if (SparseArrayValueMap* map = storage->m_sparseValueMap) {
308 if (i >= MIN_SPARSE_ARRAY_INDEX) {
309 SparseArrayValueMap::iterator it = map->find(i);
310 if (it != map->end()) {
311 descriptor.setDescriptor(it->second.get(), 0);
312 return true;
313 }
314 }
315 }
316 }
317 return JSObject::getOwnPropertyDescriptor(exec, propertyName, descriptor);
318 }
319
320 // ECMA 15.4.5.1
321 void JSArray::put(ExecState* exec, const Identifier& propertyName, JSValue value, PutPropertySlot& slot)
322 {
323 bool isArrayIndex;
324 unsigned i = propertyName.toArrayIndex(isArrayIndex);
325 if (isArrayIndex) {
326 put(exec, i, value);
327 return;
328 }
329
330 if (propertyName == exec->propertyNames().length) {
331 unsigned newLength = value.toUInt32(exec);
332 if (value.toNumber(exec) != static_cast<double>(newLength)) {
333 throwError(exec, createRangeError(exec, "Invalid array length."));
334 return;
335 }
336 setLength(newLength);
337 return;
338 }
339
340 JSObject::put(exec, propertyName, value, slot);
341 }
342
343 void JSArray::put(ExecState* exec, unsigned i, JSValue value)
344 {
345 checkConsistency();
346
347 ArrayStorage* storage = m_storage;
348
349 unsigned length = storage->m_length;
350 if (i >= length && i <= MAX_ARRAY_INDEX) {
351 length = i + 1;
352 storage->m_length = length;
353 }
354
355 if (i < m_vectorLength) {
356 WriteBarrier<Unknown>& valueSlot = storage->m_vector[i];
357 if (valueSlot) {
358 valueSlot.set(exec->globalData(), this, value);
359 checkConsistency();
360 return;
361 }
362 valueSlot.set(exec->globalData(), this, value);
363 ++storage->m_numValuesInVector;
364 checkConsistency();
365 return;
366 }
367
368 putSlowCase(exec, i, value);
369 }
370
371 NEVER_INLINE void JSArray::putSlowCase(ExecState* exec, unsigned i, JSValue value)
372 {
373 ArrayStorage* storage = m_storage;
374
375 SparseArrayValueMap* map = storage->m_sparseValueMap;
376
377 if (i >= MIN_SPARSE_ARRAY_INDEX) {
378 if (i > MAX_ARRAY_INDEX) {
379 PutPropertySlot slot;
380 put(exec, Identifier::from(exec, i), value, slot);
381 return;
382 }
383
384 // We miss some cases where we could compact the storage, such as a large array that is being filled from the end
385 // (which will only be compacted as we reach indices that are less than MIN_SPARSE_ARRAY_INDEX) - but this makes the check much faster.
386 if ((i > MAX_STORAGE_VECTOR_INDEX) || !isDenseEnoughForVector(i + 1, storage->m_numValuesInVector + 1)) {
387 if (!map) {
388 map = new SparseArrayValueMap;
389 storage->m_sparseValueMap = map;
390 }
391
392 WriteBarrier<Unknown> temp;
393 pair<SparseArrayValueMap::iterator, bool> result = map->add(i, temp);
394 result.first->second.set(exec->globalData(), this, value);
395 if (!result.second) // pre-existing entry
396 return;
397
398 size_t capacity = map->capacity();
399 if (capacity != storage->reportedMapCapacity) {
400 Heap::heap(this)->reportExtraMemoryCost((capacity - storage->reportedMapCapacity) * (sizeof(unsigned) + sizeof(JSValue)));
401 storage->reportedMapCapacity = capacity;
402 }
403 return;
404 }
405 }
406
407 // We have decided that we'll put the new item into the vector.
408 // Fast case is when there is no sparse map, so we can increase the vector size without moving values from it.
409 if (!map || map->isEmpty()) {
410 if (increaseVectorLength(i + 1)) {
411 storage = m_storage;
412 storage->m_vector[i].set(exec->globalData(), this, value);
413 ++storage->m_numValuesInVector;
414 checkConsistency();
415 } else
416 throwOutOfMemoryError(exec);
417 return;
418 }
419
420 // Decide how many values it would be best to move from the map.
421 unsigned newNumValuesInVector = storage->m_numValuesInVector + 1;
422 unsigned newVectorLength = getNewVectorLength(i + 1);
423 for (unsigned j = max(m_vectorLength, MIN_SPARSE_ARRAY_INDEX); j < newVectorLength; ++j)
424 newNumValuesInVector += map->contains(j);
425 if (i >= MIN_SPARSE_ARRAY_INDEX)
426 newNumValuesInVector -= map->contains(i);
427 if (isDenseEnoughForVector(newVectorLength, newNumValuesInVector)) {
428 unsigned needLength = max(i + 1, storage->m_length);
429 unsigned proposedNewNumValuesInVector = newNumValuesInVector;
430 // If newVectorLength is already the maximum - MAX_STORAGE_VECTOR_LENGTH - then do not attempt to grow any further.
431 while ((newVectorLength < needLength) && (newVectorLength < MAX_STORAGE_VECTOR_LENGTH)) {
432 unsigned proposedNewVectorLength = getNewVectorLength(newVectorLength + 1);
433 for (unsigned j = max(newVectorLength, MIN_SPARSE_ARRAY_INDEX); j < proposedNewVectorLength; ++j)
434 proposedNewNumValuesInVector += map->contains(j);
435 if (!isDenseEnoughForVector(proposedNewVectorLength, proposedNewNumValuesInVector))
436 break;
437 newVectorLength = proposedNewVectorLength;
438 newNumValuesInVector = proposedNewNumValuesInVector;
439 }
440 }
441
442 void* baseStorage = storage->m_allocBase;
443
444 if (!tryFastRealloc(baseStorage, storageSize(newVectorLength + m_indexBias)).getValue(baseStorage)) {
445 throwOutOfMemoryError(exec);
446 return;
447 }
448
449 m_storage = reinterpret_cast_ptr<ArrayStorage*>(static_cast<char*>(baseStorage) + m_indexBias * sizeof(JSValue));
450 m_storage->m_allocBase = baseStorage;
451 storage = m_storage;
452
453 unsigned vectorLength = m_vectorLength;
454 WriteBarrier<Unknown>* vector = storage->m_vector;
455
456 if (newNumValuesInVector == storage->m_numValuesInVector + 1) {
457 for (unsigned j = vectorLength; j < newVectorLength; ++j)
458 vector[j].clear();
459 if (i > MIN_SPARSE_ARRAY_INDEX)
460 map->remove(i);
461 } else {
462 for (unsigned j = vectorLength; j < max(vectorLength, MIN_SPARSE_ARRAY_INDEX); ++j)
463 vector[j].clear();
464 JSGlobalData& globalData = exec->globalData();
465 for (unsigned j = max(vectorLength, MIN_SPARSE_ARRAY_INDEX); j < newVectorLength; ++j)
466 vector[j].set(globalData, this, map->take(j).get());
467 }
468
469 ASSERT(i < newVectorLength);
470
471 m_vectorLength = newVectorLength;
472 storage->m_numValuesInVector = newNumValuesInVector;
473
474 storage->m_vector[i].set(exec->globalData(), this, value);
475
476 checkConsistency();
477
478 Heap::heap(this)->reportExtraMemoryCost(storageSize(newVectorLength) - storageSize(vectorLength));
479 }
480
481 bool JSArray::deleteProperty(ExecState* exec, const Identifier& propertyName)
482 {
483 bool isArrayIndex;
484 unsigned i = propertyName.toArrayIndex(isArrayIndex);
485 if (isArrayIndex)
486 return deleteProperty(exec, i);
487
488 if (propertyName == exec->propertyNames().length)
489 return false;
490
491 return JSObject::deleteProperty(exec, propertyName);
492 }
493
494 bool JSArray::deleteProperty(ExecState* exec, unsigned i)
495 {
496 checkConsistency();
497
498 ArrayStorage* storage = m_storage;
499
500 if (i < m_vectorLength) {
501 WriteBarrier<Unknown>& valueSlot = storage->m_vector[i];
502 if (!valueSlot) {
503 checkConsistency();
504 return false;
505 }
506 valueSlot.clear();
507 --storage->m_numValuesInVector;
508 checkConsistency();
509 return true;
510 }
511
512 if (SparseArrayValueMap* map = storage->m_sparseValueMap) {
513 if (i >= MIN_SPARSE_ARRAY_INDEX) {
514 SparseArrayValueMap::iterator it = map->find(i);
515 if (it != map->end()) {
516 map->remove(it);
517 checkConsistency();
518 return true;
519 }
520 }
521 }
522
523 checkConsistency();
524
525 if (i > MAX_ARRAY_INDEX)
526 return deleteProperty(exec, Identifier::from(exec, i));
527
528 return false;
529 }
530
531 void JSArray::getOwnPropertyNames(ExecState* exec, PropertyNameArray& propertyNames, EnumerationMode mode)
532 {
533 // FIXME: Filling PropertyNameArray with an identifier for every integer
534 // is incredibly inefficient for large arrays. We need a different approach,
535 // which almost certainly means a different structure for PropertyNameArray.
536
537 ArrayStorage* storage = m_storage;
538
539 unsigned usedVectorLength = min(storage->m_length, m_vectorLength);
540 for (unsigned i = 0; i < usedVectorLength; ++i) {
541 if (storage->m_vector[i])
542 propertyNames.add(Identifier::from(exec, i));
543 }
544
545 if (SparseArrayValueMap* map = storage->m_sparseValueMap) {
546 SparseArrayValueMap::iterator end = map->end();
547 for (SparseArrayValueMap::iterator it = map->begin(); it != end; ++it)
548 propertyNames.add(Identifier::from(exec, it->first));
549 }
550
551 if (mode == IncludeDontEnumProperties)
552 propertyNames.add(exec->propertyNames().length);
553
554 JSObject::getOwnPropertyNames(exec, propertyNames, mode);
555 }
556
557 ALWAYS_INLINE unsigned JSArray::getNewVectorLength(unsigned desiredLength)
558 {
559 ASSERT(desiredLength <= MAX_STORAGE_VECTOR_LENGTH);
560
561 unsigned increasedLength;
562 unsigned maxInitLength = min(m_storage->m_length, 100000U);
563
564 if (desiredLength < maxInitLength)
565 increasedLength = maxInitLength;
566 else if (!m_vectorLength)
567 increasedLength = max(desiredLength, lastArraySize);
568 else {
569 // Mathematically equivalent to:
570 // increasedLength = (newLength * 3 + 1) / 2;
571 // or:
572 // increasedLength = (unsigned)ceil(newLength * 1.5));
573 // This form is not prone to internal overflow.
574 increasedLength = desiredLength + (desiredLength >> 1) + (desiredLength & 1);
575 }
576
577 ASSERT(increasedLength >= desiredLength);
578
579 lastArraySize = min(increasedLength, FIRST_VECTOR_GROW);
580
581 return min(increasedLength, MAX_STORAGE_VECTOR_LENGTH);
582 }
583
584 bool JSArray::increaseVectorLength(unsigned newLength)
585 {
586 // This function leaves the array in an internally inconsistent state, because it does not move any values from sparse value map
587 // to the vector. Callers have to account for that, because they can do it more efficiently.
588
589 ArrayStorage* storage = m_storage;
590
591 unsigned vectorLength = m_vectorLength;
592 ASSERT(newLength > vectorLength);
593 ASSERT(newLength <= MAX_STORAGE_VECTOR_INDEX);
594 unsigned newVectorLength = getNewVectorLength(newLength);
595 void* baseStorage = storage->m_allocBase;
596
597 if (!tryFastRealloc(baseStorage, storageSize(newVectorLength + m_indexBias)).getValue(baseStorage))
598 return false;
599
600 storage = m_storage = reinterpret_cast_ptr<ArrayStorage*>(static_cast<char*>(baseStorage) + m_indexBias * sizeof(JSValue));
601 m_storage->m_allocBase = baseStorage;
602
603 WriteBarrier<Unknown>* vector = storage->m_vector;
604 for (unsigned i = vectorLength; i < newVectorLength; ++i)
605 vector[i].clear();
606
607 m_vectorLength = newVectorLength;
608
609 Heap::heap(this)->reportExtraMemoryCost(storageSize(newVectorLength) - storageSize(vectorLength));
610
611 return true;
612 }
613
614 bool JSArray::increaseVectorPrefixLength(unsigned newLength)
615 {
616 // This function leaves the array in an internally inconsistent state, because it does not move any values from sparse value map
617 // to the vector. Callers have to account for that, because they can do it more efficiently.
618
619 ArrayStorage* storage = m_storage;
620
621 unsigned vectorLength = m_vectorLength;
622 ASSERT(newLength > vectorLength);
623 ASSERT(newLength <= MAX_STORAGE_VECTOR_INDEX);
624 unsigned newVectorLength = getNewVectorLength(newLength);
625
626 void* newBaseStorage = fastMalloc(storageSize(newVectorLength + m_indexBias));
627 if (!newBaseStorage)
628 return false;
629
630 m_indexBias += newVectorLength - newLength;
631
632 m_storage = reinterpret_cast_ptr<ArrayStorage*>(static_cast<char*>(newBaseStorage) + m_indexBias * sizeof(JSValue));
633
634 memcpy(m_storage, storage, storageSize(0));
635 memcpy(&m_storage->m_vector[newLength - m_vectorLength], &storage->m_vector[0], vectorLength * sizeof(JSValue));
636
637 m_storage->m_allocBase = newBaseStorage;
638 m_vectorLength = newLength;
639
640 fastFree(storage->m_allocBase);
641 ASSERT(newLength > vectorLength);
642 unsigned delta = newLength - vectorLength;
643 for (unsigned i = 0; i < delta; i++)
644 m_storage->m_vector[i].clear();
645 Heap::heap(this)->reportExtraMemoryCost(storageSize(newVectorLength) - storageSize(vectorLength));
646
647 return true;
648 }
649
650
651 void JSArray::setLength(unsigned newLength)
652 {
653 ArrayStorage* storage = m_storage;
654
655 #if CHECK_ARRAY_CONSISTENCY
656 if (!storage->m_inCompactInitialization)
657 checkConsistency();
658 else
659 storage->m_inCompactInitialization = false;
660 #endif
661
662 unsigned length = storage->m_length;
663
664 if (newLength < length) {
665 unsigned usedVectorLength = min(length, m_vectorLength);
666 for (unsigned i = newLength; i < usedVectorLength; ++i) {
667 WriteBarrier<Unknown>& valueSlot = storage->m_vector[i];
668 bool hadValue = valueSlot;
669 valueSlot.clear();
670 storage->m_numValuesInVector -= hadValue;
671 }
672
673 if (SparseArrayValueMap* map = storage->m_sparseValueMap) {
674 SparseArrayValueMap copy = *map;
675 SparseArrayValueMap::iterator end = copy.end();
676 for (SparseArrayValueMap::iterator it = copy.begin(); it != end; ++it) {
677 if (it->first >= newLength)
678 map->remove(it->first);
679 }
680 if (map->isEmpty()) {
681 delete map;
682 storage->m_sparseValueMap = 0;
683 }
684 }
685 }
686
687 storage->m_length = newLength;
688
689 checkConsistency();
690 }
691
692 JSValue JSArray::pop()
693 {
694 checkConsistency();
695
696 ArrayStorage* storage = m_storage;
697
698 unsigned length = storage->m_length;
699 if (!length)
700 return jsUndefined();
701
702 --length;
703
704 JSValue result;
705
706 if (length < m_vectorLength) {
707 WriteBarrier<Unknown>& valueSlot = storage->m_vector[length];
708 if (valueSlot) {
709 --storage->m_numValuesInVector;
710 result = valueSlot.get();
711 valueSlot.clear();
712 } else
713 result = jsUndefined();
714 } else {
715 result = jsUndefined();
716 if (SparseArrayValueMap* map = storage->m_sparseValueMap) {
717 SparseArrayValueMap::iterator it = map->find(length);
718 if (it != map->end()) {
719 result = it->second.get();
720 map->remove(it);
721 if (map->isEmpty()) {
722 delete map;
723 storage->m_sparseValueMap = 0;
724 }
725 }
726 }
727 }
728
729 storage->m_length = length;
730
731 checkConsistency();
732
733 return result;
734 }
735
736 void JSArray::push(ExecState* exec, JSValue value)
737 {
738 checkConsistency();
739
740 ArrayStorage* storage = m_storage;
741
742 if (storage->m_length < m_vectorLength) {
743 storage->m_vector[storage->m_length].set(exec->globalData(), this, value);
744 ++storage->m_numValuesInVector;
745 ++storage->m_length;
746 checkConsistency();
747 return;
748 }
749
750 if (storage->m_length < MIN_SPARSE_ARRAY_INDEX) {
751 SparseArrayValueMap* map = storage->m_sparseValueMap;
752 if (!map || map->isEmpty()) {
753 if (increaseVectorLength(storage->m_length + 1)) {
754 storage = m_storage;
755 storage->m_vector[storage->m_length].set(exec->globalData(), this, value);
756 ++storage->m_numValuesInVector;
757 ++storage->m_length;
758 checkConsistency();
759 return;
760 }
761 checkConsistency();
762 throwOutOfMemoryError(exec);
763 return;
764 }
765 }
766
767 putSlowCase(exec, storage->m_length++, value);
768 }
769
770 void JSArray::shiftCount(ExecState* exec, int count)
771 {
772 ASSERT(count > 0);
773
774 ArrayStorage* storage = m_storage;
775
776 unsigned oldLength = storage->m_length;
777
778 if (!oldLength)
779 return;
780
781 if (oldLength != storage->m_numValuesInVector) {
782 // If m_length and m_numValuesInVector aren't the same, we have a sparse vector
783 // which means we need to go through each entry looking for the the "empty"
784 // slots and then fill them with possible properties. See ECMA spec.
785 // 15.4.4.9 steps 11 through 13.
786 for (unsigned i = count; i < oldLength; ++i) {
787 if ((i >= m_vectorLength) || (!m_storage->m_vector[i])) {
788 PropertySlot slot(this);
789 JSValue p = prototype();
790 if ((!p.isNull()) && (asObject(p)->getPropertySlot(exec, i, slot)))
791 put(exec, i, slot.getValue(exec, i));
792 }
793 }
794
795 storage = m_storage; // The put() above could have grown the vector and realloc'ed storage.
796
797 // Need to decrement numValuesInvector based on number of real entries
798 for (unsigned i = 0; i < (unsigned)count; ++i)
799 if ((i < m_vectorLength) && (storage->m_vector[i]))
800 --storage->m_numValuesInVector;
801 } else
802 storage->m_numValuesInVector -= count;
803
804 storage->m_length -= count;
805
806 if (m_vectorLength) {
807 count = min(m_vectorLength, (unsigned)count);
808
809 m_vectorLength -= count;
810
811 if (m_vectorLength) {
812 char* newBaseStorage = reinterpret_cast<char*>(storage) + count * sizeof(JSValue);
813 memmove(newBaseStorage, storage, storageSize(0));
814 m_storage = reinterpret_cast_ptr<ArrayStorage*>(newBaseStorage);
815
816 m_indexBias += count;
817 }
818 }
819 }
820
821 void JSArray::unshiftCount(ExecState* exec, int count)
822 {
823 ArrayStorage* storage = m_storage;
824
825 ASSERT(m_indexBias >= 0);
826 ASSERT(count >= 0);
827
828 unsigned length = storage->m_length;
829
830 if (length != storage->m_numValuesInVector) {
831 // If m_length and m_numValuesInVector aren't the same, we have a sparse vector
832 // which means we need to go through each entry looking for the the "empty"
833 // slots and then fill them with possible properties. See ECMA spec.
834 // 15.4.4.13 steps 8 through 10.
835 for (unsigned i = 0; i < length; ++i) {
836 if ((i >= m_vectorLength) || (!m_storage->m_vector[i])) {
837 PropertySlot slot(this);
838 JSValue p = prototype();
839 if ((!p.isNull()) && (asObject(p)->getPropertySlot(exec, i, slot)))
840 put(exec, i, slot.getValue(exec, i));
841 }
842 }
843 }
844
845 storage = m_storage; // The put() above could have grown the vector and realloc'ed storage.
846
847 if (m_indexBias >= count) {
848 m_indexBias -= count;
849 char* newBaseStorage = reinterpret_cast<char*>(storage) - count * sizeof(JSValue);
850 memmove(newBaseStorage, storage, storageSize(0));
851 m_storage = reinterpret_cast_ptr<ArrayStorage*>(newBaseStorage);
852 m_vectorLength += count;
853 } else if (!increaseVectorPrefixLength(m_vectorLength + count)) {
854 throwOutOfMemoryError(exec);
855 return;
856 }
857
858 WriteBarrier<Unknown>* vector = m_storage->m_vector;
859 for (int i = 0; i < count; i++)
860 vector[i].clear();
861 }
862
863 void JSArray::visitChildren(SlotVisitor& visitor)
864 {
865 ASSERT_GC_OBJECT_INHERITS(this, &s_info);
866 COMPILE_ASSERT(StructureFlags & OverridesVisitChildren, OverridesVisitChildrenWithoutSettingFlag);
867 ASSERT(structure()->typeInfo().overridesVisitChildren());
868 visitChildrenDirect(visitor);
869 }
870
871 static int compareNumbersForQSort(const void* a, const void* b)
872 {
873 double da = static_cast<const JSValue*>(a)->uncheckedGetNumber();
874 double db = static_cast<const JSValue*>(b)->uncheckedGetNumber();
875 return (da > db) - (da < db);
876 }
877
878 static int compareByStringPairForQSort(const void* a, const void* b)
879 {
880 const ValueStringPair* va = static_cast<const ValueStringPair*>(a);
881 const ValueStringPair* vb = static_cast<const ValueStringPair*>(b);
882 return codePointCompare(va->second, vb->second);
883 }
884
885 void JSArray::sortNumeric(ExecState* exec, JSValue compareFunction, CallType callType, const CallData& callData)
886 {
887 ArrayStorage* storage = m_storage;
888
889 unsigned lengthNotIncludingUndefined = compactForSorting();
890 if (storage->m_sparseValueMap) {
891 throwOutOfMemoryError(exec);
892 return;
893 }
894
895 if (!lengthNotIncludingUndefined)
896 return;
897
898 bool allValuesAreNumbers = true;
899 size_t size = storage->m_numValuesInVector;
900 for (size_t i = 0; i < size; ++i) {
901 if (!storage->m_vector[i].isNumber()) {
902 allValuesAreNumbers = false;
903 break;
904 }
905 }
906
907 if (!allValuesAreNumbers)
908 return sort(exec, compareFunction, callType, callData);
909
910 // For numeric comparison, which is fast, qsort is faster than mergesort. We
911 // also don't require mergesort's stability, since there's no user visible
912 // side-effect from swapping the order of equal primitive values.
913 qsort(storage->m_vector, size, sizeof(JSValue), compareNumbersForQSort);
914
915 checkConsistency(SortConsistencyCheck);
916 }
917
918 void JSArray::sort(ExecState* exec)
919 {
920 ArrayStorage* storage = m_storage;
921
922 unsigned lengthNotIncludingUndefined = compactForSorting();
923 if (storage->m_sparseValueMap) {
924 throwOutOfMemoryError(exec);
925 return;
926 }
927
928 if (!lengthNotIncludingUndefined)
929 return;
930
931 // Converting JavaScript values to strings can be expensive, so we do it once up front and sort based on that.
932 // This is a considerable improvement over doing it twice per comparison, though it requires a large temporary
933 // buffer. Besides, this protects us from crashing if some objects have custom toString methods that return
934 // random or otherwise changing results, effectively making compare function inconsistent.
935
936 Vector<ValueStringPair> values(lengthNotIncludingUndefined);
937 if (!values.begin()) {
938 throwOutOfMemoryError(exec);
939 return;
940 }
941
942 Heap::heap(this)->pushTempSortVector(&values);
943
944 for (size_t i = 0; i < lengthNotIncludingUndefined; i++) {
945 JSValue value = storage->m_vector[i].get();
946 ASSERT(!value.isUndefined());
947 values[i].first = value;
948 }
949
950 // FIXME: The following loop continues to call toString on subsequent values even after
951 // a toString call raises an exception.
952
953 for (size_t i = 0; i < lengthNotIncludingUndefined; i++)
954 values[i].second = values[i].first.toString(exec);
955
956 if (exec->hadException()) {
957 Heap::heap(this)->popTempSortVector(&values);
958 return;
959 }
960
961 // FIXME: Since we sort by string value, a fast algorithm might be to use a radix sort. That would be O(N) rather
962 // than O(N log N).
963
964 #if HAVE(MERGESORT)
965 mergesort(values.begin(), values.size(), sizeof(ValueStringPair), compareByStringPairForQSort);
966 #else
967 // FIXME: The qsort library function is likely to not be a stable sort.
968 // ECMAScript-262 does not specify a stable sort, but in practice, browsers perform a stable sort.
969 qsort(values.begin(), values.size(), sizeof(ValueStringPair), compareByStringPairForQSort);
970 #endif
971
972 // If the toString function changed the length of the array or vector storage,
973 // increase the length to handle the orignal number of actual values.
974 if (m_vectorLength < lengthNotIncludingUndefined)
975 increaseVectorLength(lengthNotIncludingUndefined);
976 if (storage->m_length < lengthNotIncludingUndefined)
977 storage->m_length = lengthNotIncludingUndefined;
978
979 JSGlobalData& globalData = exec->globalData();
980 for (size_t i = 0; i < lengthNotIncludingUndefined; i++)
981 storage->m_vector[i].set(globalData, this, values[i].first);
982
983 Heap::heap(this)->popTempSortVector(&values);
984
985 checkConsistency(SortConsistencyCheck);
986 }
987
988 struct AVLTreeNodeForArrayCompare {
989 JSValue value;
990
991 // Child pointers. The high bit of gt is robbed and used as the
992 // balance factor sign. The high bit of lt is robbed and used as
993 // the magnitude of the balance factor.
994 int32_t gt;
995 int32_t lt;
996 };
997
998 struct AVLTreeAbstractorForArrayCompare {
999 typedef int32_t handle; // Handle is an index into m_nodes vector.
1000 typedef JSValue key;
1001 typedef int32_t size;
1002
1003 Vector<AVLTreeNodeForArrayCompare> m_nodes;
1004 ExecState* m_exec;
1005 JSValue m_compareFunction;
1006 CallType m_compareCallType;
1007 const CallData* m_compareCallData;
1008 JSValue m_globalThisValue;
1009 OwnPtr<CachedCall> m_cachedCall;
1010
1011 handle get_less(handle h) { return m_nodes[h].lt & 0x7FFFFFFF; }
1012 void set_less(handle h, handle lh) { m_nodes[h].lt &= 0x80000000; m_nodes[h].lt |= lh; }
1013 handle get_greater(handle h) { return m_nodes[h].gt & 0x7FFFFFFF; }
1014 void set_greater(handle h, handle gh) { m_nodes[h].gt &= 0x80000000; m_nodes[h].gt |= gh; }
1015
1016 int get_balance_factor(handle h)
1017 {
1018 if (m_nodes[h].gt & 0x80000000)
1019 return -1;
1020 return static_cast<unsigned>(m_nodes[h].lt) >> 31;
1021 }
1022
1023 void set_balance_factor(handle h, int bf)
1024 {
1025 if (bf == 0) {
1026 m_nodes[h].lt &= 0x7FFFFFFF;
1027 m_nodes[h].gt &= 0x7FFFFFFF;
1028 } else {
1029 m_nodes[h].lt |= 0x80000000;
1030 if (bf < 0)
1031 m_nodes[h].gt |= 0x80000000;
1032 else
1033 m_nodes[h].gt &= 0x7FFFFFFF;
1034 }
1035 }
1036
1037 int compare_key_key(key va, key vb)
1038 {
1039 ASSERT(!va.isUndefined());
1040 ASSERT(!vb.isUndefined());
1041
1042 if (m_exec->hadException())
1043 return 1;
1044
1045 double compareResult;
1046 if (m_cachedCall) {
1047 m_cachedCall->setThis(m_globalThisValue);
1048 m_cachedCall->setArgument(0, va);
1049 m_cachedCall->setArgument(1, vb);
1050 compareResult = m_cachedCall->call().toNumber(m_cachedCall->newCallFrame(m_exec));
1051 } else {
1052 MarkedArgumentBuffer arguments;
1053 arguments.append(va);
1054 arguments.append(vb);
1055 compareResult = call(m_exec, m_compareFunction, m_compareCallType, *m_compareCallData, m_globalThisValue, arguments).toNumber(m_exec);
1056 }
1057 return (compareResult < 0) ? -1 : 1; // Not passing equality through, because we need to store all values, even if equivalent.
1058 }
1059
1060 int compare_key_node(key k, handle h) { return compare_key_key(k, m_nodes[h].value); }
1061 int compare_node_node(handle h1, handle h2) { return compare_key_key(m_nodes[h1].value, m_nodes[h2].value); }
1062
1063 static handle null() { return 0x7FFFFFFF; }
1064 };
1065
1066 void JSArray::sort(ExecState* exec, JSValue compareFunction, CallType callType, const CallData& callData)
1067 {
1068 checkConsistency();
1069
1070 ArrayStorage* storage = m_storage;
1071
1072 // FIXME: This ignores exceptions raised in the compare function or in toNumber.
1073
1074 // The maximum tree depth is compiled in - but the caller is clearly up to no good
1075 // if a larger array is passed.
1076 ASSERT(storage->m_length <= static_cast<unsigned>(std::numeric_limits<int>::max()));
1077 if (storage->m_length > static_cast<unsigned>(std::numeric_limits<int>::max()))
1078 return;
1079
1080 unsigned usedVectorLength = min(storage->m_length, m_vectorLength);
1081 unsigned nodeCount = usedVectorLength + (storage->m_sparseValueMap ? storage->m_sparseValueMap->size() : 0);
1082
1083 if (!nodeCount)
1084 return;
1085
1086 AVLTree<AVLTreeAbstractorForArrayCompare, 44> tree; // Depth 44 is enough for 2^31 items
1087 tree.abstractor().m_exec = exec;
1088 tree.abstractor().m_compareFunction = compareFunction;
1089 tree.abstractor().m_compareCallType = callType;
1090 tree.abstractor().m_compareCallData = &callData;
1091 tree.abstractor().m_globalThisValue = exec->globalThisValue();
1092 tree.abstractor().m_nodes.grow(nodeCount);
1093
1094 if (callType == CallTypeJS)
1095 tree.abstractor().m_cachedCall = adoptPtr(new CachedCall(exec, asFunction(compareFunction), 2));
1096
1097 if (!tree.abstractor().m_nodes.begin()) {
1098 throwOutOfMemoryError(exec);
1099 return;
1100 }
1101
1102 // FIXME: If the compare function modifies the array, the vector, map, etc. could be modified
1103 // right out from under us while we're building the tree here.
1104
1105 unsigned numDefined = 0;
1106 unsigned numUndefined = 0;
1107
1108 // Iterate over the array, ignoring missing values, counting undefined ones, and inserting all other ones into the tree.
1109 for (; numDefined < usedVectorLength; ++numDefined) {
1110 JSValue v = storage->m_vector[numDefined].get();
1111 if (!v || v.isUndefined())
1112 break;
1113 tree.abstractor().m_nodes[numDefined].value = v;
1114 tree.insert(numDefined);
1115 }
1116 for (unsigned i = numDefined; i < usedVectorLength; ++i) {
1117 JSValue v = storage->m_vector[i].get();
1118 if (v) {
1119 if (v.isUndefined())
1120 ++numUndefined;
1121 else {
1122 tree.abstractor().m_nodes[numDefined].value = v;
1123 tree.insert(numDefined);
1124 ++numDefined;
1125 }
1126 }
1127 }
1128
1129 unsigned newUsedVectorLength = numDefined + numUndefined;
1130
1131 if (SparseArrayValueMap* map = storage->m_sparseValueMap) {
1132 newUsedVectorLength += map->size();
1133 if (newUsedVectorLength > m_vectorLength) {
1134 // Check that it is possible to allocate an array large enough to hold all the entries.
1135 if ((newUsedVectorLength > MAX_STORAGE_VECTOR_LENGTH) || !increaseVectorLength(newUsedVectorLength)) {
1136 throwOutOfMemoryError(exec);
1137 return;
1138 }
1139 }
1140
1141 storage = m_storage;
1142
1143 SparseArrayValueMap::iterator end = map->end();
1144 for (SparseArrayValueMap::iterator it = map->begin(); it != end; ++it) {
1145 tree.abstractor().m_nodes[numDefined].value = it->second.get();
1146 tree.insert(numDefined);
1147 ++numDefined;
1148 }
1149
1150 delete map;
1151 storage->m_sparseValueMap = 0;
1152 }
1153
1154 ASSERT(tree.abstractor().m_nodes.size() >= numDefined);
1155
1156 // FIXME: If the compare function changed the length of the array, the following might be
1157 // modifying the vector incorrectly.
1158
1159 // Copy the values back into m_storage.
1160 AVLTree<AVLTreeAbstractorForArrayCompare, 44>::Iterator iter;
1161 iter.start_iter_least(tree);
1162 JSGlobalData& globalData = exec->globalData();
1163 for (unsigned i = 0; i < numDefined; ++i) {
1164 storage->m_vector[i].set(globalData, this, tree.abstractor().m_nodes[*iter].value);
1165 ++iter;
1166 }
1167
1168 // Put undefined values back in.
1169 for (unsigned i = numDefined; i < newUsedVectorLength; ++i)
1170 storage->m_vector[i].setUndefined();
1171
1172 // Ensure that unused values in the vector are zeroed out.
1173 for (unsigned i = newUsedVectorLength; i < usedVectorLength; ++i)
1174 storage->m_vector[i].clear();
1175
1176 storage->m_numValuesInVector = newUsedVectorLength;
1177
1178 checkConsistency(SortConsistencyCheck);
1179 }
1180
1181 void JSArray::fillArgList(ExecState* exec, MarkedArgumentBuffer& args)
1182 {
1183 ArrayStorage* storage = m_storage;
1184
1185 WriteBarrier<Unknown>* vector = storage->m_vector;
1186 unsigned vectorEnd = min(storage->m_length, m_vectorLength);
1187 unsigned i = 0;
1188 for (; i < vectorEnd; ++i) {
1189 WriteBarrier<Unknown>& v = vector[i];
1190 if (!v)
1191 break;
1192 args.append(v.get());
1193 }
1194
1195 for (; i < storage->m_length; ++i)
1196 args.append(get(exec, i));
1197 }
1198
1199 void JSArray::copyToRegisters(ExecState* exec, Register* buffer, uint32_t maxSize)
1200 {
1201 ASSERT(m_storage->m_length >= maxSize);
1202 UNUSED_PARAM(maxSize);
1203 WriteBarrier<Unknown>* vector = m_storage->m_vector;
1204 unsigned vectorEnd = min(maxSize, m_vectorLength);
1205 unsigned i = 0;
1206 for (; i < vectorEnd; ++i) {
1207 WriteBarrier<Unknown>& v = vector[i];
1208 if (!v)
1209 break;
1210 buffer[i] = v.get();
1211 }
1212
1213 for (; i < maxSize; ++i)
1214 buffer[i] = get(exec, i);
1215 }
1216
1217 unsigned JSArray::compactForSorting()
1218 {
1219 checkConsistency();
1220
1221 ArrayStorage* storage = m_storage;
1222
1223 unsigned usedVectorLength = min(storage->m_length, m_vectorLength);
1224
1225 unsigned numDefined = 0;
1226 unsigned numUndefined = 0;
1227
1228 for (; numDefined < usedVectorLength; ++numDefined) {
1229 JSValue v = storage->m_vector[numDefined].get();
1230 if (!v || v.isUndefined())
1231 break;
1232 }
1233
1234 for (unsigned i = numDefined; i < usedVectorLength; ++i) {
1235 JSValue v = storage->m_vector[i].get();
1236 if (v) {
1237 if (v.isUndefined())
1238 ++numUndefined;
1239 else
1240 storage->m_vector[numDefined++].setWithoutWriteBarrier(v);
1241 }
1242 }
1243
1244 unsigned newUsedVectorLength = numDefined + numUndefined;
1245
1246 if (SparseArrayValueMap* map = storage->m_sparseValueMap) {
1247 newUsedVectorLength += map->size();
1248 if (newUsedVectorLength > m_vectorLength) {
1249 // Check that it is possible to allocate an array large enough to hold all the entries - if not,
1250 // exception is thrown by caller.
1251 if ((newUsedVectorLength > MAX_STORAGE_VECTOR_LENGTH) || !increaseVectorLength(newUsedVectorLength))
1252 return 0;
1253
1254 storage = m_storage;
1255 }
1256
1257 SparseArrayValueMap::iterator end = map->end();
1258 for (SparseArrayValueMap::iterator it = map->begin(); it != end; ++it)
1259 storage->m_vector[numDefined++].setWithoutWriteBarrier(it->second.get());
1260
1261 delete map;
1262 storage->m_sparseValueMap = 0;
1263 }
1264
1265 for (unsigned i = numDefined; i < newUsedVectorLength; ++i)
1266 storage->m_vector[i].setUndefined();
1267 for (unsigned i = newUsedVectorLength; i < usedVectorLength; ++i)
1268 storage->m_vector[i].clear();
1269
1270 storage->m_numValuesInVector = newUsedVectorLength;
1271
1272 checkConsistency(SortConsistencyCheck);
1273
1274 return numDefined;
1275 }
1276
1277 void* JSArray::subclassData() const
1278 {
1279 return m_storage->subclassData;
1280 }
1281
1282 void JSArray::setSubclassData(void* d)
1283 {
1284 m_storage->subclassData = d;
1285 }
1286
1287 #if CHECK_ARRAY_CONSISTENCY
1288
1289 void JSArray::checkConsistency(ConsistencyCheckType type)
1290 {
1291 ArrayStorage* storage = m_storage;
1292
1293 ASSERT(storage);
1294 if (type == SortConsistencyCheck)
1295 ASSERT(!storage->m_sparseValueMap);
1296
1297 unsigned numValuesInVector = 0;
1298 for (unsigned i = 0; i < m_vectorLength; ++i) {
1299 if (JSValue value = storage->m_vector[i]) {
1300 ASSERT(i < storage->m_length);
1301 if (type != DestructorConsistencyCheck)
1302 value.isUndefined(); // Likely to crash if the object was deallocated.
1303 ++numValuesInVector;
1304 } else {
1305 if (type == SortConsistencyCheck)
1306 ASSERT(i >= storage->m_numValuesInVector);
1307 }
1308 }
1309 ASSERT(numValuesInVector == storage->m_numValuesInVector);
1310 ASSERT(numValuesInVector <= storage->m_length);
1311
1312 if (storage->m_sparseValueMap) {
1313 SparseArrayValueMap::iterator end = storage->m_sparseValueMap->end();
1314 for (SparseArrayValueMap::iterator it = storage->m_sparseValueMap->begin(); it != end; ++it) {
1315 unsigned index = it->first;
1316 ASSERT(index < storage->m_length);
1317 ASSERT(index >= storage->m_vectorLength);
1318 ASSERT(index <= MAX_ARRAY_INDEX);
1319 ASSERT(it->second);
1320 if (type != DestructorConsistencyCheck)
1321 it->second.isUndefined(); // Likely to crash if the object was deallocated.
1322 }
1323 }
1324 }
1325
1326 #endif
1327
1328 } // namespace JSC