blob: 1e4d4a4c14d8550301f5ff09b9ed6a3b0c9e6fff [file] [log] [blame]
Steve Blocka7e24c12009-10-30 11:49:00 +00001// Copyright 2006-2009 the V8 project authors. All rights reserved.
2// Redistribution and use in source and binary forms, with or without
3// modification, are permitted provided that the following conditions are
4// met:
5//
6// * Redistributions of source code must retain the above copyright
7// notice, this list of conditions and the following disclaimer.
8// * Redistributions in binary form must reproduce the above
9// copyright notice, this list of conditions and the following
10// disclaimer in the documentation and/or other materials provided
11// with the distribution.
12// * Neither the name of Google Inc. nor the names of its
13// contributors may be used to endorse or promote products derived
14// from this software without specific prior written permission.
15//
16// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27
28#include "v8.h"
29
30#include "api.h"
31#include "arguments.h"
32#include "bootstrapper.h"
33#include "debug.h"
34#include "execution.h"
35#include "objects-inl.h"
36#include "macro-assembler.h"
37#include "scanner.h"
38#include "scopeinfo.h"
39#include "string-stream.h"
Steve Blockd0582a62009-12-15 09:54:21 +000040#include "utils.h"
Steve Blocka7e24c12009-10-30 11:49:00 +000041
42#ifdef ENABLE_DISASSEMBLER
43#include "disassembler.h"
44#endif
45
46
47namespace v8 {
48namespace internal {
49
50// Getters and setters are stored in a fixed array property. These are
51// constants for their indices.
52const int kGetterIndex = 0;
53const int kSetterIndex = 1;
54
55
56static Object* CreateJSValue(JSFunction* constructor, Object* value) {
57 Object* result = Heap::AllocateJSObject(constructor);
58 if (result->IsFailure()) return result;
59 JSValue::cast(result)->set_value(value);
60 return result;
61}
62
63
64Object* Object::ToObject(Context* global_context) {
65 if (IsNumber()) {
66 return CreateJSValue(global_context->number_function(), this);
67 } else if (IsBoolean()) {
68 return CreateJSValue(global_context->boolean_function(), this);
69 } else if (IsString()) {
70 return CreateJSValue(global_context->string_function(), this);
71 }
72 ASSERT(IsJSObject());
73 return this;
74}
75
76
77Object* Object::ToObject() {
78 Context* global_context = Top::context()->global_context();
79 if (IsJSObject()) {
80 return this;
81 } else if (IsNumber()) {
82 return CreateJSValue(global_context->number_function(), this);
83 } else if (IsBoolean()) {
84 return CreateJSValue(global_context->boolean_function(), this);
85 } else if (IsString()) {
86 return CreateJSValue(global_context->string_function(), this);
87 }
88
89 // Throw a type error.
90 return Failure::InternalError();
91}
92
93
94Object* Object::ToBoolean() {
95 if (IsTrue()) return Heap::true_value();
96 if (IsFalse()) return Heap::false_value();
97 if (IsSmi()) {
98 return Heap::ToBoolean(Smi::cast(this)->value() != 0);
99 }
100 if (IsUndefined() || IsNull()) return Heap::false_value();
101 // Undetectable object is false
102 if (IsUndetectableObject()) {
103 return Heap::false_value();
104 }
105 if (IsString()) {
106 return Heap::ToBoolean(String::cast(this)->length() != 0);
107 }
108 if (IsHeapNumber()) {
109 return HeapNumber::cast(this)->HeapNumberToBoolean();
110 }
111 return Heap::true_value();
112}
113
114
115void Object::Lookup(String* name, LookupResult* result) {
116 if (IsJSObject()) return JSObject::cast(this)->Lookup(name, result);
117 Object* holder = NULL;
118 Context* global_context = Top::context()->global_context();
119 if (IsString()) {
120 holder = global_context->string_function()->instance_prototype();
121 } else if (IsNumber()) {
122 holder = global_context->number_function()->instance_prototype();
123 } else if (IsBoolean()) {
124 holder = global_context->boolean_function()->instance_prototype();
125 }
126 ASSERT(holder != NULL); // Cannot handle null or undefined.
127 JSObject::cast(holder)->Lookup(name, result);
128}
129
130
131Object* Object::GetPropertyWithReceiver(Object* receiver,
132 String* name,
133 PropertyAttributes* attributes) {
134 LookupResult result;
135 Lookup(name, &result);
136 Object* value = GetProperty(receiver, &result, name, attributes);
137 ASSERT(*attributes <= ABSENT);
138 return value;
139}
140
141
142Object* Object::GetPropertyWithCallback(Object* receiver,
143 Object* structure,
144 String* name,
145 Object* holder) {
146 // To accommodate both the old and the new api we switch on the
147 // data structure used to store the callbacks. Eventually proxy
148 // callbacks should be phased out.
149 if (structure->IsProxy()) {
150 AccessorDescriptor* callback =
151 reinterpret_cast<AccessorDescriptor*>(Proxy::cast(structure)->proxy());
152 Object* value = (callback->getter)(receiver, callback->data);
153 RETURN_IF_SCHEDULED_EXCEPTION();
154 return value;
155 }
156
157 // api style callbacks.
158 if (structure->IsAccessorInfo()) {
159 AccessorInfo* data = AccessorInfo::cast(structure);
160 Object* fun_obj = data->getter();
161 v8::AccessorGetter call_fun = v8::ToCData<v8::AccessorGetter>(fun_obj);
162 HandleScope scope;
163 JSObject* self = JSObject::cast(receiver);
164 JSObject* holder_handle = JSObject::cast(holder);
165 Handle<String> key(name);
166 LOG(ApiNamedPropertyAccess("load", self, name));
167 CustomArguments args(data->data(), self, holder_handle);
168 v8::AccessorInfo info(args.end());
169 v8::Handle<v8::Value> result;
170 {
171 // Leaving JavaScript.
172 VMState state(EXTERNAL);
173 result = call_fun(v8::Utils::ToLocal(key), info);
174 }
175 RETURN_IF_SCHEDULED_EXCEPTION();
176 if (result.IsEmpty()) return Heap::undefined_value();
177 return *v8::Utils::OpenHandle(*result);
178 }
179
180 // __defineGetter__ callback
181 if (structure->IsFixedArray()) {
182 Object* getter = FixedArray::cast(structure)->get(kGetterIndex);
183 if (getter->IsJSFunction()) {
184 return Object::GetPropertyWithDefinedGetter(receiver,
185 JSFunction::cast(getter));
186 }
187 // Getter is not a function.
188 return Heap::undefined_value();
189 }
190
191 UNREACHABLE();
Leon Clarkef7060e22010-06-03 12:02:55 +0100192 return NULL;
Steve Blocka7e24c12009-10-30 11:49:00 +0000193}
194
195
196Object* Object::GetPropertyWithDefinedGetter(Object* receiver,
197 JSFunction* getter) {
198 HandleScope scope;
199 Handle<JSFunction> fun(JSFunction::cast(getter));
200 Handle<Object> self(receiver);
201#ifdef ENABLE_DEBUGGER_SUPPORT
202 // Handle stepping into a getter if step into is active.
203 if (Debug::StepInActive()) {
204 Debug::HandleStepIn(fun, Handle<Object>::null(), 0, false);
205 }
206#endif
207 bool has_pending_exception;
208 Handle<Object> result =
209 Execution::Call(fun, self, 0, NULL, &has_pending_exception);
210 // Check for pending exception and return the result.
211 if (has_pending_exception) return Failure::Exception();
212 return *result;
213}
214
215
216// Only deal with CALLBACKS and INTERCEPTOR
217Object* JSObject::GetPropertyWithFailedAccessCheck(
218 Object* receiver,
219 LookupResult* result,
220 String* name,
221 PropertyAttributes* attributes) {
Andrei Popescu402d9372010-02-26 13:31:12 +0000222 if (result->IsProperty()) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000223 switch (result->type()) {
224 case CALLBACKS: {
225 // Only allow API accessors.
226 Object* obj = result->GetCallbackObject();
227 if (obj->IsAccessorInfo()) {
228 AccessorInfo* info = AccessorInfo::cast(obj);
229 if (info->all_can_read()) {
230 *attributes = result->GetAttributes();
231 return GetPropertyWithCallback(receiver,
232 result->GetCallbackObject(),
233 name,
234 result->holder());
235 }
236 }
237 break;
238 }
239 case NORMAL:
240 case FIELD:
241 case CONSTANT_FUNCTION: {
242 // Search ALL_CAN_READ accessors in prototype chain.
243 LookupResult r;
244 result->holder()->LookupRealNamedPropertyInPrototypes(name, &r);
Andrei Popescu402d9372010-02-26 13:31:12 +0000245 if (r.IsProperty()) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000246 return GetPropertyWithFailedAccessCheck(receiver,
247 &r,
248 name,
249 attributes);
250 }
251 break;
252 }
253 case INTERCEPTOR: {
254 // If the object has an interceptor, try real named properties.
255 // No access check in GetPropertyAttributeWithInterceptor.
256 LookupResult r;
257 result->holder()->LookupRealNamedProperty(name, &r);
Andrei Popescu402d9372010-02-26 13:31:12 +0000258 if (r.IsProperty()) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000259 return GetPropertyWithFailedAccessCheck(receiver,
260 &r,
261 name,
262 attributes);
263 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000264 break;
265 }
Andrei Popescu402d9372010-02-26 13:31:12 +0000266 default:
267 UNREACHABLE();
Steve Blocka7e24c12009-10-30 11:49:00 +0000268 }
269 }
270
271 // No accessible property found.
272 *attributes = ABSENT;
273 Top::ReportFailedAccessCheck(this, v8::ACCESS_GET);
274 return Heap::undefined_value();
275}
276
277
278PropertyAttributes JSObject::GetPropertyAttributeWithFailedAccessCheck(
279 Object* receiver,
280 LookupResult* result,
281 String* name,
282 bool continue_search) {
Andrei Popescu402d9372010-02-26 13:31:12 +0000283 if (result->IsProperty()) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000284 switch (result->type()) {
285 case CALLBACKS: {
286 // Only allow API accessors.
287 Object* obj = result->GetCallbackObject();
288 if (obj->IsAccessorInfo()) {
289 AccessorInfo* info = AccessorInfo::cast(obj);
290 if (info->all_can_read()) {
291 return result->GetAttributes();
292 }
293 }
294 break;
295 }
296
297 case NORMAL:
298 case FIELD:
299 case CONSTANT_FUNCTION: {
300 if (!continue_search) break;
301 // Search ALL_CAN_READ accessors in prototype chain.
302 LookupResult r;
303 result->holder()->LookupRealNamedPropertyInPrototypes(name, &r);
Andrei Popescu402d9372010-02-26 13:31:12 +0000304 if (r.IsProperty()) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000305 return GetPropertyAttributeWithFailedAccessCheck(receiver,
306 &r,
307 name,
308 continue_search);
309 }
310 break;
311 }
312
313 case INTERCEPTOR: {
314 // If the object has an interceptor, try real named properties.
315 // No access check in GetPropertyAttributeWithInterceptor.
316 LookupResult r;
317 if (continue_search) {
318 result->holder()->LookupRealNamedProperty(name, &r);
319 } else {
320 result->holder()->LocalLookupRealNamedProperty(name, &r);
321 }
Andrei Popescu402d9372010-02-26 13:31:12 +0000322 if (r.IsProperty()) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000323 return GetPropertyAttributeWithFailedAccessCheck(receiver,
324 &r,
325 name,
326 continue_search);
327 }
328 break;
329 }
330
Andrei Popescu402d9372010-02-26 13:31:12 +0000331 default:
332 UNREACHABLE();
Steve Blocka7e24c12009-10-30 11:49:00 +0000333 }
334 }
335
336 Top::ReportFailedAccessCheck(this, v8::ACCESS_HAS);
337 return ABSENT;
338}
339
340
Steve Blocka7e24c12009-10-30 11:49:00 +0000341Object* JSObject::GetNormalizedProperty(LookupResult* result) {
342 ASSERT(!HasFastProperties());
343 Object* value = property_dictionary()->ValueAt(result->GetDictionaryEntry());
344 if (IsGlobalObject()) {
345 value = JSGlobalPropertyCell::cast(value)->value();
346 }
347 ASSERT(!value->IsJSGlobalPropertyCell());
348 return value;
349}
350
351
352Object* JSObject::SetNormalizedProperty(LookupResult* result, Object* value) {
353 ASSERT(!HasFastProperties());
354 if (IsGlobalObject()) {
355 JSGlobalPropertyCell* cell =
356 JSGlobalPropertyCell::cast(
357 property_dictionary()->ValueAt(result->GetDictionaryEntry()));
358 cell->set_value(value);
359 } else {
360 property_dictionary()->ValueAtPut(result->GetDictionaryEntry(), value);
361 }
362 return value;
363}
364
365
366Object* JSObject::SetNormalizedProperty(String* name,
367 Object* value,
368 PropertyDetails details) {
369 ASSERT(!HasFastProperties());
370 int entry = property_dictionary()->FindEntry(name);
371 if (entry == StringDictionary::kNotFound) {
372 Object* store_value = value;
373 if (IsGlobalObject()) {
374 store_value = Heap::AllocateJSGlobalPropertyCell(value);
375 if (store_value->IsFailure()) return store_value;
376 }
377 Object* dict = property_dictionary()->Add(name, store_value, details);
378 if (dict->IsFailure()) return dict;
379 set_properties(StringDictionary::cast(dict));
380 return value;
381 }
382 // Preserve enumeration index.
383 details = PropertyDetails(details.attributes(),
384 details.type(),
385 property_dictionary()->DetailsAt(entry).index());
386 if (IsGlobalObject()) {
387 JSGlobalPropertyCell* cell =
388 JSGlobalPropertyCell::cast(property_dictionary()->ValueAt(entry));
389 cell->set_value(value);
390 // Please note we have to update the property details.
391 property_dictionary()->DetailsAtPut(entry, details);
392 } else {
393 property_dictionary()->SetEntry(entry, name, value, details);
394 }
395 return value;
396}
397
398
399Object* JSObject::DeleteNormalizedProperty(String* name, DeleteMode mode) {
400 ASSERT(!HasFastProperties());
401 StringDictionary* dictionary = property_dictionary();
402 int entry = dictionary->FindEntry(name);
403 if (entry != StringDictionary::kNotFound) {
404 // If we have a global object set the cell to the hole.
405 if (IsGlobalObject()) {
406 PropertyDetails details = dictionary->DetailsAt(entry);
407 if (details.IsDontDelete()) {
408 if (mode != FORCE_DELETION) return Heap::false_value();
409 // When forced to delete global properties, we have to make a
410 // map change to invalidate any ICs that think they can load
411 // from the DontDelete cell without checking if it contains
412 // the hole value.
413 Object* new_map = map()->CopyDropDescriptors();
414 if (new_map->IsFailure()) return new_map;
415 set_map(Map::cast(new_map));
416 }
417 JSGlobalPropertyCell* cell =
418 JSGlobalPropertyCell::cast(dictionary->ValueAt(entry));
419 cell->set_value(Heap::the_hole_value());
420 dictionary->DetailsAtPut(entry, details.AsDeleted());
421 } else {
422 return dictionary->DeleteProperty(entry, mode);
423 }
424 }
425 return Heap::true_value();
426}
427
428
429bool JSObject::IsDirty() {
430 Object* cons_obj = map()->constructor();
431 if (!cons_obj->IsJSFunction())
432 return true;
433 JSFunction* fun = JSFunction::cast(cons_obj);
Steve Block6ded16b2010-05-10 14:33:55 +0100434 if (!fun->shared()->IsApiFunction())
Steve Blocka7e24c12009-10-30 11:49:00 +0000435 return true;
436 // If the object is fully fast case and has the same map it was
437 // created with then no changes can have been made to it.
438 return map() != fun->initial_map()
439 || !HasFastElements()
440 || !HasFastProperties();
441}
442
443
444Object* Object::GetProperty(Object* receiver,
445 LookupResult* result,
446 String* name,
447 PropertyAttributes* attributes) {
448 // Make sure that the top context does not change when doing
449 // callbacks or interceptor calls.
450 AssertNoContextChange ncc;
451
452 // Traverse the prototype chain from the current object (this) to
453 // the holder and check for access rights. This avoid traversing the
454 // objects more than once in case of interceptors, because the
455 // holder will always be the interceptor holder and the search may
456 // only continue with a current object just after the interceptor
457 // holder in the prototype chain.
Andrei Popescu402d9372010-02-26 13:31:12 +0000458 Object* last = result->IsProperty() ? result->holder() : Heap::null_value();
Steve Blocka7e24c12009-10-30 11:49:00 +0000459 for (Object* current = this; true; current = current->GetPrototype()) {
460 if (current->IsAccessCheckNeeded()) {
461 // Check if we're allowed to read from the current object. Note
462 // that even though we may not actually end up loading the named
463 // property from the current object, we still check that we have
464 // access to it.
465 JSObject* checked = JSObject::cast(current);
466 if (!Top::MayNamedAccess(checked, name, v8::ACCESS_GET)) {
467 return checked->GetPropertyWithFailedAccessCheck(receiver,
468 result,
469 name,
470 attributes);
471 }
472 }
473 // Stop traversing the chain once we reach the last object in the
474 // chain; either the holder of the result or null in case of an
475 // absent property.
476 if (current == last) break;
477 }
478
479 if (!result->IsProperty()) {
480 *attributes = ABSENT;
481 return Heap::undefined_value();
482 }
483 *attributes = result->GetAttributes();
Steve Blocka7e24c12009-10-30 11:49:00 +0000484 Object* value;
485 JSObject* holder = result->holder();
486 switch (result->type()) {
487 case NORMAL:
488 value = holder->GetNormalizedProperty(result);
489 ASSERT(!value->IsTheHole() || result->IsReadOnly());
490 return value->IsTheHole() ? Heap::undefined_value() : value;
491 case FIELD:
492 value = holder->FastPropertyAt(result->GetFieldIndex());
493 ASSERT(!value->IsTheHole() || result->IsReadOnly());
494 return value->IsTheHole() ? Heap::undefined_value() : value;
495 case CONSTANT_FUNCTION:
496 return result->GetConstantFunction();
497 case CALLBACKS:
498 return GetPropertyWithCallback(receiver,
499 result->GetCallbackObject(),
500 name,
501 holder);
502 case INTERCEPTOR: {
503 JSObject* recvr = JSObject::cast(receiver);
504 return holder->GetPropertyWithInterceptor(recvr, name, attributes);
505 }
506 default:
507 UNREACHABLE();
508 return NULL;
509 }
510}
511
512
513Object* Object::GetElementWithReceiver(Object* receiver, uint32_t index) {
514 // Non-JS objects do not have integer indexed properties.
515 if (!IsJSObject()) return Heap::undefined_value();
516 return JSObject::cast(this)->GetElementWithReceiver(JSObject::cast(receiver),
517 index);
518}
519
520
521Object* Object::GetPrototype() {
522 // The object is either a number, a string, a boolean, or a real JS object.
523 if (IsJSObject()) return JSObject::cast(this)->map()->prototype();
524 Context* context = Top::context()->global_context();
525
526 if (IsNumber()) return context->number_function()->instance_prototype();
527 if (IsString()) return context->string_function()->instance_prototype();
528 if (IsBoolean()) {
529 return context->boolean_function()->instance_prototype();
530 } else {
531 return Heap::null_value();
532 }
533}
534
535
536void Object::ShortPrint() {
537 HeapStringAllocator allocator;
538 StringStream accumulator(&allocator);
539 ShortPrint(&accumulator);
540 accumulator.OutputToStdOut();
541}
542
543
544void Object::ShortPrint(StringStream* accumulator) {
545 if (IsSmi()) {
546 Smi::cast(this)->SmiPrint(accumulator);
547 } else if (IsFailure()) {
548 Failure::cast(this)->FailurePrint(accumulator);
549 } else {
550 HeapObject::cast(this)->HeapObjectShortPrint(accumulator);
551 }
552}
553
554
555void Smi::SmiPrint() {
556 PrintF("%d", value());
557}
558
559
560void Smi::SmiPrint(StringStream* accumulator) {
561 accumulator->Add("%d", value());
562}
563
564
565void Failure::FailurePrint(StringStream* accumulator) {
Steve Block3ce2e202009-11-05 08:53:23 +0000566 accumulator->Add("Failure(%p)", reinterpret_cast<void*>(value()));
Steve Blocka7e24c12009-10-30 11:49:00 +0000567}
568
569
570void Failure::FailurePrint() {
Steve Block3ce2e202009-11-05 08:53:23 +0000571 PrintF("Failure(%p)", reinterpret_cast<void*>(value()));
Steve Blocka7e24c12009-10-30 11:49:00 +0000572}
573
574
575Failure* Failure::RetryAfterGC(int requested_bytes, AllocationSpace space) {
576 ASSERT((space & ~kSpaceTagMask) == 0);
577 // TODO(X64): Stop using Smi validation for non-smi checks, even if they
578 // happen to be identical at the moment.
579
580 int requested = requested_bytes >> kObjectAlignmentBits;
581 int value = (requested << kSpaceTagSize) | space;
582 // We can't very well allocate a heap number in this situation, and if the
583 // requested memory is so large it seems reasonable to say that this is an
584 // out of memory situation. This fixes a crash in
585 // js1_5/Regress/regress-303213.js.
586 if (value >> kSpaceTagSize != requested ||
587 !Smi::IsValid(value) ||
588 value != ((value << kFailureTypeTagSize) >> kFailureTypeTagSize) ||
589 !Smi::IsValid(value << kFailureTypeTagSize)) {
590 Top::context()->mark_out_of_memory();
591 return Failure::OutOfMemoryException();
592 }
593 return Construct(RETRY_AFTER_GC, value);
594}
595
596
597// Should a word be prefixed by 'a' or 'an' in order to read naturally in
598// English? Returns false for non-ASCII or words that don't start with
599// a capital letter. The a/an rule follows pronunciation in English.
600// We don't use the BBC's overcorrect "an historic occasion" though if
601// you speak a dialect you may well say "an 'istoric occasion".
602static bool AnWord(String* str) {
603 if (str->length() == 0) return false; // A nothing.
604 int c0 = str->Get(0);
605 int c1 = str->length() > 1 ? str->Get(1) : 0;
606 if (c0 == 'U') {
607 if (c1 > 'Z') {
608 return true; // An Umpire, but a UTF8String, a U.
609 }
610 } else if (c0 == 'A' || c0 == 'E' || c0 == 'I' || c0 == 'O') {
611 return true; // An Ape, an ABCBook.
612 } else if ((c1 == 0 || (c1 >= 'A' && c1 <= 'Z')) &&
613 (c0 == 'F' || c0 == 'H' || c0 == 'M' || c0 == 'N' || c0 == 'R' ||
614 c0 == 'S' || c0 == 'X')) {
615 return true; // An MP3File, an M.
616 }
617 return false;
618}
619
620
Steve Block6ded16b2010-05-10 14:33:55 +0100621Object* String::SlowTryFlatten(PretenureFlag pretenure) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000622#ifdef DEBUG
623 // Do not attempt to flatten in debug mode when allocation is not
624 // allowed. This is to avoid an assertion failure when allocating.
625 // Flattening strings is the only case where we always allow
626 // allocation because no GC is performed if the allocation fails.
627 if (!Heap::IsAllocationAllowed()) return this;
628#endif
629
630 switch (StringShape(this).representation_tag()) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000631 case kConsStringTag: {
632 ConsString* cs = ConsString::cast(this);
633 if (cs->second()->length() == 0) {
Leon Clarkef7060e22010-06-03 12:02:55 +0100634 return cs->first();
Steve Blocka7e24c12009-10-30 11:49:00 +0000635 }
636 // There's little point in putting the flat string in new space if the
637 // cons string is in old space. It can never get GCed until there is
638 // an old space GC.
Steve Block6ded16b2010-05-10 14:33:55 +0100639 PretenureFlag tenure = Heap::InNewSpace(this) ? pretenure : TENURED;
Steve Blocka7e24c12009-10-30 11:49:00 +0000640 int len = length();
641 Object* object;
642 String* result;
643 if (IsAsciiRepresentation()) {
644 object = Heap::AllocateRawAsciiString(len, tenure);
645 if (object->IsFailure()) return object;
646 result = String::cast(object);
647 String* first = cs->first();
648 int first_length = first->length();
649 char* dest = SeqAsciiString::cast(result)->GetChars();
650 WriteToFlat(first, dest, 0, first_length);
651 String* second = cs->second();
652 WriteToFlat(second,
653 dest + first_length,
654 0,
655 len - first_length);
656 } else {
657 object = Heap::AllocateRawTwoByteString(len, tenure);
658 if (object->IsFailure()) return object;
659 result = String::cast(object);
660 uc16* dest = SeqTwoByteString::cast(result)->GetChars();
661 String* first = cs->first();
662 int first_length = first->length();
663 WriteToFlat(first, dest, 0, first_length);
664 String* second = cs->second();
665 WriteToFlat(second,
666 dest + first_length,
667 0,
668 len - first_length);
669 }
670 cs->set_first(result);
671 cs->set_second(Heap::empty_string());
Leon Clarkef7060e22010-06-03 12:02:55 +0100672 return result;
Steve Blocka7e24c12009-10-30 11:49:00 +0000673 }
674 default:
675 return this;
676 }
677}
678
679
680bool String::MakeExternal(v8::String::ExternalStringResource* resource) {
681#ifdef DEBUG
Steve Block3ce2e202009-11-05 08:53:23 +0000682 if (FLAG_enable_slow_asserts) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000683 // Assert that the resource and the string are equivalent.
684 ASSERT(static_cast<size_t>(this->length()) == resource->length());
Kristian Monsen25f61362010-05-21 11:50:48 +0100685 ScopedVector<uc16> smart_chars(this->length());
686 String::WriteToFlat(this, smart_chars.start(), 0, this->length());
687 ASSERT(memcmp(smart_chars.start(),
Steve Blocka7e24c12009-10-30 11:49:00 +0000688 resource->data(),
Kristian Monsen25f61362010-05-21 11:50:48 +0100689 resource->length() * sizeof(smart_chars[0])) == 0);
Steve Blocka7e24c12009-10-30 11:49:00 +0000690 }
691#endif // DEBUG
692
693 int size = this->Size(); // Byte size of the original string.
694 if (size < ExternalString::kSize) {
695 // The string is too small to fit an external String in its place. This can
696 // only happen for zero length strings.
697 return false;
698 }
699 ASSERT(size >= ExternalString::kSize);
700 bool is_symbol = this->IsSymbol();
701 int length = this->length();
Steve Blockd0582a62009-12-15 09:54:21 +0000702 int hash_field = this->hash_field();
Steve Blocka7e24c12009-10-30 11:49:00 +0000703
704 // Morph the object to an external string by adjusting the map and
705 // reinitializing the fields.
Steve Blockd0582a62009-12-15 09:54:21 +0000706 this->set_map(Heap::external_string_map());
Steve Blocka7e24c12009-10-30 11:49:00 +0000707 ExternalTwoByteString* self = ExternalTwoByteString::cast(this);
708 self->set_length(length);
Steve Blockd0582a62009-12-15 09:54:21 +0000709 self->set_hash_field(hash_field);
Steve Blocka7e24c12009-10-30 11:49:00 +0000710 self->set_resource(resource);
711 // Additionally make the object into an external symbol if the original string
712 // was a symbol to start with.
713 if (is_symbol) {
714 self->Hash(); // Force regeneration of the hash value.
715 // Now morph this external string into a external symbol.
Steve Blockd0582a62009-12-15 09:54:21 +0000716 this->set_map(Heap::external_symbol_map());
Steve Blocka7e24c12009-10-30 11:49:00 +0000717 }
718
719 // Fill the remainder of the string with dead wood.
720 int new_size = this->Size(); // Byte size of the external String object.
721 Heap::CreateFillerObjectAt(this->address() + new_size, size - new_size);
722 return true;
723}
724
725
726bool String::MakeExternal(v8::String::ExternalAsciiStringResource* resource) {
727#ifdef DEBUG
Steve Block3ce2e202009-11-05 08:53:23 +0000728 if (FLAG_enable_slow_asserts) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000729 // Assert that the resource and the string are equivalent.
730 ASSERT(static_cast<size_t>(this->length()) == resource->length());
Kristian Monsen25f61362010-05-21 11:50:48 +0100731 ScopedVector<char> smart_chars(this->length());
732 String::WriteToFlat(this, smart_chars.start(), 0, this->length());
733 ASSERT(memcmp(smart_chars.start(),
Steve Blocka7e24c12009-10-30 11:49:00 +0000734 resource->data(),
Kristian Monsen25f61362010-05-21 11:50:48 +0100735 resource->length() * sizeof(smart_chars[0])) == 0);
Steve Blocka7e24c12009-10-30 11:49:00 +0000736 }
737#endif // DEBUG
738
739 int size = this->Size(); // Byte size of the original string.
740 if (size < ExternalString::kSize) {
741 // The string is too small to fit an external String in its place. This can
742 // only happen for zero length strings.
743 return false;
744 }
745 ASSERT(size >= ExternalString::kSize);
746 bool is_symbol = this->IsSymbol();
747 int length = this->length();
Steve Blockd0582a62009-12-15 09:54:21 +0000748 int hash_field = this->hash_field();
Steve Blocka7e24c12009-10-30 11:49:00 +0000749
750 // Morph the object to an external string by adjusting the map and
751 // reinitializing the fields.
Steve Blockd0582a62009-12-15 09:54:21 +0000752 this->set_map(Heap::external_ascii_string_map());
Steve Blocka7e24c12009-10-30 11:49:00 +0000753 ExternalAsciiString* self = ExternalAsciiString::cast(this);
754 self->set_length(length);
Steve Blockd0582a62009-12-15 09:54:21 +0000755 self->set_hash_field(hash_field);
Steve Blocka7e24c12009-10-30 11:49:00 +0000756 self->set_resource(resource);
757 // Additionally make the object into an external symbol if the original string
758 // was a symbol to start with.
759 if (is_symbol) {
760 self->Hash(); // Force regeneration of the hash value.
761 // Now morph this external string into a external symbol.
Steve Blockd0582a62009-12-15 09:54:21 +0000762 this->set_map(Heap::external_ascii_symbol_map());
Steve Blocka7e24c12009-10-30 11:49:00 +0000763 }
764
765 // Fill the remainder of the string with dead wood.
766 int new_size = this->Size(); // Byte size of the external String object.
767 Heap::CreateFillerObjectAt(this->address() + new_size, size - new_size);
768 return true;
769}
770
771
772void String::StringShortPrint(StringStream* accumulator) {
773 int len = length();
Steve Blockd0582a62009-12-15 09:54:21 +0000774 if (len > kMaxShortPrintLength) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000775 accumulator->Add("<Very long string[%u]>", len);
776 return;
777 }
778
779 if (!LooksValid()) {
780 accumulator->Add("<Invalid String>");
781 return;
782 }
783
784 StringInputBuffer buf(this);
785
786 bool truncated = false;
787 if (len > kMaxShortPrintLength) {
788 len = kMaxShortPrintLength;
789 truncated = true;
790 }
791 bool ascii = true;
792 for (int i = 0; i < len; i++) {
793 int c = buf.GetNext();
794
795 if (c < 32 || c >= 127) {
796 ascii = false;
797 }
798 }
799 buf.Reset(this);
800 if (ascii) {
801 accumulator->Add("<String[%u]: ", length());
802 for (int i = 0; i < len; i++) {
803 accumulator->Put(buf.GetNext());
804 }
805 accumulator->Put('>');
806 } else {
807 // Backslash indicates that the string contains control
808 // characters and that backslashes are therefore escaped.
809 accumulator->Add("<String[%u]\\: ", length());
810 for (int i = 0; i < len; i++) {
811 int c = buf.GetNext();
812 if (c == '\n') {
813 accumulator->Add("\\n");
814 } else if (c == '\r') {
815 accumulator->Add("\\r");
816 } else if (c == '\\') {
817 accumulator->Add("\\\\");
818 } else if (c < 32 || c > 126) {
819 accumulator->Add("\\x%02x", c);
820 } else {
821 accumulator->Put(c);
822 }
823 }
824 if (truncated) {
825 accumulator->Put('.');
826 accumulator->Put('.');
827 accumulator->Put('.');
828 }
829 accumulator->Put('>');
830 }
831 return;
832}
833
834
835void JSObject::JSObjectShortPrint(StringStream* accumulator) {
836 switch (map()->instance_type()) {
837 case JS_ARRAY_TYPE: {
838 double length = JSArray::cast(this)->length()->Number();
839 accumulator->Add("<JS array[%u]>", static_cast<uint32_t>(length));
840 break;
841 }
842 case JS_REGEXP_TYPE: {
843 accumulator->Add("<JS RegExp>");
844 break;
845 }
846 case JS_FUNCTION_TYPE: {
847 Object* fun_name = JSFunction::cast(this)->shared()->name();
848 bool printed = false;
849 if (fun_name->IsString()) {
850 String* str = String::cast(fun_name);
851 if (str->length() > 0) {
852 accumulator->Add("<JS Function ");
853 accumulator->Put(str);
854 accumulator->Put('>');
855 printed = true;
856 }
857 }
858 if (!printed) {
859 accumulator->Add("<JS Function>");
860 }
861 break;
862 }
863 // All other JSObjects are rather similar to each other (JSObject,
864 // JSGlobalProxy, JSGlobalObject, JSUndetectableObject, JSValue).
865 default: {
866 Object* constructor = map()->constructor();
867 bool printed = false;
868 if (constructor->IsHeapObject() &&
869 !Heap::Contains(HeapObject::cast(constructor))) {
870 accumulator->Add("!!!INVALID CONSTRUCTOR!!!");
871 } else {
872 bool global_object = IsJSGlobalProxy();
873 if (constructor->IsJSFunction()) {
874 if (!Heap::Contains(JSFunction::cast(constructor)->shared())) {
875 accumulator->Add("!!!INVALID SHARED ON CONSTRUCTOR!!!");
876 } else {
877 Object* constructor_name =
878 JSFunction::cast(constructor)->shared()->name();
879 if (constructor_name->IsString()) {
880 String* str = String::cast(constructor_name);
881 if (str->length() > 0) {
882 bool vowel = AnWord(str);
883 accumulator->Add("<%sa%s ",
884 global_object ? "Global Object: " : "",
885 vowel ? "n" : "");
886 accumulator->Put(str);
887 accumulator->Put('>');
888 printed = true;
889 }
890 }
891 }
892 }
893 if (!printed) {
894 accumulator->Add("<JS %sObject", global_object ? "Global " : "");
895 }
896 }
897 if (IsJSValue()) {
898 accumulator->Add(" value = ");
899 JSValue::cast(this)->value()->ShortPrint(accumulator);
900 }
901 accumulator->Put('>');
902 break;
903 }
904 }
905}
906
907
908void HeapObject::HeapObjectShortPrint(StringStream* accumulator) {
909 // if (!Heap::InNewSpace(this)) PrintF("*", this);
910 if (!Heap::Contains(this)) {
911 accumulator->Add("!!!INVALID POINTER!!!");
912 return;
913 }
914 if (!Heap::Contains(map())) {
915 accumulator->Add("!!!INVALID MAP!!!");
916 return;
917 }
918
919 accumulator->Add("%p ", this);
920
921 if (IsString()) {
922 String::cast(this)->StringShortPrint(accumulator);
923 return;
924 }
925 if (IsJSObject()) {
926 JSObject::cast(this)->JSObjectShortPrint(accumulator);
927 return;
928 }
929 switch (map()->instance_type()) {
930 case MAP_TYPE:
931 accumulator->Add("<Map>");
932 break;
933 case FIXED_ARRAY_TYPE:
934 accumulator->Add("<FixedArray[%u]>", FixedArray::cast(this)->length());
935 break;
936 case BYTE_ARRAY_TYPE:
937 accumulator->Add("<ByteArray[%u]>", ByteArray::cast(this)->length());
938 break;
939 case PIXEL_ARRAY_TYPE:
940 accumulator->Add("<PixelArray[%u]>", PixelArray::cast(this)->length());
941 break;
Steve Block3ce2e202009-11-05 08:53:23 +0000942 case EXTERNAL_BYTE_ARRAY_TYPE:
943 accumulator->Add("<ExternalByteArray[%u]>",
944 ExternalByteArray::cast(this)->length());
945 break;
946 case EXTERNAL_UNSIGNED_BYTE_ARRAY_TYPE:
947 accumulator->Add("<ExternalUnsignedByteArray[%u]>",
948 ExternalUnsignedByteArray::cast(this)->length());
949 break;
950 case EXTERNAL_SHORT_ARRAY_TYPE:
951 accumulator->Add("<ExternalShortArray[%u]>",
952 ExternalShortArray::cast(this)->length());
953 break;
954 case EXTERNAL_UNSIGNED_SHORT_ARRAY_TYPE:
955 accumulator->Add("<ExternalUnsignedShortArray[%u]>",
956 ExternalUnsignedShortArray::cast(this)->length());
957 break;
958 case EXTERNAL_INT_ARRAY_TYPE:
959 accumulator->Add("<ExternalIntArray[%u]>",
960 ExternalIntArray::cast(this)->length());
961 break;
962 case EXTERNAL_UNSIGNED_INT_ARRAY_TYPE:
963 accumulator->Add("<ExternalUnsignedIntArray[%u]>",
964 ExternalUnsignedIntArray::cast(this)->length());
965 break;
966 case EXTERNAL_FLOAT_ARRAY_TYPE:
967 accumulator->Add("<ExternalFloatArray[%u]>",
968 ExternalFloatArray::cast(this)->length());
969 break;
Steve Blocka7e24c12009-10-30 11:49:00 +0000970 case SHARED_FUNCTION_INFO_TYPE:
971 accumulator->Add("<SharedFunctionInfo>");
972 break;
973#define MAKE_STRUCT_CASE(NAME, Name, name) \
974 case NAME##_TYPE: \
975 accumulator->Put('<'); \
976 accumulator->Add(#Name); \
977 accumulator->Put('>'); \
978 break;
979 STRUCT_LIST(MAKE_STRUCT_CASE)
980#undef MAKE_STRUCT_CASE
981 case CODE_TYPE:
982 accumulator->Add("<Code>");
983 break;
984 case ODDBALL_TYPE: {
985 if (IsUndefined())
986 accumulator->Add("<undefined>");
987 else if (IsTheHole())
988 accumulator->Add("<the hole>");
989 else if (IsNull())
990 accumulator->Add("<null>");
991 else if (IsTrue())
992 accumulator->Add("<true>");
993 else if (IsFalse())
994 accumulator->Add("<false>");
995 else
996 accumulator->Add("<Odd Oddball>");
997 break;
998 }
999 case HEAP_NUMBER_TYPE:
1000 accumulator->Add("<Number: ");
1001 HeapNumber::cast(this)->HeapNumberPrint(accumulator);
1002 accumulator->Put('>');
1003 break;
1004 case PROXY_TYPE:
1005 accumulator->Add("<Proxy>");
1006 break;
1007 case JS_GLOBAL_PROPERTY_CELL_TYPE:
1008 accumulator->Add("Cell for ");
1009 JSGlobalPropertyCell::cast(this)->value()->ShortPrint(accumulator);
1010 break;
1011 default:
1012 accumulator->Add("<Other heap object (%d)>", map()->instance_type());
1013 break;
1014 }
1015}
1016
1017
1018int HeapObject::SlowSizeFromMap(Map* map) {
1019 // Avoid calling functions such as FixedArray::cast during GC, which
1020 // read map pointer of this object again.
1021 InstanceType instance_type = map->instance_type();
1022 uint32_t type = static_cast<uint32_t>(instance_type);
1023
1024 if (instance_type < FIRST_NONSTRING_TYPE
1025 && (StringShape(instance_type).IsSequential())) {
1026 if ((type & kStringEncodingMask) == kAsciiStringTag) {
1027 SeqAsciiString* seq_ascii_this = reinterpret_cast<SeqAsciiString*>(this);
1028 return seq_ascii_this->SeqAsciiStringSize(instance_type);
1029 } else {
1030 SeqTwoByteString* self = reinterpret_cast<SeqTwoByteString*>(this);
1031 return self->SeqTwoByteStringSize(instance_type);
1032 }
1033 }
1034
1035 switch (instance_type) {
1036 case FIXED_ARRAY_TYPE:
1037 return reinterpret_cast<FixedArray*>(this)->FixedArraySize();
1038 case BYTE_ARRAY_TYPE:
1039 return reinterpret_cast<ByteArray*>(this)->ByteArraySize();
1040 case CODE_TYPE:
1041 return reinterpret_cast<Code*>(this)->CodeSize();
1042 case MAP_TYPE:
1043 return Map::kSize;
1044 default:
1045 return map->instance_size();
1046 }
1047}
1048
1049
1050void HeapObject::Iterate(ObjectVisitor* v) {
1051 // Handle header
1052 IteratePointer(v, kMapOffset);
1053 // Handle object body
1054 Map* m = map();
1055 IterateBody(m->instance_type(), SizeFromMap(m), v);
1056}
1057
1058
1059void HeapObject::IterateBody(InstanceType type, int object_size,
1060 ObjectVisitor* v) {
1061 // Avoiding <Type>::cast(this) because it accesses the map pointer field.
1062 // During GC, the map pointer field is encoded.
1063 if (type < FIRST_NONSTRING_TYPE) {
1064 switch (type & kStringRepresentationMask) {
1065 case kSeqStringTag:
1066 break;
1067 case kConsStringTag:
1068 reinterpret_cast<ConsString*>(this)->ConsStringIterateBody(v);
1069 break;
Steve Blockd0582a62009-12-15 09:54:21 +00001070 case kExternalStringTag:
1071 if ((type & kStringEncodingMask) == kAsciiStringTag) {
1072 reinterpret_cast<ExternalAsciiString*>(this)->
1073 ExternalAsciiStringIterateBody(v);
1074 } else {
1075 reinterpret_cast<ExternalTwoByteString*>(this)->
1076 ExternalTwoByteStringIterateBody(v);
1077 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001078 break;
1079 }
1080 return;
1081 }
1082
1083 switch (type) {
1084 case FIXED_ARRAY_TYPE:
1085 reinterpret_cast<FixedArray*>(this)->FixedArrayIterateBody(v);
1086 break;
1087 case JS_OBJECT_TYPE:
1088 case JS_CONTEXT_EXTENSION_OBJECT_TYPE:
1089 case JS_VALUE_TYPE:
1090 case JS_ARRAY_TYPE:
1091 case JS_REGEXP_TYPE:
1092 case JS_FUNCTION_TYPE:
1093 case JS_GLOBAL_PROXY_TYPE:
1094 case JS_GLOBAL_OBJECT_TYPE:
1095 case JS_BUILTINS_OBJECT_TYPE:
1096 reinterpret_cast<JSObject*>(this)->JSObjectIterateBody(object_size, v);
1097 break;
1098 case ODDBALL_TYPE:
1099 reinterpret_cast<Oddball*>(this)->OddballIterateBody(v);
1100 break;
1101 case PROXY_TYPE:
1102 reinterpret_cast<Proxy*>(this)->ProxyIterateBody(v);
1103 break;
1104 case MAP_TYPE:
1105 reinterpret_cast<Map*>(this)->MapIterateBody(v);
1106 break;
1107 case CODE_TYPE:
1108 reinterpret_cast<Code*>(this)->CodeIterateBody(v);
1109 break;
1110 case JS_GLOBAL_PROPERTY_CELL_TYPE:
1111 reinterpret_cast<JSGlobalPropertyCell*>(this)
1112 ->JSGlobalPropertyCellIterateBody(v);
1113 break;
1114 case HEAP_NUMBER_TYPE:
1115 case FILLER_TYPE:
1116 case BYTE_ARRAY_TYPE:
1117 case PIXEL_ARRAY_TYPE:
Steve Block3ce2e202009-11-05 08:53:23 +00001118 case EXTERNAL_BYTE_ARRAY_TYPE:
1119 case EXTERNAL_UNSIGNED_BYTE_ARRAY_TYPE:
1120 case EXTERNAL_SHORT_ARRAY_TYPE:
1121 case EXTERNAL_UNSIGNED_SHORT_ARRAY_TYPE:
1122 case EXTERNAL_INT_ARRAY_TYPE:
1123 case EXTERNAL_UNSIGNED_INT_ARRAY_TYPE:
1124 case EXTERNAL_FLOAT_ARRAY_TYPE:
Steve Blocka7e24c12009-10-30 11:49:00 +00001125 break;
1126 case SHARED_FUNCTION_INFO_TYPE: {
1127 SharedFunctionInfo* shared = reinterpret_cast<SharedFunctionInfo*>(this);
1128 shared->SharedFunctionInfoIterateBody(v);
1129 break;
1130 }
1131#define MAKE_STRUCT_CASE(NAME, Name, name) \
1132 case NAME##_TYPE:
1133 STRUCT_LIST(MAKE_STRUCT_CASE)
1134#undef MAKE_STRUCT_CASE
1135 IterateStructBody(object_size, v);
1136 break;
1137 default:
1138 PrintF("Unknown type: %d\n", type);
1139 UNREACHABLE();
1140 }
1141}
1142
1143
1144void HeapObject::IterateStructBody(int object_size, ObjectVisitor* v) {
1145 IteratePointers(v, HeapObject::kHeaderSize, object_size);
1146}
1147
1148
1149Object* HeapNumber::HeapNumberToBoolean() {
1150 // NaN, +0, and -0 should return the false object
1151 switch (fpclassify(value())) {
1152 case FP_NAN: // fall through
1153 case FP_ZERO: return Heap::false_value();
1154 default: return Heap::true_value();
1155 }
1156}
1157
1158
1159void HeapNumber::HeapNumberPrint() {
1160 PrintF("%.16g", Number());
1161}
1162
1163
1164void HeapNumber::HeapNumberPrint(StringStream* accumulator) {
1165 // The Windows version of vsnprintf can allocate when printing a %g string
1166 // into a buffer that may not be big enough. We don't want random memory
1167 // allocation when producing post-crash stack traces, so we print into a
1168 // buffer that is plenty big enough for any floating point number, then
1169 // print that using vsnprintf (which may truncate but never allocate if
1170 // there is no more space in the buffer).
1171 EmbeddedVector<char, 100> buffer;
1172 OS::SNPrintF(buffer, "%.16g", Number());
1173 accumulator->Add("%s", buffer.start());
1174}
1175
1176
1177String* JSObject::class_name() {
1178 if (IsJSFunction()) {
1179 return Heap::function_class_symbol();
1180 }
1181 if (map()->constructor()->IsJSFunction()) {
1182 JSFunction* constructor = JSFunction::cast(map()->constructor());
1183 return String::cast(constructor->shared()->instance_class_name());
1184 }
1185 // If the constructor is not present, return "Object".
1186 return Heap::Object_symbol();
1187}
1188
1189
1190String* JSObject::constructor_name() {
1191 if (IsJSFunction()) {
Steve Block6ded16b2010-05-10 14:33:55 +01001192 return Heap::closure_symbol();
Steve Blocka7e24c12009-10-30 11:49:00 +00001193 }
1194 if (map()->constructor()->IsJSFunction()) {
1195 JSFunction* constructor = JSFunction::cast(map()->constructor());
1196 String* name = String::cast(constructor->shared()->name());
1197 return name->length() > 0 ? name : constructor->shared()->inferred_name();
1198 }
1199 // If the constructor is not present, return "Object".
1200 return Heap::Object_symbol();
1201}
1202
1203
1204void JSObject::JSObjectIterateBody(int object_size, ObjectVisitor* v) {
1205 // Iterate over all fields in the body. Assumes all are Object*.
1206 IteratePointers(v, kPropertiesOffset, object_size);
1207}
1208
1209
1210Object* JSObject::AddFastPropertyUsingMap(Map* new_map,
1211 String* name,
1212 Object* value) {
1213 int index = new_map->PropertyIndexFor(name);
1214 if (map()->unused_property_fields() == 0) {
1215 ASSERT(map()->unused_property_fields() == 0);
1216 int new_unused = new_map->unused_property_fields();
1217 Object* values =
1218 properties()->CopySize(properties()->length() + new_unused + 1);
1219 if (values->IsFailure()) return values;
1220 set_properties(FixedArray::cast(values));
1221 }
1222 set_map(new_map);
1223 return FastPropertyAtPut(index, value);
1224}
1225
1226
1227Object* JSObject::AddFastProperty(String* name,
1228 Object* value,
1229 PropertyAttributes attributes) {
1230 // Normalize the object if the name is an actual string (not the
1231 // hidden symbols) and is not a real identifier.
1232 StringInputBuffer buffer(name);
1233 if (!Scanner::IsIdentifier(&buffer) && name != Heap::hidden_symbol()) {
1234 Object* obj = NormalizeProperties(CLEAR_INOBJECT_PROPERTIES, 0);
1235 if (obj->IsFailure()) return obj;
1236 return AddSlowProperty(name, value, attributes);
1237 }
1238
1239 DescriptorArray* old_descriptors = map()->instance_descriptors();
1240 // Compute the new index for new field.
1241 int index = map()->NextFreePropertyIndex();
1242
1243 // Allocate new instance descriptors with (name, index) added
1244 FieldDescriptor new_field(name, index, attributes);
1245 Object* new_descriptors =
1246 old_descriptors->CopyInsert(&new_field, REMOVE_TRANSITIONS);
1247 if (new_descriptors->IsFailure()) return new_descriptors;
1248
1249 // Only allow map transition if the object's map is NOT equal to the
1250 // global object_function's map and there is not a transition for name.
1251 bool allow_map_transition =
1252 !old_descriptors->Contains(name) &&
1253 (Top::context()->global_context()->object_function()->map() != map());
1254
1255 ASSERT(index < map()->inobject_properties() ||
1256 (index - map()->inobject_properties()) < properties()->length() ||
1257 map()->unused_property_fields() == 0);
1258 // Allocate a new map for the object.
1259 Object* r = map()->CopyDropDescriptors();
1260 if (r->IsFailure()) return r;
1261 Map* new_map = Map::cast(r);
1262 if (allow_map_transition) {
1263 // Allocate new instance descriptors for the old map with map transition.
1264 MapTransitionDescriptor d(name, Map::cast(new_map), attributes);
1265 Object* r = old_descriptors->CopyInsert(&d, KEEP_TRANSITIONS);
1266 if (r->IsFailure()) return r;
1267 old_descriptors = DescriptorArray::cast(r);
1268 }
1269
1270 if (map()->unused_property_fields() == 0) {
1271 if (properties()->length() > kMaxFastProperties) {
1272 Object* obj = NormalizeProperties(CLEAR_INOBJECT_PROPERTIES, 0);
1273 if (obj->IsFailure()) return obj;
1274 return AddSlowProperty(name, value, attributes);
1275 }
1276 // Make room for the new value
1277 Object* values =
1278 properties()->CopySize(properties()->length() + kFieldsAdded);
1279 if (values->IsFailure()) return values;
1280 set_properties(FixedArray::cast(values));
1281 new_map->set_unused_property_fields(kFieldsAdded - 1);
1282 } else {
1283 new_map->set_unused_property_fields(map()->unused_property_fields() - 1);
1284 }
1285 // We have now allocated all the necessary objects.
1286 // All the changes can be applied at once, so they are atomic.
1287 map()->set_instance_descriptors(old_descriptors);
1288 new_map->set_instance_descriptors(DescriptorArray::cast(new_descriptors));
1289 set_map(new_map);
1290 return FastPropertyAtPut(index, value);
1291}
1292
1293
1294Object* JSObject::AddConstantFunctionProperty(String* name,
1295 JSFunction* function,
1296 PropertyAttributes attributes) {
Leon Clarkee46be812010-01-19 14:06:41 +00001297 ASSERT(!Heap::InNewSpace(function));
1298
Steve Blocka7e24c12009-10-30 11:49:00 +00001299 // Allocate new instance descriptors with (name, function) added
1300 ConstantFunctionDescriptor d(name, function, attributes);
1301 Object* new_descriptors =
1302 map()->instance_descriptors()->CopyInsert(&d, REMOVE_TRANSITIONS);
1303 if (new_descriptors->IsFailure()) return new_descriptors;
1304
1305 // Allocate a new map for the object.
1306 Object* new_map = map()->CopyDropDescriptors();
1307 if (new_map->IsFailure()) return new_map;
1308
1309 DescriptorArray* descriptors = DescriptorArray::cast(new_descriptors);
1310 Map::cast(new_map)->set_instance_descriptors(descriptors);
1311 Map* old_map = map();
1312 set_map(Map::cast(new_map));
1313
1314 // If the old map is the global object map (from new Object()),
1315 // then transitions are not added to it, so we are done.
1316 if (old_map == Top::context()->global_context()->object_function()->map()) {
1317 return function;
1318 }
1319
1320 // Do not add CONSTANT_TRANSITIONS to global objects
1321 if (IsGlobalObject()) {
1322 return function;
1323 }
1324
1325 // Add a CONSTANT_TRANSITION descriptor to the old map,
1326 // so future assignments to this property on other objects
1327 // of the same type will create a normal field, not a constant function.
1328 // Don't do this for special properties, with non-trival attributes.
1329 if (attributes != NONE) {
1330 return function;
1331 }
1332 ConstTransitionDescriptor mark(name);
1333 new_descriptors =
1334 old_map->instance_descriptors()->CopyInsert(&mark, KEEP_TRANSITIONS);
1335 if (new_descriptors->IsFailure()) {
1336 return function; // We have accomplished the main goal, so return success.
1337 }
1338 old_map->set_instance_descriptors(DescriptorArray::cast(new_descriptors));
1339
1340 return function;
1341}
1342
1343
1344// Add property in slow mode
1345Object* JSObject::AddSlowProperty(String* name,
1346 Object* value,
1347 PropertyAttributes attributes) {
1348 ASSERT(!HasFastProperties());
1349 StringDictionary* dict = property_dictionary();
1350 Object* store_value = value;
1351 if (IsGlobalObject()) {
1352 // In case name is an orphaned property reuse the cell.
1353 int entry = dict->FindEntry(name);
1354 if (entry != StringDictionary::kNotFound) {
1355 store_value = dict->ValueAt(entry);
1356 JSGlobalPropertyCell::cast(store_value)->set_value(value);
1357 // Assign an enumeration index to the property and update
1358 // SetNextEnumerationIndex.
1359 int index = dict->NextEnumerationIndex();
1360 PropertyDetails details = PropertyDetails(attributes, NORMAL, index);
1361 dict->SetNextEnumerationIndex(index + 1);
1362 dict->SetEntry(entry, name, store_value, details);
1363 return value;
1364 }
1365 store_value = Heap::AllocateJSGlobalPropertyCell(value);
1366 if (store_value->IsFailure()) return store_value;
1367 JSGlobalPropertyCell::cast(store_value)->set_value(value);
1368 }
1369 PropertyDetails details = PropertyDetails(attributes, NORMAL);
1370 Object* result = dict->Add(name, store_value, details);
1371 if (result->IsFailure()) return result;
1372 if (dict != result) set_properties(StringDictionary::cast(result));
1373 return value;
1374}
1375
1376
1377Object* JSObject::AddProperty(String* name,
1378 Object* value,
1379 PropertyAttributes attributes) {
1380 ASSERT(!IsJSGlobalProxy());
1381 if (HasFastProperties()) {
1382 // Ensure the descriptor array does not get too big.
1383 if (map()->instance_descriptors()->number_of_descriptors() <
1384 DescriptorArray::kMaxNumberOfDescriptors) {
Leon Clarkee46be812010-01-19 14:06:41 +00001385 if (value->IsJSFunction() && !Heap::InNewSpace(value)) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001386 return AddConstantFunctionProperty(name,
1387 JSFunction::cast(value),
1388 attributes);
1389 } else {
1390 return AddFastProperty(name, value, attributes);
1391 }
1392 } else {
1393 // Normalize the object to prevent very large instance descriptors.
1394 // This eliminates unwanted N^2 allocation and lookup behavior.
1395 Object* obj = NormalizeProperties(CLEAR_INOBJECT_PROPERTIES, 0);
1396 if (obj->IsFailure()) return obj;
1397 }
1398 }
1399 return AddSlowProperty(name, value, attributes);
1400}
1401
1402
1403Object* JSObject::SetPropertyPostInterceptor(String* name,
1404 Object* value,
1405 PropertyAttributes attributes) {
1406 // Check local property, ignore interceptor.
1407 LookupResult result;
1408 LocalLookupRealNamedProperty(name, &result);
Andrei Popescu402d9372010-02-26 13:31:12 +00001409 if (result.IsFound()) {
1410 // An existing property, a map transition or a null descriptor was
1411 // found. Use set property to handle all these cases.
1412 return SetProperty(&result, name, value, attributes);
1413 }
1414 // Add a new real property.
Steve Blocka7e24c12009-10-30 11:49:00 +00001415 return AddProperty(name, value, attributes);
1416}
1417
1418
1419Object* JSObject::ReplaceSlowProperty(String* name,
Steve Blockd0582a62009-12-15 09:54:21 +00001420 Object* value,
1421 PropertyAttributes attributes) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001422 StringDictionary* dictionary = property_dictionary();
1423 int old_index = dictionary->FindEntry(name);
1424 int new_enumeration_index = 0; // 0 means "Use the next available index."
1425 if (old_index != -1) {
1426 // All calls to ReplaceSlowProperty have had all transitions removed.
1427 ASSERT(!dictionary->DetailsAt(old_index).IsTransition());
1428 new_enumeration_index = dictionary->DetailsAt(old_index).index();
1429 }
1430
1431 PropertyDetails new_details(attributes, NORMAL, new_enumeration_index);
1432 return SetNormalizedProperty(name, value, new_details);
1433}
1434
Steve Blockd0582a62009-12-15 09:54:21 +00001435
Steve Blocka7e24c12009-10-30 11:49:00 +00001436Object* JSObject::ConvertDescriptorToFieldAndMapTransition(
1437 String* name,
1438 Object* new_value,
1439 PropertyAttributes attributes) {
1440 Map* old_map = map();
1441 Object* result = ConvertDescriptorToField(name, new_value, attributes);
1442 if (result->IsFailure()) return result;
1443 // If we get to this point we have succeeded - do not return failure
1444 // after this point. Later stuff is optional.
1445 if (!HasFastProperties()) {
1446 return result;
1447 }
1448 // Do not add transitions to the map of "new Object()".
1449 if (map() == Top::context()->global_context()->object_function()->map()) {
1450 return result;
1451 }
1452
1453 MapTransitionDescriptor transition(name,
1454 map(),
1455 attributes);
1456 Object* new_descriptors =
1457 old_map->instance_descriptors()->
1458 CopyInsert(&transition, KEEP_TRANSITIONS);
1459 if (new_descriptors->IsFailure()) return result; // Yes, return _result_.
1460 old_map->set_instance_descriptors(DescriptorArray::cast(new_descriptors));
1461 return result;
1462}
1463
1464
1465Object* JSObject::ConvertDescriptorToField(String* name,
1466 Object* new_value,
1467 PropertyAttributes attributes) {
1468 if (map()->unused_property_fields() == 0 &&
1469 properties()->length() > kMaxFastProperties) {
1470 Object* obj = NormalizeProperties(CLEAR_INOBJECT_PROPERTIES, 0);
1471 if (obj->IsFailure()) return obj;
1472 return ReplaceSlowProperty(name, new_value, attributes);
1473 }
1474
1475 int index = map()->NextFreePropertyIndex();
1476 FieldDescriptor new_field(name, index, attributes);
1477 // Make a new DescriptorArray replacing an entry with FieldDescriptor.
1478 Object* descriptors_unchecked = map()->instance_descriptors()->
1479 CopyInsert(&new_field, REMOVE_TRANSITIONS);
1480 if (descriptors_unchecked->IsFailure()) return descriptors_unchecked;
1481 DescriptorArray* new_descriptors =
1482 DescriptorArray::cast(descriptors_unchecked);
1483
1484 // Make a new map for the object.
1485 Object* new_map_unchecked = map()->CopyDropDescriptors();
1486 if (new_map_unchecked->IsFailure()) return new_map_unchecked;
1487 Map* new_map = Map::cast(new_map_unchecked);
1488 new_map->set_instance_descriptors(new_descriptors);
1489
1490 // Make new properties array if necessary.
1491 FixedArray* new_properties = 0; // Will always be NULL or a valid pointer.
1492 int new_unused_property_fields = map()->unused_property_fields() - 1;
1493 if (map()->unused_property_fields() == 0) {
1494 new_unused_property_fields = kFieldsAdded - 1;
1495 Object* new_properties_unchecked =
1496 properties()->CopySize(properties()->length() + kFieldsAdded);
1497 if (new_properties_unchecked->IsFailure()) return new_properties_unchecked;
1498 new_properties = FixedArray::cast(new_properties_unchecked);
1499 }
1500
1501 // Update pointers to commit changes.
1502 // Object points to the new map.
1503 new_map->set_unused_property_fields(new_unused_property_fields);
1504 set_map(new_map);
1505 if (new_properties) {
1506 set_properties(FixedArray::cast(new_properties));
1507 }
1508 return FastPropertyAtPut(index, new_value);
1509}
1510
1511
1512
1513Object* JSObject::SetPropertyWithInterceptor(String* name,
1514 Object* value,
1515 PropertyAttributes attributes) {
1516 HandleScope scope;
1517 Handle<JSObject> this_handle(this);
1518 Handle<String> name_handle(name);
1519 Handle<Object> value_handle(value);
1520 Handle<InterceptorInfo> interceptor(GetNamedInterceptor());
1521 if (!interceptor->setter()->IsUndefined()) {
1522 LOG(ApiNamedPropertyAccess("interceptor-named-set", this, name));
1523 CustomArguments args(interceptor->data(), this, this);
1524 v8::AccessorInfo info(args.end());
1525 v8::NamedPropertySetter setter =
1526 v8::ToCData<v8::NamedPropertySetter>(interceptor->setter());
1527 v8::Handle<v8::Value> result;
1528 {
1529 // Leaving JavaScript.
1530 VMState state(EXTERNAL);
1531 Handle<Object> value_unhole(value->IsTheHole() ?
1532 Heap::undefined_value() :
1533 value);
1534 result = setter(v8::Utils::ToLocal(name_handle),
1535 v8::Utils::ToLocal(value_unhole),
1536 info);
1537 }
1538 RETURN_IF_SCHEDULED_EXCEPTION();
1539 if (!result.IsEmpty()) return *value_handle;
1540 }
1541 Object* raw_result = this_handle->SetPropertyPostInterceptor(*name_handle,
1542 *value_handle,
1543 attributes);
1544 RETURN_IF_SCHEDULED_EXCEPTION();
1545 return raw_result;
1546}
1547
1548
1549Object* JSObject::SetProperty(String* name,
1550 Object* value,
1551 PropertyAttributes attributes) {
1552 LookupResult result;
1553 LocalLookup(name, &result);
1554 return SetProperty(&result, name, value, attributes);
1555}
1556
1557
1558Object* JSObject::SetPropertyWithCallback(Object* structure,
1559 String* name,
1560 Object* value,
1561 JSObject* holder) {
1562 HandleScope scope;
1563
1564 // We should never get here to initialize a const with the hole
1565 // value since a const declaration would conflict with the setter.
1566 ASSERT(!value->IsTheHole());
1567 Handle<Object> value_handle(value);
1568
1569 // To accommodate both the old and the new api we switch on the
1570 // data structure used to store the callbacks. Eventually proxy
1571 // callbacks should be phased out.
1572 if (structure->IsProxy()) {
1573 AccessorDescriptor* callback =
1574 reinterpret_cast<AccessorDescriptor*>(Proxy::cast(structure)->proxy());
1575 Object* obj = (callback->setter)(this, value, callback->data);
1576 RETURN_IF_SCHEDULED_EXCEPTION();
1577 if (obj->IsFailure()) return obj;
1578 return *value_handle;
1579 }
1580
1581 if (structure->IsAccessorInfo()) {
1582 // api style callbacks
1583 AccessorInfo* data = AccessorInfo::cast(structure);
1584 Object* call_obj = data->setter();
1585 v8::AccessorSetter call_fun = v8::ToCData<v8::AccessorSetter>(call_obj);
1586 if (call_fun == NULL) return value;
1587 Handle<String> key(name);
1588 LOG(ApiNamedPropertyAccess("store", this, name));
1589 CustomArguments args(data->data(), this, JSObject::cast(holder));
1590 v8::AccessorInfo info(args.end());
1591 {
1592 // Leaving JavaScript.
1593 VMState state(EXTERNAL);
1594 call_fun(v8::Utils::ToLocal(key),
1595 v8::Utils::ToLocal(value_handle),
1596 info);
1597 }
1598 RETURN_IF_SCHEDULED_EXCEPTION();
1599 return *value_handle;
1600 }
1601
1602 if (structure->IsFixedArray()) {
1603 Object* setter = FixedArray::cast(structure)->get(kSetterIndex);
1604 if (setter->IsJSFunction()) {
1605 return SetPropertyWithDefinedSetter(JSFunction::cast(setter), value);
1606 } else {
1607 Handle<String> key(name);
1608 Handle<Object> holder_handle(holder);
1609 Handle<Object> args[2] = { key, holder_handle };
1610 return Top::Throw(*Factory::NewTypeError("no_setter_in_callback",
1611 HandleVector(args, 2)));
1612 }
1613 }
1614
1615 UNREACHABLE();
Leon Clarkef7060e22010-06-03 12:02:55 +01001616 return NULL;
Steve Blocka7e24c12009-10-30 11:49:00 +00001617}
1618
1619
1620Object* JSObject::SetPropertyWithDefinedSetter(JSFunction* setter,
1621 Object* value) {
1622 Handle<Object> value_handle(value);
1623 Handle<JSFunction> fun(JSFunction::cast(setter));
1624 Handle<JSObject> self(this);
1625#ifdef ENABLE_DEBUGGER_SUPPORT
1626 // Handle stepping into a setter if step into is active.
1627 if (Debug::StepInActive()) {
1628 Debug::HandleStepIn(fun, Handle<Object>::null(), 0, false);
1629 }
1630#endif
1631 bool has_pending_exception;
1632 Object** argv[] = { value_handle.location() };
1633 Execution::Call(fun, self, 1, argv, &has_pending_exception);
1634 // Check for pending exception and return the result.
1635 if (has_pending_exception) return Failure::Exception();
1636 return *value_handle;
1637}
1638
1639
1640void JSObject::LookupCallbackSetterInPrototypes(String* name,
1641 LookupResult* result) {
1642 for (Object* pt = GetPrototype();
1643 pt != Heap::null_value();
1644 pt = pt->GetPrototype()) {
1645 JSObject::cast(pt)->LocalLookupRealNamedProperty(name, result);
Andrei Popescu402d9372010-02-26 13:31:12 +00001646 if (result->IsProperty()) {
1647 if (result->IsReadOnly()) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001648 result->NotFound();
1649 return;
1650 }
1651 if (result->type() == CALLBACKS) {
1652 return;
1653 }
1654 }
1655 }
1656 result->NotFound();
1657}
1658
1659
Leon Clarkef7060e22010-06-03 12:02:55 +01001660bool JSObject::SetElementWithCallbackSetterInPrototypes(uint32_t index,
1661 Object* value) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001662 for (Object* pt = GetPrototype();
1663 pt != Heap::null_value();
1664 pt = pt->GetPrototype()) {
1665 if (!JSObject::cast(pt)->HasDictionaryElements()) {
1666 continue;
1667 }
1668 NumberDictionary* dictionary = JSObject::cast(pt)->element_dictionary();
1669 int entry = dictionary->FindEntry(index);
1670 if (entry != NumberDictionary::kNotFound) {
1671 Object* element = dictionary->ValueAt(entry);
1672 PropertyDetails details = dictionary->DetailsAt(entry);
1673 if (details.type() == CALLBACKS) {
Leon Clarkef7060e22010-06-03 12:02:55 +01001674 SetElementWithCallback(element, index, value, JSObject::cast(pt));
1675 return true;
Steve Blocka7e24c12009-10-30 11:49:00 +00001676 }
1677 }
1678 }
Leon Clarkef7060e22010-06-03 12:02:55 +01001679 return false;
Steve Blocka7e24c12009-10-30 11:49:00 +00001680}
1681
1682
1683void JSObject::LookupInDescriptor(String* name, LookupResult* result) {
1684 DescriptorArray* descriptors = map()->instance_descriptors();
1685 int number = DescriptorLookupCache::Lookup(descriptors, name);
1686 if (number == DescriptorLookupCache::kAbsent) {
1687 number = descriptors->Search(name);
1688 DescriptorLookupCache::Update(descriptors, name, number);
1689 }
1690 if (number != DescriptorArray::kNotFound) {
1691 result->DescriptorResult(this, descriptors->GetDetails(number), number);
1692 } else {
1693 result->NotFound();
1694 }
1695}
1696
1697
1698void JSObject::LocalLookupRealNamedProperty(String* name,
1699 LookupResult* result) {
1700 if (IsJSGlobalProxy()) {
1701 Object* proto = GetPrototype();
1702 if (proto->IsNull()) return result->NotFound();
1703 ASSERT(proto->IsJSGlobalObject());
1704 return JSObject::cast(proto)->LocalLookupRealNamedProperty(name, result);
1705 }
1706
1707 if (HasFastProperties()) {
1708 LookupInDescriptor(name, result);
Andrei Popescu402d9372010-02-26 13:31:12 +00001709 if (result->IsFound()) {
1710 // A property, a map transition or a null descriptor was found.
1711 // We return all of these result types because
1712 // LocalLookupRealNamedProperty is used when setting properties
1713 // where map transitions and null descriptors are handled.
Steve Blocka7e24c12009-10-30 11:49:00 +00001714 ASSERT(result->holder() == this && result->type() != NORMAL);
1715 // Disallow caching for uninitialized constants. These can only
1716 // occur as fields.
1717 if (result->IsReadOnly() && result->type() == FIELD &&
1718 FastPropertyAt(result->GetFieldIndex())->IsTheHole()) {
1719 result->DisallowCaching();
1720 }
1721 return;
1722 }
1723 } else {
1724 int entry = property_dictionary()->FindEntry(name);
1725 if (entry != StringDictionary::kNotFound) {
1726 Object* value = property_dictionary()->ValueAt(entry);
1727 if (IsGlobalObject()) {
1728 PropertyDetails d = property_dictionary()->DetailsAt(entry);
1729 if (d.IsDeleted()) {
1730 result->NotFound();
1731 return;
1732 }
1733 value = JSGlobalPropertyCell::cast(value)->value();
Steve Blocka7e24c12009-10-30 11:49:00 +00001734 }
1735 // Make sure to disallow caching for uninitialized constants
1736 // found in the dictionary-mode objects.
1737 if (value->IsTheHole()) result->DisallowCaching();
1738 result->DictionaryResult(this, entry);
1739 return;
1740 }
1741 // Slow case object skipped during lookup. Do not use inline caching.
1742 if (!IsGlobalObject()) result->DisallowCaching();
1743 }
1744 result->NotFound();
1745}
1746
1747
1748void JSObject::LookupRealNamedProperty(String* name, LookupResult* result) {
1749 LocalLookupRealNamedProperty(name, result);
1750 if (result->IsProperty()) return;
1751
1752 LookupRealNamedPropertyInPrototypes(name, result);
1753}
1754
1755
1756void JSObject::LookupRealNamedPropertyInPrototypes(String* name,
1757 LookupResult* result) {
1758 for (Object* pt = GetPrototype();
1759 pt != Heap::null_value();
1760 pt = JSObject::cast(pt)->GetPrototype()) {
1761 JSObject::cast(pt)->LocalLookupRealNamedProperty(name, result);
Andrei Popescu402d9372010-02-26 13:31:12 +00001762 if (result->IsProperty() && (result->type() != INTERCEPTOR)) return;
Steve Blocka7e24c12009-10-30 11:49:00 +00001763 }
1764 result->NotFound();
1765}
1766
1767
1768// We only need to deal with CALLBACKS and INTERCEPTORS
1769Object* JSObject::SetPropertyWithFailedAccessCheck(LookupResult* result,
1770 String* name,
1771 Object* value) {
1772 if (!result->IsProperty()) {
1773 LookupCallbackSetterInPrototypes(name, result);
1774 }
1775
1776 if (result->IsProperty()) {
1777 if (!result->IsReadOnly()) {
1778 switch (result->type()) {
1779 case CALLBACKS: {
1780 Object* obj = result->GetCallbackObject();
1781 if (obj->IsAccessorInfo()) {
1782 AccessorInfo* info = AccessorInfo::cast(obj);
1783 if (info->all_can_write()) {
1784 return SetPropertyWithCallback(result->GetCallbackObject(),
1785 name,
1786 value,
1787 result->holder());
1788 }
1789 }
1790 break;
1791 }
1792 case INTERCEPTOR: {
1793 // Try lookup real named properties. Note that only property can be
1794 // set is callbacks marked as ALL_CAN_WRITE on the prototype chain.
1795 LookupResult r;
1796 LookupRealNamedProperty(name, &r);
1797 if (r.IsProperty()) {
1798 return SetPropertyWithFailedAccessCheck(&r, name, value);
1799 }
1800 break;
1801 }
1802 default: {
1803 break;
1804 }
1805 }
1806 }
1807 }
1808
1809 Top::ReportFailedAccessCheck(this, v8::ACCESS_SET);
1810 return value;
1811}
1812
1813
1814Object* JSObject::SetProperty(LookupResult* result,
1815 String* name,
1816 Object* value,
1817 PropertyAttributes attributes) {
1818 // Make sure that the top context does not change when doing callbacks or
1819 // interceptor calls.
1820 AssertNoContextChange ncc;
1821
Steve Blockd0582a62009-12-15 09:54:21 +00001822 // Optimization for 2-byte strings often used as keys in a decompression
1823 // dictionary. We make these short keys into symbols to avoid constantly
1824 // reallocating them.
1825 if (!name->IsSymbol() && name->length() <= 2) {
1826 Object* symbol_version = Heap::LookupSymbol(name);
1827 if (!symbol_version->IsFailure()) name = String::cast(symbol_version);
1828 }
1829
Steve Blocka7e24c12009-10-30 11:49:00 +00001830 // Check access rights if needed.
1831 if (IsAccessCheckNeeded()
1832 && !Top::MayNamedAccess(this, name, v8::ACCESS_SET)) {
1833 return SetPropertyWithFailedAccessCheck(result, name, value);
1834 }
1835
1836 if (IsJSGlobalProxy()) {
1837 Object* proto = GetPrototype();
1838 if (proto->IsNull()) return value;
1839 ASSERT(proto->IsJSGlobalObject());
1840 return JSObject::cast(proto)->SetProperty(result, name, value, attributes);
1841 }
1842
1843 if (!result->IsProperty() && !IsJSContextExtensionObject()) {
1844 // We could not find a local property so let's check whether there is an
1845 // accessor that wants to handle the property.
1846 LookupResult accessor_result;
1847 LookupCallbackSetterInPrototypes(name, &accessor_result);
Andrei Popescu402d9372010-02-26 13:31:12 +00001848 if (accessor_result.IsProperty()) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001849 return SetPropertyWithCallback(accessor_result.GetCallbackObject(),
1850 name,
1851 value,
1852 accessor_result.holder());
1853 }
1854 }
Andrei Popescu402d9372010-02-26 13:31:12 +00001855 if (!result->IsFound()) {
1856 // Neither properties nor transitions found.
Steve Blocka7e24c12009-10-30 11:49:00 +00001857 return AddProperty(name, value, attributes);
1858 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001859 if (result->IsReadOnly() && result->IsProperty()) return value;
1860 // This is a real property that is not read-only, or it is a
1861 // transition or null descriptor and there are no setters in the prototypes.
1862 switch (result->type()) {
1863 case NORMAL:
1864 return SetNormalizedProperty(result, value);
1865 case FIELD:
1866 return FastPropertyAtPut(result->GetFieldIndex(), value);
1867 case MAP_TRANSITION:
1868 if (attributes == result->GetAttributes()) {
1869 // Only use map transition if the attributes match.
1870 return AddFastPropertyUsingMap(result->GetTransitionMap(),
1871 name,
1872 value);
1873 }
1874 return ConvertDescriptorToField(name, value, attributes);
1875 case CONSTANT_FUNCTION:
1876 // Only replace the function if necessary.
1877 if (value == result->GetConstantFunction()) return value;
1878 // Preserve the attributes of this existing property.
1879 attributes = result->GetAttributes();
1880 return ConvertDescriptorToField(name, value, attributes);
1881 case CALLBACKS:
1882 return SetPropertyWithCallback(result->GetCallbackObject(),
1883 name,
1884 value,
1885 result->holder());
1886 case INTERCEPTOR:
1887 return SetPropertyWithInterceptor(name, value, attributes);
1888 case CONSTANT_TRANSITION:
1889 // Replace with a MAP_TRANSITION to a new map with a FIELD, even
1890 // if the value is a function.
1891 return ConvertDescriptorToFieldAndMapTransition(name, value, attributes);
1892 case NULL_DESCRIPTOR:
1893 return ConvertDescriptorToFieldAndMapTransition(name, value, attributes);
1894 default:
1895 UNREACHABLE();
1896 }
1897 UNREACHABLE();
1898 return value;
1899}
1900
1901
1902// Set a real local property, even if it is READ_ONLY. If the property is not
1903// present, add it with attributes NONE. This code is an exact clone of
1904// SetProperty, with the check for IsReadOnly and the check for a
1905// callback setter removed. The two lines looking up the LookupResult
1906// result are also added. If one of the functions is changed, the other
1907// should be.
1908Object* JSObject::IgnoreAttributesAndSetLocalProperty(
1909 String* name,
1910 Object* value,
1911 PropertyAttributes attributes) {
1912 // Make sure that the top context does not change when doing callbacks or
1913 // interceptor calls.
1914 AssertNoContextChange ncc;
Andrei Popescu402d9372010-02-26 13:31:12 +00001915 LookupResult result;
1916 LocalLookup(name, &result);
Steve Blocka7e24c12009-10-30 11:49:00 +00001917 // Check access rights if needed.
1918 if (IsAccessCheckNeeded()
Andrei Popescu402d9372010-02-26 13:31:12 +00001919 && !Top::MayNamedAccess(this, name, v8::ACCESS_SET)) {
1920 return SetPropertyWithFailedAccessCheck(&result, name, value);
Steve Blocka7e24c12009-10-30 11:49:00 +00001921 }
1922
1923 if (IsJSGlobalProxy()) {
1924 Object* proto = GetPrototype();
1925 if (proto->IsNull()) return value;
1926 ASSERT(proto->IsJSGlobalObject());
1927 return JSObject::cast(proto)->IgnoreAttributesAndSetLocalProperty(
1928 name,
1929 value,
1930 attributes);
1931 }
1932
1933 // Check for accessor in prototype chain removed here in clone.
Andrei Popescu402d9372010-02-26 13:31:12 +00001934 if (!result.IsFound()) {
1935 // Neither properties nor transitions found.
Steve Blocka7e24c12009-10-30 11:49:00 +00001936 return AddProperty(name, value, attributes);
1937 }
Steve Block6ded16b2010-05-10 14:33:55 +01001938
Andrei Popescu402d9372010-02-26 13:31:12 +00001939 PropertyDetails details = PropertyDetails(attributes, NORMAL);
1940
Steve Blocka7e24c12009-10-30 11:49:00 +00001941 // Check of IsReadOnly removed from here in clone.
Andrei Popescu402d9372010-02-26 13:31:12 +00001942 switch (result.type()) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001943 case NORMAL:
Andrei Popescu402d9372010-02-26 13:31:12 +00001944 return SetNormalizedProperty(name, value, details);
Steve Blocka7e24c12009-10-30 11:49:00 +00001945 case FIELD:
Andrei Popescu402d9372010-02-26 13:31:12 +00001946 return FastPropertyAtPut(result.GetFieldIndex(), value);
Steve Blocka7e24c12009-10-30 11:49:00 +00001947 case MAP_TRANSITION:
Andrei Popescu402d9372010-02-26 13:31:12 +00001948 if (attributes == result.GetAttributes()) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001949 // Only use map transition if the attributes match.
Andrei Popescu402d9372010-02-26 13:31:12 +00001950 return AddFastPropertyUsingMap(result.GetTransitionMap(),
Steve Blocka7e24c12009-10-30 11:49:00 +00001951 name,
1952 value);
1953 }
1954 return ConvertDescriptorToField(name, value, attributes);
1955 case CONSTANT_FUNCTION:
1956 // Only replace the function if necessary.
Andrei Popescu402d9372010-02-26 13:31:12 +00001957 if (value == result.GetConstantFunction()) return value;
Steve Blocka7e24c12009-10-30 11:49:00 +00001958 // Preserve the attributes of this existing property.
Andrei Popescu402d9372010-02-26 13:31:12 +00001959 attributes = result.GetAttributes();
Steve Blocka7e24c12009-10-30 11:49:00 +00001960 return ConvertDescriptorToField(name, value, attributes);
1961 case CALLBACKS:
1962 case INTERCEPTOR:
1963 // Override callback in clone
1964 return ConvertDescriptorToField(name, value, attributes);
1965 case CONSTANT_TRANSITION:
1966 // Replace with a MAP_TRANSITION to a new map with a FIELD, even
1967 // if the value is a function.
1968 return ConvertDescriptorToFieldAndMapTransition(name, value, attributes);
1969 case NULL_DESCRIPTOR:
1970 return ConvertDescriptorToFieldAndMapTransition(name, value, attributes);
1971 default:
1972 UNREACHABLE();
1973 }
1974 UNREACHABLE();
1975 return value;
1976}
1977
1978
1979PropertyAttributes JSObject::GetPropertyAttributePostInterceptor(
1980 JSObject* receiver,
1981 String* name,
1982 bool continue_search) {
1983 // Check local property, ignore interceptor.
1984 LookupResult result;
1985 LocalLookupRealNamedProperty(name, &result);
1986 if (result.IsProperty()) return result.GetAttributes();
1987
1988 if (continue_search) {
1989 // Continue searching via the prototype chain.
1990 Object* pt = GetPrototype();
1991 if (pt != Heap::null_value()) {
1992 return JSObject::cast(pt)->
1993 GetPropertyAttributeWithReceiver(receiver, name);
1994 }
1995 }
1996 return ABSENT;
1997}
1998
1999
2000PropertyAttributes JSObject::GetPropertyAttributeWithInterceptor(
2001 JSObject* receiver,
2002 String* name,
2003 bool continue_search) {
2004 // Make sure that the top context does not change when doing
2005 // callbacks or interceptor calls.
2006 AssertNoContextChange ncc;
2007
2008 HandleScope scope;
2009 Handle<InterceptorInfo> interceptor(GetNamedInterceptor());
2010 Handle<JSObject> receiver_handle(receiver);
2011 Handle<JSObject> holder_handle(this);
2012 Handle<String> name_handle(name);
2013 CustomArguments args(interceptor->data(), receiver, this);
2014 v8::AccessorInfo info(args.end());
2015 if (!interceptor->query()->IsUndefined()) {
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01002016 v8::NamedPropertyQueryImpl query =
2017 v8::ToCData<v8::NamedPropertyQueryImpl>(interceptor->query());
Steve Blocka7e24c12009-10-30 11:49:00 +00002018 LOG(ApiNamedPropertyAccess("interceptor-named-has", *holder_handle, name));
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01002019 v8::Handle<v8::Value> result;
Steve Blocka7e24c12009-10-30 11:49:00 +00002020 {
2021 // Leaving JavaScript.
2022 VMState state(EXTERNAL);
2023 result = query(v8::Utils::ToLocal(name_handle), info);
2024 }
2025 if (!result.IsEmpty()) {
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01002026 // Temporary complicated logic, would be removed soon.
2027 if (result->IsBoolean()) {
2028 // Convert the boolean result to a property attribute
2029 // specification.
2030 return result->IsTrue() ? NONE : ABSENT;
2031 } else {
2032 ASSERT(result->IsInt32());
2033 return static_cast<PropertyAttributes>(result->Int32Value());
2034 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002035 }
2036 } else if (!interceptor->getter()->IsUndefined()) {
2037 v8::NamedPropertyGetter getter =
2038 v8::ToCData<v8::NamedPropertyGetter>(interceptor->getter());
2039 LOG(ApiNamedPropertyAccess("interceptor-named-get-has", this, name));
2040 v8::Handle<v8::Value> result;
2041 {
2042 // Leaving JavaScript.
2043 VMState state(EXTERNAL);
2044 result = getter(v8::Utils::ToLocal(name_handle), info);
2045 }
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01002046 if (!result.IsEmpty()) return DONT_ENUM;
Steve Blocka7e24c12009-10-30 11:49:00 +00002047 }
2048 return holder_handle->GetPropertyAttributePostInterceptor(*receiver_handle,
2049 *name_handle,
2050 continue_search);
2051}
2052
2053
2054PropertyAttributes JSObject::GetPropertyAttributeWithReceiver(
2055 JSObject* receiver,
2056 String* key) {
2057 uint32_t index = 0;
2058 if (key->AsArrayIndex(&index)) {
2059 if (HasElementWithReceiver(receiver, index)) return NONE;
2060 return ABSENT;
2061 }
2062 // Named property.
2063 LookupResult result;
2064 Lookup(key, &result);
2065 return GetPropertyAttribute(receiver, &result, key, true);
2066}
2067
2068
2069PropertyAttributes JSObject::GetPropertyAttribute(JSObject* receiver,
2070 LookupResult* result,
2071 String* name,
2072 bool continue_search) {
2073 // Check access rights if needed.
2074 if (IsAccessCheckNeeded() &&
2075 !Top::MayNamedAccess(this, name, v8::ACCESS_HAS)) {
2076 return GetPropertyAttributeWithFailedAccessCheck(receiver,
2077 result,
2078 name,
2079 continue_search);
2080 }
Andrei Popescu402d9372010-02-26 13:31:12 +00002081 if (result->IsProperty()) {
Steve Blocka7e24c12009-10-30 11:49:00 +00002082 switch (result->type()) {
2083 case NORMAL: // fall through
2084 case FIELD:
2085 case CONSTANT_FUNCTION:
2086 case CALLBACKS:
2087 return result->GetAttributes();
2088 case INTERCEPTOR:
2089 return result->holder()->
2090 GetPropertyAttributeWithInterceptor(receiver, name, continue_search);
Steve Blocka7e24c12009-10-30 11:49:00 +00002091 default:
2092 UNREACHABLE();
Steve Blocka7e24c12009-10-30 11:49:00 +00002093 }
2094 }
2095 return ABSENT;
2096}
2097
2098
2099PropertyAttributes JSObject::GetLocalPropertyAttribute(String* name) {
2100 // Check whether the name is an array index.
2101 uint32_t index = 0;
2102 if (name->AsArrayIndex(&index)) {
2103 if (HasLocalElement(index)) return NONE;
2104 return ABSENT;
2105 }
2106 // Named property.
2107 LookupResult result;
2108 LocalLookup(name, &result);
2109 return GetPropertyAttribute(this, &result, name, false);
2110}
2111
2112
2113Object* JSObject::NormalizeProperties(PropertyNormalizationMode mode,
2114 int expected_additional_properties) {
2115 if (!HasFastProperties()) return this;
2116
2117 // The global object is always normalized.
2118 ASSERT(!IsGlobalObject());
2119
2120 // Allocate new content.
2121 int property_count = map()->NumberOfDescribedProperties();
2122 if (expected_additional_properties > 0) {
2123 property_count += expected_additional_properties;
2124 } else {
2125 property_count += 2; // Make space for two more properties.
2126 }
2127 Object* obj =
Steve Block6ded16b2010-05-10 14:33:55 +01002128 StringDictionary::Allocate(property_count);
Steve Blocka7e24c12009-10-30 11:49:00 +00002129 if (obj->IsFailure()) return obj;
2130 StringDictionary* dictionary = StringDictionary::cast(obj);
2131
2132 DescriptorArray* descs = map()->instance_descriptors();
2133 for (int i = 0; i < descs->number_of_descriptors(); i++) {
2134 PropertyDetails details = descs->GetDetails(i);
2135 switch (details.type()) {
2136 case CONSTANT_FUNCTION: {
2137 PropertyDetails d =
2138 PropertyDetails(details.attributes(), NORMAL, details.index());
2139 Object* value = descs->GetConstantFunction(i);
2140 Object* result = dictionary->Add(descs->GetKey(i), value, d);
2141 if (result->IsFailure()) return result;
2142 dictionary = StringDictionary::cast(result);
2143 break;
2144 }
2145 case FIELD: {
2146 PropertyDetails d =
2147 PropertyDetails(details.attributes(), NORMAL, details.index());
2148 Object* value = FastPropertyAt(descs->GetFieldIndex(i));
2149 Object* result = dictionary->Add(descs->GetKey(i), value, d);
2150 if (result->IsFailure()) return result;
2151 dictionary = StringDictionary::cast(result);
2152 break;
2153 }
2154 case CALLBACKS: {
2155 PropertyDetails d =
2156 PropertyDetails(details.attributes(), CALLBACKS, details.index());
2157 Object* value = descs->GetCallbacksObject(i);
2158 Object* result = dictionary->Add(descs->GetKey(i), value, d);
2159 if (result->IsFailure()) return result;
2160 dictionary = StringDictionary::cast(result);
2161 break;
2162 }
2163 case MAP_TRANSITION:
2164 case CONSTANT_TRANSITION:
2165 case NULL_DESCRIPTOR:
2166 case INTERCEPTOR:
2167 break;
2168 default:
2169 UNREACHABLE();
2170 }
2171 }
2172
2173 // Copy the next enumeration index from instance descriptor.
2174 int index = map()->instance_descriptors()->NextEnumerationIndex();
2175 dictionary->SetNextEnumerationIndex(index);
2176
2177 // Allocate new map.
2178 obj = map()->CopyDropDescriptors();
2179 if (obj->IsFailure()) return obj;
2180 Map* new_map = Map::cast(obj);
2181
2182 // Clear inobject properties if needed by adjusting the instance size and
2183 // putting in a filler object instead of the inobject properties.
2184 if (mode == CLEAR_INOBJECT_PROPERTIES && map()->inobject_properties() > 0) {
2185 int instance_size_delta = map()->inobject_properties() * kPointerSize;
2186 int new_instance_size = map()->instance_size() - instance_size_delta;
2187 new_map->set_inobject_properties(0);
2188 new_map->set_instance_size(new_instance_size);
2189 Heap::CreateFillerObjectAt(this->address() + new_instance_size,
2190 instance_size_delta);
2191 }
2192 new_map->set_unused_property_fields(0);
2193
2194 // We have now successfully allocated all the necessary objects.
2195 // Changes can now be made with the guarantee that all of them take effect.
2196 set_map(new_map);
2197 map()->set_instance_descriptors(Heap::empty_descriptor_array());
2198
2199 set_properties(dictionary);
2200
2201 Counters::props_to_dictionary.Increment();
2202
2203#ifdef DEBUG
2204 if (FLAG_trace_normalization) {
2205 PrintF("Object properties have been normalized:\n");
2206 Print();
2207 }
2208#endif
2209 return this;
2210}
2211
2212
2213Object* JSObject::TransformToFastProperties(int unused_property_fields) {
2214 if (HasFastProperties()) return this;
2215 ASSERT(!IsGlobalObject());
2216 return property_dictionary()->
2217 TransformPropertiesToFastFor(this, unused_property_fields);
2218}
2219
2220
2221Object* JSObject::NormalizeElements() {
Steve Block3ce2e202009-11-05 08:53:23 +00002222 ASSERT(!HasPixelElements() && !HasExternalArrayElements());
Steve Blocka7e24c12009-10-30 11:49:00 +00002223 if (HasDictionaryElements()) return this;
2224
2225 // Get number of entries.
2226 FixedArray* array = FixedArray::cast(elements());
2227
2228 // Compute the effective length.
2229 int length = IsJSArray() ?
2230 Smi::cast(JSArray::cast(this)->length())->value() :
2231 array->length();
2232 Object* obj = NumberDictionary::Allocate(length);
2233 if (obj->IsFailure()) return obj;
2234 NumberDictionary* dictionary = NumberDictionary::cast(obj);
2235 // Copy entries.
2236 for (int i = 0; i < length; i++) {
2237 Object* value = array->get(i);
2238 if (!value->IsTheHole()) {
2239 PropertyDetails details = PropertyDetails(NONE, NORMAL);
2240 Object* result = dictionary->AddNumberEntry(i, array->get(i), details);
2241 if (result->IsFailure()) return result;
2242 dictionary = NumberDictionary::cast(result);
2243 }
2244 }
2245 // Switch to using the dictionary as the backing storage for elements.
2246 set_elements(dictionary);
2247
2248 Counters::elements_to_dictionary.Increment();
2249
2250#ifdef DEBUG
2251 if (FLAG_trace_normalization) {
2252 PrintF("Object elements have been normalized:\n");
2253 Print();
2254 }
2255#endif
2256
2257 return this;
2258}
2259
2260
2261Object* JSObject::DeletePropertyPostInterceptor(String* name, DeleteMode mode) {
2262 // Check local property, ignore interceptor.
2263 LookupResult result;
2264 LocalLookupRealNamedProperty(name, &result);
Andrei Popescu402d9372010-02-26 13:31:12 +00002265 if (!result.IsProperty()) return Heap::true_value();
Steve Blocka7e24c12009-10-30 11:49:00 +00002266
2267 // Normalize object if needed.
2268 Object* obj = NormalizeProperties(CLEAR_INOBJECT_PROPERTIES, 0);
2269 if (obj->IsFailure()) return obj;
2270
2271 return DeleteNormalizedProperty(name, mode);
2272}
2273
2274
2275Object* JSObject::DeletePropertyWithInterceptor(String* name) {
2276 HandleScope scope;
2277 Handle<InterceptorInfo> interceptor(GetNamedInterceptor());
2278 Handle<String> name_handle(name);
2279 Handle<JSObject> this_handle(this);
2280 if (!interceptor->deleter()->IsUndefined()) {
2281 v8::NamedPropertyDeleter deleter =
2282 v8::ToCData<v8::NamedPropertyDeleter>(interceptor->deleter());
2283 LOG(ApiNamedPropertyAccess("interceptor-named-delete", *this_handle, name));
2284 CustomArguments args(interceptor->data(), this, this);
2285 v8::AccessorInfo info(args.end());
2286 v8::Handle<v8::Boolean> result;
2287 {
2288 // Leaving JavaScript.
2289 VMState state(EXTERNAL);
2290 result = deleter(v8::Utils::ToLocal(name_handle), info);
2291 }
2292 RETURN_IF_SCHEDULED_EXCEPTION();
2293 if (!result.IsEmpty()) {
2294 ASSERT(result->IsBoolean());
2295 return *v8::Utils::OpenHandle(*result);
2296 }
2297 }
2298 Object* raw_result =
2299 this_handle->DeletePropertyPostInterceptor(*name_handle, NORMAL_DELETION);
2300 RETURN_IF_SCHEDULED_EXCEPTION();
2301 return raw_result;
2302}
2303
2304
2305Object* JSObject::DeleteElementPostInterceptor(uint32_t index,
2306 DeleteMode mode) {
Steve Block3ce2e202009-11-05 08:53:23 +00002307 ASSERT(!HasPixelElements() && !HasExternalArrayElements());
Steve Blocka7e24c12009-10-30 11:49:00 +00002308 switch (GetElementsKind()) {
2309 case FAST_ELEMENTS: {
2310 uint32_t length = IsJSArray() ?
2311 static_cast<uint32_t>(Smi::cast(JSArray::cast(this)->length())->value()) :
2312 static_cast<uint32_t>(FixedArray::cast(elements())->length());
2313 if (index < length) {
2314 FixedArray::cast(elements())->set_the_hole(index);
2315 }
2316 break;
2317 }
2318 case DICTIONARY_ELEMENTS: {
2319 NumberDictionary* dictionary = element_dictionary();
2320 int entry = dictionary->FindEntry(index);
2321 if (entry != NumberDictionary::kNotFound) {
2322 return dictionary->DeleteProperty(entry, mode);
2323 }
2324 break;
2325 }
2326 default:
2327 UNREACHABLE();
2328 break;
2329 }
2330 return Heap::true_value();
2331}
2332
2333
2334Object* JSObject::DeleteElementWithInterceptor(uint32_t index) {
2335 // Make sure that the top context does not change when doing
2336 // callbacks or interceptor calls.
2337 AssertNoContextChange ncc;
2338 HandleScope scope;
2339 Handle<InterceptorInfo> interceptor(GetIndexedInterceptor());
2340 if (interceptor->deleter()->IsUndefined()) return Heap::false_value();
2341 v8::IndexedPropertyDeleter deleter =
2342 v8::ToCData<v8::IndexedPropertyDeleter>(interceptor->deleter());
2343 Handle<JSObject> this_handle(this);
2344 LOG(ApiIndexedPropertyAccess("interceptor-indexed-delete", this, index));
2345 CustomArguments args(interceptor->data(), this, this);
2346 v8::AccessorInfo info(args.end());
2347 v8::Handle<v8::Boolean> result;
2348 {
2349 // Leaving JavaScript.
2350 VMState state(EXTERNAL);
2351 result = deleter(index, info);
2352 }
2353 RETURN_IF_SCHEDULED_EXCEPTION();
2354 if (!result.IsEmpty()) {
2355 ASSERT(result->IsBoolean());
2356 return *v8::Utils::OpenHandle(*result);
2357 }
2358 Object* raw_result =
2359 this_handle->DeleteElementPostInterceptor(index, NORMAL_DELETION);
2360 RETURN_IF_SCHEDULED_EXCEPTION();
2361 return raw_result;
2362}
2363
2364
2365Object* JSObject::DeleteElement(uint32_t index, DeleteMode mode) {
2366 // Check access rights if needed.
2367 if (IsAccessCheckNeeded() &&
2368 !Top::MayIndexedAccess(this, index, v8::ACCESS_DELETE)) {
2369 Top::ReportFailedAccessCheck(this, v8::ACCESS_DELETE);
2370 return Heap::false_value();
2371 }
2372
2373 if (IsJSGlobalProxy()) {
2374 Object* proto = GetPrototype();
2375 if (proto->IsNull()) return Heap::false_value();
2376 ASSERT(proto->IsJSGlobalObject());
2377 return JSGlobalObject::cast(proto)->DeleteElement(index, mode);
2378 }
2379
2380 if (HasIndexedInterceptor()) {
2381 // Skip interceptor if forcing deletion.
2382 if (mode == FORCE_DELETION) {
2383 return DeleteElementPostInterceptor(index, mode);
2384 }
2385 return DeleteElementWithInterceptor(index);
2386 }
2387
2388 switch (GetElementsKind()) {
2389 case FAST_ELEMENTS: {
2390 uint32_t length = IsJSArray() ?
2391 static_cast<uint32_t>(Smi::cast(JSArray::cast(this)->length())->value()) :
2392 static_cast<uint32_t>(FixedArray::cast(elements())->length());
2393 if (index < length) {
2394 FixedArray::cast(elements())->set_the_hole(index);
2395 }
2396 break;
2397 }
Steve Block3ce2e202009-11-05 08:53:23 +00002398 case PIXEL_ELEMENTS:
2399 case EXTERNAL_BYTE_ELEMENTS:
2400 case EXTERNAL_UNSIGNED_BYTE_ELEMENTS:
2401 case EXTERNAL_SHORT_ELEMENTS:
2402 case EXTERNAL_UNSIGNED_SHORT_ELEMENTS:
2403 case EXTERNAL_INT_ELEMENTS:
2404 case EXTERNAL_UNSIGNED_INT_ELEMENTS:
2405 case EXTERNAL_FLOAT_ELEMENTS:
2406 // Pixel and external array elements cannot be deleted. Just
2407 // silently ignore here.
Steve Blocka7e24c12009-10-30 11:49:00 +00002408 break;
Steve Blocka7e24c12009-10-30 11:49:00 +00002409 case DICTIONARY_ELEMENTS: {
2410 NumberDictionary* dictionary = element_dictionary();
2411 int entry = dictionary->FindEntry(index);
2412 if (entry != NumberDictionary::kNotFound) {
2413 return dictionary->DeleteProperty(entry, mode);
2414 }
2415 break;
2416 }
2417 default:
2418 UNREACHABLE();
2419 break;
2420 }
2421 return Heap::true_value();
2422}
2423
2424
2425Object* JSObject::DeleteProperty(String* name, DeleteMode mode) {
2426 // ECMA-262, 3rd, 8.6.2.5
2427 ASSERT(name->IsString());
2428
2429 // Check access rights if needed.
2430 if (IsAccessCheckNeeded() &&
2431 !Top::MayNamedAccess(this, name, v8::ACCESS_DELETE)) {
2432 Top::ReportFailedAccessCheck(this, v8::ACCESS_DELETE);
2433 return Heap::false_value();
2434 }
2435
2436 if (IsJSGlobalProxy()) {
2437 Object* proto = GetPrototype();
2438 if (proto->IsNull()) return Heap::false_value();
2439 ASSERT(proto->IsJSGlobalObject());
2440 return JSGlobalObject::cast(proto)->DeleteProperty(name, mode);
2441 }
2442
2443 uint32_t index = 0;
2444 if (name->AsArrayIndex(&index)) {
2445 return DeleteElement(index, mode);
2446 } else {
2447 LookupResult result;
2448 LocalLookup(name, &result);
Andrei Popescu402d9372010-02-26 13:31:12 +00002449 if (!result.IsProperty()) return Heap::true_value();
Steve Blocka7e24c12009-10-30 11:49:00 +00002450 // Ignore attributes if forcing a deletion.
2451 if (result.IsDontDelete() && mode != FORCE_DELETION) {
2452 return Heap::false_value();
2453 }
2454 // Check for interceptor.
2455 if (result.type() == INTERCEPTOR) {
2456 // Skip interceptor if forcing a deletion.
2457 if (mode == FORCE_DELETION) {
2458 return DeletePropertyPostInterceptor(name, mode);
2459 }
2460 return DeletePropertyWithInterceptor(name);
2461 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002462 // Normalize object if needed.
2463 Object* obj = NormalizeProperties(CLEAR_INOBJECT_PROPERTIES, 0);
2464 if (obj->IsFailure()) return obj;
2465 // Make sure the properties are normalized before removing the entry.
2466 return DeleteNormalizedProperty(name, mode);
2467 }
2468}
2469
2470
2471// Check whether this object references another object.
2472bool JSObject::ReferencesObject(Object* obj) {
2473 AssertNoAllocation no_alloc;
2474
2475 // Is the object the constructor for this object?
2476 if (map()->constructor() == obj) {
2477 return true;
2478 }
2479
2480 // Is the object the prototype for this object?
2481 if (map()->prototype() == obj) {
2482 return true;
2483 }
2484
2485 // Check if the object is among the named properties.
2486 Object* key = SlowReverseLookup(obj);
2487 if (key != Heap::undefined_value()) {
2488 return true;
2489 }
2490
2491 // Check if the object is among the indexed properties.
2492 switch (GetElementsKind()) {
2493 case PIXEL_ELEMENTS:
Steve Block3ce2e202009-11-05 08:53:23 +00002494 case EXTERNAL_BYTE_ELEMENTS:
2495 case EXTERNAL_UNSIGNED_BYTE_ELEMENTS:
2496 case EXTERNAL_SHORT_ELEMENTS:
2497 case EXTERNAL_UNSIGNED_SHORT_ELEMENTS:
2498 case EXTERNAL_INT_ELEMENTS:
2499 case EXTERNAL_UNSIGNED_INT_ELEMENTS:
2500 case EXTERNAL_FLOAT_ELEMENTS:
2501 // Raw pixels and external arrays do not reference other
2502 // objects.
Steve Blocka7e24c12009-10-30 11:49:00 +00002503 break;
2504 case FAST_ELEMENTS: {
2505 int length = IsJSArray() ?
2506 Smi::cast(JSArray::cast(this)->length())->value() :
2507 FixedArray::cast(elements())->length();
2508 for (int i = 0; i < length; i++) {
2509 Object* element = FixedArray::cast(elements())->get(i);
2510 if (!element->IsTheHole() && element == obj) {
2511 return true;
2512 }
2513 }
2514 break;
2515 }
2516 case DICTIONARY_ELEMENTS: {
2517 key = element_dictionary()->SlowReverseLookup(obj);
2518 if (key != Heap::undefined_value()) {
2519 return true;
2520 }
2521 break;
2522 }
2523 default:
2524 UNREACHABLE();
2525 break;
2526 }
2527
Steve Block6ded16b2010-05-10 14:33:55 +01002528 // For functions check the context.
2529 if (IsJSFunction()) {
Steve Blocka7e24c12009-10-30 11:49:00 +00002530 // Get the constructor function for arguments array.
2531 JSObject* arguments_boilerplate =
2532 Top::context()->global_context()->arguments_boilerplate();
2533 JSFunction* arguments_function =
2534 JSFunction::cast(arguments_boilerplate->map()->constructor());
2535
2536 // Get the context and don't check if it is the global context.
2537 JSFunction* f = JSFunction::cast(this);
2538 Context* context = f->context();
2539 if (context->IsGlobalContext()) {
2540 return false;
2541 }
2542
2543 // Check the non-special context slots.
2544 for (int i = Context::MIN_CONTEXT_SLOTS; i < context->length(); i++) {
2545 // Only check JS objects.
2546 if (context->get(i)->IsJSObject()) {
2547 JSObject* ctxobj = JSObject::cast(context->get(i));
2548 // If it is an arguments array check the content.
2549 if (ctxobj->map()->constructor() == arguments_function) {
2550 if (ctxobj->ReferencesObject(obj)) {
2551 return true;
2552 }
2553 } else if (ctxobj == obj) {
2554 return true;
2555 }
2556 }
2557 }
2558
2559 // Check the context extension if any.
2560 if (context->has_extension()) {
2561 return context->extension()->ReferencesObject(obj);
2562 }
2563 }
2564
2565 // No references to object.
2566 return false;
2567}
2568
2569
2570// Tests for the fast common case for property enumeration:
Steve Blockd0582a62009-12-15 09:54:21 +00002571// - This object and all prototypes has an enum cache (which means that it has
2572// no interceptors and needs no access checks).
2573// - This object has no elements.
2574// - No prototype has enumerable properties/elements.
Steve Blocka7e24c12009-10-30 11:49:00 +00002575bool JSObject::IsSimpleEnum() {
Steve Blocka7e24c12009-10-30 11:49:00 +00002576 for (Object* o = this;
2577 o != Heap::null_value();
2578 o = JSObject::cast(o)->GetPrototype()) {
2579 JSObject* curr = JSObject::cast(o);
Steve Blocka7e24c12009-10-30 11:49:00 +00002580 if (!curr->map()->instance_descriptors()->HasEnumCache()) return false;
Steve Blockd0582a62009-12-15 09:54:21 +00002581 ASSERT(!curr->HasNamedInterceptor());
2582 ASSERT(!curr->HasIndexedInterceptor());
2583 ASSERT(!curr->IsAccessCheckNeeded());
Steve Blocka7e24c12009-10-30 11:49:00 +00002584 if (curr->NumberOfEnumElements() > 0) return false;
Steve Blocka7e24c12009-10-30 11:49:00 +00002585 if (curr != this) {
2586 FixedArray* curr_fixed_array =
2587 FixedArray::cast(curr->map()->instance_descriptors()->GetEnumCache());
Steve Blockd0582a62009-12-15 09:54:21 +00002588 if (curr_fixed_array->length() > 0) return false;
Steve Blocka7e24c12009-10-30 11:49:00 +00002589 }
2590 }
2591 return true;
2592}
2593
2594
2595int Map::NumberOfDescribedProperties() {
2596 int result = 0;
2597 DescriptorArray* descs = instance_descriptors();
2598 for (int i = 0; i < descs->number_of_descriptors(); i++) {
2599 if (descs->IsProperty(i)) result++;
2600 }
2601 return result;
2602}
2603
2604
2605int Map::PropertyIndexFor(String* name) {
2606 DescriptorArray* descs = instance_descriptors();
2607 for (int i = 0; i < descs->number_of_descriptors(); i++) {
2608 if (name->Equals(descs->GetKey(i)) && !descs->IsNullDescriptor(i)) {
2609 return descs->GetFieldIndex(i);
2610 }
2611 }
2612 return -1;
2613}
2614
2615
2616int Map::NextFreePropertyIndex() {
2617 int max_index = -1;
2618 DescriptorArray* descs = instance_descriptors();
2619 for (int i = 0; i < descs->number_of_descriptors(); i++) {
2620 if (descs->GetType(i) == FIELD) {
2621 int current_index = descs->GetFieldIndex(i);
2622 if (current_index > max_index) max_index = current_index;
2623 }
2624 }
2625 return max_index + 1;
2626}
2627
2628
2629AccessorDescriptor* Map::FindAccessor(String* name) {
2630 DescriptorArray* descs = instance_descriptors();
2631 for (int i = 0; i < descs->number_of_descriptors(); i++) {
2632 if (name->Equals(descs->GetKey(i)) && descs->GetType(i) == CALLBACKS) {
2633 return descs->GetCallbacks(i);
2634 }
2635 }
2636 return NULL;
2637}
2638
2639
2640void JSObject::LocalLookup(String* name, LookupResult* result) {
2641 ASSERT(name->IsString());
2642
2643 if (IsJSGlobalProxy()) {
2644 Object* proto = GetPrototype();
2645 if (proto->IsNull()) return result->NotFound();
2646 ASSERT(proto->IsJSGlobalObject());
2647 return JSObject::cast(proto)->LocalLookup(name, result);
2648 }
2649
2650 // Do not use inline caching if the object is a non-global object
2651 // that requires access checks.
2652 if (!IsJSGlobalProxy() && IsAccessCheckNeeded()) {
2653 result->DisallowCaching();
2654 }
2655
2656 // Check __proto__ before interceptor.
2657 if (name->Equals(Heap::Proto_symbol()) && !IsJSContextExtensionObject()) {
2658 result->ConstantResult(this);
2659 return;
2660 }
2661
2662 // Check for lookup interceptor except when bootstrapping.
2663 if (HasNamedInterceptor() && !Bootstrapper::IsActive()) {
2664 result->InterceptorResult(this);
2665 return;
2666 }
2667
2668 LocalLookupRealNamedProperty(name, result);
2669}
2670
2671
2672void JSObject::Lookup(String* name, LookupResult* result) {
2673 // Ecma-262 3rd 8.6.2.4
2674 for (Object* current = this;
2675 current != Heap::null_value();
2676 current = JSObject::cast(current)->GetPrototype()) {
2677 JSObject::cast(current)->LocalLookup(name, result);
Andrei Popescu402d9372010-02-26 13:31:12 +00002678 if (result->IsProperty()) return;
Steve Blocka7e24c12009-10-30 11:49:00 +00002679 }
2680 result->NotFound();
2681}
2682
2683
2684// Search object and it's prototype chain for callback properties.
2685void JSObject::LookupCallback(String* name, LookupResult* result) {
2686 for (Object* current = this;
2687 current != Heap::null_value();
2688 current = JSObject::cast(current)->GetPrototype()) {
2689 JSObject::cast(current)->LocalLookupRealNamedProperty(name, result);
Andrei Popescu402d9372010-02-26 13:31:12 +00002690 if (result->IsProperty() && result->type() == CALLBACKS) return;
Steve Blocka7e24c12009-10-30 11:49:00 +00002691 }
2692 result->NotFound();
2693}
2694
2695
2696Object* JSObject::DefineGetterSetter(String* name,
2697 PropertyAttributes attributes) {
2698 // Make sure that the top context does not change when doing callbacks or
2699 // interceptor calls.
2700 AssertNoContextChange ncc;
2701
Steve Blocka7e24c12009-10-30 11:49:00 +00002702 // Try to flatten before operating on the string.
Steve Block6ded16b2010-05-10 14:33:55 +01002703 name->TryFlatten();
Steve Blocka7e24c12009-10-30 11:49:00 +00002704
Leon Clarkef7060e22010-06-03 12:02:55 +01002705 if (!CanSetCallback(name)) {
2706 return Heap::undefined_value();
Steve Blocka7e24c12009-10-30 11:49:00 +00002707 }
2708
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01002709 uint32_t index = 0;
Steve Blocka7e24c12009-10-30 11:49:00 +00002710 bool is_element = name->AsArrayIndex(&index);
2711 if (is_element && IsJSArray()) return Heap::undefined_value();
2712
2713 if (is_element) {
2714 switch (GetElementsKind()) {
2715 case FAST_ELEMENTS:
2716 break;
2717 case PIXEL_ELEMENTS:
Steve Block3ce2e202009-11-05 08:53:23 +00002718 case EXTERNAL_BYTE_ELEMENTS:
2719 case EXTERNAL_UNSIGNED_BYTE_ELEMENTS:
2720 case EXTERNAL_SHORT_ELEMENTS:
2721 case EXTERNAL_UNSIGNED_SHORT_ELEMENTS:
2722 case EXTERNAL_INT_ELEMENTS:
2723 case EXTERNAL_UNSIGNED_INT_ELEMENTS:
2724 case EXTERNAL_FLOAT_ELEMENTS:
2725 // Ignore getters and setters on pixel and external array
2726 // elements.
Steve Blocka7e24c12009-10-30 11:49:00 +00002727 return Heap::undefined_value();
2728 case DICTIONARY_ELEMENTS: {
2729 // Lookup the index.
2730 NumberDictionary* dictionary = element_dictionary();
2731 int entry = dictionary->FindEntry(index);
2732 if (entry != NumberDictionary::kNotFound) {
2733 Object* result = dictionary->ValueAt(entry);
2734 PropertyDetails details = dictionary->DetailsAt(entry);
2735 if (details.IsReadOnly()) return Heap::undefined_value();
2736 if (details.type() == CALLBACKS) {
Leon Clarkef7060e22010-06-03 12:02:55 +01002737 if (result->IsFixedArray()) {
2738 return result;
2739 }
2740 // Otherwise allow to override it.
Steve Blocka7e24c12009-10-30 11:49:00 +00002741 }
2742 }
2743 break;
2744 }
2745 default:
2746 UNREACHABLE();
2747 break;
2748 }
2749 } else {
2750 // Lookup the name.
2751 LookupResult result;
2752 LocalLookup(name, &result);
Andrei Popescu402d9372010-02-26 13:31:12 +00002753 if (result.IsProperty()) {
Steve Blocka7e24c12009-10-30 11:49:00 +00002754 if (result.IsReadOnly()) return Heap::undefined_value();
2755 if (result.type() == CALLBACKS) {
2756 Object* obj = result.GetCallbackObject();
Leon Clarkef7060e22010-06-03 12:02:55 +01002757 // Need to preserve old getters/setters.
Leon Clarked91b9f72010-01-27 17:25:45 +00002758 if (obj->IsFixedArray()) {
Leon Clarkef7060e22010-06-03 12:02:55 +01002759 // Use set to update attributes.
2760 return SetPropertyCallback(name, obj, attributes);
Leon Clarked91b9f72010-01-27 17:25:45 +00002761 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002762 }
2763 }
2764 }
2765
2766 // Allocate the fixed array to hold getter and setter.
2767 Object* structure = Heap::AllocateFixedArray(2, TENURED);
2768 if (structure->IsFailure()) return structure;
Steve Blocka7e24c12009-10-30 11:49:00 +00002769
2770 if (is_element) {
Leon Clarkef7060e22010-06-03 12:02:55 +01002771 return SetElementCallback(index, structure, attributes);
Steve Blocka7e24c12009-10-30 11:49:00 +00002772 } else {
Leon Clarkef7060e22010-06-03 12:02:55 +01002773 return SetPropertyCallback(name, structure, attributes);
Steve Blocka7e24c12009-10-30 11:49:00 +00002774 }
Leon Clarkef7060e22010-06-03 12:02:55 +01002775}
2776
2777
2778bool JSObject::CanSetCallback(String* name) {
2779 ASSERT(!IsAccessCheckNeeded()
2780 || Top::MayNamedAccess(this, name, v8::ACCESS_SET));
2781
2782 // Check if there is an API defined callback object which prohibits
2783 // callback overwriting in this object or it's prototype chain.
2784 // This mechanism is needed for instance in a browser setting, where
2785 // certain accessors such as window.location should not be allowed
2786 // to be overwritten because allowing overwriting could potentially
2787 // cause security problems.
2788 LookupResult callback_result;
2789 LookupCallback(name, &callback_result);
2790 if (callback_result.IsProperty()) {
2791 Object* obj = callback_result.GetCallbackObject();
2792 if (obj->IsAccessorInfo() &&
2793 AccessorInfo::cast(obj)->prohibits_overwriting()) {
2794 return false;
2795 }
2796 }
2797
2798 return true;
2799}
2800
2801
2802Object* JSObject::SetElementCallback(uint32_t index,
2803 Object* structure,
2804 PropertyAttributes attributes) {
2805 PropertyDetails details = PropertyDetails(attributes, CALLBACKS);
2806
2807 // Normalize elements to make this operation simple.
2808 Object* ok = NormalizeElements();
2809 if (ok->IsFailure()) return ok;
2810
2811 // Update the dictionary with the new CALLBACKS property.
2812 Object* dict =
2813 element_dictionary()->Set(index, structure, details);
2814 if (dict->IsFailure()) return dict;
2815
2816 NumberDictionary* elements = NumberDictionary::cast(dict);
2817 elements->set_requires_slow_elements();
2818 // Set the potential new dictionary on the object.
2819 set_elements(elements);
Steve Blocka7e24c12009-10-30 11:49:00 +00002820
2821 return structure;
2822}
2823
2824
Leon Clarkef7060e22010-06-03 12:02:55 +01002825Object* JSObject::SetPropertyCallback(String* name,
2826 Object* structure,
2827 PropertyAttributes attributes) {
2828 PropertyDetails details = PropertyDetails(attributes, CALLBACKS);
2829
2830 bool convert_back_to_fast = HasFastProperties() &&
2831 (map()->instance_descriptors()->number_of_descriptors()
2832 < DescriptorArray::kMaxNumberOfDescriptors);
2833
2834 // Normalize object to make this operation simple.
2835 Object* ok = NormalizeProperties(CLEAR_INOBJECT_PROPERTIES, 0);
2836 if (ok->IsFailure()) return ok;
2837
2838 // For the global object allocate a new map to invalidate the global inline
2839 // caches which have a global property cell reference directly in the code.
2840 if (IsGlobalObject()) {
2841 Object* new_map = map()->CopyDropDescriptors();
2842 if (new_map->IsFailure()) return new_map;
2843 set_map(Map::cast(new_map));
2844 }
2845
2846 // Update the dictionary with the new CALLBACKS property.
2847 Object* result = SetNormalizedProperty(name, structure, details);
2848 if (result->IsFailure()) return result;
2849
2850 if (convert_back_to_fast) {
2851 ok = TransformToFastProperties(0);
2852 if (ok->IsFailure()) return ok;
2853 }
2854 return result;
2855}
2856
Steve Blocka7e24c12009-10-30 11:49:00 +00002857Object* JSObject::DefineAccessor(String* name, bool is_getter, JSFunction* fun,
2858 PropertyAttributes attributes) {
2859 // Check access rights if needed.
2860 if (IsAccessCheckNeeded() &&
Leon Clarkef7060e22010-06-03 12:02:55 +01002861 !Top::MayNamedAccess(this, name, v8::ACCESS_SET)) {
2862 Top::ReportFailedAccessCheck(this, v8::ACCESS_SET);
Steve Blocka7e24c12009-10-30 11:49:00 +00002863 return Heap::undefined_value();
2864 }
2865
2866 if (IsJSGlobalProxy()) {
2867 Object* proto = GetPrototype();
2868 if (proto->IsNull()) return this;
2869 ASSERT(proto->IsJSGlobalObject());
2870 return JSObject::cast(proto)->DefineAccessor(name, is_getter,
2871 fun, attributes);
2872 }
2873
2874 Object* array = DefineGetterSetter(name, attributes);
2875 if (array->IsFailure() || array->IsUndefined()) return array;
2876 FixedArray::cast(array)->set(is_getter ? 0 : 1, fun);
2877 return this;
2878}
2879
2880
Leon Clarkef7060e22010-06-03 12:02:55 +01002881Object* JSObject::DefineAccessor(AccessorInfo* info) {
2882 String* name = String::cast(info->name());
2883 // Check access rights if needed.
2884 if (IsAccessCheckNeeded() &&
2885 !Top::MayNamedAccess(this, name, v8::ACCESS_SET)) {
2886 Top::ReportFailedAccessCheck(this, v8::ACCESS_SET);
2887 return Heap::undefined_value();
2888 }
2889
2890 if (IsJSGlobalProxy()) {
2891 Object* proto = GetPrototype();
2892 if (proto->IsNull()) return this;
2893 ASSERT(proto->IsJSGlobalObject());
2894 return JSObject::cast(proto)->DefineAccessor(info);
2895 }
2896
2897 // Make sure that the top context does not change when doing callbacks or
2898 // interceptor calls.
2899 AssertNoContextChange ncc;
2900
2901 // Try to flatten before operating on the string.
2902 name->TryFlatten();
2903
2904 if (!CanSetCallback(name)) {
2905 return Heap::undefined_value();
2906 }
2907
2908 uint32_t index = 0;
2909 bool is_element = name->AsArrayIndex(&index);
2910
2911 if (is_element) {
2912 if (IsJSArray()) return Heap::undefined_value();
2913
2914 // Accessors overwrite previous callbacks (cf. with getters/setters).
2915 switch (GetElementsKind()) {
2916 case FAST_ELEMENTS:
2917 break;
2918 case PIXEL_ELEMENTS:
2919 case EXTERNAL_BYTE_ELEMENTS:
2920 case EXTERNAL_UNSIGNED_BYTE_ELEMENTS:
2921 case EXTERNAL_SHORT_ELEMENTS:
2922 case EXTERNAL_UNSIGNED_SHORT_ELEMENTS:
2923 case EXTERNAL_INT_ELEMENTS:
2924 case EXTERNAL_UNSIGNED_INT_ELEMENTS:
2925 case EXTERNAL_FLOAT_ELEMENTS:
2926 // Ignore getters and setters on pixel and external array
2927 // elements.
2928 return Heap::undefined_value();
2929 case DICTIONARY_ELEMENTS:
2930 break;
2931 default:
2932 UNREACHABLE();
2933 break;
2934 }
2935
2936 SetElementCallback(index, info, info->property_attributes());
2937 } else {
2938 // Lookup the name.
2939 LookupResult result;
2940 LocalLookup(name, &result);
2941 // ES5 forbids turning a property into an accessor if it's not
2942 // configurable (that is IsDontDelete in ES3 and v8), see 8.6.1 (Table 5).
2943 if (result.IsProperty() && (result.IsReadOnly() || result.IsDontDelete())) {
2944 return Heap::undefined_value();
2945 }
2946 SetPropertyCallback(name, info, info->property_attributes());
2947 }
2948
2949 return this;
2950}
2951
2952
Steve Blocka7e24c12009-10-30 11:49:00 +00002953Object* JSObject::LookupAccessor(String* name, bool is_getter) {
2954 // Make sure that the top context does not change when doing callbacks or
2955 // interceptor calls.
2956 AssertNoContextChange ncc;
2957
2958 // Check access rights if needed.
2959 if (IsAccessCheckNeeded() &&
2960 !Top::MayNamedAccess(this, name, v8::ACCESS_HAS)) {
2961 Top::ReportFailedAccessCheck(this, v8::ACCESS_HAS);
2962 return Heap::undefined_value();
2963 }
2964
2965 // Make the lookup and include prototypes.
2966 int accessor_index = is_getter ? kGetterIndex : kSetterIndex;
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01002967 uint32_t index = 0;
Steve Blocka7e24c12009-10-30 11:49:00 +00002968 if (name->AsArrayIndex(&index)) {
2969 for (Object* obj = this;
2970 obj != Heap::null_value();
2971 obj = JSObject::cast(obj)->GetPrototype()) {
2972 JSObject* js_object = JSObject::cast(obj);
2973 if (js_object->HasDictionaryElements()) {
2974 NumberDictionary* dictionary = js_object->element_dictionary();
2975 int entry = dictionary->FindEntry(index);
2976 if (entry != NumberDictionary::kNotFound) {
2977 Object* element = dictionary->ValueAt(entry);
2978 PropertyDetails details = dictionary->DetailsAt(entry);
2979 if (details.type() == CALLBACKS) {
Leon Clarkef7060e22010-06-03 12:02:55 +01002980 if (element->IsFixedArray()) {
2981 return FixedArray::cast(element)->get(accessor_index);
2982 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002983 }
2984 }
2985 }
2986 }
2987 } else {
2988 for (Object* obj = this;
2989 obj != Heap::null_value();
2990 obj = JSObject::cast(obj)->GetPrototype()) {
2991 LookupResult result;
2992 JSObject::cast(obj)->LocalLookup(name, &result);
Andrei Popescu402d9372010-02-26 13:31:12 +00002993 if (result.IsProperty()) {
Steve Blocka7e24c12009-10-30 11:49:00 +00002994 if (result.IsReadOnly()) return Heap::undefined_value();
2995 if (result.type() == CALLBACKS) {
2996 Object* obj = result.GetCallbackObject();
2997 if (obj->IsFixedArray()) {
2998 return FixedArray::cast(obj)->get(accessor_index);
2999 }
3000 }
3001 }
3002 }
3003 }
3004 return Heap::undefined_value();
3005}
3006
3007
3008Object* JSObject::SlowReverseLookup(Object* value) {
3009 if (HasFastProperties()) {
3010 DescriptorArray* descs = map()->instance_descriptors();
3011 for (int i = 0; i < descs->number_of_descriptors(); i++) {
3012 if (descs->GetType(i) == FIELD) {
3013 if (FastPropertyAt(descs->GetFieldIndex(i)) == value) {
3014 return descs->GetKey(i);
3015 }
3016 } else if (descs->GetType(i) == CONSTANT_FUNCTION) {
3017 if (descs->GetConstantFunction(i) == value) {
3018 return descs->GetKey(i);
3019 }
3020 }
3021 }
3022 return Heap::undefined_value();
3023 } else {
3024 return property_dictionary()->SlowReverseLookup(value);
3025 }
3026}
3027
3028
3029Object* Map::CopyDropDescriptors() {
3030 Object* result = Heap::AllocateMap(instance_type(), instance_size());
3031 if (result->IsFailure()) return result;
3032 Map::cast(result)->set_prototype(prototype());
3033 Map::cast(result)->set_constructor(constructor());
3034 // Don't copy descriptors, so map transitions always remain a forest.
3035 // If we retained the same descriptors we would have two maps
3036 // pointing to the same transition which is bad because the garbage
3037 // collector relies on being able to reverse pointers from transitions
3038 // to maps. If properties need to be retained use CopyDropTransitions.
3039 Map::cast(result)->set_instance_descriptors(Heap::empty_descriptor_array());
3040 // Please note instance_type and instance_size are set when allocated.
3041 Map::cast(result)->set_inobject_properties(inobject_properties());
3042 Map::cast(result)->set_unused_property_fields(unused_property_fields());
3043
3044 // If the map has pre-allocated properties always start out with a descriptor
3045 // array describing these properties.
3046 if (pre_allocated_property_fields() > 0) {
3047 ASSERT(constructor()->IsJSFunction());
3048 JSFunction* ctor = JSFunction::cast(constructor());
3049 Object* descriptors =
3050 ctor->initial_map()->instance_descriptors()->RemoveTransitions();
3051 if (descriptors->IsFailure()) return descriptors;
3052 Map::cast(result)->set_instance_descriptors(
3053 DescriptorArray::cast(descriptors));
3054 Map::cast(result)->set_pre_allocated_property_fields(
3055 pre_allocated_property_fields());
3056 }
3057 Map::cast(result)->set_bit_field(bit_field());
3058 Map::cast(result)->set_bit_field2(bit_field2());
3059 Map::cast(result)->ClearCodeCache();
3060 return result;
3061}
3062
3063
3064Object* Map::CopyDropTransitions() {
3065 Object* new_map = CopyDropDescriptors();
3066 if (new_map->IsFailure()) return new_map;
3067 Object* descriptors = instance_descriptors()->RemoveTransitions();
3068 if (descriptors->IsFailure()) return descriptors;
3069 cast(new_map)->set_instance_descriptors(DescriptorArray::cast(descriptors));
3070 return cast(new_map);
3071}
3072
3073
3074Object* Map::UpdateCodeCache(String* name, Code* code) {
Steve Block6ded16b2010-05-10 14:33:55 +01003075 // Allocate the code cache if not present.
3076 if (code_cache()->IsFixedArray()) {
3077 Object* result = Heap::AllocateCodeCache();
3078 if (result->IsFailure()) return result;
3079 set_code_cache(result);
3080 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003081
Steve Block6ded16b2010-05-10 14:33:55 +01003082 // Update the code cache.
3083 return CodeCache::cast(code_cache())->Update(name, code);
3084}
3085
3086
3087Object* Map::FindInCodeCache(String* name, Code::Flags flags) {
3088 // Do a lookup if a code cache exists.
3089 if (!code_cache()->IsFixedArray()) {
3090 return CodeCache::cast(code_cache())->Lookup(name, flags);
3091 } else {
3092 return Heap::undefined_value();
3093 }
3094}
3095
3096
3097int Map::IndexInCodeCache(Object* name, Code* code) {
3098 // Get the internal index if a code cache exists.
3099 if (!code_cache()->IsFixedArray()) {
3100 return CodeCache::cast(code_cache())->GetIndex(name, code);
3101 }
3102 return -1;
3103}
3104
3105
3106void Map::RemoveFromCodeCache(String* name, Code* code, int index) {
3107 // No GC is supposed to happen between a call to IndexInCodeCache and
3108 // RemoveFromCodeCache so the code cache must be there.
3109 ASSERT(!code_cache()->IsFixedArray());
3110 CodeCache::cast(code_cache())->RemoveByIndex(name, code, index);
3111}
3112
3113
3114Object* CodeCache::Update(String* name, Code* code) {
3115 ASSERT(code->ic_state() == MONOMORPHIC);
3116
3117 // The number of monomorphic stubs for normal load/store/call IC's can grow to
3118 // a large number and therefore they need to go into a hash table. They are
3119 // used to load global properties from cells.
3120 if (code->type() == NORMAL) {
3121 // Make sure that a hash table is allocated for the normal load code cache.
3122 if (normal_type_cache()->IsUndefined()) {
3123 Object* result =
3124 CodeCacheHashTable::Allocate(CodeCacheHashTable::kInitialSize);
3125 if (result->IsFailure()) return result;
3126 set_normal_type_cache(result);
3127 }
3128 return UpdateNormalTypeCache(name, code);
3129 } else {
3130 ASSERT(default_cache()->IsFixedArray());
3131 return UpdateDefaultCache(name, code);
3132 }
3133}
3134
3135
3136Object* CodeCache::UpdateDefaultCache(String* name, Code* code) {
3137 // When updating the default code cache we disregard the type encoded in the
Steve Blocka7e24c12009-10-30 11:49:00 +00003138 // flags. This allows call constant stubs to overwrite call field
3139 // stubs, etc.
3140 Code::Flags flags = Code::RemoveTypeFromFlags(code->flags());
3141
3142 // First check whether we can update existing code cache without
3143 // extending it.
Steve Block6ded16b2010-05-10 14:33:55 +01003144 FixedArray* cache = default_cache();
Steve Blocka7e24c12009-10-30 11:49:00 +00003145 int length = cache->length();
3146 int deleted_index = -1;
Steve Block6ded16b2010-05-10 14:33:55 +01003147 for (int i = 0; i < length; i += kCodeCacheEntrySize) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003148 Object* key = cache->get(i);
3149 if (key->IsNull()) {
3150 if (deleted_index < 0) deleted_index = i;
3151 continue;
3152 }
3153 if (key->IsUndefined()) {
3154 if (deleted_index >= 0) i = deleted_index;
Steve Block6ded16b2010-05-10 14:33:55 +01003155 cache->set(i + kCodeCacheEntryNameOffset, name);
3156 cache->set(i + kCodeCacheEntryCodeOffset, code);
Steve Blocka7e24c12009-10-30 11:49:00 +00003157 return this;
3158 }
3159 if (name->Equals(String::cast(key))) {
Steve Block6ded16b2010-05-10 14:33:55 +01003160 Code::Flags found =
3161 Code::cast(cache->get(i + kCodeCacheEntryCodeOffset))->flags();
Steve Blocka7e24c12009-10-30 11:49:00 +00003162 if (Code::RemoveTypeFromFlags(found) == flags) {
Steve Block6ded16b2010-05-10 14:33:55 +01003163 cache->set(i + kCodeCacheEntryCodeOffset, code);
Steve Blocka7e24c12009-10-30 11:49:00 +00003164 return this;
3165 }
3166 }
3167 }
3168
3169 // Reached the end of the code cache. If there were deleted
3170 // elements, reuse the space for the first of them.
3171 if (deleted_index >= 0) {
Steve Block6ded16b2010-05-10 14:33:55 +01003172 cache->set(deleted_index + kCodeCacheEntryNameOffset, name);
3173 cache->set(deleted_index + kCodeCacheEntryCodeOffset, code);
Steve Blocka7e24c12009-10-30 11:49:00 +00003174 return this;
3175 }
3176
Steve Block6ded16b2010-05-10 14:33:55 +01003177 // Extend the code cache with some new entries (at least one). Must be a
3178 // multiple of the entry size.
3179 int new_length = length + ((length >> 1)) + kCodeCacheEntrySize;
3180 new_length = new_length - new_length % kCodeCacheEntrySize;
3181 ASSERT((new_length % kCodeCacheEntrySize) == 0);
Steve Blocka7e24c12009-10-30 11:49:00 +00003182 Object* result = cache->CopySize(new_length);
3183 if (result->IsFailure()) return result;
3184
3185 // Add the (name, code) pair to the new cache.
3186 cache = FixedArray::cast(result);
Steve Block6ded16b2010-05-10 14:33:55 +01003187 cache->set(length + kCodeCacheEntryNameOffset, name);
3188 cache->set(length + kCodeCacheEntryCodeOffset, code);
3189 set_default_cache(cache);
Steve Blocka7e24c12009-10-30 11:49:00 +00003190 return this;
3191}
3192
3193
Steve Block6ded16b2010-05-10 14:33:55 +01003194Object* CodeCache::UpdateNormalTypeCache(String* name, Code* code) {
3195 // Adding a new entry can cause a new cache to be allocated.
3196 CodeCacheHashTable* cache = CodeCacheHashTable::cast(normal_type_cache());
3197 Object* new_cache = cache->Put(name, code);
3198 if (new_cache->IsFailure()) return new_cache;
3199 set_normal_type_cache(new_cache);
3200 return this;
3201}
3202
3203
3204Object* CodeCache::Lookup(String* name, Code::Flags flags) {
3205 if (Code::ExtractTypeFromFlags(flags) == NORMAL) {
3206 return LookupNormalTypeCache(name, flags);
3207 } else {
3208 return LookupDefaultCache(name, flags);
3209 }
3210}
3211
3212
3213Object* CodeCache::LookupDefaultCache(String* name, Code::Flags flags) {
3214 FixedArray* cache = default_cache();
Steve Blocka7e24c12009-10-30 11:49:00 +00003215 int length = cache->length();
Steve Block6ded16b2010-05-10 14:33:55 +01003216 for (int i = 0; i < length; i += kCodeCacheEntrySize) {
3217 Object* key = cache->get(i + kCodeCacheEntryNameOffset);
Steve Blocka7e24c12009-10-30 11:49:00 +00003218 // Skip deleted elements.
3219 if (key->IsNull()) continue;
3220 if (key->IsUndefined()) return key;
3221 if (name->Equals(String::cast(key))) {
Steve Block6ded16b2010-05-10 14:33:55 +01003222 Code* code = Code::cast(cache->get(i + kCodeCacheEntryCodeOffset));
3223 if (code->flags() == flags) {
3224 return code;
3225 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003226 }
3227 }
3228 return Heap::undefined_value();
3229}
3230
3231
Steve Block6ded16b2010-05-10 14:33:55 +01003232Object* CodeCache::LookupNormalTypeCache(String* name, Code::Flags flags) {
3233 if (!normal_type_cache()->IsUndefined()) {
3234 CodeCacheHashTable* cache = CodeCacheHashTable::cast(normal_type_cache());
3235 return cache->Lookup(name, flags);
3236 } else {
3237 return Heap::undefined_value();
3238 }
3239}
3240
3241
3242int CodeCache::GetIndex(Object* name, Code* code) {
3243 if (code->type() == NORMAL) {
3244 if (normal_type_cache()->IsUndefined()) return -1;
3245 CodeCacheHashTable* cache = CodeCacheHashTable::cast(normal_type_cache());
3246 return cache->GetIndex(String::cast(name), code->flags());
3247 }
3248
3249 FixedArray* array = default_cache();
Steve Blocka7e24c12009-10-30 11:49:00 +00003250 int len = array->length();
Steve Block6ded16b2010-05-10 14:33:55 +01003251 for (int i = 0; i < len; i += kCodeCacheEntrySize) {
3252 if (array->get(i + kCodeCacheEntryCodeOffset) == code) return i + 1;
Steve Blocka7e24c12009-10-30 11:49:00 +00003253 }
3254 return -1;
3255}
3256
3257
Steve Block6ded16b2010-05-10 14:33:55 +01003258void CodeCache::RemoveByIndex(Object* name, Code* code, int index) {
3259 if (code->type() == NORMAL) {
3260 ASSERT(!normal_type_cache()->IsUndefined());
3261 CodeCacheHashTable* cache = CodeCacheHashTable::cast(normal_type_cache());
3262 ASSERT(cache->GetIndex(String::cast(name), code->flags()) == index);
3263 cache->RemoveByIndex(index);
3264 } else {
3265 FixedArray* array = default_cache();
3266 ASSERT(array->length() >= index && array->get(index)->IsCode());
3267 // Use null instead of undefined for deleted elements to distinguish
3268 // deleted elements from unused elements. This distinction is used
3269 // when looking up in the cache and when updating the cache.
3270 ASSERT_EQ(1, kCodeCacheEntryCodeOffset - kCodeCacheEntryNameOffset);
3271 array->set_null(index - 1); // Name.
3272 array->set_null(index); // Code.
3273 }
3274}
3275
3276
3277// The key in the code cache hash table consists of the property name and the
3278// code object. The actual match is on the name and the code flags. If a key
3279// is created using the flags and not a code object it can only be used for
3280// lookup not to create a new entry.
3281class CodeCacheHashTableKey : public HashTableKey {
3282 public:
3283 CodeCacheHashTableKey(String* name, Code::Flags flags)
3284 : name_(name), flags_(flags), code_(NULL) { }
3285
3286 CodeCacheHashTableKey(String* name, Code* code)
3287 : name_(name),
3288 flags_(code->flags()),
3289 code_(code) { }
3290
3291
3292 bool IsMatch(Object* other) {
3293 if (!other->IsFixedArray()) return false;
3294 FixedArray* pair = FixedArray::cast(other);
3295 String* name = String::cast(pair->get(0));
3296 Code::Flags flags = Code::cast(pair->get(1))->flags();
3297 if (flags != flags_) {
3298 return false;
3299 }
3300 return name_->Equals(name);
3301 }
3302
3303 static uint32_t NameFlagsHashHelper(String* name, Code::Flags flags) {
3304 return name->Hash() ^ flags;
3305 }
3306
3307 uint32_t Hash() { return NameFlagsHashHelper(name_, flags_); }
3308
3309 uint32_t HashForObject(Object* obj) {
3310 FixedArray* pair = FixedArray::cast(obj);
3311 String* name = String::cast(pair->get(0));
3312 Code* code = Code::cast(pair->get(1));
3313 return NameFlagsHashHelper(name, code->flags());
3314 }
3315
3316 Object* AsObject() {
3317 ASSERT(code_ != NULL);
3318 Object* obj = Heap::AllocateFixedArray(2);
3319 if (obj->IsFailure()) return obj;
3320 FixedArray* pair = FixedArray::cast(obj);
3321 pair->set(0, name_);
3322 pair->set(1, code_);
3323 return pair;
3324 }
3325
3326 private:
3327 String* name_;
3328 Code::Flags flags_;
3329 Code* code_;
3330};
3331
3332
3333Object* CodeCacheHashTable::Lookup(String* name, Code::Flags flags) {
3334 CodeCacheHashTableKey key(name, flags);
3335 int entry = FindEntry(&key);
3336 if (entry == kNotFound) return Heap::undefined_value();
3337 return get(EntryToIndex(entry) + 1);
3338}
3339
3340
3341Object* CodeCacheHashTable::Put(String* name, Code* code) {
3342 CodeCacheHashTableKey key(name, code);
3343 Object* obj = EnsureCapacity(1, &key);
3344 if (obj->IsFailure()) return obj;
3345
3346 // Don't use this, as the table might have grown.
3347 CodeCacheHashTable* cache = reinterpret_cast<CodeCacheHashTable*>(obj);
3348
3349 int entry = cache->FindInsertionEntry(key.Hash());
3350 Object* k = key.AsObject();
3351 if (k->IsFailure()) return k;
3352
3353 cache->set(EntryToIndex(entry), k);
3354 cache->set(EntryToIndex(entry) + 1, code);
3355 cache->ElementAdded();
3356 return cache;
3357}
3358
3359
3360int CodeCacheHashTable::GetIndex(String* name, Code::Flags flags) {
3361 CodeCacheHashTableKey key(name, flags);
3362 int entry = FindEntry(&key);
3363 return (entry == kNotFound) ? -1 : entry;
3364}
3365
3366
3367void CodeCacheHashTable::RemoveByIndex(int index) {
3368 ASSERT(index >= 0);
3369 set(EntryToIndex(index), Heap::null_value());
3370 set(EntryToIndex(index) + 1, Heap::null_value());
3371 ElementRemoved();
Steve Blocka7e24c12009-10-30 11:49:00 +00003372}
3373
3374
3375void FixedArray::FixedArrayIterateBody(ObjectVisitor* v) {
3376 IteratePointers(v, kHeaderSize, kHeaderSize + length() * kPointerSize);
3377}
3378
3379
3380static bool HasKey(FixedArray* array, Object* key) {
3381 int len0 = array->length();
3382 for (int i = 0; i < len0; i++) {
3383 Object* element = array->get(i);
3384 if (element->IsSmi() && key->IsSmi() && (element == key)) return true;
3385 if (element->IsString() &&
3386 key->IsString() && String::cast(element)->Equals(String::cast(key))) {
3387 return true;
3388 }
3389 }
3390 return false;
3391}
3392
3393
3394Object* FixedArray::AddKeysFromJSArray(JSArray* array) {
Steve Block3ce2e202009-11-05 08:53:23 +00003395 ASSERT(!array->HasPixelElements() && !array->HasExternalArrayElements());
Steve Blocka7e24c12009-10-30 11:49:00 +00003396 switch (array->GetElementsKind()) {
3397 case JSObject::FAST_ELEMENTS:
3398 return UnionOfKeys(FixedArray::cast(array->elements()));
3399 case JSObject::DICTIONARY_ELEMENTS: {
3400 NumberDictionary* dict = array->element_dictionary();
3401 int size = dict->NumberOfElements();
3402
3403 // Allocate a temporary fixed array.
3404 Object* object = Heap::AllocateFixedArray(size);
3405 if (object->IsFailure()) return object;
3406 FixedArray* key_array = FixedArray::cast(object);
3407
3408 int capacity = dict->Capacity();
3409 int pos = 0;
3410 // Copy the elements from the JSArray to the temporary fixed array.
3411 for (int i = 0; i < capacity; i++) {
3412 if (dict->IsKey(dict->KeyAt(i))) {
3413 key_array->set(pos++, dict->ValueAt(i));
3414 }
3415 }
3416 // Compute the union of this and the temporary fixed array.
3417 return UnionOfKeys(key_array);
3418 }
3419 default:
3420 UNREACHABLE();
3421 }
3422 UNREACHABLE();
3423 return Heap::null_value(); // Failure case needs to "return" a value.
3424}
3425
3426
3427Object* FixedArray::UnionOfKeys(FixedArray* other) {
3428 int len0 = length();
3429 int len1 = other->length();
3430 // Optimize if either is empty.
3431 if (len0 == 0) return other;
3432 if (len1 == 0) return this;
3433
3434 // Compute how many elements are not in this.
3435 int extra = 0;
3436 for (int y = 0; y < len1; y++) {
3437 Object* value = other->get(y);
3438 if (!value->IsTheHole() && !HasKey(this, value)) extra++;
3439 }
3440
3441 if (extra == 0) return this;
3442
3443 // Allocate the result
3444 Object* obj = Heap::AllocateFixedArray(len0 + extra);
3445 if (obj->IsFailure()) return obj;
3446 // Fill in the content
Leon Clarke4515c472010-02-03 11:58:03 +00003447 AssertNoAllocation no_gc;
Steve Blocka7e24c12009-10-30 11:49:00 +00003448 FixedArray* result = FixedArray::cast(obj);
Leon Clarke4515c472010-02-03 11:58:03 +00003449 WriteBarrierMode mode = result->GetWriteBarrierMode(no_gc);
Steve Blocka7e24c12009-10-30 11:49:00 +00003450 for (int i = 0; i < len0; i++) {
3451 result->set(i, get(i), mode);
3452 }
3453 // Fill in the extra keys.
3454 int index = 0;
3455 for (int y = 0; y < len1; y++) {
3456 Object* value = other->get(y);
3457 if (!value->IsTheHole() && !HasKey(this, value)) {
3458 result->set(len0 + index, other->get(y), mode);
3459 index++;
3460 }
3461 }
3462 ASSERT(extra == index);
3463 return result;
3464}
3465
3466
3467Object* FixedArray::CopySize(int new_length) {
3468 if (new_length == 0) return Heap::empty_fixed_array();
3469 Object* obj = Heap::AllocateFixedArray(new_length);
3470 if (obj->IsFailure()) return obj;
3471 FixedArray* result = FixedArray::cast(obj);
3472 // Copy the content
Leon Clarke4515c472010-02-03 11:58:03 +00003473 AssertNoAllocation no_gc;
Steve Blocka7e24c12009-10-30 11:49:00 +00003474 int len = length();
3475 if (new_length < len) len = new_length;
3476 result->set_map(map());
Leon Clarke4515c472010-02-03 11:58:03 +00003477 WriteBarrierMode mode = result->GetWriteBarrierMode(no_gc);
Steve Blocka7e24c12009-10-30 11:49:00 +00003478 for (int i = 0; i < len; i++) {
3479 result->set(i, get(i), mode);
3480 }
3481 return result;
3482}
3483
3484
3485void FixedArray::CopyTo(int pos, FixedArray* dest, int dest_pos, int len) {
Leon Clarke4515c472010-02-03 11:58:03 +00003486 AssertNoAllocation no_gc;
3487 WriteBarrierMode mode = dest->GetWriteBarrierMode(no_gc);
Steve Blocka7e24c12009-10-30 11:49:00 +00003488 for (int index = 0; index < len; index++) {
3489 dest->set(dest_pos+index, get(pos+index), mode);
3490 }
3491}
3492
3493
3494#ifdef DEBUG
3495bool FixedArray::IsEqualTo(FixedArray* other) {
3496 if (length() != other->length()) return false;
3497 for (int i = 0 ; i < length(); ++i) {
3498 if (get(i) != other->get(i)) return false;
3499 }
3500 return true;
3501}
3502#endif
3503
3504
3505Object* DescriptorArray::Allocate(int number_of_descriptors) {
3506 if (number_of_descriptors == 0) {
3507 return Heap::empty_descriptor_array();
3508 }
3509 // Allocate the array of keys.
Leon Clarkee46be812010-01-19 14:06:41 +00003510 Object* array =
3511 Heap::AllocateFixedArray(ToKeyIndex(number_of_descriptors));
Steve Blocka7e24c12009-10-30 11:49:00 +00003512 if (array->IsFailure()) return array;
3513 // Do not use DescriptorArray::cast on incomplete object.
3514 FixedArray* result = FixedArray::cast(array);
3515
3516 // Allocate the content array and set it in the descriptor array.
3517 array = Heap::AllocateFixedArray(number_of_descriptors << 1);
3518 if (array->IsFailure()) return array;
3519 result->set(kContentArrayIndex, array);
3520 result->set(kEnumerationIndexIndex,
Leon Clarke4515c472010-02-03 11:58:03 +00003521 Smi::FromInt(PropertyDetails::kInitialIndex));
Steve Blocka7e24c12009-10-30 11:49:00 +00003522 return result;
3523}
3524
3525
3526void DescriptorArray::SetEnumCache(FixedArray* bridge_storage,
3527 FixedArray* new_cache) {
3528 ASSERT(bridge_storage->length() >= kEnumCacheBridgeLength);
3529 if (HasEnumCache()) {
3530 FixedArray::cast(get(kEnumerationIndexIndex))->
3531 set(kEnumCacheBridgeCacheIndex, new_cache);
3532 } else {
3533 if (IsEmpty()) return; // Do nothing for empty descriptor array.
3534 FixedArray::cast(bridge_storage)->
3535 set(kEnumCacheBridgeCacheIndex, new_cache);
3536 fast_set(FixedArray::cast(bridge_storage),
3537 kEnumCacheBridgeEnumIndex,
3538 get(kEnumerationIndexIndex));
3539 set(kEnumerationIndexIndex, bridge_storage);
3540 }
3541}
3542
3543
3544Object* DescriptorArray::CopyInsert(Descriptor* descriptor,
3545 TransitionFlag transition_flag) {
3546 // Transitions are only kept when inserting another transition.
3547 // This precondition is not required by this function's implementation, but
3548 // is currently required by the semantics of maps, so we check it.
3549 // Conversely, we filter after replacing, so replacing a transition and
3550 // removing all other transitions is not supported.
3551 bool remove_transitions = transition_flag == REMOVE_TRANSITIONS;
3552 ASSERT(remove_transitions == !descriptor->GetDetails().IsTransition());
3553 ASSERT(descriptor->GetDetails().type() != NULL_DESCRIPTOR);
3554
3555 // Ensure the key is a symbol.
3556 Object* result = descriptor->KeyToSymbol();
3557 if (result->IsFailure()) return result;
3558
3559 int transitions = 0;
3560 int null_descriptors = 0;
3561 if (remove_transitions) {
3562 for (int i = 0; i < number_of_descriptors(); i++) {
3563 if (IsTransition(i)) transitions++;
3564 if (IsNullDescriptor(i)) null_descriptors++;
3565 }
3566 } else {
3567 for (int i = 0; i < number_of_descriptors(); i++) {
3568 if (IsNullDescriptor(i)) null_descriptors++;
3569 }
3570 }
3571 int new_size = number_of_descriptors() - transitions - null_descriptors;
3572
3573 // If key is in descriptor, we replace it in-place when filtering.
3574 // Count a null descriptor for key as inserted, not replaced.
3575 int index = Search(descriptor->GetKey());
3576 const bool inserting = (index == kNotFound);
3577 const bool replacing = !inserting;
3578 bool keep_enumeration_index = false;
3579 if (inserting) {
3580 ++new_size;
3581 }
3582 if (replacing) {
3583 // We are replacing an existing descriptor. We keep the enumeration
3584 // index of a visible property.
3585 PropertyType t = PropertyDetails(GetDetails(index)).type();
3586 if (t == CONSTANT_FUNCTION ||
3587 t == FIELD ||
3588 t == CALLBACKS ||
3589 t == INTERCEPTOR) {
3590 keep_enumeration_index = true;
3591 } else if (remove_transitions) {
3592 // Replaced descriptor has been counted as removed if it is
3593 // a transition that will be replaced. Adjust count in this case.
3594 ++new_size;
3595 }
3596 }
3597 result = Allocate(new_size);
3598 if (result->IsFailure()) return result;
3599 DescriptorArray* new_descriptors = DescriptorArray::cast(result);
3600 // Set the enumeration index in the descriptors and set the enumeration index
3601 // in the result.
3602 int enumeration_index = NextEnumerationIndex();
3603 if (!descriptor->GetDetails().IsTransition()) {
3604 if (keep_enumeration_index) {
3605 descriptor->SetEnumerationIndex(
3606 PropertyDetails(GetDetails(index)).index());
3607 } else {
3608 descriptor->SetEnumerationIndex(enumeration_index);
3609 ++enumeration_index;
3610 }
3611 }
3612 new_descriptors->SetNextEnumerationIndex(enumeration_index);
3613
3614 // Copy the descriptors, filtering out transitions and null descriptors,
3615 // and inserting or replacing a descriptor.
3616 uint32_t descriptor_hash = descriptor->GetKey()->Hash();
3617 int from_index = 0;
3618 int to_index = 0;
3619
3620 for (; from_index < number_of_descriptors(); from_index++) {
3621 String* key = GetKey(from_index);
3622 if (key->Hash() > descriptor_hash || key == descriptor->GetKey()) {
3623 break;
3624 }
3625 if (IsNullDescriptor(from_index)) continue;
3626 if (remove_transitions && IsTransition(from_index)) continue;
3627 new_descriptors->CopyFrom(to_index++, this, from_index);
3628 }
3629
3630 new_descriptors->Set(to_index++, descriptor);
3631 if (replacing) from_index++;
3632
3633 for (; from_index < number_of_descriptors(); from_index++) {
3634 if (IsNullDescriptor(from_index)) continue;
3635 if (remove_transitions && IsTransition(from_index)) continue;
3636 new_descriptors->CopyFrom(to_index++, this, from_index);
3637 }
3638
3639 ASSERT(to_index == new_descriptors->number_of_descriptors());
3640 SLOW_ASSERT(new_descriptors->IsSortedNoDuplicates());
3641
3642 return new_descriptors;
3643}
3644
3645
3646Object* DescriptorArray::RemoveTransitions() {
3647 // Remove all transitions and null descriptors. Return a copy of the array
3648 // with all transitions removed, or a Failure object if the new array could
3649 // not be allocated.
3650
3651 // Compute the size of the map transition entries to be removed.
3652 int num_removed = 0;
3653 for (int i = 0; i < number_of_descriptors(); i++) {
3654 if (!IsProperty(i)) num_removed++;
3655 }
3656
3657 // Allocate the new descriptor array.
3658 Object* result = Allocate(number_of_descriptors() - num_removed);
3659 if (result->IsFailure()) return result;
3660 DescriptorArray* new_descriptors = DescriptorArray::cast(result);
3661
3662 // Copy the content.
3663 int next_descriptor = 0;
3664 for (int i = 0; i < number_of_descriptors(); i++) {
3665 if (IsProperty(i)) new_descriptors->CopyFrom(next_descriptor++, this, i);
3666 }
3667 ASSERT(next_descriptor == new_descriptors->number_of_descriptors());
3668
3669 return new_descriptors;
3670}
3671
3672
3673void DescriptorArray::Sort() {
3674 // In-place heap sort.
3675 int len = number_of_descriptors();
3676
3677 // Bottom-up max-heap construction.
Steve Block6ded16b2010-05-10 14:33:55 +01003678 // Index of the last node with children
3679 const int max_parent_index = (len / 2) - 1;
3680 for (int i = max_parent_index; i >= 0; --i) {
3681 int parent_index = i;
3682 const uint32_t parent_hash = GetKey(i)->Hash();
3683 while (parent_index <= max_parent_index) {
3684 int child_index = 2 * parent_index + 1;
Steve Blocka7e24c12009-10-30 11:49:00 +00003685 uint32_t child_hash = GetKey(child_index)->Hash();
Steve Block6ded16b2010-05-10 14:33:55 +01003686 if (child_index + 1 < len) {
3687 uint32_t right_child_hash = GetKey(child_index + 1)->Hash();
3688 if (right_child_hash > child_hash) {
3689 child_index++;
3690 child_hash = right_child_hash;
3691 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003692 }
Steve Block6ded16b2010-05-10 14:33:55 +01003693 if (child_hash <= parent_hash) break;
3694 Swap(parent_index, child_index);
3695 // Now element at child_index could be < its children.
3696 parent_index = child_index; // parent_hash remains correct.
Steve Blocka7e24c12009-10-30 11:49:00 +00003697 }
3698 }
3699
3700 // Extract elements and create sorted array.
3701 for (int i = len - 1; i > 0; --i) {
3702 // Put max element at the back of the array.
3703 Swap(0, i);
3704 // Sift down the new top element.
3705 int parent_index = 0;
Steve Block6ded16b2010-05-10 14:33:55 +01003706 const uint32_t parent_hash = GetKey(parent_index)->Hash();
3707 const int max_parent_index = (i / 2) - 1;
3708 while (parent_index <= max_parent_index) {
3709 int child_index = parent_index * 2 + 1;
3710 uint32_t child_hash = GetKey(child_index)->Hash();
3711 if (child_index + 1 < i) {
3712 uint32_t right_child_hash = GetKey(child_index + 1)->Hash();
3713 if (right_child_hash > child_hash) {
3714 child_index++;
3715 child_hash = right_child_hash;
3716 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003717 }
Steve Block6ded16b2010-05-10 14:33:55 +01003718 if (child_hash <= parent_hash) break;
3719 Swap(parent_index, child_index);
3720 parent_index = child_index;
Steve Blocka7e24c12009-10-30 11:49:00 +00003721 }
3722 }
3723
3724 SLOW_ASSERT(IsSortedNoDuplicates());
3725}
3726
3727
3728int DescriptorArray::BinarySearch(String* name, int low, int high) {
3729 uint32_t hash = name->Hash();
3730
3731 while (low <= high) {
3732 int mid = (low + high) / 2;
3733 String* mid_name = GetKey(mid);
3734 uint32_t mid_hash = mid_name->Hash();
3735
3736 if (mid_hash > hash) {
3737 high = mid - 1;
3738 continue;
3739 }
3740 if (mid_hash < hash) {
3741 low = mid + 1;
3742 continue;
3743 }
3744 // Found an element with the same hash-code.
3745 ASSERT(hash == mid_hash);
3746 // There might be more, so we find the first one and
3747 // check them all to see if we have a match.
3748 if (name == mid_name && !is_null_descriptor(mid)) return mid;
3749 while ((mid > low) && (GetKey(mid - 1)->Hash() == hash)) mid--;
3750 for (; (mid <= high) && (GetKey(mid)->Hash() == hash); mid++) {
3751 if (GetKey(mid)->Equals(name) && !is_null_descriptor(mid)) return mid;
3752 }
3753 break;
3754 }
3755 return kNotFound;
3756}
3757
3758
3759int DescriptorArray::LinearSearch(String* name, int len) {
3760 uint32_t hash = name->Hash();
3761 for (int number = 0; number < len; number++) {
3762 String* entry = GetKey(number);
3763 if ((entry->Hash() == hash) &&
3764 name->Equals(entry) &&
3765 !is_null_descriptor(number)) {
3766 return number;
3767 }
3768 }
3769 return kNotFound;
3770}
3771
3772
3773#ifdef DEBUG
3774bool DescriptorArray::IsEqualTo(DescriptorArray* other) {
3775 if (IsEmpty()) return other->IsEmpty();
3776 if (other->IsEmpty()) return false;
3777 if (length() != other->length()) return false;
3778 for (int i = 0; i < length(); ++i) {
3779 if (get(i) != other->get(i) && i != kContentArrayIndex) return false;
3780 }
3781 return GetContentArray()->IsEqualTo(other->GetContentArray());
3782}
3783#endif
3784
3785
3786static StaticResource<StringInputBuffer> string_input_buffer;
3787
3788
3789bool String::LooksValid() {
3790 if (!Heap::Contains(this)) return false;
3791 return true;
3792}
3793
3794
3795int String::Utf8Length() {
3796 if (IsAsciiRepresentation()) return length();
3797 // Attempt to flatten before accessing the string. It probably
3798 // doesn't make Utf8Length faster, but it is very likely that
3799 // the string will be accessed later (for example by WriteUtf8)
3800 // so it's still a good idea.
Steve Block6ded16b2010-05-10 14:33:55 +01003801 TryFlatten();
Steve Blocka7e24c12009-10-30 11:49:00 +00003802 Access<StringInputBuffer> buffer(&string_input_buffer);
3803 buffer->Reset(0, this);
3804 int result = 0;
3805 while (buffer->has_more())
3806 result += unibrow::Utf8::Length(buffer->GetNext());
3807 return result;
3808}
3809
3810
3811Vector<const char> String::ToAsciiVector() {
3812 ASSERT(IsAsciiRepresentation());
3813 ASSERT(IsFlat());
3814
3815 int offset = 0;
3816 int length = this->length();
3817 StringRepresentationTag string_tag = StringShape(this).representation_tag();
3818 String* string = this;
Steve Blockd0582a62009-12-15 09:54:21 +00003819 if (string_tag == kConsStringTag) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003820 ConsString* cons = ConsString::cast(string);
3821 ASSERT(cons->second()->length() == 0);
3822 string = cons->first();
3823 string_tag = StringShape(string).representation_tag();
3824 }
3825 if (string_tag == kSeqStringTag) {
3826 SeqAsciiString* seq = SeqAsciiString::cast(string);
3827 char* start = seq->GetChars();
3828 return Vector<const char>(start + offset, length);
3829 }
3830 ASSERT(string_tag == kExternalStringTag);
3831 ExternalAsciiString* ext = ExternalAsciiString::cast(string);
3832 const char* start = ext->resource()->data();
3833 return Vector<const char>(start + offset, length);
3834}
3835
3836
3837Vector<const uc16> String::ToUC16Vector() {
3838 ASSERT(IsTwoByteRepresentation());
3839 ASSERT(IsFlat());
3840
3841 int offset = 0;
3842 int length = this->length();
3843 StringRepresentationTag string_tag = StringShape(this).representation_tag();
3844 String* string = this;
Steve Blockd0582a62009-12-15 09:54:21 +00003845 if (string_tag == kConsStringTag) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003846 ConsString* cons = ConsString::cast(string);
3847 ASSERT(cons->second()->length() == 0);
3848 string = cons->first();
3849 string_tag = StringShape(string).representation_tag();
3850 }
3851 if (string_tag == kSeqStringTag) {
3852 SeqTwoByteString* seq = SeqTwoByteString::cast(string);
3853 return Vector<const uc16>(seq->GetChars() + offset, length);
3854 }
3855 ASSERT(string_tag == kExternalStringTag);
3856 ExternalTwoByteString* ext = ExternalTwoByteString::cast(string);
3857 const uc16* start =
3858 reinterpret_cast<const uc16*>(ext->resource()->data());
3859 return Vector<const uc16>(start + offset, length);
3860}
3861
3862
3863SmartPointer<char> String::ToCString(AllowNullsFlag allow_nulls,
3864 RobustnessFlag robust_flag,
3865 int offset,
3866 int length,
3867 int* length_return) {
3868 ASSERT(NativeAllocationChecker::allocation_allowed());
3869 if (robust_flag == ROBUST_STRING_TRAVERSAL && !LooksValid()) {
3870 return SmartPointer<char>(NULL);
3871 }
3872
3873 // Negative length means the to the end of the string.
3874 if (length < 0) length = kMaxInt - offset;
3875
3876 // Compute the size of the UTF-8 string. Start at the specified offset.
3877 Access<StringInputBuffer> buffer(&string_input_buffer);
3878 buffer->Reset(offset, this);
3879 int character_position = offset;
3880 int utf8_bytes = 0;
3881 while (buffer->has_more()) {
3882 uint16_t character = buffer->GetNext();
3883 if (character_position < offset + length) {
3884 utf8_bytes += unibrow::Utf8::Length(character);
3885 }
3886 character_position++;
3887 }
3888
3889 if (length_return) {
3890 *length_return = utf8_bytes;
3891 }
3892
3893 char* result = NewArray<char>(utf8_bytes + 1);
3894
3895 // Convert the UTF-16 string to a UTF-8 buffer. Start at the specified offset.
3896 buffer->Rewind();
3897 buffer->Seek(offset);
3898 character_position = offset;
3899 int utf8_byte_position = 0;
3900 while (buffer->has_more()) {
3901 uint16_t character = buffer->GetNext();
3902 if (character_position < offset + length) {
3903 if (allow_nulls == DISALLOW_NULLS && character == 0) {
3904 character = ' ';
3905 }
3906 utf8_byte_position +=
3907 unibrow::Utf8::Encode(result + utf8_byte_position, character);
3908 }
3909 character_position++;
3910 }
3911 result[utf8_byte_position] = 0;
3912 return SmartPointer<char>(result);
3913}
3914
3915
3916SmartPointer<char> String::ToCString(AllowNullsFlag allow_nulls,
3917 RobustnessFlag robust_flag,
3918 int* length_return) {
3919 return ToCString(allow_nulls, robust_flag, 0, -1, length_return);
3920}
3921
3922
3923const uc16* String::GetTwoByteData() {
3924 return GetTwoByteData(0);
3925}
3926
3927
3928const uc16* String::GetTwoByteData(unsigned start) {
3929 ASSERT(!IsAsciiRepresentation());
3930 switch (StringShape(this).representation_tag()) {
3931 case kSeqStringTag:
3932 return SeqTwoByteString::cast(this)->SeqTwoByteStringGetData(start);
3933 case kExternalStringTag:
3934 return ExternalTwoByteString::cast(this)->
3935 ExternalTwoByteStringGetData(start);
Steve Blocka7e24c12009-10-30 11:49:00 +00003936 case kConsStringTag:
3937 UNREACHABLE();
3938 return NULL;
3939 }
3940 UNREACHABLE();
3941 return NULL;
3942}
3943
3944
3945SmartPointer<uc16> String::ToWideCString(RobustnessFlag robust_flag) {
3946 ASSERT(NativeAllocationChecker::allocation_allowed());
3947
3948 if (robust_flag == ROBUST_STRING_TRAVERSAL && !LooksValid()) {
3949 return SmartPointer<uc16>();
3950 }
3951
3952 Access<StringInputBuffer> buffer(&string_input_buffer);
3953 buffer->Reset(this);
3954
3955 uc16* result = NewArray<uc16>(length() + 1);
3956
3957 int i = 0;
3958 while (buffer->has_more()) {
3959 uint16_t character = buffer->GetNext();
3960 result[i++] = character;
3961 }
3962 result[i] = 0;
3963 return SmartPointer<uc16>(result);
3964}
3965
3966
3967const uc16* SeqTwoByteString::SeqTwoByteStringGetData(unsigned start) {
3968 return reinterpret_cast<uc16*>(
3969 reinterpret_cast<char*>(this) - kHeapObjectTag + kHeaderSize) + start;
3970}
3971
3972
3973void SeqTwoByteString::SeqTwoByteStringReadBlockIntoBuffer(ReadBlockBuffer* rbb,
3974 unsigned* offset_ptr,
3975 unsigned max_chars) {
3976 unsigned chars_read = 0;
3977 unsigned offset = *offset_ptr;
3978 while (chars_read < max_chars) {
3979 uint16_t c = *reinterpret_cast<uint16_t*>(
3980 reinterpret_cast<char*>(this) -
3981 kHeapObjectTag + kHeaderSize + offset * kShortSize);
3982 if (c <= kMaxAsciiCharCode) {
3983 // Fast case for ASCII characters. Cursor is an input output argument.
3984 if (!unibrow::CharacterStream::EncodeAsciiCharacter(c,
3985 rbb->util_buffer,
3986 rbb->capacity,
3987 rbb->cursor)) {
3988 break;
3989 }
3990 } else {
3991 if (!unibrow::CharacterStream::EncodeNonAsciiCharacter(c,
3992 rbb->util_buffer,
3993 rbb->capacity,
3994 rbb->cursor)) {
3995 break;
3996 }
3997 }
3998 offset++;
3999 chars_read++;
4000 }
4001 *offset_ptr = offset;
4002 rbb->remaining += chars_read;
4003}
4004
4005
4006const unibrow::byte* SeqAsciiString::SeqAsciiStringReadBlock(
4007 unsigned* remaining,
4008 unsigned* offset_ptr,
4009 unsigned max_chars) {
4010 const unibrow::byte* b = reinterpret_cast<unibrow::byte*>(this) -
4011 kHeapObjectTag + kHeaderSize + *offset_ptr * kCharSize;
4012 *remaining = max_chars;
4013 *offset_ptr += max_chars;
4014 return b;
4015}
4016
4017
4018// This will iterate unless the block of string data spans two 'halves' of
4019// a ConsString, in which case it will recurse. Since the block of string
4020// data to be read has a maximum size this limits the maximum recursion
4021// depth to something sane. Since C++ does not have tail call recursion
4022// elimination, the iteration must be explicit. Since this is not an
4023// -IntoBuffer method it can delegate to one of the efficient
4024// *AsciiStringReadBlock routines.
4025const unibrow::byte* ConsString::ConsStringReadBlock(ReadBlockBuffer* rbb,
4026 unsigned* offset_ptr,
4027 unsigned max_chars) {
4028 ConsString* current = this;
4029 unsigned offset = *offset_ptr;
4030 int offset_correction = 0;
4031
4032 while (true) {
4033 String* left = current->first();
4034 unsigned left_length = (unsigned)left->length();
4035 if (left_length > offset &&
4036 (max_chars <= left_length - offset ||
4037 (rbb->capacity <= left_length - offset &&
4038 (max_chars = left_length - offset, true)))) { // comma operator!
4039 // Left hand side only - iterate unless we have reached the bottom of
4040 // the cons tree. The assignment on the left of the comma operator is
4041 // in order to make use of the fact that the -IntoBuffer routines can
4042 // produce at most 'capacity' characters. This enables us to postpone
4043 // the point where we switch to the -IntoBuffer routines (below) in order
4044 // to maximize the chances of delegating a big chunk of work to the
4045 // efficient *AsciiStringReadBlock routines.
4046 if (StringShape(left).IsCons()) {
4047 current = ConsString::cast(left);
4048 continue;
4049 } else {
4050 const unibrow::byte* answer =
4051 String::ReadBlock(left, rbb, &offset, max_chars);
4052 *offset_ptr = offset + offset_correction;
4053 return answer;
4054 }
4055 } else if (left_length <= offset) {
4056 // Right hand side only - iterate unless we have reached the bottom of
4057 // the cons tree.
4058 String* right = current->second();
4059 offset -= left_length;
4060 offset_correction += left_length;
4061 if (StringShape(right).IsCons()) {
4062 current = ConsString::cast(right);
4063 continue;
4064 } else {
4065 const unibrow::byte* answer =
4066 String::ReadBlock(right, rbb, &offset, max_chars);
4067 *offset_ptr = offset + offset_correction;
4068 return answer;
4069 }
4070 } else {
4071 // The block to be read spans two sides of the ConsString, so we call the
4072 // -IntoBuffer version, which will recurse. The -IntoBuffer methods
4073 // are able to assemble data from several part strings because they use
4074 // the util_buffer to store their data and never return direct pointers
4075 // to their storage. We don't try to read more than the buffer capacity
4076 // here or we can get too much recursion.
4077 ASSERT(rbb->remaining == 0);
4078 ASSERT(rbb->cursor == 0);
4079 current->ConsStringReadBlockIntoBuffer(
4080 rbb,
4081 &offset,
4082 max_chars > rbb->capacity ? rbb->capacity : max_chars);
4083 *offset_ptr = offset + offset_correction;
4084 return rbb->util_buffer;
4085 }
4086 }
4087}
4088
4089
Steve Blocka7e24c12009-10-30 11:49:00 +00004090uint16_t ExternalAsciiString::ExternalAsciiStringGet(int index) {
4091 ASSERT(index >= 0 && index < length());
4092 return resource()->data()[index];
4093}
4094
4095
4096const unibrow::byte* ExternalAsciiString::ExternalAsciiStringReadBlock(
4097 unsigned* remaining,
4098 unsigned* offset_ptr,
4099 unsigned max_chars) {
4100 // Cast const char* to unibrow::byte* (signedness difference).
4101 const unibrow::byte* b =
4102 reinterpret_cast<const unibrow::byte*>(resource()->data()) + *offset_ptr;
4103 *remaining = max_chars;
4104 *offset_ptr += max_chars;
4105 return b;
4106}
4107
4108
4109const uc16* ExternalTwoByteString::ExternalTwoByteStringGetData(
4110 unsigned start) {
4111 return resource()->data() + start;
4112}
4113
4114
4115uint16_t ExternalTwoByteString::ExternalTwoByteStringGet(int index) {
4116 ASSERT(index >= 0 && index < length());
4117 return resource()->data()[index];
4118}
4119
4120
4121void ExternalTwoByteString::ExternalTwoByteStringReadBlockIntoBuffer(
4122 ReadBlockBuffer* rbb,
4123 unsigned* offset_ptr,
4124 unsigned max_chars) {
4125 unsigned chars_read = 0;
4126 unsigned offset = *offset_ptr;
4127 const uint16_t* data = resource()->data();
4128 while (chars_read < max_chars) {
4129 uint16_t c = data[offset];
4130 if (c <= kMaxAsciiCharCode) {
4131 // Fast case for ASCII characters. Cursor is an input output argument.
4132 if (!unibrow::CharacterStream::EncodeAsciiCharacter(c,
4133 rbb->util_buffer,
4134 rbb->capacity,
4135 rbb->cursor))
4136 break;
4137 } else {
4138 if (!unibrow::CharacterStream::EncodeNonAsciiCharacter(c,
4139 rbb->util_buffer,
4140 rbb->capacity,
4141 rbb->cursor))
4142 break;
4143 }
4144 offset++;
4145 chars_read++;
4146 }
4147 *offset_ptr = offset;
4148 rbb->remaining += chars_read;
4149}
4150
4151
4152void SeqAsciiString::SeqAsciiStringReadBlockIntoBuffer(ReadBlockBuffer* rbb,
4153 unsigned* offset_ptr,
4154 unsigned max_chars) {
4155 unsigned capacity = rbb->capacity - rbb->cursor;
4156 if (max_chars > capacity) max_chars = capacity;
4157 memcpy(rbb->util_buffer + rbb->cursor,
4158 reinterpret_cast<char*>(this) - kHeapObjectTag + kHeaderSize +
4159 *offset_ptr * kCharSize,
4160 max_chars);
4161 rbb->remaining += max_chars;
4162 *offset_ptr += max_chars;
4163 rbb->cursor += max_chars;
4164}
4165
4166
4167void ExternalAsciiString::ExternalAsciiStringReadBlockIntoBuffer(
4168 ReadBlockBuffer* rbb,
4169 unsigned* offset_ptr,
4170 unsigned max_chars) {
4171 unsigned capacity = rbb->capacity - rbb->cursor;
4172 if (max_chars > capacity) max_chars = capacity;
4173 memcpy(rbb->util_buffer + rbb->cursor,
4174 resource()->data() + *offset_ptr,
4175 max_chars);
4176 rbb->remaining += max_chars;
4177 *offset_ptr += max_chars;
4178 rbb->cursor += max_chars;
4179}
4180
4181
4182// This method determines the type of string involved and then copies
4183// a whole chunk of characters into a buffer, or returns a pointer to a buffer
4184// where they can be found. The pointer is not necessarily valid across a GC
4185// (see AsciiStringReadBlock).
4186const unibrow::byte* String::ReadBlock(String* input,
4187 ReadBlockBuffer* rbb,
4188 unsigned* offset_ptr,
4189 unsigned max_chars) {
4190 ASSERT(*offset_ptr <= static_cast<unsigned>(input->length()));
4191 if (max_chars == 0) {
4192 rbb->remaining = 0;
4193 return NULL;
4194 }
4195 switch (StringShape(input).representation_tag()) {
4196 case kSeqStringTag:
4197 if (input->IsAsciiRepresentation()) {
4198 SeqAsciiString* str = SeqAsciiString::cast(input);
4199 return str->SeqAsciiStringReadBlock(&rbb->remaining,
4200 offset_ptr,
4201 max_chars);
4202 } else {
4203 SeqTwoByteString* str = SeqTwoByteString::cast(input);
4204 str->SeqTwoByteStringReadBlockIntoBuffer(rbb,
4205 offset_ptr,
4206 max_chars);
4207 return rbb->util_buffer;
4208 }
4209 case kConsStringTag:
4210 return ConsString::cast(input)->ConsStringReadBlock(rbb,
4211 offset_ptr,
4212 max_chars);
Steve Blocka7e24c12009-10-30 11:49:00 +00004213 case kExternalStringTag:
4214 if (input->IsAsciiRepresentation()) {
4215 return ExternalAsciiString::cast(input)->ExternalAsciiStringReadBlock(
4216 &rbb->remaining,
4217 offset_ptr,
4218 max_chars);
4219 } else {
4220 ExternalTwoByteString::cast(input)->
4221 ExternalTwoByteStringReadBlockIntoBuffer(rbb,
4222 offset_ptr,
4223 max_chars);
4224 return rbb->util_buffer;
4225 }
4226 default:
4227 break;
4228 }
4229
4230 UNREACHABLE();
4231 return 0;
4232}
4233
4234
4235Relocatable* Relocatable::top_ = NULL;
4236
4237
4238void Relocatable::PostGarbageCollectionProcessing() {
4239 Relocatable* current = top_;
4240 while (current != NULL) {
4241 current->PostGarbageCollection();
4242 current = current->prev_;
4243 }
4244}
4245
4246
4247// Reserve space for statics needing saving and restoring.
4248int Relocatable::ArchiveSpacePerThread() {
4249 return sizeof(top_);
4250}
4251
4252
4253// Archive statics that are thread local.
4254char* Relocatable::ArchiveState(char* to) {
4255 *reinterpret_cast<Relocatable**>(to) = top_;
4256 top_ = NULL;
4257 return to + ArchiveSpacePerThread();
4258}
4259
4260
4261// Restore statics that are thread local.
4262char* Relocatable::RestoreState(char* from) {
4263 top_ = *reinterpret_cast<Relocatable**>(from);
4264 return from + ArchiveSpacePerThread();
4265}
4266
4267
4268char* Relocatable::Iterate(ObjectVisitor* v, char* thread_storage) {
4269 Relocatable* top = *reinterpret_cast<Relocatable**>(thread_storage);
4270 Iterate(v, top);
4271 return thread_storage + ArchiveSpacePerThread();
4272}
4273
4274
4275void Relocatable::Iterate(ObjectVisitor* v) {
4276 Iterate(v, top_);
4277}
4278
4279
4280void Relocatable::Iterate(ObjectVisitor* v, Relocatable* top) {
4281 Relocatable* current = top;
4282 while (current != NULL) {
4283 current->IterateInstance(v);
4284 current = current->prev_;
4285 }
4286}
4287
4288
4289FlatStringReader::FlatStringReader(Handle<String> str)
4290 : str_(str.location()),
4291 length_(str->length()) {
4292 PostGarbageCollection();
4293}
4294
4295
4296FlatStringReader::FlatStringReader(Vector<const char> input)
4297 : str_(0),
4298 is_ascii_(true),
4299 length_(input.length()),
4300 start_(input.start()) { }
4301
4302
4303void FlatStringReader::PostGarbageCollection() {
4304 if (str_ == NULL) return;
4305 Handle<String> str(str_);
4306 ASSERT(str->IsFlat());
4307 is_ascii_ = str->IsAsciiRepresentation();
4308 if (is_ascii_) {
4309 start_ = str->ToAsciiVector().start();
4310 } else {
4311 start_ = str->ToUC16Vector().start();
4312 }
4313}
4314
4315
4316void StringInputBuffer::Seek(unsigned pos) {
4317 Reset(pos, input_);
4318}
4319
4320
4321void SafeStringInputBuffer::Seek(unsigned pos) {
4322 Reset(pos, input_);
4323}
4324
4325
4326// This method determines the type of string involved and then copies
4327// a whole chunk of characters into a buffer. It can be used with strings
4328// that have been glued together to form a ConsString and which must cooperate
4329// to fill up a buffer.
4330void String::ReadBlockIntoBuffer(String* input,
4331 ReadBlockBuffer* rbb,
4332 unsigned* offset_ptr,
4333 unsigned max_chars) {
4334 ASSERT(*offset_ptr <= (unsigned)input->length());
4335 if (max_chars == 0) return;
4336
4337 switch (StringShape(input).representation_tag()) {
4338 case kSeqStringTag:
4339 if (input->IsAsciiRepresentation()) {
4340 SeqAsciiString::cast(input)->SeqAsciiStringReadBlockIntoBuffer(rbb,
4341 offset_ptr,
4342 max_chars);
4343 return;
4344 } else {
4345 SeqTwoByteString::cast(input)->SeqTwoByteStringReadBlockIntoBuffer(rbb,
4346 offset_ptr,
4347 max_chars);
4348 return;
4349 }
4350 case kConsStringTag:
4351 ConsString::cast(input)->ConsStringReadBlockIntoBuffer(rbb,
4352 offset_ptr,
4353 max_chars);
4354 return;
Steve Blocka7e24c12009-10-30 11:49:00 +00004355 case kExternalStringTag:
4356 if (input->IsAsciiRepresentation()) {
Steve Blockd0582a62009-12-15 09:54:21 +00004357 ExternalAsciiString::cast(input)->
4358 ExternalAsciiStringReadBlockIntoBuffer(rbb, offset_ptr, max_chars);
4359 } else {
4360 ExternalTwoByteString::cast(input)->
4361 ExternalTwoByteStringReadBlockIntoBuffer(rbb,
4362 offset_ptr,
4363 max_chars);
Steve Blocka7e24c12009-10-30 11:49:00 +00004364 }
4365 return;
4366 default:
4367 break;
4368 }
4369
4370 UNREACHABLE();
4371 return;
4372}
4373
4374
4375const unibrow::byte* String::ReadBlock(String* input,
4376 unibrow::byte* util_buffer,
4377 unsigned capacity,
4378 unsigned* remaining,
4379 unsigned* offset_ptr) {
4380 ASSERT(*offset_ptr <= (unsigned)input->length());
4381 unsigned chars = input->length() - *offset_ptr;
4382 ReadBlockBuffer rbb(util_buffer, 0, capacity, 0);
4383 const unibrow::byte* answer = ReadBlock(input, &rbb, offset_ptr, chars);
4384 ASSERT(rbb.remaining <= static_cast<unsigned>(input->length()));
4385 *remaining = rbb.remaining;
4386 return answer;
4387}
4388
4389
4390const unibrow::byte* String::ReadBlock(String** raw_input,
4391 unibrow::byte* util_buffer,
4392 unsigned capacity,
4393 unsigned* remaining,
4394 unsigned* offset_ptr) {
4395 Handle<String> input(raw_input);
4396 ASSERT(*offset_ptr <= (unsigned)input->length());
4397 unsigned chars = input->length() - *offset_ptr;
4398 if (chars > capacity) chars = capacity;
4399 ReadBlockBuffer rbb(util_buffer, 0, capacity, 0);
4400 ReadBlockIntoBuffer(*input, &rbb, offset_ptr, chars);
4401 ASSERT(rbb.remaining <= static_cast<unsigned>(input->length()));
4402 *remaining = rbb.remaining;
4403 return rbb.util_buffer;
4404}
4405
4406
4407// This will iterate unless the block of string data spans two 'halves' of
4408// a ConsString, in which case it will recurse. Since the block of string
4409// data to be read has a maximum size this limits the maximum recursion
4410// depth to something sane. Since C++ does not have tail call recursion
4411// elimination, the iteration must be explicit.
4412void ConsString::ConsStringReadBlockIntoBuffer(ReadBlockBuffer* rbb,
4413 unsigned* offset_ptr,
4414 unsigned max_chars) {
4415 ConsString* current = this;
4416 unsigned offset = *offset_ptr;
4417 int offset_correction = 0;
4418
4419 while (true) {
4420 String* left = current->first();
4421 unsigned left_length = (unsigned)left->length();
4422 if (left_length > offset &&
4423 max_chars <= left_length - offset) {
4424 // Left hand side only - iterate unless we have reached the bottom of
4425 // the cons tree.
4426 if (StringShape(left).IsCons()) {
4427 current = ConsString::cast(left);
4428 continue;
4429 } else {
4430 String::ReadBlockIntoBuffer(left, rbb, &offset, max_chars);
4431 *offset_ptr = offset + offset_correction;
4432 return;
4433 }
4434 } else if (left_length <= offset) {
4435 // Right hand side only - iterate unless we have reached the bottom of
4436 // the cons tree.
4437 offset -= left_length;
4438 offset_correction += left_length;
4439 String* right = current->second();
4440 if (StringShape(right).IsCons()) {
4441 current = ConsString::cast(right);
4442 continue;
4443 } else {
4444 String::ReadBlockIntoBuffer(right, rbb, &offset, max_chars);
4445 *offset_ptr = offset + offset_correction;
4446 return;
4447 }
4448 } else {
4449 // The block to be read spans two sides of the ConsString, so we recurse.
4450 // First recurse on the left.
4451 max_chars -= left_length - offset;
4452 String::ReadBlockIntoBuffer(left, rbb, &offset, left_length - offset);
4453 // We may have reached the max or there may not have been enough space
4454 // in the buffer for the characters in the left hand side.
4455 if (offset == left_length) {
4456 // Recurse on the right.
4457 String* right = String::cast(current->second());
4458 offset -= left_length;
4459 offset_correction += left_length;
4460 String::ReadBlockIntoBuffer(right, rbb, &offset, max_chars);
4461 }
4462 *offset_ptr = offset + offset_correction;
4463 return;
4464 }
4465 }
4466}
4467
4468
Steve Blocka7e24c12009-10-30 11:49:00 +00004469void ConsString::ConsStringIterateBody(ObjectVisitor* v) {
4470 IteratePointers(v, kFirstOffset, kSecondOffset + kPointerSize);
4471}
4472
4473
4474void JSGlobalPropertyCell::JSGlobalPropertyCellIterateBody(ObjectVisitor* v) {
4475 IteratePointers(v, kValueOffset, kValueOffset + kPointerSize);
4476}
4477
4478
4479uint16_t ConsString::ConsStringGet(int index) {
4480 ASSERT(index >= 0 && index < this->length());
4481
4482 // Check for a flattened cons string
4483 if (second()->length() == 0) {
4484 String* left = first();
4485 return left->Get(index);
4486 }
4487
4488 String* string = String::cast(this);
4489
4490 while (true) {
4491 if (StringShape(string).IsCons()) {
4492 ConsString* cons_string = ConsString::cast(string);
4493 String* left = cons_string->first();
4494 if (left->length() > index) {
4495 string = left;
4496 } else {
4497 index -= left->length();
4498 string = cons_string->second();
4499 }
4500 } else {
4501 return string->Get(index);
4502 }
4503 }
4504
4505 UNREACHABLE();
4506 return 0;
4507}
4508
4509
4510template <typename sinkchar>
4511void String::WriteToFlat(String* src,
4512 sinkchar* sink,
4513 int f,
4514 int t) {
4515 String* source = src;
4516 int from = f;
4517 int to = t;
4518 while (true) {
4519 ASSERT(0 <= from && from <= to && to <= source->length());
4520 switch (StringShape(source).full_representation_tag()) {
4521 case kAsciiStringTag | kExternalStringTag: {
4522 CopyChars(sink,
4523 ExternalAsciiString::cast(source)->resource()->data() + from,
4524 to - from);
4525 return;
4526 }
4527 case kTwoByteStringTag | kExternalStringTag: {
4528 const uc16* data =
4529 ExternalTwoByteString::cast(source)->resource()->data();
4530 CopyChars(sink,
4531 data + from,
4532 to - from);
4533 return;
4534 }
4535 case kAsciiStringTag | kSeqStringTag: {
4536 CopyChars(sink,
4537 SeqAsciiString::cast(source)->GetChars() + from,
4538 to - from);
4539 return;
4540 }
4541 case kTwoByteStringTag | kSeqStringTag: {
4542 CopyChars(sink,
4543 SeqTwoByteString::cast(source)->GetChars() + from,
4544 to - from);
4545 return;
4546 }
Steve Blocka7e24c12009-10-30 11:49:00 +00004547 case kAsciiStringTag | kConsStringTag:
4548 case kTwoByteStringTag | kConsStringTag: {
4549 ConsString* cons_string = ConsString::cast(source);
4550 String* first = cons_string->first();
4551 int boundary = first->length();
4552 if (to - boundary >= boundary - from) {
4553 // Right hand side is longer. Recurse over left.
4554 if (from < boundary) {
4555 WriteToFlat(first, sink, from, boundary);
4556 sink += boundary - from;
4557 from = 0;
4558 } else {
4559 from -= boundary;
4560 }
4561 to -= boundary;
4562 source = cons_string->second();
4563 } else {
4564 // Left hand side is longer. Recurse over right.
4565 if (to > boundary) {
4566 String* second = cons_string->second();
4567 WriteToFlat(second,
4568 sink + boundary - from,
4569 0,
4570 to - boundary);
4571 to = boundary;
4572 }
4573 source = first;
4574 }
4575 break;
4576 }
4577 }
4578 }
4579}
4580
4581
Steve Blockd0582a62009-12-15 09:54:21 +00004582#define FIELD_ADDR(p, offset) \
4583 (reinterpret_cast<byte*>(p) + offset - kHeapObjectTag)
4584
4585void ExternalAsciiString::ExternalAsciiStringIterateBody(ObjectVisitor* v) {
4586 typedef v8::String::ExternalAsciiStringResource Resource;
4587 v->VisitExternalAsciiString(
4588 reinterpret_cast<Resource**>(FIELD_ADDR(this, kResourceOffset)));
Steve Blocka7e24c12009-10-30 11:49:00 +00004589}
4590
4591
Steve Blockd0582a62009-12-15 09:54:21 +00004592void ExternalTwoByteString::ExternalTwoByteStringIterateBody(ObjectVisitor* v) {
4593 typedef v8::String::ExternalStringResource Resource;
4594 v->VisitExternalTwoByteString(
4595 reinterpret_cast<Resource**>(FIELD_ADDR(this, kResourceOffset)));
Steve Blocka7e24c12009-10-30 11:49:00 +00004596}
4597
Steve Blockd0582a62009-12-15 09:54:21 +00004598#undef FIELD_ADDR
Steve Blocka7e24c12009-10-30 11:49:00 +00004599
4600template <typename IteratorA, typename IteratorB>
4601static inline bool CompareStringContents(IteratorA* ia, IteratorB* ib) {
4602 // General slow case check. We know that the ia and ib iterators
4603 // have the same length.
4604 while (ia->has_more()) {
4605 uc32 ca = ia->GetNext();
4606 uc32 cb = ib->GetNext();
4607 if (ca != cb)
4608 return false;
4609 }
4610 return true;
4611}
4612
4613
4614// Compares the contents of two strings by reading and comparing
4615// int-sized blocks of characters.
4616template <typename Char>
4617static inline bool CompareRawStringContents(Vector<Char> a, Vector<Char> b) {
4618 int length = a.length();
4619 ASSERT_EQ(length, b.length());
4620 const Char* pa = a.start();
4621 const Char* pb = b.start();
4622 int i = 0;
4623#ifndef V8_HOST_CAN_READ_UNALIGNED
4624 // If this architecture isn't comfortable reading unaligned ints
4625 // then we have to check that the strings are aligned before
4626 // comparing them blockwise.
4627 const int kAlignmentMask = sizeof(uint32_t) - 1; // NOLINT
4628 uint32_t pa_addr = reinterpret_cast<uint32_t>(pa);
4629 uint32_t pb_addr = reinterpret_cast<uint32_t>(pb);
4630 if (((pa_addr & kAlignmentMask) | (pb_addr & kAlignmentMask)) == 0) {
4631#endif
4632 const int kStepSize = sizeof(int) / sizeof(Char); // NOLINT
4633 int endpoint = length - kStepSize;
4634 // Compare blocks until we reach near the end of the string.
4635 for (; i <= endpoint; i += kStepSize) {
4636 uint32_t wa = *reinterpret_cast<const uint32_t*>(pa + i);
4637 uint32_t wb = *reinterpret_cast<const uint32_t*>(pb + i);
4638 if (wa != wb) {
4639 return false;
4640 }
4641 }
4642#ifndef V8_HOST_CAN_READ_UNALIGNED
4643 }
4644#endif
4645 // Compare the remaining characters that didn't fit into a block.
4646 for (; i < length; i++) {
4647 if (a[i] != b[i]) {
4648 return false;
4649 }
4650 }
4651 return true;
4652}
4653
4654
4655static StringInputBuffer string_compare_buffer_b;
4656
4657
4658template <typename IteratorA>
4659static inline bool CompareStringContentsPartial(IteratorA* ia, String* b) {
4660 if (b->IsFlat()) {
4661 if (b->IsAsciiRepresentation()) {
4662 VectorIterator<char> ib(b->ToAsciiVector());
4663 return CompareStringContents(ia, &ib);
4664 } else {
4665 VectorIterator<uc16> ib(b->ToUC16Vector());
4666 return CompareStringContents(ia, &ib);
4667 }
4668 } else {
4669 string_compare_buffer_b.Reset(0, b);
4670 return CompareStringContents(ia, &string_compare_buffer_b);
4671 }
4672}
4673
4674
4675static StringInputBuffer string_compare_buffer_a;
4676
4677
4678bool String::SlowEquals(String* other) {
4679 // Fast check: negative check with lengths.
4680 int len = length();
4681 if (len != other->length()) return false;
4682 if (len == 0) return true;
4683
4684 // Fast check: if hash code is computed for both strings
4685 // a fast negative check can be performed.
4686 if (HasHashCode() && other->HasHashCode()) {
4687 if (Hash() != other->Hash()) return false;
4688 }
4689
Leon Clarkef7060e22010-06-03 12:02:55 +01004690 // We know the strings are both non-empty. Compare the first chars
4691 // before we try to flatten the strings.
4692 if (this->Get(0) != other->Get(0)) return false;
4693
4694 String* lhs = this->TryFlattenGetString();
4695 String* rhs = other->TryFlattenGetString();
4696
4697 if (StringShape(lhs).IsSequentialAscii() &&
4698 StringShape(rhs).IsSequentialAscii()) {
4699 const char* str1 = SeqAsciiString::cast(lhs)->GetChars();
4700 const char* str2 = SeqAsciiString::cast(rhs)->GetChars();
Steve Blocka7e24c12009-10-30 11:49:00 +00004701 return CompareRawStringContents(Vector<const char>(str1, len),
4702 Vector<const char>(str2, len));
4703 }
4704
Leon Clarkef7060e22010-06-03 12:02:55 +01004705 if (lhs->IsFlat()) {
Steve Blocka7e24c12009-10-30 11:49:00 +00004706 if (IsAsciiRepresentation()) {
Leon Clarkef7060e22010-06-03 12:02:55 +01004707 Vector<const char> vec1 = lhs->ToAsciiVector();
4708 if (rhs->IsFlat()) {
4709 if (rhs->IsAsciiRepresentation()) {
4710 Vector<const char> vec2 = rhs->ToAsciiVector();
Steve Blocka7e24c12009-10-30 11:49:00 +00004711 return CompareRawStringContents(vec1, vec2);
4712 } else {
4713 VectorIterator<char> buf1(vec1);
Leon Clarkef7060e22010-06-03 12:02:55 +01004714 VectorIterator<uc16> ib(rhs->ToUC16Vector());
Steve Blocka7e24c12009-10-30 11:49:00 +00004715 return CompareStringContents(&buf1, &ib);
4716 }
4717 } else {
4718 VectorIterator<char> buf1(vec1);
Leon Clarkef7060e22010-06-03 12:02:55 +01004719 string_compare_buffer_b.Reset(0, rhs);
Steve Blocka7e24c12009-10-30 11:49:00 +00004720 return CompareStringContents(&buf1, &string_compare_buffer_b);
4721 }
4722 } else {
Leon Clarkef7060e22010-06-03 12:02:55 +01004723 Vector<const uc16> vec1 = lhs->ToUC16Vector();
4724 if (rhs->IsFlat()) {
4725 if (rhs->IsAsciiRepresentation()) {
Steve Blocka7e24c12009-10-30 11:49:00 +00004726 VectorIterator<uc16> buf1(vec1);
Leon Clarkef7060e22010-06-03 12:02:55 +01004727 VectorIterator<char> ib(rhs->ToAsciiVector());
Steve Blocka7e24c12009-10-30 11:49:00 +00004728 return CompareStringContents(&buf1, &ib);
4729 } else {
Leon Clarkef7060e22010-06-03 12:02:55 +01004730 Vector<const uc16> vec2(rhs->ToUC16Vector());
Steve Blocka7e24c12009-10-30 11:49:00 +00004731 return CompareRawStringContents(vec1, vec2);
4732 }
4733 } else {
4734 VectorIterator<uc16> buf1(vec1);
Leon Clarkef7060e22010-06-03 12:02:55 +01004735 string_compare_buffer_b.Reset(0, rhs);
Steve Blocka7e24c12009-10-30 11:49:00 +00004736 return CompareStringContents(&buf1, &string_compare_buffer_b);
4737 }
4738 }
4739 } else {
Leon Clarkef7060e22010-06-03 12:02:55 +01004740 string_compare_buffer_a.Reset(0, lhs);
4741 return CompareStringContentsPartial(&string_compare_buffer_a, rhs);
Steve Blocka7e24c12009-10-30 11:49:00 +00004742 }
4743}
4744
4745
4746bool String::MarkAsUndetectable() {
4747 if (StringShape(this).IsSymbol()) return false;
4748
4749 Map* map = this->map();
Steve Blockd0582a62009-12-15 09:54:21 +00004750 if (map == Heap::string_map()) {
4751 this->set_map(Heap::undetectable_string_map());
Steve Blocka7e24c12009-10-30 11:49:00 +00004752 return true;
Steve Blockd0582a62009-12-15 09:54:21 +00004753 } else if (map == Heap::ascii_string_map()) {
4754 this->set_map(Heap::undetectable_ascii_string_map());
Steve Blocka7e24c12009-10-30 11:49:00 +00004755 return true;
4756 }
4757 // Rest cannot be marked as undetectable
4758 return false;
4759}
4760
4761
4762bool String::IsEqualTo(Vector<const char> str) {
4763 int slen = length();
4764 Access<Scanner::Utf8Decoder> decoder(Scanner::utf8_decoder());
4765 decoder->Reset(str.start(), str.length());
4766 int i;
4767 for (i = 0; i < slen && decoder->has_more(); i++) {
4768 uc32 r = decoder->GetNext();
4769 if (Get(i) != r) return false;
4770 }
4771 return i == slen && !decoder->has_more();
4772}
4773
4774
Steve Block6ded16b2010-05-10 14:33:55 +01004775template <typename schar>
4776static inline uint32_t HashSequentialString(const schar* chars, int length) {
4777 StringHasher hasher(length);
4778 if (!hasher.has_trivial_hash()) {
4779 int i;
4780 for (i = 0; hasher.is_array_index() && (i < length); i++) {
4781 hasher.AddCharacter(chars[i]);
4782 }
4783 for (; i < length; i++) {
4784 hasher.AddCharacterNoIndex(chars[i]);
4785 }
4786 }
4787 return hasher.GetHashField();
4788}
4789
4790
Steve Blocka7e24c12009-10-30 11:49:00 +00004791uint32_t String::ComputeAndSetHash() {
4792 // Should only be called if hash code has not yet been computed.
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01004793 ASSERT(!HasHashCode());
Steve Blocka7e24c12009-10-30 11:49:00 +00004794
Steve Block6ded16b2010-05-10 14:33:55 +01004795 const int len = length();
4796
Steve Blocka7e24c12009-10-30 11:49:00 +00004797 // Compute the hash code.
Steve Block6ded16b2010-05-10 14:33:55 +01004798 uint32_t field = 0;
4799 if (StringShape(this).IsSequentialAscii()) {
4800 field = HashSequentialString(SeqAsciiString::cast(this)->GetChars(), len);
4801 } else if (StringShape(this).IsSequentialTwoByte()) {
4802 field = HashSequentialString(SeqTwoByteString::cast(this)->GetChars(), len);
4803 } else {
4804 StringInputBuffer buffer(this);
4805 field = ComputeHashField(&buffer, len);
4806 }
Steve Blocka7e24c12009-10-30 11:49:00 +00004807
4808 // Store the hash code in the object.
Steve Blockd0582a62009-12-15 09:54:21 +00004809 set_hash_field(field);
Steve Blocka7e24c12009-10-30 11:49:00 +00004810
4811 // Check the hash code is there.
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01004812 ASSERT(HasHashCode());
Steve Blocka7e24c12009-10-30 11:49:00 +00004813 uint32_t result = field >> kHashShift;
4814 ASSERT(result != 0); // Ensure that the hash value of 0 is never computed.
4815 return result;
4816}
4817
4818
4819bool String::ComputeArrayIndex(unibrow::CharacterStream* buffer,
4820 uint32_t* index,
4821 int length) {
4822 if (length == 0 || length > kMaxArrayIndexSize) return false;
4823 uc32 ch = buffer->GetNext();
4824
4825 // If the string begins with a '0' character, it must only consist
4826 // of it to be a legal array index.
4827 if (ch == '0') {
4828 *index = 0;
4829 return length == 1;
4830 }
4831
4832 // Convert string to uint32 array index; character by character.
4833 int d = ch - '0';
4834 if (d < 0 || d > 9) return false;
4835 uint32_t result = d;
4836 while (buffer->has_more()) {
4837 d = buffer->GetNext() - '0';
4838 if (d < 0 || d > 9) return false;
4839 // Check that the new result is below the 32 bit limit.
4840 if (result > 429496729U - ((d > 5) ? 1 : 0)) return false;
4841 result = (result * 10) + d;
4842 }
4843
4844 *index = result;
4845 return true;
4846}
4847
4848
4849bool String::SlowAsArrayIndex(uint32_t* index) {
4850 if (length() <= kMaxCachedArrayIndexLength) {
4851 Hash(); // force computation of hash code
Steve Blockd0582a62009-12-15 09:54:21 +00004852 uint32_t field = hash_field();
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01004853 if ((field & kIsNotArrayIndexMask) != 0) return false;
Steve Blockd0582a62009-12-15 09:54:21 +00004854 // Isolate the array index form the full hash field.
4855 *index = (kArrayIndexHashMask & field) >> kHashShift;
Steve Blocka7e24c12009-10-30 11:49:00 +00004856 return true;
4857 } else {
4858 StringInputBuffer buffer(this);
4859 return ComputeArrayIndex(&buffer, index, length());
4860 }
4861}
4862
4863
Steve Blockd0582a62009-12-15 09:54:21 +00004864static inline uint32_t HashField(uint32_t hash,
4865 bool is_array_index,
4866 int length = -1) {
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01004867 uint32_t result = (hash << String::kHashShift);
Steve Blockd0582a62009-12-15 09:54:21 +00004868 if (is_array_index) {
4869 // For array indexes mix the length into the hash as an array index could
4870 // be zero.
4871 ASSERT(length > 0);
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01004872 ASSERT(length <= String::kMaxArrayIndexSize);
Steve Blockd0582a62009-12-15 09:54:21 +00004873 ASSERT(TenToThe(String::kMaxCachedArrayIndexLength) <
4874 (1 << String::kArrayIndexValueBits));
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01004875 ASSERT(String::kMaxArrayIndexSize < (1 << String::kArrayIndexValueBits));
4876 result &= ~String::kIsNotArrayIndexMask;
Steve Blockd0582a62009-12-15 09:54:21 +00004877 result |= length << String::kArrayIndexHashLengthShift;
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01004878 } else {
4879 result |= String::kIsNotArrayIndexMask;
Steve Blockd0582a62009-12-15 09:54:21 +00004880 }
Steve Blocka7e24c12009-10-30 11:49:00 +00004881 return result;
4882}
4883
4884
4885uint32_t StringHasher::GetHashField() {
4886 ASSERT(is_valid());
Steve Blockd0582a62009-12-15 09:54:21 +00004887 if (length_ <= String::kMaxHashCalcLength) {
Steve Blocka7e24c12009-10-30 11:49:00 +00004888 if (is_array_index()) {
Steve Blockd0582a62009-12-15 09:54:21 +00004889 return v8::internal::HashField(array_index(), true, length_);
Steve Blocka7e24c12009-10-30 11:49:00 +00004890 } else {
Steve Blockd0582a62009-12-15 09:54:21 +00004891 return v8::internal::HashField(GetHash(), false);
Steve Blocka7e24c12009-10-30 11:49:00 +00004892 }
Steve Blocka7e24c12009-10-30 11:49:00 +00004893 uint32_t payload = v8::internal::HashField(GetHash(), false);
Steve Blockd0582a62009-12-15 09:54:21 +00004894 return payload;
Steve Blocka7e24c12009-10-30 11:49:00 +00004895 } else {
4896 return v8::internal::HashField(length_, false);
4897 }
4898}
4899
4900
Steve Blockd0582a62009-12-15 09:54:21 +00004901uint32_t String::ComputeHashField(unibrow::CharacterStream* buffer,
4902 int length) {
Steve Blocka7e24c12009-10-30 11:49:00 +00004903 StringHasher hasher(length);
4904
4905 // Very long strings have a trivial hash that doesn't inspect the
4906 // string contents.
4907 if (hasher.has_trivial_hash()) {
4908 return hasher.GetHashField();
4909 }
4910
4911 // Do the iterative array index computation as long as there is a
4912 // chance this is an array index.
4913 while (buffer->has_more() && hasher.is_array_index()) {
4914 hasher.AddCharacter(buffer->GetNext());
4915 }
4916
4917 // Process the remaining characters without updating the array
4918 // index.
4919 while (buffer->has_more()) {
4920 hasher.AddCharacterNoIndex(buffer->GetNext());
4921 }
4922
4923 return hasher.GetHashField();
4924}
4925
4926
Steve Block6ded16b2010-05-10 14:33:55 +01004927Object* String::SubString(int start, int end, PretenureFlag pretenure) {
Steve Blocka7e24c12009-10-30 11:49:00 +00004928 if (start == 0 && end == length()) return this;
Steve Block6ded16b2010-05-10 14:33:55 +01004929 Object* result = Heap::AllocateSubString(this, start, end, pretenure);
Steve Blockd0582a62009-12-15 09:54:21 +00004930 return result;
Steve Blocka7e24c12009-10-30 11:49:00 +00004931}
4932
4933
4934void String::PrintOn(FILE* file) {
4935 int length = this->length();
4936 for (int i = 0; i < length; i++) {
4937 fprintf(file, "%c", Get(i));
4938 }
4939}
4940
4941
4942void Map::CreateBackPointers() {
4943 DescriptorArray* descriptors = instance_descriptors();
4944 for (int i = 0; i < descriptors->number_of_descriptors(); i++) {
4945 if (descriptors->GetType(i) == MAP_TRANSITION) {
4946 // Get target.
4947 Map* target = Map::cast(descriptors->GetValue(i));
4948#ifdef DEBUG
4949 // Verify target.
4950 Object* source_prototype = prototype();
4951 Object* target_prototype = target->prototype();
4952 ASSERT(source_prototype->IsJSObject() ||
4953 source_prototype->IsMap() ||
4954 source_prototype->IsNull());
4955 ASSERT(target_prototype->IsJSObject() ||
4956 target_prototype->IsNull());
4957 ASSERT(source_prototype->IsMap() ||
4958 source_prototype == target_prototype);
4959#endif
4960 // Point target back to source. set_prototype() will not let us set
4961 // the prototype to a map, as we do here.
4962 *RawField(target, kPrototypeOffset) = this;
4963 }
4964 }
4965}
4966
4967
4968void Map::ClearNonLiveTransitions(Object* real_prototype) {
4969 // Live DescriptorArray objects will be marked, so we must use
4970 // low-level accessors to get and modify their data.
4971 DescriptorArray* d = reinterpret_cast<DescriptorArray*>(
4972 *RawField(this, Map::kInstanceDescriptorsOffset));
4973 if (d == Heap::raw_unchecked_empty_descriptor_array()) return;
4974 Smi* NullDescriptorDetails =
4975 PropertyDetails(NONE, NULL_DESCRIPTOR).AsSmi();
4976 FixedArray* contents = reinterpret_cast<FixedArray*>(
4977 d->get(DescriptorArray::kContentArrayIndex));
4978 ASSERT(contents->length() >= 2);
4979 for (int i = 0; i < contents->length(); i += 2) {
4980 // If the pair (value, details) is a map transition,
4981 // check if the target is live. If not, null the descriptor.
4982 // Also drop the back pointer for that map transition, so that this
4983 // map is not reached again by following a back pointer from a
4984 // non-live object.
4985 PropertyDetails details(Smi::cast(contents->get(i + 1)));
4986 if (details.type() == MAP_TRANSITION) {
4987 Map* target = reinterpret_cast<Map*>(contents->get(i));
4988 ASSERT(target->IsHeapObject());
4989 if (!target->IsMarked()) {
4990 ASSERT(target->IsMap());
Leon Clarke4515c472010-02-03 11:58:03 +00004991 contents->set(i + 1, NullDescriptorDetails);
4992 contents->set_null(i);
Steve Blocka7e24c12009-10-30 11:49:00 +00004993 ASSERT(target->prototype() == this ||
4994 target->prototype() == real_prototype);
4995 // Getter prototype() is read-only, set_prototype() has side effects.
4996 *RawField(target, Map::kPrototypeOffset) = real_prototype;
4997 }
4998 }
4999 }
5000}
5001
5002
5003void Map::MapIterateBody(ObjectVisitor* v) {
5004 // Assumes all Object* members are contiguously allocated!
5005 IteratePointers(v, kPrototypeOffset, kCodeCacheOffset + kPointerSize);
5006}
5007
5008
5009Object* JSFunction::SetInstancePrototype(Object* value) {
5010 ASSERT(value->IsJSObject());
5011
5012 if (has_initial_map()) {
5013 initial_map()->set_prototype(value);
5014 } else {
5015 // Put the value in the initial map field until an initial map is
5016 // needed. At that point, a new initial map is created and the
5017 // prototype is put into the initial map where it belongs.
5018 set_prototype_or_initial_map(value);
5019 }
Kristian Monsen25f61362010-05-21 11:50:48 +01005020 Heap::ClearInstanceofCache();
Steve Blocka7e24c12009-10-30 11:49:00 +00005021 return value;
5022}
5023
5024
5025
5026Object* JSFunction::SetPrototype(Object* value) {
Steve Block6ded16b2010-05-10 14:33:55 +01005027 ASSERT(should_have_prototype());
Steve Blocka7e24c12009-10-30 11:49:00 +00005028 Object* construct_prototype = value;
5029
5030 // If the value is not a JSObject, store the value in the map's
5031 // constructor field so it can be accessed. Also, set the prototype
5032 // used for constructing objects to the original object prototype.
5033 // See ECMA-262 13.2.2.
5034 if (!value->IsJSObject()) {
5035 // Copy the map so this does not affect unrelated functions.
5036 // Remove map transitions because they point to maps with a
5037 // different prototype.
5038 Object* new_map = map()->CopyDropTransitions();
5039 if (new_map->IsFailure()) return new_map;
5040 set_map(Map::cast(new_map));
5041 map()->set_constructor(value);
5042 map()->set_non_instance_prototype(true);
5043 construct_prototype =
5044 Top::context()->global_context()->initial_object_prototype();
5045 } else {
5046 map()->set_non_instance_prototype(false);
5047 }
5048
5049 return SetInstancePrototype(construct_prototype);
5050}
5051
5052
Steve Block6ded16b2010-05-10 14:33:55 +01005053Object* JSFunction::RemovePrototype() {
5054 ASSERT(map() == context()->global_context()->function_map());
5055 set_map(context()->global_context()->function_without_prototype_map());
5056 set_prototype_or_initial_map(Heap::the_hole_value());
5057 return this;
5058}
5059
5060
Steve Blocka7e24c12009-10-30 11:49:00 +00005061Object* JSFunction::SetInstanceClassName(String* name) {
5062 shared()->set_instance_class_name(name);
5063 return this;
5064}
5065
5066
5067Context* JSFunction::GlobalContextFromLiterals(FixedArray* literals) {
5068 return Context::cast(literals->get(JSFunction::kLiteralGlobalContextIndex));
5069}
5070
5071
5072void Oddball::OddballIterateBody(ObjectVisitor* v) {
5073 // Assumes all Object* members are contiguously allocated!
5074 IteratePointers(v, kToStringOffset, kToNumberOffset + kPointerSize);
5075}
5076
5077
5078Object* Oddball::Initialize(const char* to_string, Object* to_number) {
5079 Object* symbol = Heap::LookupAsciiSymbol(to_string);
5080 if (symbol->IsFailure()) return symbol;
5081 set_to_string(String::cast(symbol));
5082 set_to_number(to_number);
5083 return this;
5084}
5085
5086
5087bool SharedFunctionInfo::HasSourceCode() {
5088 return !script()->IsUndefined() &&
5089 !Script::cast(script())->source()->IsUndefined();
5090}
5091
5092
5093Object* SharedFunctionInfo::GetSourceCode() {
5094 HandleScope scope;
5095 if (script()->IsUndefined()) return Heap::undefined_value();
5096 Object* source = Script::cast(script())->source();
5097 if (source->IsUndefined()) return Heap::undefined_value();
5098 return *SubString(Handle<String>(String::cast(source)),
5099 start_position(), end_position());
5100}
5101
5102
5103int SharedFunctionInfo::CalculateInstanceSize() {
5104 int instance_size =
5105 JSObject::kHeaderSize +
5106 expected_nof_properties() * kPointerSize;
5107 if (instance_size > JSObject::kMaxInstanceSize) {
5108 instance_size = JSObject::kMaxInstanceSize;
5109 }
5110 return instance_size;
5111}
5112
5113
5114int SharedFunctionInfo::CalculateInObjectProperties() {
5115 return (CalculateInstanceSize() - JSObject::kHeaderSize) / kPointerSize;
5116}
5117
5118
Andrei Popescu402d9372010-02-26 13:31:12 +00005119bool SharedFunctionInfo::CanGenerateInlineConstructor(Object* prototype) {
5120 // Check the basic conditions for generating inline constructor code.
5121 if (!FLAG_inline_new
5122 || !has_only_simple_this_property_assignments()
5123 || this_property_assignments_count() == 0) {
5124 return false;
5125 }
5126
5127 // If the prototype is null inline constructors cause no problems.
5128 if (!prototype->IsJSObject()) {
5129 ASSERT(prototype->IsNull());
5130 return true;
5131 }
5132
5133 // Traverse the proposed prototype chain looking for setters for properties of
5134 // the same names as are set by the inline constructor.
5135 for (Object* obj = prototype;
5136 obj != Heap::null_value();
5137 obj = obj->GetPrototype()) {
5138 JSObject* js_object = JSObject::cast(obj);
5139 for (int i = 0; i < this_property_assignments_count(); i++) {
5140 LookupResult result;
5141 String* name = GetThisPropertyAssignmentName(i);
5142 js_object->LocalLookupRealNamedProperty(name, &result);
5143 if (result.IsProperty() && result.type() == CALLBACKS) {
5144 return false;
5145 }
5146 }
5147 }
5148
5149 return true;
5150}
5151
5152
Steve Blocka7e24c12009-10-30 11:49:00 +00005153void SharedFunctionInfo::SetThisPropertyAssignmentsInfo(
Steve Blocka7e24c12009-10-30 11:49:00 +00005154 bool only_simple_this_property_assignments,
5155 FixedArray* assignments) {
5156 set_compiler_hints(BooleanBit::set(compiler_hints(),
Steve Blocka7e24c12009-10-30 11:49:00 +00005157 kHasOnlySimpleThisPropertyAssignments,
5158 only_simple_this_property_assignments));
5159 set_this_property_assignments(assignments);
5160 set_this_property_assignments_count(assignments->length() / 3);
5161}
5162
5163
5164void SharedFunctionInfo::ClearThisPropertyAssignmentsInfo() {
5165 set_compiler_hints(BooleanBit::set(compiler_hints(),
Steve Blocka7e24c12009-10-30 11:49:00 +00005166 kHasOnlySimpleThisPropertyAssignments,
5167 false));
5168 set_this_property_assignments(Heap::undefined_value());
5169 set_this_property_assignments_count(0);
5170}
5171
5172
5173String* SharedFunctionInfo::GetThisPropertyAssignmentName(int index) {
5174 Object* obj = this_property_assignments();
5175 ASSERT(obj->IsFixedArray());
5176 ASSERT(index < this_property_assignments_count());
5177 obj = FixedArray::cast(obj)->get(index * 3);
5178 ASSERT(obj->IsString());
5179 return String::cast(obj);
5180}
5181
5182
5183bool SharedFunctionInfo::IsThisPropertyAssignmentArgument(int index) {
5184 Object* obj = this_property_assignments();
5185 ASSERT(obj->IsFixedArray());
5186 ASSERT(index < this_property_assignments_count());
5187 obj = FixedArray::cast(obj)->get(index * 3 + 1);
5188 return Smi::cast(obj)->value() != -1;
5189}
5190
5191
5192int SharedFunctionInfo::GetThisPropertyAssignmentArgument(int index) {
5193 ASSERT(IsThisPropertyAssignmentArgument(index));
5194 Object* obj =
5195 FixedArray::cast(this_property_assignments())->get(index * 3 + 1);
5196 return Smi::cast(obj)->value();
5197}
5198
5199
5200Object* SharedFunctionInfo::GetThisPropertyAssignmentConstant(int index) {
5201 ASSERT(!IsThisPropertyAssignmentArgument(index));
5202 Object* obj =
5203 FixedArray::cast(this_property_assignments())->get(index * 3 + 2);
5204 return obj;
5205}
5206
5207
Steve Blocka7e24c12009-10-30 11:49:00 +00005208// Support function for printing the source code to a StringStream
5209// without any allocation in the heap.
5210void SharedFunctionInfo::SourceCodePrint(StringStream* accumulator,
5211 int max_length) {
5212 // For some native functions there is no source.
5213 if (script()->IsUndefined() ||
5214 Script::cast(script())->source()->IsUndefined()) {
5215 accumulator->Add("<No Source>");
5216 return;
5217 }
5218
Steve Blockd0582a62009-12-15 09:54:21 +00005219 // Get the source for the script which this function came from.
Steve Blocka7e24c12009-10-30 11:49:00 +00005220 // Don't use String::cast because we don't want more assertion errors while
5221 // we are already creating a stack dump.
5222 String* script_source =
5223 reinterpret_cast<String*>(Script::cast(script())->source());
5224
5225 if (!script_source->LooksValid()) {
5226 accumulator->Add("<Invalid Source>");
5227 return;
5228 }
5229
5230 if (!is_toplevel()) {
5231 accumulator->Add("function ");
5232 Object* name = this->name();
5233 if (name->IsString() && String::cast(name)->length() > 0) {
5234 accumulator->PrintName(name);
5235 }
5236 }
5237
5238 int len = end_position() - start_position();
5239 if (len > max_length) {
5240 accumulator->Put(script_source,
5241 start_position(),
5242 start_position() + max_length);
5243 accumulator->Add("...\n");
5244 } else {
5245 accumulator->Put(script_source, start_position(), end_position());
5246 }
5247}
5248
5249
5250void SharedFunctionInfo::SharedFunctionInfoIterateBody(ObjectVisitor* v) {
Steve Block6ded16b2010-05-10 14:33:55 +01005251 IteratePointers(v,
5252 kNameOffset,
5253 kThisPropertyAssignmentsOffset + kPointerSize);
Steve Blocka7e24c12009-10-30 11:49:00 +00005254}
5255
5256
5257void ObjectVisitor::VisitCodeTarget(RelocInfo* rinfo) {
5258 ASSERT(RelocInfo::IsCodeTarget(rinfo->rmode()));
5259 Object* target = Code::GetCodeFromTargetAddress(rinfo->target_address());
5260 Object* old_target = target;
5261 VisitPointer(&target);
5262 CHECK_EQ(target, old_target); // VisitPointer doesn't change Code* *target.
5263}
5264
5265
5266void ObjectVisitor::VisitDebugTarget(RelocInfo* rinfo) {
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01005267 ASSERT((RelocInfo::IsJSReturn(rinfo->rmode()) &&
5268 rinfo->IsPatchedReturnSequence()) ||
5269 (RelocInfo::IsDebugBreakSlot(rinfo->rmode()) &&
5270 rinfo->IsPatchedDebugBreakSlotSequence()));
Steve Blocka7e24c12009-10-30 11:49:00 +00005271 Object* target = Code::GetCodeFromTargetAddress(rinfo->call_address());
5272 Object* old_target = target;
5273 VisitPointer(&target);
5274 CHECK_EQ(target, old_target); // VisitPointer doesn't change Code* *target.
5275}
5276
5277
5278void Code::CodeIterateBody(ObjectVisitor* v) {
5279 int mode_mask = RelocInfo::kCodeTargetMask |
5280 RelocInfo::ModeMask(RelocInfo::EMBEDDED_OBJECT) |
5281 RelocInfo::ModeMask(RelocInfo::EXTERNAL_REFERENCE) |
5282 RelocInfo::ModeMask(RelocInfo::JS_RETURN) |
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01005283 RelocInfo::ModeMask(RelocInfo::DEBUG_BREAK_SLOT) |
Steve Blocka7e24c12009-10-30 11:49:00 +00005284 RelocInfo::ModeMask(RelocInfo::RUNTIME_ENTRY);
5285
5286 for (RelocIterator it(this, mode_mask); !it.done(); it.next()) {
Leon Clarkef7060e22010-06-03 12:02:55 +01005287 it.rinfo()->Visit(v);
Steve Blocka7e24c12009-10-30 11:49:00 +00005288 }
5289
5290 ScopeInfo<>::IterateScopeInfo(this, v);
5291}
5292
5293
Steve Blockd0582a62009-12-15 09:54:21 +00005294void Code::Relocate(intptr_t delta) {
Steve Blocka7e24c12009-10-30 11:49:00 +00005295 for (RelocIterator it(this, RelocInfo::kApplyMask); !it.done(); it.next()) {
5296 it.rinfo()->apply(delta);
5297 }
5298 CPU::FlushICache(instruction_start(), instruction_size());
5299}
5300
5301
5302void Code::CopyFrom(const CodeDesc& desc) {
5303 // copy code
5304 memmove(instruction_start(), desc.buffer, desc.instr_size);
5305
5306 // fill gap with zero bytes
5307 { byte* p = instruction_start() + desc.instr_size;
5308 byte* q = relocation_start();
5309 while (p < q) {
5310 *p++ = 0;
5311 }
5312 }
5313
5314 // copy reloc info
5315 memmove(relocation_start(),
5316 desc.buffer + desc.buffer_size - desc.reloc_size,
5317 desc.reloc_size);
5318
5319 // unbox handles and relocate
Steve Block3ce2e202009-11-05 08:53:23 +00005320 intptr_t delta = instruction_start() - desc.buffer;
Steve Blocka7e24c12009-10-30 11:49:00 +00005321 int mode_mask = RelocInfo::kCodeTargetMask |
5322 RelocInfo::ModeMask(RelocInfo::EMBEDDED_OBJECT) |
5323 RelocInfo::kApplyMask;
Steve Block3ce2e202009-11-05 08:53:23 +00005324 Assembler* origin = desc.origin; // Needed to find target_object on X64.
Steve Blocka7e24c12009-10-30 11:49:00 +00005325 for (RelocIterator it(this, mode_mask); !it.done(); it.next()) {
5326 RelocInfo::Mode mode = it.rinfo()->rmode();
5327 if (mode == RelocInfo::EMBEDDED_OBJECT) {
Steve Block3ce2e202009-11-05 08:53:23 +00005328 Handle<Object> p = it.rinfo()->target_object_handle(origin);
Steve Blocka7e24c12009-10-30 11:49:00 +00005329 it.rinfo()->set_target_object(*p);
5330 } else if (RelocInfo::IsCodeTarget(mode)) {
5331 // rewrite code handles in inline cache targets to direct
5332 // pointers to the first instruction in the code object
Steve Block3ce2e202009-11-05 08:53:23 +00005333 Handle<Object> p = it.rinfo()->target_object_handle(origin);
Steve Blocka7e24c12009-10-30 11:49:00 +00005334 Code* code = Code::cast(*p);
5335 it.rinfo()->set_target_address(code->instruction_start());
5336 } else {
5337 it.rinfo()->apply(delta);
5338 }
5339 }
5340 CPU::FlushICache(instruction_start(), instruction_size());
5341}
5342
5343
5344// Locate the source position which is closest to the address in the code. This
5345// is using the source position information embedded in the relocation info.
5346// The position returned is relative to the beginning of the script where the
5347// source for this function is found.
5348int Code::SourcePosition(Address pc) {
5349 int distance = kMaxInt;
5350 int position = RelocInfo::kNoPosition; // Initially no position found.
5351 // Run through all the relocation info to find the best matching source
5352 // position. All the code needs to be considered as the sequence of the
5353 // instructions in the code does not necessarily follow the same order as the
5354 // source.
5355 RelocIterator it(this, RelocInfo::kPositionMask);
5356 while (!it.done()) {
5357 // Only look at positions after the current pc.
5358 if (it.rinfo()->pc() < pc) {
5359 // Get position and distance.
Steve Blockd0582a62009-12-15 09:54:21 +00005360
5361 int dist = static_cast<int>(pc - it.rinfo()->pc());
5362 int pos = static_cast<int>(it.rinfo()->data());
Steve Blocka7e24c12009-10-30 11:49:00 +00005363 // If this position is closer than the current candidate or if it has the
5364 // same distance as the current candidate and the position is higher then
5365 // this position is the new candidate.
5366 if ((dist < distance) ||
5367 (dist == distance && pos > position)) {
5368 position = pos;
5369 distance = dist;
5370 }
5371 }
5372 it.next();
5373 }
5374 return position;
5375}
5376
5377
5378// Same as Code::SourcePosition above except it only looks for statement
5379// positions.
5380int Code::SourceStatementPosition(Address pc) {
5381 // First find the position as close as possible using all position
5382 // information.
5383 int position = SourcePosition(pc);
5384 // Now find the closest statement position before the position.
5385 int statement_position = 0;
5386 RelocIterator it(this, RelocInfo::kPositionMask);
5387 while (!it.done()) {
5388 if (RelocInfo::IsStatementPosition(it.rinfo()->rmode())) {
Steve Blockd0582a62009-12-15 09:54:21 +00005389 int p = static_cast<int>(it.rinfo()->data());
Steve Blocka7e24c12009-10-30 11:49:00 +00005390 if (statement_position < p && p <= position) {
5391 statement_position = p;
5392 }
5393 }
5394 it.next();
5395 }
5396 return statement_position;
5397}
5398
5399
5400#ifdef ENABLE_DISASSEMBLER
5401// Identify kind of code.
5402const char* Code::Kind2String(Kind kind) {
5403 switch (kind) {
5404 case FUNCTION: return "FUNCTION";
5405 case STUB: return "STUB";
5406 case BUILTIN: return "BUILTIN";
5407 case LOAD_IC: return "LOAD_IC";
5408 case KEYED_LOAD_IC: return "KEYED_LOAD_IC";
5409 case STORE_IC: return "STORE_IC";
5410 case KEYED_STORE_IC: return "KEYED_STORE_IC";
5411 case CALL_IC: return "CALL_IC";
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01005412 case KEYED_CALL_IC: return "KEYED_CALL_IC";
Steve Block6ded16b2010-05-10 14:33:55 +01005413 case BINARY_OP_IC: return "BINARY_OP_IC";
Steve Blocka7e24c12009-10-30 11:49:00 +00005414 }
5415 UNREACHABLE();
5416 return NULL;
5417}
5418
5419
5420const char* Code::ICState2String(InlineCacheState state) {
5421 switch (state) {
5422 case UNINITIALIZED: return "UNINITIALIZED";
5423 case PREMONOMORPHIC: return "PREMONOMORPHIC";
5424 case MONOMORPHIC: return "MONOMORPHIC";
5425 case MONOMORPHIC_PROTOTYPE_FAILURE: return "MONOMORPHIC_PROTOTYPE_FAILURE";
5426 case MEGAMORPHIC: return "MEGAMORPHIC";
5427 case DEBUG_BREAK: return "DEBUG_BREAK";
5428 case DEBUG_PREPARE_STEP_IN: return "DEBUG_PREPARE_STEP_IN";
5429 }
5430 UNREACHABLE();
5431 return NULL;
5432}
5433
5434
5435const char* Code::PropertyType2String(PropertyType type) {
5436 switch (type) {
5437 case NORMAL: return "NORMAL";
5438 case FIELD: return "FIELD";
5439 case CONSTANT_FUNCTION: return "CONSTANT_FUNCTION";
5440 case CALLBACKS: return "CALLBACKS";
5441 case INTERCEPTOR: return "INTERCEPTOR";
5442 case MAP_TRANSITION: return "MAP_TRANSITION";
5443 case CONSTANT_TRANSITION: return "CONSTANT_TRANSITION";
5444 case NULL_DESCRIPTOR: return "NULL_DESCRIPTOR";
5445 }
5446 UNREACHABLE();
5447 return NULL;
5448}
5449
5450void Code::Disassemble(const char* name) {
5451 PrintF("kind = %s\n", Kind2String(kind()));
5452 if (is_inline_cache_stub()) {
5453 PrintF("ic_state = %s\n", ICState2String(ic_state()));
5454 PrintF("ic_in_loop = %d\n", ic_in_loop() == IN_LOOP);
5455 if (ic_state() == MONOMORPHIC) {
5456 PrintF("type = %s\n", PropertyType2String(type()));
5457 }
5458 }
5459 if ((name != NULL) && (name[0] != '\0')) {
5460 PrintF("name = %s\n", name);
5461 }
5462
5463 PrintF("Instructions (size = %d)\n", instruction_size());
5464 Disassembler::Decode(NULL, this);
5465 PrintF("\n");
5466
5467 PrintF("RelocInfo (size = %d)\n", relocation_size());
5468 for (RelocIterator it(this); !it.done(); it.next())
5469 it.rinfo()->Print();
5470 PrintF("\n");
5471}
5472#endif // ENABLE_DISASSEMBLER
5473
5474
5475void JSObject::SetFastElements(FixedArray* elems) {
Steve Block3ce2e202009-11-05 08:53:23 +00005476 // We should never end in here with a pixel or external array.
5477 ASSERT(!HasPixelElements() && !HasExternalArrayElements());
Steve Blocka7e24c12009-10-30 11:49:00 +00005478#ifdef DEBUG
5479 // Check the provided array is filled with the_hole.
5480 uint32_t len = static_cast<uint32_t>(elems->length());
5481 for (uint32_t i = 0; i < len; i++) ASSERT(elems->get(i)->IsTheHole());
5482#endif
Leon Clarke4515c472010-02-03 11:58:03 +00005483 AssertNoAllocation no_gc;
5484 WriteBarrierMode mode = elems->GetWriteBarrierMode(no_gc);
Steve Blocka7e24c12009-10-30 11:49:00 +00005485 switch (GetElementsKind()) {
5486 case FAST_ELEMENTS: {
5487 FixedArray* old_elements = FixedArray::cast(elements());
5488 uint32_t old_length = static_cast<uint32_t>(old_elements->length());
5489 // Fill out the new array with this content and array holes.
5490 for (uint32_t i = 0; i < old_length; i++) {
5491 elems->set(i, old_elements->get(i), mode);
5492 }
5493 break;
5494 }
5495 case DICTIONARY_ELEMENTS: {
5496 NumberDictionary* dictionary = NumberDictionary::cast(elements());
5497 for (int i = 0; i < dictionary->Capacity(); i++) {
5498 Object* key = dictionary->KeyAt(i);
5499 if (key->IsNumber()) {
5500 uint32_t entry = static_cast<uint32_t>(key->Number());
5501 elems->set(entry, dictionary->ValueAt(i), mode);
5502 }
5503 }
5504 break;
5505 }
5506 default:
5507 UNREACHABLE();
5508 break;
5509 }
5510 set_elements(elems);
5511}
5512
5513
5514Object* JSObject::SetSlowElements(Object* len) {
Steve Block3ce2e202009-11-05 08:53:23 +00005515 // We should never end in here with a pixel or external array.
5516 ASSERT(!HasPixelElements() && !HasExternalArrayElements());
Steve Blocka7e24c12009-10-30 11:49:00 +00005517
5518 uint32_t new_length = static_cast<uint32_t>(len->Number());
5519
5520 switch (GetElementsKind()) {
5521 case FAST_ELEMENTS: {
5522 // Make sure we never try to shrink dense arrays into sparse arrays.
5523 ASSERT(static_cast<uint32_t>(FixedArray::cast(elements())->length()) <=
5524 new_length);
5525 Object* obj = NormalizeElements();
5526 if (obj->IsFailure()) return obj;
5527
5528 // Update length for JSArrays.
5529 if (IsJSArray()) JSArray::cast(this)->set_length(len);
5530 break;
5531 }
5532 case DICTIONARY_ELEMENTS: {
5533 if (IsJSArray()) {
5534 uint32_t old_length =
Steve Block6ded16b2010-05-10 14:33:55 +01005535 static_cast<uint32_t>(JSArray::cast(this)->length()->Number());
Steve Blocka7e24c12009-10-30 11:49:00 +00005536 element_dictionary()->RemoveNumberEntries(new_length, old_length),
5537 JSArray::cast(this)->set_length(len);
5538 }
5539 break;
5540 }
5541 default:
5542 UNREACHABLE();
5543 break;
5544 }
5545 return this;
5546}
5547
5548
5549Object* JSArray::Initialize(int capacity) {
5550 ASSERT(capacity >= 0);
Leon Clarke4515c472010-02-03 11:58:03 +00005551 set_length(Smi::FromInt(0));
Steve Blocka7e24c12009-10-30 11:49:00 +00005552 FixedArray* new_elements;
5553 if (capacity == 0) {
5554 new_elements = Heap::empty_fixed_array();
5555 } else {
5556 Object* obj = Heap::AllocateFixedArrayWithHoles(capacity);
5557 if (obj->IsFailure()) return obj;
5558 new_elements = FixedArray::cast(obj);
5559 }
5560 set_elements(new_elements);
5561 return this;
5562}
5563
5564
5565void JSArray::Expand(int required_size) {
5566 Handle<JSArray> self(this);
5567 Handle<FixedArray> old_backing(FixedArray::cast(elements()));
5568 int old_size = old_backing->length();
Steve Blockd0582a62009-12-15 09:54:21 +00005569 int new_size = required_size > old_size ? required_size : old_size;
Steve Blocka7e24c12009-10-30 11:49:00 +00005570 Handle<FixedArray> new_backing = Factory::NewFixedArray(new_size);
5571 // Can't use this any more now because we may have had a GC!
5572 for (int i = 0; i < old_size; i++) new_backing->set(i, old_backing->get(i));
5573 self->SetContent(*new_backing);
5574}
5575
5576
5577// Computes the new capacity when expanding the elements of a JSObject.
5578static int NewElementsCapacity(int old_capacity) {
5579 // (old_capacity + 50%) + 16
5580 return old_capacity + (old_capacity >> 1) + 16;
5581}
5582
5583
5584static Object* ArrayLengthRangeError() {
5585 HandleScope scope;
5586 return Top::Throw(*Factory::NewRangeError("invalid_array_length",
5587 HandleVector<Object>(NULL, 0)));
5588}
5589
5590
5591Object* JSObject::SetElementsLength(Object* len) {
Steve Block3ce2e202009-11-05 08:53:23 +00005592 // We should never end in here with a pixel or external array.
Steve Block6ded16b2010-05-10 14:33:55 +01005593 ASSERT(AllowsSetElementsLength());
Steve Blocka7e24c12009-10-30 11:49:00 +00005594
5595 Object* smi_length = len->ToSmi();
5596 if (smi_length->IsSmi()) {
5597 int value = Smi::cast(smi_length)->value();
5598 if (value < 0) return ArrayLengthRangeError();
5599 switch (GetElementsKind()) {
5600 case FAST_ELEMENTS: {
5601 int old_capacity = FixedArray::cast(elements())->length();
5602 if (value <= old_capacity) {
5603 if (IsJSArray()) {
5604 int old_length = FastD2I(JSArray::cast(this)->length()->Number());
5605 // NOTE: We may be able to optimize this by removing the
5606 // last part of the elements backing storage array and
5607 // setting the capacity to the new size.
5608 for (int i = value; i < old_length; i++) {
5609 FixedArray::cast(elements())->set_the_hole(i);
5610 }
Leon Clarke4515c472010-02-03 11:58:03 +00005611 JSArray::cast(this)->set_length(Smi::cast(smi_length));
Steve Blocka7e24c12009-10-30 11:49:00 +00005612 }
5613 return this;
5614 }
5615 int min = NewElementsCapacity(old_capacity);
5616 int new_capacity = value > min ? value : min;
5617 if (new_capacity <= kMaxFastElementsLength ||
5618 !ShouldConvertToSlowElements(new_capacity)) {
5619 Object* obj = Heap::AllocateFixedArrayWithHoles(new_capacity);
5620 if (obj->IsFailure()) return obj;
Leon Clarke4515c472010-02-03 11:58:03 +00005621 if (IsJSArray()) {
5622 JSArray::cast(this)->set_length(Smi::cast(smi_length));
5623 }
Steve Blocka7e24c12009-10-30 11:49:00 +00005624 SetFastElements(FixedArray::cast(obj));
5625 return this;
5626 }
5627 break;
5628 }
5629 case DICTIONARY_ELEMENTS: {
5630 if (IsJSArray()) {
5631 if (value == 0) {
5632 // If the length of a slow array is reset to zero, we clear
5633 // the array and flush backing storage. This has the added
5634 // benefit that the array returns to fast mode.
5635 initialize_elements();
5636 } else {
5637 // Remove deleted elements.
5638 uint32_t old_length =
5639 static_cast<uint32_t>(JSArray::cast(this)->length()->Number());
5640 element_dictionary()->RemoveNumberEntries(value, old_length);
5641 }
Leon Clarke4515c472010-02-03 11:58:03 +00005642 JSArray::cast(this)->set_length(Smi::cast(smi_length));
Steve Blocka7e24c12009-10-30 11:49:00 +00005643 }
5644 return this;
5645 }
5646 default:
5647 UNREACHABLE();
5648 break;
5649 }
5650 }
5651
5652 // General slow case.
5653 if (len->IsNumber()) {
5654 uint32_t length;
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01005655 if (len->ToArrayIndex(&length)) {
Steve Blocka7e24c12009-10-30 11:49:00 +00005656 return SetSlowElements(len);
5657 } else {
5658 return ArrayLengthRangeError();
5659 }
5660 }
5661
5662 // len is not a number so make the array size one and
5663 // set only element to len.
5664 Object* obj = Heap::AllocateFixedArray(1);
5665 if (obj->IsFailure()) return obj;
5666 FixedArray::cast(obj)->set(0, len);
Leon Clarke4515c472010-02-03 11:58:03 +00005667 if (IsJSArray()) JSArray::cast(this)->set_length(Smi::FromInt(1));
Steve Blocka7e24c12009-10-30 11:49:00 +00005668 set_elements(FixedArray::cast(obj));
5669 return this;
5670}
5671
5672
Andrei Popescu402d9372010-02-26 13:31:12 +00005673Object* JSObject::SetPrototype(Object* value,
5674 bool skip_hidden_prototypes) {
5675 // Silently ignore the change if value is not a JSObject or null.
5676 // SpiderMonkey behaves this way.
5677 if (!value->IsJSObject() && !value->IsNull()) return value;
5678
5679 // Before we can set the prototype we need to be sure
5680 // prototype cycles are prevented.
5681 // It is sufficient to validate that the receiver is not in the new prototype
5682 // chain.
5683 for (Object* pt = value; pt != Heap::null_value(); pt = pt->GetPrototype()) {
5684 if (JSObject::cast(pt) == this) {
5685 // Cycle detected.
5686 HandleScope scope;
5687 return Top::Throw(*Factory::NewError("cyclic_proto",
5688 HandleVector<Object>(NULL, 0)));
5689 }
5690 }
5691
5692 JSObject* real_receiver = this;
5693
5694 if (skip_hidden_prototypes) {
5695 // Find the first object in the chain whose prototype object is not
5696 // hidden and set the new prototype on that object.
5697 Object* current_proto = real_receiver->GetPrototype();
5698 while (current_proto->IsJSObject() &&
5699 JSObject::cast(current_proto)->map()->is_hidden_prototype()) {
5700 real_receiver = JSObject::cast(current_proto);
5701 current_proto = current_proto->GetPrototype();
5702 }
5703 }
5704
5705 // Set the new prototype of the object.
5706 Object* new_map = real_receiver->map()->CopyDropTransitions();
5707 if (new_map->IsFailure()) return new_map;
5708 Map::cast(new_map)->set_prototype(value);
5709 real_receiver->set_map(Map::cast(new_map));
5710
Kristian Monsen25f61362010-05-21 11:50:48 +01005711 Heap::ClearInstanceofCache();
5712
Andrei Popescu402d9372010-02-26 13:31:12 +00005713 return value;
5714}
5715
5716
Steve Blocka7e24c12009-10-30 11:49:00 +00005717bool JSObject::HasElementPostInterceptor(JSObject* receiver, uint32_t index) {
5718 switch (GetElementsKind()) {
5719 case FAST_ELEMENTS: {
5720 uint32_t length = IsJSArray() ?
5721 static_cast<uint32_t>
5722 (Smi::cast(JSArray::cast(this)->length())->value()) :
5723 static_cast<uint32_t>(FixedArray::cast(elements())->length());
5724 if ((index < length) &&
5725 !FixedArray::cast(elements())->get(index)->IsTheHole()) {
5726 return true;
5727 }
5728 break;
5729 }
5730 case PIXEL_ELEMENTS: {
5731 // TODO(iposva): Add testcase.
5732 PixelArray* pixels = PixelArray::cast(elements());
5733 if (index < static_cast<uint32_t>(pixels->length())) {
5734 return true;
5735 }
5736 break;
5737 }
Steve Block3ce2e202009-11-05 08:53:23 +00005738 case EXTERNAL_BYTE_ELEMENTS:
5739 case EXTERNAL_UNSIGNED_BYTE_ELEMENTS:
5740 case EXTERNAL_SHORT_ELEMENTS:
5741 case EXTERNAL_UNSIGNED_SHORT_ELEMENTS:
5742 case EXTERNAL_INT_ELEMENTS:
5743 case EXTERNAL_UNSIGNED_INT_ELEMENTS:
5744 case EXTERNAL_FLOAT_ELEMENTS: {
5745 // TODO(kbr): Add testcase.
5746 ExternalArray* array = ExternalArray::cast(elements());
5747 if (index < static_cast<uint32_t>(array->length())) {
5748 return true;
5749 }
5750 break;
5751 }
Steve Blocka7e24c12009-10-30 11:49:00 +00005752 case DICTIONARY_ELEMENTS: {
5753 if (element_dictionary()->FindEntry(index)
5754 != NumberDictionary::kNotFound) {
5755 return true;
5756 }
5757 break;
5758 }
5759 default:
5760 UNREACHABLE();
5761 break;
5762 }
5763
5764 // Handle [] on String objects.
5765 if (this->IsStringObjectWithCharacterAt(index)) return true;
5766
5767 Object* pt = GetPrototype();
5768 if (pt == Heap::null_value()) return false;
5769 return JSObject::cast(pt)->HasElementWithReceiver(receiver, index);
5770}
5771
5772
5773bool JSObject::HasElementWithInterceptor(JSObject* receiver, uint32_t index) {
5774 // Make sure that the top context does not change when doing
5775 // callbacks or interceptor calls.
5776 AssertNoContextChange ncc;
5777 HandleScope scope;
5778 Handle<InterceptorInfo> interceptor(GetIndexedInterceptor());
5779 Handle<JSObject> receiver_handle(receiver);
5780 Handle<JSObject> holder_handle(this);
5781 CustomArguments args(interceptor->data(), receiver, this);
5782 v8::AccessorInfo info(args.end());
5783 if (!interceptor->query()->IsUndefined()) {
5784 v8::IndexedPropertyQuery query =
5785 v8::ToCData<v8::IndexedPropertyQuery>(interceptor->query());
5786 LOG(ApiIndexedPropertyAccess("interceptor-indexed-has", this, index));
5787 v8::Handle<v8::Boolean> result;
5788 {
5789 // Leaving JavaScript.
5790 VMState state(EXTERNAL);
5791 result = query(index, info);
5792 }
5793 if (!result.IsEmpty()) return result->IsTrue();
5794 } else if (!interceptor->getter()->IsUndefined()) {
5795 v8::IndexedPropertyGetter getter =
5796 v8::ToCData<v8::IndexedPropertyGetter>(interceptor->getter());
5797 LOG(ApiIndexedPropertyAccess("interceptor-indexed-has-get", this, index));
5798 v8::Handle<v8::Value> result;
5799 {
5800 // Leaving JavaScript.
5801 VMState state(EXTERNAL);
5802 result = getter(index, info);
5803 }
5804 if (!result.IsEmpty()) return true;
5805 }
5806 return holder_handle->HasElementPostInterceptor(*receiver_handle, index);
5807}
5808
5809
5810bool JSObject::HasLocalElement(uint32_t index) {
5811 // Check access rights if needed.
5812 if (IsAccessCheckNeeded() &&
5813 !Top::MayIndexedAccess(this, index, v8::ACCESS_HAS)) {
5814 Top::ReportFailedAccessCheck(this, v8::ACCESS_HAS);
5815 return false;
5816 }
5817
5818 // Check for lookup interceptor
5819 if (HasIndexedInterceptor()) {
5820 return HasElementWithInterceptor(this, index);
5821 }
5822
5823 // Handle [] on String objects.
5824 if (this->IsStringObjectWithCharacterAt(index)) return true;
5825
5826 switch (GetElementsKind()) {
5827 case FAST_ELEMENTS: {
5828 uint32_t length = IsJSArray() ?
5829 static_cast<uint32_t>
5830 (Smi::cast(JSArray::cast(this)->length())->value()) :
5831 static_cast<uint32_t>(FixedArray::cast(elements())->length());
5832 return (index < length) &&
5833 !FixedArray::cast(elements())->get(index)->IsTheHole();
5834 }
5835 case PIXEL_ELEMENTS: {
5836 PixelArray* pixels = PixelArray::cast(elements());
5837 return (index < static_cast<uint32_t>(pixels->length()));
5838 }
Steve Block3ce2e202009-11-05 08:53:23 +00005839 case EXTERNAL_BYTE_ELEMENTS:
5840 case EXTERNAL_UNSIGNED_BYTE_ELEMENTS:
5841 case EXTERNAL_SHORT_ELEMENTS:
5842 case EXTERNAL_UNSIGNED_SHORT_ELEMENTS:
5843 case EXTERNAL_INT_ELEMENTS:
5844 case EXTERNAL_UNSIGNED_INT_ELEMENTS:
5845 case EXTERNAL_FLOAT_ELEMENTS: {
5846 ExternalArray* array = ExternalArray::cast(elements());
5847 return (index < static_cast<uint32_t>(array->length()));
5848 }
Steve Blocka7e24c12009-10-30 11:49:00 +00005849 case DICTIONARY_ELEMENTS: {
5850 return element_dictionary()->FindEntry(index)
5851 != NumberDictionary::kNotFound;
5852 }
5853 default:
5854 UNREACHABLE();
5855 break;
5856 }
5857 UNREACHABLE();
5858 return Heap::null_value();
5859}
5860
5861
5862bool JSObject::HasElementWithReceiver(JSObject* receiver, uint32_t index) {
5863 // Check access rights if needed.
5864 if (IsAccessCheckNeeded() &&
5865 !Top::MayIndexedAccess(this, index, v8::ACCESS_HAS)) {
5866 Top::ReportFailedAccessCheck(this, v8::ACCESS_HAS);
5867 return false;
5868 }
5869
5870 // Check for lookup interceptor
5871 if (HasIndexedInterceptor()) {
5872 return HasElementWithInterceptor(receiver, index);
5873 }
5874
5875 switch (GetElementsKind()) {
5876 case FAST_ELEMENTS: {
5877 uint32_t length = IsJSArray() ?
5878 static_cast<uint32_t>
5879 (Smi::cast(JSArray::cast(this)->length())->value()) :
5880 static_cast<uint32_t>(FixedArray::cast(elements())->length());
5881 if ((index < length) &&
5882 !FixedArray::cast(elements())->get(index)->IsTheHole()) return true;
5883 break;
5884 }
5885 case PIXEL_ELEMENTS: {
5886 PixelArray* pixels = PixelArray::cast(elements());
5887 if (index < static_cast<uint32_t>(pixels->length())) {
5888 return true;
5889 }
5890 break;
5891 }
Steve Block3ce2e202009-11-05 08:53:23 +00005892 case EXTERNAL_BYTE_ELEMENTS:
5893 case EXTERNAL_UNSIGNED_BYTE_ELEMENTS:
5894 case EXTERNAL_SHORT_ELEMENTS:
5895 case EXTERNAL_UNSIGNED_SHORT_ELEMENTS:
5896 case EXTERNAL_INT_ELEMENTS:
5897 case EXTERNAL_UNSIGNED_INT_ELEMENTS:
5898 case EXTERNAL_FLOAT_ELEMENTS: {
5899 ExternalArray* array = ExternalArray::cast(elements());
5900 if (index < static_cast<uint32_t>(array->length())) {
5901 return true;
5902 }
5903 break;
5904 }
Steve Blocka7e24c12009-10-30 11:49:00 +00005905 case DICTIONARY_ELEMENTS: {
5906 if (element_dictionary()->FindEntry(index)
5907 != NumberDictionary::kNotFound) {
5908 return true;
5909 }
5910 break;
5911 }
5912 default:
5913 UNREACHABLE();
5914 break;
5915 }
5916
5917 // Handle [] on String objects.
5918 if (this->IsStringObjectWithCharacterAt(index)) return true;
5919
5920 Object* pt = GetPrototype();
5921 if (pt == Heap::null_value()) return false;
5922 return JSObject::cast(pt)->HasElementWithReceiver(receiver, index);
5923}
5924
5925
5926Object* JSObject::SetElementWithInterceptor(uint32_t index, Object* value) {
5927 // Make sure that the top context does not change when doing
5928 // callbacks or interceptor calls.
5929 AssertNoContextChange ncc;
5930 HandleScope scope;
5931 Handle<InterceptorInfo> interceptor(GetIndexedInterceptor());
5932 Handle<JSObject> this_handle(this);
5933 Handle<Object> value_handle(value);
5934 if (!interceptor->setter()->IsUndefined()) {
5935 v8::IndexedPropertySetter setter =
5936 v8::ToCData<v8::IndexedPropertySetter>(interceptor->setter());
5937 LOG(ApiIndexedPropertyAccess("interceptor-indexed-set", this, index));
5938 CustomArguments args(interceptor->data(), this, this);
5939 v8::AccessorInfo info(args.end());
5940 v8::Handle<v8::Value> result;
5941 {
5942 // Leaving JavaScript.
5943 VMState state(EXTERNAL);
5944 result = setter(index, v8::Utils::ToLocal(value_handle), info);
5945 }
5946 RETURN_IF_SCHEDULED_EXCEPTION();
5947 if (!result.IsEmpty()) return *value_handle;
5948 }
5949 Object* raw_result =
5950 this_handle->SetElementWithoutInterceptor(index, *value_handle);
5951 RETURN_IF_SCHEDULED_EXCEPTION();
5952 return raw_result;
5953}
5954
5955
Leon Clarkef7060e22010-06-03 12:02:55 +01005956Object* JSObject::GetElementWithCallback(Object* receiver,
5957 Object* structure,
5958 uint32_t index,
5959 Object* holder) {
5960 ASSERT(!structure->IsProxy());
5961
5962 // api style callbacks.
5963 if (structure->IsAccessorInfo()) {
5964 AccessorInfo* data = AccessorInfo::cast(structure);
5965 Object* fun_obj = data->getter();
5966 v8::AccessorGetter call_fun = v8::ToCData<v8::AccessorGetter>(fun_obj);
5967 HandleScope scope;
5968 Handle<JSObject> self(JSObject::cast(receiver));
5969 Handle<JSObject> holder_handle(JSObject::cast(holder));
5970 Handle<Object> number = Factory::NewNumberFromUint(index);
5971 Handle<String> key(Factory::NumberToString(number));
5972 LOG(ApiNamedPropertyAccess("load", *self, *key));
5973 CustomArguments args(data->data(), *self, *holder_handle);
5974 v8::AccessorInfo info(args.end());
5975 v8::Handle<v8::Value> result;
5976 {
5977 // Leaving JavaScript.
5978 VMState state(EXTERNAL);
5979 result = call_fun(v8::Utils::ToLocal(key), info);
5980 }
5981 RETURN_IF_SCHEDULED_EXCEPTION();
5982 if (result.IsEmpty()) return Heap::undefined_value();
5983 return *v8::Utils::OpenHandle(*result);
5984 }
5985
5986 // __defineGetter__ callback
5987 if (structure->IsFixedArray()) {
5988 Object* getter = FixedArray::cast(structure)->get(kGetterIndex);
5989 if (getter->IsJSFunction()) {
5990 return Object::GetPropertyWithDefinedGetter(receiver,
5991 JSFunction::cast(getter));
5992 }
5993 // Getter is not a function.
5994 return Heap::undefined_value();
5995 }
5996
5997 UNREACHABLE();
5998 return NULL;
5999}
6000
6001
6002Object* JSObject::SetElementWithCallback(Object* structure,
6003 uint32_t index,
6004 Object* value,
6005 JSObject* holder) {
6006 HandleScope scope;
6007
6008 // We should never get here to initialize a const with the hole
6009 // value since a const declaration would conflict with the setter.
6010 ASSERT(!value->IsTheHole());
6011 Handle<Object> value_handle(value);
6012
6013 // To accommodate both the old and the new api we switch on the
6014 // data structure used to store the callbacks. Eventually proxy
6015 // callbacks should be phased out.
6016 ASSERT(!structure->IsProxy());
6017
6018 if (structure->IsAccessorInfo()) {
6019 // api style callbacks
6020 AccessorInfo* data = AccessorInfo::cast(structure);
6021 Object* call_obj = data->setter();
6022 v8::AccessorSetter call_fun = v8::ToCData<v8::AccessorSetter>(call_obj);
6023 if (call_fun == NULL) return value;
6024 Handle<Object> number = Factory::NewNumberFromUint(index);
6025 Handle<String> key(Factory::NumberToString(number));
6026 LOG(ApiNamedPropertyAccess("store", this, *key));
6027 CustomArguments args(data->data(), this, JSObject::cast(holder));
6028 v8::AccessorInfo info(args.end());
6029 {
6030 // Leaving JavaScript.
6031 VMState state(EXTERNAL);
6032 call_fun(v8::Utils::ToLocal(key),
6033 v8::Utils::ToLocal(value_handle),
6034 info);
6035 }
6036 RETURN_IF_SCHEDULED_EXCEPTION();
6037 return *value_handle;
6038 }
6039
6040 if (structure->IsFixedArray()) {
6041 Object* setter = FixedArray::cast(structure)->get(kSetterIndex);
6042 if (setter->IsJSFunction()) {
6043 return SetPropertyWithDefinedSetter(JSFunction::cast(setter), value);
6044 } else {
6045 Handle<Object> holder_handle(holder);
6046 Handle<Object> key(Factory::NewNumberFromUint(index));
6047 Handle<Object> args[2] = { key, holder_handle };
6048 return Top::Throw(*Factory::NewTypeError("no_setter_in_callback",
6049 HandleVector(args, 2)));
6050 }
6051 }
6052
6053 UNREACHABLE();
6054 return NULL;
6055}
6056
6057
Steve Blocka7e24c12009-10-30 11:49:00 +00006058// Adding n elements in fast case is O(n*n).
6059// Note: revisit design to have dual undefined values to capture absent
6060// elements.
6061Object* JSObject::SetFastElement(uint32_t index, Object* value) {
6062 ASSERT(HasFastElements());
6063
6064 FixedArray* elms = FixedArray::cast(elements());
6065 uint32_t elms_length = static_cast<uint32_t>(elms->length());
6066
6067 if (!IsJSArray() && (index >= elms_length || elms->get(index)->IsTheHole())) {
Leon Clarkef7060e22010-06-03 12:02:55 +01006068 if (SetElementWithCallbackSetterInPrototypes(index, value)) {
6069 return value;
Steve Blocka7e24c12009-10-30 11:49:00 +00006070 }
6071 }
6072
6073 // Check whether there is extra space in fixed array..
6074 if (index < elms_length) {
6075 elms->set(index, value);
6076 if (IsJSArray()) {
6077 // Update the length of the array if needed.
6078 uint32_t array_length = 0;
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01006079 CHECK(JSArray::cast(this)->length()->ToArrayIndex(&array_length));
Steve Blocka7e24c12009-10-30 11:49:00 +00006080 if (index >= array_length) {
Leon Clarke4515c472010-02-03 11:58:03 +00006081 JSArray::cast(this)->set_length(Smi::FromInt(index + 1));
Steve Blocka7e24c12009-10-30 11:49:00 +00006082 }
6083 }
6084 return value;
6085 }
6086
6087 // Allow gap in fast case.
6088 if ((index - elms_length) < kMaxGap) {
6089 // Try allocating extra space.
6090 int new_capacity = NewElementsCapacity(index+1);
6091 if (new_capacity <= kMaxFastElementsLength ||
6092 !ShouldConvertToSlowElements(new_capacity)) {
6093 ASSERT(static_cast<uint32_t>(new_capacity) > index);
6094 Object* obj = Heap::AllocateFixedArrayWithHoles(new_capacity);
6095 if (obj->IsFailure()) return obj;
6096 SetFastElements(FixedArray::cast(obj));
Leon Clarke4515c472010-02-03 11:58:03 +00006097 if (IsJSArray()) {
6098 JSArray::cast(this)->set_length(Smi::FromInt(index + 1));
6099 }
Steve Blocka7e24c12009-10-30 11:49:00 +00006100 FixedArray::cast(elements())->set(index, value);
6101 return value;
6102 }
6103 }
6104
6105 // Otherwise default to slow case.
6106 Object* obj = NormalizeElements();
6107 if (obj->IsFailure()) return obj;
6108 ASSERT(HasDictionaryElements());
6109 return SetElement(index, value);
6110}
6111
6112Object* JSObject::SetElement(uint32_t index, Object* value) {
6113 // Check access rights if needed.
6114 if (IsAccessCheckNeeded() &&
6115 !Top::MayIndexedAccess(this, index, v8::ACCESS_SET)) {
6116 Top::ReportFailedAccessCheck(this, v8::ACCESS_SET);
6117 return value;
6118 }
6119
6120 if (IsJSGlobalProxy()) {
6121 Object* proto = GetPrototype();
6122 if (proto->IsNull()) return value;
6123 ASSERT(proto->IsJSGlobalObject());
6124 return JSObject::cast(proto)->SetElement(index, value);
6125 }
6126
6127 // Check for lookup interceptor
6128 if (HasIndexedInterceptor()) {
6129 return SetElementWithInterceptor(index, value);
6130 }
6131
6132 return SetElementWithoutInterceptor(index, value);
6133}
6134
6135
6136Object* JSObject::SetElementWithoutInterceptor(uint32_t index, Object* value) {
6137 switch (GetElementsKind()) {
6138 case FAST_ELEMENTS:
6139 // Fast case.
6140 return SetFastElement(index, value);
6141 case PIXEL_ELEMENTS: {
6142 PixelArray* pixels = PixelArray::cast(elements());
6143 return pixels->SetValue(index, value);
6144 }
Steve Block3ce2e202009-11-05 08:53:23 +00006145 case EXTERNAL_BYTE_ELEMENTS: {
6146 ExternalByteArray* array = ExternalByteArray::cast(elements());
6147 return array->SetValue(index, value);
6148 }
6149 case EXTERNAL_UNSIGNED_BYTE_ELEMENTS: {
6150 ExternalUnsignedByteArray* array =
6151 ExternalUnsignedByteArray::cast(elements());
6152 return array->SetValue(index, value);
6153 }
6154 case EXTERNAL_SHORT_ELEMENTS: {
6155 ExternalShortArray* array = ExternalShortArray::cast(elements());
6156 return array->SetValue(index, value);
6157 }
6158 case EXTERNAL_UNSIGNED_SHORT_ELEMENTS: {
6159 ExternalUnsignedShortArray* array =
6160 ExternalUnsignedShortArray::cast(elements());
6161 return array->SetValue(index, value);
6162 }
6163 case EXTERNAL_INT_ELEMENTS: {
6164 ExternalIntArray* array = ExternalIntArray::cast(elements());
6165 return array->SetValue(index, value);
6166 }
6167 case EXTERNAL_UNSIGNED_INT_ELEMENTS: {
6168 ExternalUnsignedIntArray* array =
6169 ExternalUnsignedIntArray::cast(elements());
6170 return array->SetValue(index, value);
6171 }
6172 case EXTERNAL_FLOAT_ELEMENTS: {
6173 ExternalFloatArray* array = ExternalFloatArray::cast(elements());
6174 return array->SetValue(index, value);
6175 }
Steve Blocka7e24c12009-10-30 11:49:00 +00006176 case DICTIONARY_ELEMENTS: {
6177 // Insert element in the dictionary.
6178 FixedArray* elms = FixedArray::cast(elements());
6179 NumberDictionary* dictionary = NumberDictionary::cast(elms);
6180
6181 int entry = dictionary->FindEntry(index);
6182 if (entry != NumberDictionary::kNotFound) {
6183 Object* element = dictionary->ValueAt(entry);
6184 PropertyDetails details = dictionary->DetailsAt(entry);
6185 if (details.type() == CALLBACKS) {
Leon Clarkef7060e22010-06-03 12:02:55 +01006186 return SetElementWithCallback(element, index, value, this);
Steve Blocka7e24c12009-10-30 11:49:00 +00006187 } else {
6188 dictionary->UpdateMaxNumberKey(index);
6189 dictionary->ValueAtPut(entry, value);
6190 }
6191 } else {
6192 // Index not already used. Look for an accessor in the prototype chain.
6193 if (!IsJSArray()) {
Leon Clarkef7060e22010-06-03 12:02:55 +01006194 if (SetElementWithCallbackSetterInPrototypes(index, value)) {
6195 return value;
Steve Blocka7e24c12009-10-30 11:49:00 +00006196 }
6197 }
6198 Object* result = dictionary->AtNumberPut(index, value);
6199 if (result->IsFailure()) return result;
6200 if (elms != FixedArray::cast(result)) {
6201 set_elements(FixedArray::cast(result));
6202 }
6203 }
6204
6205 // Update the array length if this JSObject is an array.
6206 if (IsJSArray()) {
6207 JSArray* array = JSArray::cast(this);
6208 Object* return_value = array->JSArrayUpdateLengthFromIndex(index,
6209 value);
6210 if (return_value->IsFailure()) return return_value;
6211 }
6212
6213 // Attempt to put this object back in fast case.
6214 if (ShouldConvertToFastElements()) {
6215 uint32_t new_length = 0;
6216 if (IsJSArray()) {
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01006217 CHECK(JSArray::cast(this)->length()->ToArrayIndex(&new_length));
Steve Blocka7e24c12009-10-30 11:49:00 +00006218 JSArray::cast(this)->set_length(Smi::FromInt(new_length));
6219 } else {
6220 new_length = NumberDictionary::cast(elements())->max_number_key() + 1;
6221 }
6222 Object* obj = Heap::AllocateFixedArrayWithHoles(new_length);
6223 if (obj->IsFailure()) return obj;
6224 SetFastElements(FixedArray::cast(obj));
6225#ifdef DEBUG
6226 if (FLAG_trace_normalization) {
6227 PrintF("Object elements are fast case again:\n");
6228 Print();
6229 }
6230#endif
6231 }
6232
6233 return value;
6234 }
6235 default:
6236 UNREACHABLE();
6237 break;
6238 }
6239 // All possible cases have been handled above. Add a return to avoid the
6240 // complaints from the compiler.
6241 UNREACHABLE();
6242 return Heap::null_value();
6243}
6244
6245
6246Object* JSArray::JSArrayUpdateLengthFromIndex(uint32_t index, Object* value) {
6247 uint32_t old_len = 0;
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01006248 CHECK(length()->ToArrayIndex(&old_len));
Steve Blocka7e24c12009-10-30 11:49:00 +00006249 // Check to see if we need to update the length. For now, we make
6250 // sure that the length stays within 32-bits (unsigned).
6251 if (index >= old_len && index != 0xffffffff) {
6252 Object* len =
6253 Heap::NumberFromDouble(static_cast<double>(index) + 1);
6254 if (len->IsFailure()) return len;
6255 set_length(len);
6256 }
6257 return value;
6258}
6259
6260
6261Object* JSObject::GetElementPostInterceptor(JSObject* receiver,
6262 uint32_t index) {
6263 // Get element works for both JSObject and JSArray since
6264 // JSArray::length cannot change.
6265 switch (GetElementsKind()) {
6266 case FAST_ELEMENTS: {
6267 FixedArray* elms = FixedArray::cast(elements());
6268 if (index < static_cast<uint32_t>(elms->length())) {
6269 Object* value = elms->get(index);
6270 if (!value->IsTheHole()) return value;
6271 }
6272 break;
6273 }
6274 case PIXEL_ELEMENTS: {
6275 // TODO(iposva): Add testcase and implement.
6276 UNIMPLEMENTED();
6277 break;
6278 }
Steve Block3ce2e202009-11-05 08:53:23 +00006279 case EXTERNAL_BYTE_ELEMENTS:
6280 case EXTERNAL_UNSIGNED_BYTE_ELEMENTS:
6281 case EXTERNAL_SHORT_ELEMENTS:
6282 case EXTERNAL_UNSIGNED_SHORT_ELEMENTS:
6283 case EXTERNAL_INT_ELEMENTS:
6284 case EXTERNAL_UNSIGNED_INT_ELEMENTS:
6285 case EXTERNAL_FLOAT_ELEMENTS: {
6286 // TODO(kbr): Add testcase and implement.
6287 UNIMPLEMENTED();
6288 break;
6289 }
Steve Blocka7e24c12009-10-30 11:49:00 +00006290 case DICTIONARY_ELEMENTS: {
6291 NumberDictionary* dictionary = element_dictionary();
6292 int entry = dictionary->FindEntry(index);
6293 if (entry != NumberDictionary::kNotFound) {
6294 Object* element = dictionary->ValueAt(entry);
6295 PropertyDetails details = dictionary->DetailsAt(entry);
6296 if (details.type() == CALLBACKS) {
Leon Clarkef7060e22010-06-03 12:02:55 +01006297 return GetElementWithCallback(receiver,
6298 element,
6299 index,
6300 this);
Steve Blocka7e24c12009-10-30 11:49:00 +00006301 }
6302 return element;
6303 }
6304 break;
6305 }
6306 default:
6307 UNREACHABLE();
6308 break;
6309 }
6310
6311 // Continue searching via the prototype chain.
6312 Object* pt = GetPrototype();
6313 if (pt == Heap::null_value()) return Heap::undefined_value();
6314 return pt->GetElementWithReceiver(receiver, index);
6315}
6316
6317
6318Object* JSObject::GetElementWithInterceptor(JSObject* receiver,
6319 uint32_t index) {
6320 // Make sure that the top context does not change when doing
6321 // callbacks or interceptor calls.
6322 AssertNoContextChange ncc;
6323 HandleScope scope;
6324 Handle<InterceptorInfo> interceptor(GetIndexedInterceptor());
6325 Handle<JSObject> this_handle(receiver);
6326 Handle<JSObject> holder_handle(this);
6327
6328 if (!interceptor->getter()->IsUndefined()) {
6329 v8::IndexedPropertyGetter getter =
6330 v8::ToCData<v8::IndexedPropertyGetter>(interceptor->getter());
6331 LOG(ApiIndexedPropertyAccess("interceptor-indexed-get", this, index));
6332 CustomArguments args(interceptor->data(), receiver, this);
6333 v8::AccessorInfo info(args.end());
6334 v8::Handle<v8::Value> result;
6335 {
6336 // Leaving JavaScript.
6337 VMState state(EXTERNAL);
6338 result = getter(index, info);
6339 }
6340 RETURN_IF_SCHEDULED_EXCEPTION();
6341 if (!result.IsEmpty()) return *v8::Utils::OpenHandle(*result);
6342 }
6343
6344 Object* raw_result =
6345 holder_handle->GetElementPostInterceptor(*this_handle, index);
6346 RETURN_IF_SCHEDULED_EXCEPTION();
6347 return raw_result;
6348}
6349
6350
6351Object* JSObject::GetElementWithReceiver(JSObject* receiver, uint32_t index) {
6352 // Check access rights if needed.
6353 if (IsAccessCheckNeeded() &&
6354 !Top::MayIndexedAccess(this, index, v8::ACCESS_GET)) {
6355 Top::ReportFailedAccessCheck(this, v8::ACCESS_GET);
6356 return Heap::undefined_value();
6357 }
6358
6359 if (HasIndexedInterceptor()) {
6360 return GetElementWithInterceptor(receiver, index);
6361 }
6362
6363 // Get element works for both JSObject and JSArray since
6364 // JSArray::length cannot change.
6365 switch (GetElementsKind()) {
6366 case FAST_ELEMENTS: {
6367 FixedArray* elms = FixedArray::cast(elements());
6368 if (index < static_cast<uint32_t>(elms->length())) {
6369 Object* value = elms->get(index);
6370 if (!value->IsTheHole()) return value;
6371 }
6372 break;
6373 }
6374 case PIXEL_ELEMENTS: {
6375 PixelArray* pixels = PixelArray::cast(elements());
6376 if (index < static_cast<uint32_t>(pixels->length())) {
6377 uint8_t value = pixels->get(index);
6378 return Smi::FromInt(value);
6379 }
6380 break;
6381 }
Steve Block3ce2e202009-11-05 08:53:23 +00006382 case EXTERNAL_BYTE_ELEMENTS: {
6383 ExternalByteArray* array = ExternalByteArray::cast(elements());
6384 if (index < static_cast<uint32_t>(array->length())) {
6385 int8_t value = array->get(index);
6386 return Smi::FromInt(value);
6387 }
6388 break;
6389 }
6390 case EXTERNAL_UNSIGNED_BYTE_ELEMENTS: {
6391 ExternalUnsignedByteArray* array =
6392 ExternalUnsignedByteArray::cast(elements());
6393 if (index < static_cast<uint32_t>(array->length())) {
6394 uint8_t value = array->get(index);
6395 return Smi::FromInt(value);
6396 }
6397 break;
6398 }
6399 case EXTERNAL_SHORT_ELEMENTS: {
6400 ExternalShortArray* array = ExternalShortArray::cast(elements());
6401 if (index < static_cast<uint32_t>(array->length())) {
6402 int16_t value = array->get(index);
6403 return Smi::FromInt(value);
6404 }
6405 break;
6406 }
6407 case EXTERNAL_UNSIGNED_SHORT_ELEMENTS: {
6408 ExternalUnsignedShortArray* array =
6409 ExternalUnsignedShortArray::cast(elements());
6410 if (index < static_cast<uint32_t>(array->length())) {
6411 uint16_t value = array->get(index);
6412 return Smi::FromInt(value);
6413 }
6414 break;
6415 }
6416 case EXTERNAL_INT_ELEMENTS: {
6417 ExternalIntArray* array = ExternalIntArray::cast(elements());
6418 if (index < static_cast<uint32_t>(array->length())) {
6419 int32_t value = array->get(index);
6420 return Heap::NumberFromInt32(value);
6421 }
6422 break;
6423 }
6424 case EXTERNAL_UNSIGNED_INT_ELEMENTS: {
6425 ExternalUnsignedIntArray* array =
6426 ExternalUnsignedIntArray::cast(elements());
6427 if (index < static_cast<uint32_t>(array->length())) {
6428 uint32_t value = array->get(index);
6429 return Heap::NumberFromUint32(value);
6430 }
6431 break;
6432 }
6433 case EXTERNAL_FLOAT_ELEMENTS: {
6434 ExternalFloatArray* array = ExternalFloatArray::cast(elements());
6435 if (index < static_cast<uint32_t>(array->length())) {
6436 float value = array->get(index);
6437 return Heap::AllocateHeapNumber(value);
6438 }
6439 break;
6440 }
Steve Blocka7e24c12009-10-30 11:49:00 +00006441 case DICTIONARY_ELEMENTS: {
6442 NumberDictionary* dictionary = element_dictionary();
6443 int entry = dictionary->FindEntry(index);
6444 if (entry != NumberDictionary::kNotFound) {
6445 Object* element = dictionary->ValueAt(entry);
6446 PropertyDetails details = dictionary->DetailsAt(entry);
6447 if (details.type() == CALLBACKS) {
Leon Clarkef7060e22010-06-03 12:02:55 +01006448 return GetElementWithCallback(receiver,
6449 element,
6450 index,
6451 this);
Steve Blocka7e24c12009-10-30 11:49:00 +00006452 }
6453 return element;
6454 }
6455 break;
6456 }
6457 }
6458
6459 Object* pt = GetPrototype();
6460 if (pt == Heap::null_value()) return Heap::undefined_value();
6461 return pt->GetElementWithReceiver(receiver, index);
6462}
6463
6464
6465bool JSObject::HasDenseElements() {
6466 int capacity = 0;
6467 int number_of_elements = 0;
6468
6469 switch (GetElementsKind()) {
6470 case FAST_ELEMENTS: {
6471 FixedArray* elms = FixedArray::cast(elements());
6472 capacity = elms->length();
6473 for (int i = 0; i < capacity; i++) {
6474 if (!elms->get(i)->IsTheHole()) number_of_elements++;
6475 }
6476 break;
6477 }
Steve Block3ce2e202009-11-05 08:53:23 +00006478 case PIXEL_ELEMENTS:
6479 case EXTERNAL_BYTE_ELEMENTS:
6480 case EXTERNAL_UNSIGNED_BYTE_ELEMENTS:
6481 case EXTERNAL_SHORT_ELEMENTS:
6482 case EXTERNAL_UNSIGNED_SHORT_ELEMENTS:
6483 case EXTERNAL_INT_ELEMENTS:
6484 case EXTERNAL_UNSIGNED_INT_ELEMENTS:
6485 case EXTERNAL_FLOAT_ELEMENTS: {
Steve Blocka7e24c12009-10-30 11:49:00 +00006486 return true;
6487 }
6488 case DICTIONARY_ELEMENTS: {
6489 NumberDictionary* dictionary = NumberDictionary::cast(elements());
6490 capacity = dictionary->Capacity();
6491 number_of_elements = dictionary->NumberOfElements();
6492 break;
6493 }
6494 default:
6495 UNREACHABLE();
6496 break;
6497 }
6498
6499 if (capacity == 0) return true;
6500 return (number_of_elements > (capacity / 2));
6501}
6502
6503
6504bool JSObject::ShouldConvertToSlowElements(int new_capacity) {
6505 ASSERT(HasFastElements());
6506 // Keep the array in fast case if the current backing storage is
6507 // almost filled and if the new capacity is no more than twice the
6508 // old capacity.
6509 int elements_length = FixedArray::cast(elements())->length();
6510 return !HasDenseElements() || ((new_capacity / 2) > elements_length);
6511}
6512
6513
6514bool JSObject::ShouldConvertToFastElements() {
6515 ASSERT(HasDictionaryElements());
6516 NumberDictionary* dictionary = NumberDictionary::cast(elements());
6517 // If the elements are sparse, we should not go back to fast case.
6518 if (!HasDenseElements()) return false;
6519 // If an element has been added at a very high index in the elements
6520 // dictionary, we cannot go back to fast case.
6521 if (dictionary->requires_slow_elements()) return false;
6522 // An object requiring access checks is never allowed to have fast
6523 // elements. If it had fast elements we would skip security checks.
6524 if (IsAccessCheckNeeded()) return false;
6525 // If the dictionary backing storage takes up roughly half as much
6526 // space as a fast-case backing storage would the array should have
6527 // fast elements.
6528 uint32_t length = 0;
6529 if (IsJSArray()) {
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01006530 CHECK(JSArray::cast(this)->length()->ToArrayIndex(&length));
Steve Blocka7e24c12009-10-30 11:49:00 +00006531 } else {
6532 length = dictionary->max_number_key();
6533 }
6534 return static_cast<uint32_t>(dictionary->Capacity()) >=
6535 (length / (2 * NumberDictionary::kEntrySize));
6536}
6537
6538
6539// Certain compilers request function template instantiation when they
6540// see the definition of the other template functions in the
6541// class. This requires us to have the template functions put
6542// together, so even though this function belongs in objects-debug.cc,
6543// we keep it here instead to satisfy certain compilers.
6544#ifdef DEBUG
6545template<typename Shape, typename Key>
6546void Dictionary<Shape, Key>::Print() {
6547 int capacity = HashTable<Shape, Key>::Capacity();
6548 for (int i = 0; i < capacity; i++) {
6549 Object* k = HashTable<Shape, Key>::KeyAt(i);
6550 if (HashTable<Shape, Key>::IsKey(k)) {
6551 PrintF(" ");
6552 if (k->IsString()) {
6553 String::cast(k)->StringPrint();
6554 } else {
6555 k->ShortPrint();
6556 }
6557 PrintF(": ");
6558 ValueAt(i)->ShortPrint();
6559 PrintF("\n");
6560 }
6561 }
6562}
6563#endif
6564
6565
6566template<typename Shape, typename Key>
6567void Dictionary<Shape, Key>::CopyValuesTo(FixedArray* elements) {
6568 int pos = 0;
6569 int capacity = HashTable<Shape, Key>::Capacity();
Leon Clarke4515c472010-02-03 11:58:03 +00006570 AssertNoAllocation no_gc;
6571 WriteBarrierMode mode = elements->GetWriteBarrierMode(no_gc);
Steve Blocka7e24c12009-10-30 11:49:00 +00006572 for (int i = 0; i < capacity; i++) {
6573 Object* k = Dictionary<Shape, Key>::KeyAt(i);
6574 if (Dictionary<Shape, Key>::IsKey(k)) {
6575 elements->set(pos++, ValueAt(i), mode);
6576 }
6577 }
6578 ASSERT(pos == elements->length());
6579}
6580
6581
6582InterceptorInfo* JSObject::GetNamedInterceptor() {
6583 ASSERT(map()->has_named_interceptor());
6584 JSFunction* constructor = JSFunction::cast(map()->constructor());
Steve Block6ded16b2010-05-10 14:33:55 +01006585 ASSERT(constructor->shared()->IsApiFunction());
Steve Blocka7e24c12009-10-30 11:49:00 +00006586 Object* result =
Steve Block6ded16b2010-05-10 14:33:55 +01006587 constructor->shared()->get_api_func_data()->named_property_handler();
Steve Blocka7e24c12009-10-30 11:49:00 +00006588 return InterceptorInfo::cast(result);
6589}
6590
6591
6592InterceptorInfo* JSObject::GetIndexedInterceptor() {
6593 ASSERT(map()->has_indexed_interceptor());
6594 JSFunction* constructor = JSFunction::cast(map()->constructor());
Steve Block6ded16b2010-05-10 14:33:55 +01006595 ASSERT(constructor->shared()->IsApiFunction());
Steve Blocka7e24c12009-10-30 11:49:00 +00006596 Object* result =
Steve Block6ded16b2010-05-10 14:33:55 +01006597 constructor->shared()->get_api_func_data()->indexed_property_handler();
Steve Blocka7e24c12009-10-30 11:49:00 +00006598 return InterceptorInfo::cast(result);
6599}
6600
6601
6602Object* JSObject::GetPropertyPostInterceptor(JSObject* receiver,
6603 String* name,
6604 PropertyAttributes* attributes) {
6605 // Check local property in holder, ignore interceptor.
6606 LookupResult result;
6607 LocalLookupRealNamedProperty(name, &result);
Andrei Popescu402d9372010-02-26 13:31:12 +00006608 if (result.IsProperty()) {
6609 return GetProperty(receiver, &result, name, attributes);
6610 }
Steve Blocka7e24c12009-10-30 11:49:00 +00006611 // Continue searching via the prototype chain.
6612 Object* pt = GetPrototype();
6613 *attributes = ABSENT;
6614 if (pt == Heap::null_value()) return Heap::undefined_value();
6615 return pt->GetPropertyWithReceiver(receiver, name, attributes);
6616}
6617
6618
Steve Blockd0582a62009-12-15 09:54:21 +00006619Object* JSObject::GetLocalPropertyPostInterceptor(
6620 JSObject* receiver,
6621 String* name,
6622 PropertyAttributes* attributes) {
6623 // Check local property in holder, ignore interceptor.
6624 LookupResult result;
6625 LocalLookupRealNamedProperty(name, &result);
Andrei Popescu402d9372010-02-26 13:31:12 +00006626 if (result.IsProperty()) {
6627 return GetProperty(receiver, &result, name, attributes);
6628 }
6629 return Heap::undefined_value();
Steve Blockd0582a62009-12-15 09:54:21 +00006630}
6631
6632
Steve Blocka7e24c12009-10-30 11:49:00 +00006633Object* JSObject::GetPropertyWithInterceptor(
6634 JSObject* receiver,
6635 String* name,
6636 PropertyAttributes* attributes) {
6637 InterceptorInfo* interceptor = GetNamedInterceptor();
6638 HandleScope scope;
6639 Handle<JSObject> receiver_handle(receiver);
6640 Handle<JSObject> holder_handle(this);
6641 Handle<String> name_handle(name);
6642
6643 if (!interceptor->getter()->IsUndefined()) {
6644 v8::NamedPropertyGetter getter =
6645 v8::ToCData<v8::NamedPropertyGetter>(interceptor->getter());
6646 LOG(ApiNamedPropertyAccess("interceptor-named-get", *holder_handle, name));
6647 CustomArguments args(interceptor->data(), receiver, this);
6648 v8::AccessorInfo info(args.end());
6649 v8::Handle<v8::Value> result;
6650 {
6651 // Leaving JavaScript.
6652 VMState state(EXTERNAL);
6653 result = getter(v8::Utils::ToLocal(name_handle), info);
6654 }
6655 RETURN_IF_SCHEDULED_EXCEPTION();
6656 if (!result.IsEmpty()) {
6657 *attributes = NONE;
6658 return *v8::Utils::OpenHandle(*result);
6659 }
6660 }
6661
6662 Object* result = holder_handle->GetPropertyPostInterceptor(
6663 *receiver_handle,
6664 *name_handle,
6665 attributes);
6666 RETURN_IF_SCHEDULED_EXCEPTION();
6667 return result;
6668}
6669
6670
6671bool JSObject::HasRealNamedProperty(String* key) {
6672 // Check access rights if needed.
6673 if (IsAccessCheckNeeded() &&
6674 !Top::MayNamedAccess(this, key, v8::ACCESS_HAS)) {
6675 Top::ReportFailedAccessCheck(this, v8::ACCESS_HAS);
6676 return false;
6677 }
6678
6679 LookupResult result;
6680 LocalLookupRealNamedProperty(key, &result);
Andrei Popescu402d9372010-02-26 13:31:12 +00006681 return result.IsProperty() && (result.type() != INTERCEPTOR);
Steve Blocka7e24c12009-10-30 11:49:00 +00006682}
6683
6684
6685bool JSObject::HasRealElementProperty(uint32_t index) {
6686 // Check access rights if needed.
6687 if (IsAccessCheckNeeded() &&
6688 !Top::MayIndexedAccess(this, index, v8::ACCESS_HAS)) {
6689 Top::ReportFailedAccessCheck(this, v8::ACCESS_HAS);
6690 return false;
6691 }
6692
6693 // Handle [] on String objects.
6694 if (this->IsStringObjectWithCharacterAt(index)) return true;
6695
6696 switch (GetElementsKind()) {
6697 case FAST_ELEMENTS: {
6698 uint32_t length = IsJSArray() ?
6699 static_cast<uint32_t>(
6700 Smi::cast(JSArray::cast(this)->length())->value()) :
6701 static_cast<uint32_t>(FixedArray::cast(elements())->length());
6702 return (index < length) &&
6703 !FixedArray::cast(elements())->get(index)->IsTheHole();
6704 }
6705 case PIXEL_ELEMENTS: {
6706 PixelArray* pixels = PixelArray::cast(elements());
6707 return index < static_cast<uint32_t>(pixels->length());
6708 }
Steve Block3ce2e202009-11-05 08:53:23 +00006709 case EXTERNAL_BYTE_ELEMENTS:
6710 case EXTERNAL_UNSIGNED_BYTE_ELEMENTS:
6711 case EXTERNAL_SHORT_ELEMENTS:
6712 case EXTERNAL_UNSIGNED_SHORT_ELEMENTS:
6713 case EXTERNAL_INT_ELEMENTS:
6714 case EXTERNAL_UNSIGNED_INT_ELEMENTS:
6715 case EXTERNAL_FLOAT_ELEMENTS: {
6716 ExternalArray* array = ExternalArray::cast(elements());
6717 return index < static_cast<uint32_t>(array->length());
6718 }
Steve Blocka7e24c12009-10-30 11:49:00 +00006719 case DICTIONARY_ELEMENTS: {
6720 return element_dictionary()->FindEntry(index)
6721 != NumberDictionary::kNotFound;
6722 }
6723 default:
6724 UNREACHABLE();
6725 break;
6726 }
6727 // All possibilities have been handled above already.
6728 UNREACHABLE();
6729 return Heap::null_value();
6730}
6731
6732
6733bool JSObject::HasRealNamedCallbackProperty(String* key) {
6734 // Check access rights if needed.
6735 if (IsAccessCheckNeeded() &&
6736 !Top::MayNamedAccess(this, key, v8::ACCESS_HAS)) {
6737 Top::ReportFailedAccessCheck(this, v8::ACCESS_HAS);
6738 return false;
6739 }
6740
6741 LookupResult result;
6742 LocalLookupRealNamedProperty(key, &result);
Andrei Popescu402d9372010-02-26 13:31:12 +00006743 return result.IsProperty() && (result.type() == CALLBACKS);
Steve Blocka7e24c12009-10-30 11:49:00 +00006744}
6745
6746
6747int JSObject::NumberOfLocalProperties(PropertyAttributes filter) {
6748 if (HasFastProperties()) {
6749 DescriptorArray* descs = map()->instance_descriptors();
6750 int result = 0;
6751 for (int i = 0; i < descs->number_of_descriptors(); i++) {
6752 PropertyDetails details = descs->GetDetails(i);
6753 if (details.IsProperty() && (details.attributes() & filter) == 0) {
6754 result++;
6755 }
6756 }
6757 return result;
6758 } else {
6759 return property_dictionary()->NumberOfElementsFilterAttributes(filter);
6760 }
6761}
6762
6763
6764int JSObject::NumberOfEnumProperties() {
6765 return NumberOfLocalProperties(static_cast<PropertyAttributes>(DONT_ENUM));
6766}
6767
6768
6769void FixedArray::SwapPairs(FixedArray* numbers, int i, int j) {
6770 Object* temp = get(i);
6771 set(i, get(j));
6772 set(j, temp);
6773 if (this != numbers) {
6774 temp = numbers->get(i);
6775 numbers->set(i, numbers->get(j));
6776 numbers->set(j, temp);
6777 }
6778}
6779
6780
6781static void InsertionSortPairs(FixedArray* content,
6782 FixedArray* numbers,
6783 int len) {
6784 for (int i = 1; i < len; i++) {
6785 int j = i;
6786 while (j > 0 &&
6787 (NumberToUint32(numbers->get(j - 1)) >
6788 NumberToUint32(numbers->get(j)))) {
6789 content->SwapPairs(numbers, j - 1, j);
6790 j--;
6791 }
6792 }
6793}
6794
6795
6796void HeapSortPairs(FixedArray* content, FixedArray* numbers, int len) {
6797 // In-place heap sort.
6798 ASSERT(content->length() == numbers->length());
6799
6800 // Bottom-up max-heap construction.
6801 for (int i = 1; i < len; ++i) {
6802 int child_index = i;
6803 while (child_index > 0) {
6804 int parent_index = ((child_index + 1) >> 1) - 1;
6805 uint32_t parent_value = NumberToUint32(numbers->get(parent_index));
6806 uint32_t child_value = NumberToUint32(numbers->get(child_index));
6807 if (parent_value < child_value) {
6808 content->SwapPairs(numbers, parent_index, child_index);
6809 } else {
6810 break;
6811 }
6812 child_index = parent_index;
6813 }
6814 }
6815
6816 // Extract elements and create sorted array.
6817 for (int i = len - 1; i > 0; --i) {
6818 // Put max element at the back of the array.
6819 content->SwapPairs(numbers, 0, i);
6820 // Sift down the new top element.
6821 int parent_index = 0;
6822 while (true) {
6823 int child_index = ((parent_index + 1) << 1) - 1;
6824 if (child_index >= i) break;
6825 uint32_t child1_value = NumberToUint32(numbers->get(child_index));
6826 uint32_t child2_value = NumberToUint32(numbers->get(child_index + 1));
6827 uint32_t parent_value = NumberToUint32(numbers->get(parent_index));
6828 if (child_index + 1 >= i || child1_value > child2_value) {
6829 if (parent_value > child1_value) break;
6830 content->SwapPairs(numbers, parent_index, child_index);
6831 parent_index = child_index;
6832 } else {
6833 if (parent_value > child2_value) break;
6834 content->SwapPairs(numbers, parent_index, child_index + 1);
6835 parent_index = child_index + 1;
6836 }
6837 }
6838 }
6839}
6840
6841
6842// Sort this array and the numbers as pairs wrt. the (distinct) numbers.
6843void FixedArray::SortPairs(FixedArray* numbers, uint32_t len) {
6844 ASSERT(this->length() == numbers->length());
6845 // For small arrays, simply use insertion sort.
6846 if (len <= 10) {
6847 InsertionSortPairs(this, numbers, len);
6848 return;
6849 }
6850 // Check the range of indices.
6851 uint32_t min_index = NumberToUint32(numbers->get(0));
6852 uint32_t max_index = min_index;
6853 uint32_t i;
6854 for (i = 1; i < len; i++) {
6855 if (NumberToUint32(numbers->get(i)) < min_index) {
6856 min_index = NumberToUint32(numbers->get(i));
6857 } else if (NumberToUint32(numbers->get(i)) > max_index) {
6858 max_index = NumberToUint32(numbers->get(i));
6859 }
6860 }
6861 if (max_index - min_index + 1 == len) {
6862 // Indices form a contiguous range, unless there are duplicates.
6863 // Do an in-place linear time sort assuming distinct numbers, but
6864 // avoid hanging in case they are not.
6865 for (i = 0; i < len; i++) {
6866 uint32_t p;
6867 uint32_t j = 0;
6868 // While the current element at i is not at its correct position p,
6869 // swap the elements at these two positions.
6870 while ((p = NumberToUint32(numbers->get(i)) - min_index) != i &&
6871 j++ < len) {
6872 SwapPairs(numbers, i, p);
6873 }
6874 }
6875 } else {
6876 HeapSortPairs(this, numbers, len);
6877 return;
6878 }
6879}
6880
6881
6882// Fill in the names of local properties into the supplied storage. The main
6883// purpose of this function is to provide reflection information for the object
6884// mirrors.
6885void JSObject::GetLocalPropertyNames(FixedArray* storage, int index) {
6886 ASSERT(storage->length() >= (NumberOfLocalProperties(NONE) - index));
6887 if (HasFastProperties()) {
6888 DescriptorArray* descs = map()->instance_descriptors();
6889 for (int i = 0; i < descs->number_of_descriptors(); i++) {
6890 if (descs->IsProperty(i)) storage->set(index++, descs->GetKey(i));
6891 }
6892 ASSERT(storage->length() >= index);
6893 } else {
6894 property_dictionary()->CopyKeysTo(storage);
6895 }
6896}
6897
6898
6899int JSObject::NumberOfLocalElements(PropertyAttributes filter) {
6900 return GetLocalElementKeys(NULL, filter);
6901}
6902
6903
6904int JSObject::NumberOfEnumElements() {
Steve Blockd0582a62009-12-15 09:54:21 +00006905 // Fast case for objects with no elements.
6906 if (!IsJSValue() && HasFastElements()) {
6907 uint32_t length = IsJSArray() ?
6908 static_cast<uint32_t>(
6909 Smi::cast(JSArray::cast(this)->length())->value()) :
6910 static_cast<uint32_t>(FixedArray::cast(elements())->length());
6911 if (length == 0) return 0;
6912 }
6913 // Compute the number of enumerable elements.
Steve Blocka7e24c12009-10-30 11:49:00 +00006914 return NumberOfLocalElements(static_cast<PropertyAttributes>(DONT_ENUM));
6915}
6916
6917
6918int JSObject::GetLocalElementKeys(FixedArray* storage,
6919 PropertyAttributes filter) {
6920 int counter = 0;
6921 switch (GetElementsKind()) {
6922 case FAST_ELEMENTS: {
6923 int length = IsJSArray() ?
6924 Smi::cast(JSArray::cast(this)->length())->value() :
6925 FixedArray::cast(elements())->length();
6926 for (int i = 0; i < length; i++) {
6927 if (!FixedArray::cast(elements())->get(i)->IsTheHole()) {
6928 if (storage != NULL) {
Leon Clarke4515c472010-02-03 11:58:03 +00006929 storage->set(counter, Smi::FromInt(i));
Steve Blocka7e24c12009-10-30 11:49:00 +00006930 }
6931 counter++;
6932 }
6933 }
6934 ASSERT(!storage || storage->length() >= counter);
6935 break;
6936 }
6937 case PIXEL_ELEMENTS: {
6938 int length = PixelArray::cast(elements())->length();
6939 while (counter < length) {
6940 if (storage != NULL) {
Leon Clarke4515c472010-02-03 11:58:03 +00006941 storage->set(counter, Smi::FromInt(counter));
Steve Blocka7e24c12009-10-30 11:49:00 +00006942 }
6943 counter++;
6944 }
6945 ASSERT(!storage || storage->length() >= counter);
6946 break;
6947 }
Steve Block3ce2e202009-11-05 08:53:23 +00006948 case EXTERNAL_BYTE_ELEMENTS:
6949 case EXTERNAL_UNSIGNED_BYTE_ELEMENTS:
6950 case EXTERNAL_SHORT_ELEMENTS:
6951 case EXTERNAL_UNSIGNED_SHORT_ELEMENTS:
6952 case EXTERNAL_INT_ELEMENTS:
6953 case EXTERNAL_UNSIGNED_INT_ELEMENTS:
6954 case EXTERNAL_FLOAT_ELEMENTS: {
6955 int length = ExternalArray::cast(elements())->length();
6956 while (counter < length) {
6957 if (storage != NULL) {
Leon Clarke4515c472010-02-03 11:58:03 +00006958 storage->set(counter, Smi::FromInt(counter));
Steve Block3ce2e202009-11-05 08:53:23 +00006959 }
6960 counter++;
6961 }
6962 ASSERT(!storage || storage->length() >= counter);
6963 break;
6964 }
Steve Blocka7e24c12009-10-30 11:49:00 +00006965 case DICTIONARY_ELEMENTS: {
6966 if (storage != NULL) {
6967 element_dictionary()->CopyKeysTo(storage, filter);
6968 }
6969 counter = element_dictionary()->NumberOfElementsFilterAttributes(filter);
6970 break;
6971 }
6972 default:
6973 UNREACHABLE();
6974 break;
6975 }
6976
6977 if (this->IsJSValue()) {
6978 Object* val = JSValue::cast(this)->value();
6979 if (val->IsString()) {
6980 String* str = String::cast(val);
6981 if (storage) {
6982 for (int i = 0; i < str->length(); i++) {
Leon Clarke4515c472010-02-03 11:58:03 +00006983 storage->set(counter + i, Smi::FromInt(i));
Steve Blocka7e24c12009-10-30 11:49:00 +00006984 }
6985 }
6986 counter += str->length();
6987 }
6988 }
6989 ASSERT(!storage || storage->length() == counter);
6990 return counter;
6991}
6992
6993
6994int JSObject::GetEnumElementKeys(FixedArray* storage) {
6995 return GetLocalElementKeys(storage,
6996 static_cast<PropertyAttributes>(DONT_ENUM));
6997}
6998
6999
7000bool NumberDictionaryShape::IsMatch(uint32_t key, Object* other) {
7001 ASSERT(other->IsNumber());
7002 return key == static_cast<uint32_t>(other->Number());
7003}
7004
7005
7006uint32_t NumberDictionaryShape::Hash(uint32_t key) {
7007 return ComputeIntegerHash(key);
7008}
7009
7010
7011uint32_t NumberDictionaryShape::HashForObject(uint32_t key, Object* other) {
7012 ASSERT(other->IsNumber());
7013 return ComputeIntegerHash(static_cast<uint32_t>(other->Number()));
7014}
7015
7016
7017Object* NumberDictionaryShape::AsObject(uint32_t key) {
7018 return Heap::NumberFromUint32(key);
7019}
7020
7021
7022bool StringDictionaryShape::IsMatch(String* key, Object* other) {
7023 // We know that all entries in a hash table had their hash keys created.
7024 // Use that knowledge to have fast failure.
7025 if (key->Hash() != String::cast(other)->Hash()) return false;
7026 return key->Equals(String::cast(other));
7027}
7028
7029
7030uint32_t StringDictionaryShape::Hash(String* key) {
7031 return key->Hash();
7032}
7033
7034
7035uint32_t StringDictionaryShape::HashForObject(String* key, Object* other) {
7036 return String::cast(other)->Hash();
7037}
7038
7039
7040Object* StringDictionaryShape::AsObject(String* key) {
7041 return key;
7042}
7043
7044
7045// StringKey simply carries a string object as key.
7046class StringKey : public HashTableKey {
7047 public:
7048 explicit StringKey(String* string) :
7049 string_(string),
7050 hash_(HashForObject(string)) { }
7051
7052 bool IsMatch(Object* string) {
7053 // We know that all entries in a hash table had their hash keys created.
7054 // Use that knowledge to have fast failure.
7055 if (hash_ != HashForObject(string)) {
7056 return false;
7057 }
7058 return string_->Equals(String::cast(string));
7059 }
7060
7061 uint32_t Hash() { return hash_; }
7062
7063 uint32_t HashForObject(Object* other) { return String::cast(other)->Hash(); }
7064
7065 Object* AsObject() { return string_; }
7066
7067 String* string_;
7068 uint32_t hash_;
7069};
7070
7071
7072// StringSharedKeys are used as keys in the eval cache.
7073class StringSharedKey : public HashTableKey {
7074 public:
7075 StringSharedKey(String* source, SharedFunctionInfo* shared)
7076 : source_(source), shared_(shared) { }
7077
7078 bool IsMatch(Object* other) {
7079 if (!other->IsFixedArray()) return false;
7080 FixedArray* pair = FixedArray::cast(other);
7081 SharedFunctionInfo* shared = SharedFunctionInfo::cast(pair->get(0));
7082 if (shared != shared_) return false;
7083 String* source = String::cast(pair->get(1));
7084 return source->Equals(source_);
7085 }
7086
7087 static uint32_t StringSharedHashHelper(String* source,
7088 SharedFunctionInfo* shared) {
7089 uint32_t hash = source->Hash();
7090 if (shared->HasSourceCode()) {
7091 // Instead of using the SharedFunctionInfo pointer in the hash
7092 // code computation, we use a combination of the hash of the
7093 // script source code and the start and end positions. We do
7094 // this to ensure that the cache entries can survive garbage
7095 // collection.
7096 Script* script = Script::cast(shared->script());
7097 hash ^= String::cast(script->source())->Hash();
7098 hash += shared->start_position();
7099 }
7100 return hash;
7101 }
7102
7103 uint32_t Hash() {
7104 return StringSharedHashHelper(source_, shared_);
7105 }
7106
7107 uint32_t HashForObject(Object* obj) {
7108 FixedArray* pair = FixedArray::cast(obj);
7109 SharedFunctionInfo* shared = SharedFunctionInfo::cast(pair->get(0));
7110 String* source = String::cast(pair->get(1));
7111 return StringSharedHashHelper(source, shared);
7112 }
7113
7114 Object* AsObject() {
7115 Object* obj = Heap::AllocateFixedArray(2);
7116 if (obj->IsFailure()) return obj;
7117 FixedArray* pair = FixedArray::cast(obj);
7118 pair->set(0, shared_);
7119 pair->set(1, source_);
7120 return pair;
7121 }
7122
7123 private:
7124 String* source_;
7125 SharedFunctionInfo* shared_;
7126};
7127
7128
7129// RegExpKey carries the source and flags of a regular expression as key.
7130class RegExpKey : public HashTableKey {
7131 public:
7132 RegExpKey(String* string, JSRegExp::Flags flags)
7133 : string_(string),
7134 flags_(Smi::FromInt(flags.value())) { }
7135
Steve Block3ce2e202009-11-05 08:53:23 +00007136 // Rather than storing the key in the hash table, a pointer to the
7137 // stored value is stored where the key should be. IsMatch then
7138 // compares the search key to the found object, rather than comparing
7139 // a key to a key.
Steve Blocka7e24c12009-10-30 11:49:00 +00007140 bool IsMatch(Object* obj) {
7141 FixedArray* val = FixedArray::cast(obj);
7142 return string_->Equals(String::cast(val->get(JSRegExp::kSourceIndex)))
7143 && (flags_ == val->get(JSRegExp::kFlagsIndex));
7144 }
7145
7146 uint32_t Hash() { return RegExpHash(string_, flags_); }
7147
7148 Object* AsObject() {
7149 // Plain hash maps, which is where regexp keys are used, don't
7150 // use this function.
7151 UNREACHABLE();
7152 return NULL;
7153 }
7154
7155 uint32_t HashForObject(Object* obj) {
7156 FixedArray* val = FixedArray::cast(obj);
7157 return RegExpHash(String::cast(val->get(JSRegExp::kSourceIndex)),
7158 Smi::cast(val->get(JSRegExp::kFlagsIndex)));
7159 }
7160
7161 static uint32_t RegExpHash(String* string, Smi* flags) {
7162 return string->Hash() + flags->value();
7163 }
7164
7165 String* string_;
7166 Smi* flags_;
7167};
7168
7169// Utf8SymbolKey carries a vector of chars as key.
7170class Utf8SymbolKey : public HashTableKey {
7171 public:
7172 explicit Utf8SymbolKey(Vector<const char> string)
Steve Blockd0582a62009-12-15 09:54:21 +00007173 : string_(string), hash_field_(0) { }
Steve Blocka7e24c12009-10-30 11:49:00 +00007174
7175 bool IsMatch(Object* string) {
7176 return String::cast(string)->IsEqualTo(string_);
7177 }
7178
7179 uint32_t Hash() {
Steve Blockd0582a62009-12-15 09:54:21 +00007180 if (hash_field_ != 0) return hash_field_ >> String::kHashShift;
Steve Blocka7e24c12009-10-30 11:49:00 +00007181 unibrow::Utf8InputBuffer<> buffer(string_.start(),
7182 static_cast<unsigned>(string_.length()));
7183 chars_ = buffer.Length();
Steve Blockd0582a62009-12-15 09:54:21 +00007184 hash_field_ = String::ComputeHashField(&buffer, chars_);
7185 uint32_t result = hash_field_ >> String::kHashShift;
Steve Blocka7e24c12009-10-30 11:49:00 +00007186 ASSERT(result != 0); // Ensure that the hash value of 0 is never computed.
7187 return result;
7188 }
7189
7190 uint32_t HashForObject(Object* other) {
7191 return String::cast(other)->Hash();
7192 }
7193
7194 Object* AsObject() {
Steve Blockd0582a62009-12-15 09:54:21 +00007195 if (hash_field_ == 0) Hash();
7196 return Heap::AllocateSymbol(string_, chars_, hash_field_);
Steve Blocka7e24c12009-10-30 11:49:00 +00007197 }
7198
7199 Vector<const char> string_;
Steve Blockd0582a62009-12-15 09:54:21 +00007200 uint32_t hash_field_;
Steve Blocka7e24c12009-10-30 11:49:00 +00007201 int chars_; // Caches the number of characters when computing the hash code.
7202};
7203
7204
7205// SymbolKey carries a string/symbol object as key.
7206class SymbolKey : public HashTableKey {
7207 public:
7208 explicit SymbolKey(String* string) : string_(string) { }
7209
7210 bool IsMatch(Object* string) {
7211 return String::cast(string)->Equals(string_);
7212 }
7213
7214 uint32_t Hash() { return string_->Hash(); }
7215
7216 uint32_t HashForObject(Object* other) {
7217 return String::cast(other)->Hash();
7218 }
7219
7220 Object* AsObject() {
Leon Clarkef7060e22010-06-03 12:02:55 +01007221 // Attempt to flatten the string, so that symbols will most often
7222 // be flat strings.
7223 string_ = string_->TryFlattenGetString();
Steve Blocka7e24c12009-10-30 11:49:00 +00007224 // Transform string to symbol if possible.
7225 Map* map = Heap::SymbolMapForString(string_);
7226 if (map != NULL) {
7227 string_->set_map(map);
7228 ASSERT(string_->IsSymbol());
7229 return string_;
7230 }
7231 // Otherwise allocate a new symbol.
7232 StringInputBuffer buffer(string_);
7233 return Heap::AllocateInternalSymbol(&buffer,
7234 string_->length(),
Steve Blockd0582a62009-12-15 09:54:21 +00007235 string_->hash_field());
Steve Blocka7e24c12009-10-30 11:49:00 +00007236 }
7237
7238 static uint32_t StringHash(Object* obj) {
7239 return String::cast(obj)->Hash();
7240 }
7241
7242 String* string_;
7243};
7244
7245
7246template<typename Shape, typename Key>
7247void HashTable<Shape, Key>::IteratePrefix(ObjectVisitor* v) {
7248 IteratePointers(v, 0, kElementsStartOffset);
7249}
7250
7251
7252template<typename Shape, typename Key>
7253void HashTable<Shape, Key>::IterateElements(ObjectVisitor* v) {
7254 IteratePointers(v,
7255 kElementsStartOffset,
7256 kHeaderSize + length() * kPointerSize);
7257}
7258
7259
7260template<typename Shape, typename Key>
Steve Block6ded16b2010-05-10 14:33:55 +01007261Object* HashTable<Shape, Key>::Allocate(int at_least_space_for,
7262 PretenureFlag pretenure) {
7263 const int kMinCapacity = 32;
7264 int capacity = RoundUpToPowerOf2(at_least_space_for * 2);
7265 if (capacity < kMinCapacity) {
7266 capacity = kMinCapacity; // Guarantee min capacity.
Leon Clarkee46be812010-01-19 14:06:41 +00007267 } else if (capacity > HashTable::kMaxCapacity) {
7268 return Failure::OutOfMemoryException();
7269 }
7270
Steve Block6ded16b2010-05-10 14:33:55 +01007271 Object* obj = Heap::AllocateHashTable(EntryToIndex(capacity), pretenure);
Steve Blocka7e24c12009-10-30 11:49:00 +00007272 if (!obj->IsFailure()) {
7273 HashTable::cast(obj)->SetNumberOfElements(0);
Leon Clarkee46be812010-01-19 14:06:41 +00007274 HashTable::cast(obj)->SetNumberOfDeletedElements(0);
Steve Blocka7e24c12009-10-30 11:49:00 +00007275 HashTable::cast(obj)->SetCapacity(capacity);
7276 }
7277 return obj;
7278}
7279
7280
Leon Clarkee46be812010-01-19 14:06:41 +00007281// Find entry for key otherwise return kNotFound.
Steve Blocka7e24c12009-10-30 11:49:00 +00007282template<typename Shape, typename Key>
7283int HashTable<Shape, Key>::FindEntry(Key key) {
Steve Blocka7e24c12009-10-30 11:49:00 +00007284 uint32_t capacity = Capacity();
Leon Clarkee46be812010-01-19 14:06:41 +00007285 uint32_t entry = FirstProbe(Shape::Hash(key), capacity);
7286 uint32_t count = 1;
7287 // EnsureCapacity will guarantee the hash table is never full.
7288 while (true) {
7289 Object* element = KeyAt(entry);
7290 if (element->IsUndefined()) break; // Empty entry.
7291 if (!element->IsNull() && Shape::IsMatch(key, element)) return entry;
7292 entry = NextProbe(entry, count++, capacity);
Steve Blocka7e24c12009-10-30 11:49:00 +00007293 }
7294 return kNotFound;
7295}
7296
7297
7298template<typename Shape, typename Key>
7299Object* HashTable<Shape, Key>::EnsureCapacity(int n, Key key) {
7300 int capacity = Capacity();
7301 int nof = NumberOfElements() + n;
Leon Clarkee46be812010-01-19 14:06:41 +00007302 int nod = NumberOfDeletedElements();
7303 // Return if:
7304 // 50% is still free after adding n elements and
7305 // at most 50% of the free elements are deleted elements.
Steve Block6ded16b2010-05-10 14:33:55 +01007306 if (nod <= (capacity - nof) >> 1) {
7307 int needed_free = nof >> 1;
7308 if (nof + needed_free <= capacity) return this;
7309 }
Steve Blocka7e24c12009-10-30 11:49:00 +00007310
Steve Block6ded16b2010-05-10 14:33:55 +01007311 const int kMinCapacityForPretenure = 256;
7312 bool pretenure =
7313 (capacity > kMinCapacityForPretenure) && !Heap::InNewSpace(this);
7314 Object* obj = Allocate(nof * 2, pretenure ? TENURED : NOT_TENURED);
Steve Blocka7e24c12009-10-30 11:49:00 +00007315 if (obj->IsFailure()) return obj;
Leon Clarke4515c472010-02-03 11:58:03 +00007316
7317 AssertNoAllocation no_gc;
Steve Blocka7e24c12009-10-30 11:49:00 +00007318 HashTable* table = HashTable::cast(obj);
Leon Clarke4515c472010-02-03 11:58:03 +00007319 WriteBarrierMode mode = table->GetWriteBarrierMode(no_gc);
Steve Blocka7e24c12009-10-30 11:49:00 +00007320
7321 // Copy prefix to new array.
7322 for (int i = kPrefixStartIndex;
7323 i < kPrefixStartIndex + Shape::kPrefixSize;
7324 i++) {
7325 table->set(i, get(i), mode);
7326 }
7327 // Rehash the elements.
7328 for (int i = 0; i < capacity; i++) {
7329 uint32_t from_index = EntryToIndex(i);
7330 Object* k = get(from_index);
7331 if (IsKey(k)) {
7332 uint32_t hash = Shape::HashForObject(key, k);
7333 uint32_t insertion_index =
7334 EntryToIndex(table->FindInsertionEntry(hash));
7335 for (int j = 0; j < Shape::kEntrySize; j++) {
7336 table->set(insertion_index + j, get(from_index + j), mode);
7337 }
7338 }
7339 }
7340 table->SetNumberOfElements(NumberOfElements());
Leon Clarkee46be812010-01-19 14:06:41 +00007341 table->SetNumberOfDeletedElements(0);
Steve Blocka7e24c12009-10-30 11:49:00 +00007342 return table;
7343}
7344
7345
7346template<typename Shape, typename Key>
7347uint32_t HashTable<Shape, Key>::FindInsertionEntry(uint32_t hash) {
7348 uint32_t capacity = Capacity();
Leon Clarkee46be812010-01-19 14:06:41 +00007349 uint32_t entry = FirstProbe(hash, capacity);
7350 uint32_t count = 1;
7351 // EnsureCapacity will guarantee the hash table is never full.
7352 while (true) {
7353 Object* element = KeyAt(entry);
7354 if (element->IsUndefined() || element->IsNull()) break;
7355 entry = NextProbe(entry, count++, capacity);
Steve Blocka7e24c12009-10-30 11:49:00 +00007356 }
Steve Blocka7e24c12009-10-30 11:49:00 +00007357 return entry;
7358}
7359
7360// Force instantiation of template instances class.
7361// Please note this list is compiler dependent.
7362
7363template class HashTable<SymbolTableShape, HashTableKey*>;
7364
7365template class HashTable<CompilationCacheShape, HashTableKey*>;
7366
7367template class HashTable<MapCacheShape, HashTableKey*>;
7368
7369template class Dictionary<StringDictionaryShape, String*>;
7370
7371template class Dictionary<NumberDictionaryShape, uint32_t>;
7372
7373template Object* Dictionary<NumberDictionaryShape, uint32_t>::Allocate(
7374 int);
7375
7376template Object* Dictionary<StringDictionaryShape, String*>::Allocate(
7377 int);
7378
7379template Object* Dictionary<NumberDictionaryShape, uint32_t>::AtPut(
7380 uint32_t, Object*);
7381
7382template Object* Dictionary<NumberDictionaryShape, uint32_t>::SlowReverseLookup(
7383 Object*);
7384
7385template Object* Dictionary<StringDictionaryShape, String*>::SlowReverseLookup(
7386 Object*);
7387
7388template void Dictionary<NumberDictionaryShape, uint32_t>::CopyKeysTo(
7389 FixedArray*, PropertyAttributes);
7390
7391template Object* Dictionary<StringDictionaryShape, String*>::DeleteProperty(
7392 int, JSObject::DeleteMode);
7393
7394template Object* Dictionary<NumberDictionaryShape, uint32_t>::DeleteProperty(
7395 int, JSObject::DeleteMode);
7396
7397template void Dictionary<StringDictionaryShape, String*>::CopyKeysTo(
7398 FixedArray*);
7399
7400template int
7401Dictionary<StringDictionaryShape, String*>::NumberOfElementsFilterAttributes(
7402 PropertyAttributes);
7403
7404template Object* Dictionary<StringDictionaryShape, String*>::Add(
7405 String*, Object*, PropertyDetails);
7406
7407template Object*
7408Dictionary<StringDictionaryShape, String*>::GenerateNewEnumerationIndices();
7409
7410template int
7411Dictionary<NumberDictionaryShape, uint32_t>::NumberOfElementsFilterAttributes(
7412 PropertyAttributes);
7413
7414template Object* Dictionary<NumberDictionaryShape, uint32_t>::Add(
7415 uint32_t, Object*, PropertyDetails);
7416
7417template Object* Dictionary<NumberDictionaryShape, uint32_t>::EnsureCapacity(
7418 int, uint32_t);
7419
7420template Object* Dictionary<StringDictionaryShape, String*>::EnsureCapacity(
7421 int, String*);
7422
7423template Object* Dictionary<NumberDictionaryShape, uint32_t>::AddEntry(
7424 uint32_t, Object*, PropertyDetails, uint32_t);
7425
7426template Object* Dictionary<StringDictionaryShape, String*>::AddEntry(
7427 String*, Object*, PropertyDetails, uint32_t);
7428
7429template
7430int Dictionary<NumberDictionaryShape, uint32_t>::NumberOfEnumElements();
7431
7432template
7433int Dictionary<StringDictionaryShape, String*>::NumberOfEnumElements();
7434
Leon Clarkee46be812010-01-19 14:06:41 +00007435template
7436int HashTable<NumberDictionaryShape, uint32_t>::FindEntry(uint32_t);
7437
7438
Steve Blocka7e24c12009-10-30 11:49:00 +00007439// Collates undefined and unexisting elements below limit from position
7440// zero of the elements. The object stays in Dictionary mode.
7441Object* JSObject::PrepareSlowElementsForSort(uint32_t limit) {
7442 ASSERT(HasDictionaryElements());
7443 // Must stay in dictionary mode, either because of requires_slow_elements,
7444 // or because we are not going to sort (and therefore compact) all of the
7445 // elements.
7446 NumberDictionary* dict = element_dictionary();
7447 HeapNumber* result_double = NULL;
7448 if (limit > static_cast<uint32_t>(Smi::kMaxValue)) {
7449 // Allocate space for result before we start mutating the object.
7450 Object* new_double = Heap::AllocateHeapNumber(0.0);
7451 if (new_double->IsFailure()) return new_double;
7452 result_double = HeapNumber::cast(new_double);
7453 }
7454
Steve Block6ded16b2010-05-10 14:33:55 +01007455 Object* obj = NumberDictionary::Allocate(dict->NumberOfElements());
Steve Blocka7e24c12009-10-30 11:49:00 +00007456 if (obj->IsFailure()) return obj;
7457 NumberDictionary* new_dict = NumberDictionary::cast(obj);
7458
7459 AssertNoAllocation no_alloc;
7460
7461 uint32_t pos = 0;
7462 uint32_t undefs = 0;
Steve Block6ded16b2010-05-10 14:33:55 +01007463 int capacity = dict->Capacity();
Steve Blocka7e24c12009-10-30 11:49:00 +00007464 for (int i = 0; i < capacity; i++) {
7465 Object* k = dict->KeyAt(i);
7466 if (dict->IsKey(k)) {
7467 ASSERT(k->IsNumber());
7468 ASSERT(!k->IsSmi() || Smi::cast(k)->value() >= 0);
7469 ASSERT(!k->IsHeapNumber() || HeapNumber::cast(k)->value() >= 0);
7470 ASSERT(!k->IsHeapNumber() || HeapNumber::cast(k)->value() <= kMaxUInt32);
7471 Object* value = dict->ValueAt(i);
7472 PropertyDetails details = dict->DetailsAt(i);
7473 if (details.type() == CALLBACKS) {
7474 // Bail out and do the sorting of undefineds and array holes in JS.
7475 return Smi::FromInt(-1);
7476 }
7477 uint32_t key = NumberToUint32(k);
7478 if (key < limit) {
7479 if (value->IsUndefined()) {
7480 undefs++;
7481 } else {
7482 new_dict->AddNumberEntry(pos, value, details);
7483 pos++;
7484 }
7485 } else {
7486 new_dict->AddNumberEntry(key, value, details);
7487 }
7488 }
7489 }
7490
7491 uint32_t result = pos;
7492 PropertyDetails no_details = PropertyDetails(NONE, NORMAL);
7493 while (undefs > 0) {
7494 new_dict->AddNumberEntry(pos, Heap::undefined_value(), no_details);
7495 pos++;
7496 undefs--;
7497 }
7498
7499 set_elements(new_dict);
7500
7501 if (result <= static_cast<uint32_t>(Smi::kMaxValue)) {
7502 return Smi::FromInt(static_cast<int>(result));
7503 }
7504
7505 ASSERT_NE(NULL, result_double);
7506 result_double->set_value(static_cast<double>(result));
7507 return result_double;
7508}
7509
7510
7511// Collects all defined (non-hole) and non-undefined (array) elements at
7512// the start of the elements array.
7513// If the object is in dictionary mode, it is converted to fast elements
7514// mode.
7515Object* JSObject::PrepareElementsForSort(uint32_t limit) {
Steve Block3ce2e202009-11-05 08:53:23 +00007516 ASSERT(!HasPixelElements() && !HasExternalArrayElements());
Steve Blocka7e24c12009-10-30 11:49:00 +00007517
7518 if (HasDictionaryElements()) {
7519 // Convert to fast elements containing only the existing properties.
7520 // Ordering is irrelevant, since we are going to sort anyway.
7521 NumberDictionary* dict = element_dictionary();
7522 if (IsJSArray() || dict->requires_slow_elements() ||
7523 dict->max_number_key() >= limit) {
7524 return PrepareSlowElementsForSort(limit);
7525 }
7526 // Convert to fast elements.
7527
7528 PretenureFlag tenure = Heap::InNewSpace(this) ? NOT_TENURED: TENURED;
7529 Object* new_array =
7530 Heap::AllocateFixedArray(dict->NumberOfElements(), tenure);
7531 if (new_array->IsFailure()) {
7532 return new_array;
7533 }
7534 FixedArray* fast_elements = FixedArray::cast(new_array);
7535 dict->CopyValuesTo(fast_elements);
7536 set_elements(fast_elements);
7537 }
7538 ASSERT(HasFastElements());
7539
7540 // Collect holes at the end, undefined before that and the rest at the
7541 // start, and return the number of non-hole, non-undefined values.
7542
7543 FixedArray* elements = FixedArray::cast(this->elements());
7544 uint32_t elements_length = static_cast<uint32_t>(elements->length());
7545 if (limit > elements_length) {
7546 limit = elements_length ;
7547 }
7548 if (limit == 0) {
7549 return Smi::FromInt(0);
7550 }
7551
7552 HeapNumber* result_double = NULL;
7553 if (limit > static_cast<uint32_t>(Smi::kMaxValue)) {
7554 // Pessimistically allocate space for return value before
7555 // we start mutating the array.
7556 Object* new_double = Heap::AllocateHeapNumber(0.0);
7557 if (new_double->IsFailure()) return new_double;
7558 result_double = HeapNumber::cast(new_double);
7559 }
7560
7561 AssertNoAllocation no_alloc;
7562
7563 // Split elements into defined, undefined and the_hole, in that order.
7564 // Only count locations for undefined and the hole, and fill them afterwards.
Leon Clarke4515c472010-02-03 11:58:03 +00007565 WriteBarrierMode write_barrier = elements->GetWriteBarrierMode(no_alloc);
Steve Blocka7e24c12009-10-30 11:49:00 +00007566 unsigned int undefs = limit;
7567 unsigned int holes = limit;
7568 // Assume most arrays contain no holes and undefined values, so minimize the
7569 // number of stores of non-undefined, non-the-hole values.
7570 for (unsigned int i = 0; i < undefs; i++) {
7571 Object* current = elements->get(i);
7572 if (current->IsTheHole()) {
7573 holes--;
7574 undefs--;
7575 } else if (current->IsUndefined()) {
7576 undefs--;
7577 } else {
7578 continue;
7579 }
7580 // Position i needs to be filled.
7581 while (undefs > i) {
7582 current = elements->get(undefs);
7583 if (current->IsTheHole()) {
7584 holes--;
7585 undefs--;
7586 } else if (current->IsUndefined()) {
7587 undefs--;
7588 } else {
7589 elements->set(i, current, write_barrier);
7590 break;
7591 }
7592 }
7593 }
7594 uint32_t result = undefs;
7595 while (undefs < holes) {
7596 elements->set_undefined(undefs);
7597 undefs++;
7598 }
7599 while (holes < limit) {
7600 elements->set_the_hole(holes);
7601 holes++;
7602 }
7603
7604 if (result <= static_cast<uint32_t>(Smi::kMaxValue)) {
7605 return Smi::FromInt(static_cast<int>(result));
7606 }
7607 ASSERT_NE(NULL, result_double);
7608 result_double->set_value(static_cast<double>(result));
7609 return result_double;
7610}
7611
7612
7613Object* PixelArray::SetValue(uint32_t index, Object* value) {
7614 uint8_t clamped_value = 0;
7615 if (index < static_cast<uint32_t>(length())) {
7616 if (value->IsSmi()) {
7617 int int_value = Smi::cast(value)->value();
7618 if (int_value < 0) {
7619 clamped_value = 0;
7620 } else if (int_value > 255) {
7621 clamped_value = 255;
7622 } else {
7623 clamped_value = static_cast<uint8_t>(int_value);
7624 }
7625 } else if (value->IsHeapNumber()) {
7626 double double_value = HeapNumber::cast(value)->value();
7627 if (!(double_value > 0)) {
7628 // NaN and less than zero clamp to zero.
7629 clamped_value = 0;
7630 } else if (double_value > 255) {
7631 // Greater than 255 clamp to 255.
7632 clamped_value = 255;
7633 } else {
7634 // Other doubles are rounded to the nearest integer.
7635 clamped_value = static_cast<uint8_t>(double_value + 0.5);
7636 }
7637 } else {
7638 // Clamp undefined to zero (default). All other types have been
7639 // converted to a number type further up in the call chain.
7640 ASSERT(value->IsUndefined());
7641 }
7642 set(index, clamped_value);
7643 }
7644 return Smi::FromInt(clamped_value);
7645}
7646
7647
Steve Block3ce2e202009-11-05 08:53:23 +00007648template<typename ExternalArrayClass, typename ValueType>
7649static Object* ExternalArrayIntSetter(ExternalArrayClass* receiver,
7650 uint32_t index,
7651 Object* value) {
7652 ValueType cast_value = 0;
7653 if (index < static_cast<uint32_t>(receiver->length())) {
7654 if (value->IsSmi()) {
7655 int int_value = Smi::cast(value)->value();
7656 cast_value = static_cast<ValueType>(int_value);
7657 } else if (value->IsHeapNumber()) {
7658 double double_value = HeapNumber::cast(value)->value();
7659 cast_value = static_cast<ValueType>(DoubleToInt32(double_value));
7660 } else {
7661 // Clamp undefined to zero (default). All other types have been
7662 // converted to a number type further up in the call chain.
7663 ASSERT(value->IsUndefined());
7664 }
7665 receiver->set(index, cast_value);
7666 }
7667 return Heap::NumberFromInt32(cast_value);
7668}
7669
7670
7671Object* ExternalByteArray::SetValue(uint32_t index, Object* value) {
7672 return ExternalArrayIntSetter<ExternalByteArray, int8_t>
7673 (this, index, value);
7674}
7675
7676
7677Object* ExternalUnsignedByteArray::SetValue(uint32_t index, Object* value) {
7678 return ExternalArrayIntSetter<ExternalUnsignedByteArray, uint8_t>
7679 (this, index, value);
7680}
7681
7682
7683Object* ExternalShortArray::SetValue(uint32_t index, Object* value) {
7684 return ExternalArrayIntSetter<ExternalShortArray, int16_t>
7685 (this, index, value);
7686}
7687
7688
7689Object* ExternalUnsignedShortArray::SetValue(uint32_t index, Object* value) {
7690 return ExternalArrayIntSetter<ExternalUnsignedShortArray, uint16_t>
7691 (this, index, value);
7692}
7693
7694
7695Object* ExternalIntArray::SetValue(uint32_t index, Object* value) {
7696 return ExternalArrayIntSetter<ExternalIntArray, int32_t>
7697 (this, index, value);
7698}
7699
7700
7701Object* ExternalUnsignedIntArray::SetValue(uint32_t index, Object* value) {
7702 uint32_t cast_value = 0;
7703 if (index < static_cast<uint32_t>(length())) {
7704 if (value->IsSmi()) {
7705 int int_value = Smi::cast(value)->value();
7706 cast_value = static_cast<uint32_t>(int_value);
7707 } else if (value->IsHeapNumber()) {
7708 double double_value = HeapNumber::cast(value)->value();
7709 cast_value = static_cast<uint32_t>(DoubleToUint32(double_value));
7710 } else {
7711 // Clamp undefined to zero (default). All other types have been
7712 // converted to a number type further up in the call chain.
7713 ASSERT(value->IsUndefined());
7714 }
7715 set(index, cast_value);
7716 }
7717 return Heap::NumberFromUint32(cast_value);
7718}
7719
7720
7721Object* ExternalFloatArray::SetValue(uint32_t index, Object* value) {
7722 float cast_value = 0;
7723 if (index < static_cast<uint32_t>(length())) {
7724 if (value->IsSmi()) {
7725 int int_value = Smi::cast(value)->value();
7726 cast_value = static_cast<float>(int_value);
7727 } else if (value->IsHeapNumber()) {
7728 double double_value = HeapNumber::cast(value)->value();
7729 cast_value = static_cast<float>(double_value);
7730 } else {
7731 // Clamp undefined to zero (default). All other types have been
7732 // converted to a number type further up in the call chain.
7733 ASSERT(value->IsUndefined());
7734 }
7735 set(index, cast_value);
7736 }
7737 return Heap::AllocateHeapNumber(cast_value);
7738}
7739
7740
Steve Blocka7e24c12009-10-30 11:49:00 +00007741Object* GlobalObject::GetPropertyCell(LookupResult* result) {
7742 ASSERT(!HasFastProperties());
7743 Object* value = property_dictionary()->ValueAt(result->GetDictionaryEntry());
7744 ASSERT(value->IsJSGlobalPropertyCell());
7745 return value;
7746}
7747
7748
7749Object* GlobalObject::EnsurePropertyCell(String* name) {
7750 ASSERT(!HasFastProperties());
7751 int entry = property_dictionary()->FindEntry(name);
7752 if (entry == StringDictionary::kNotFound) {
7753 Object* cell = Heap::AllocateJSGlobalPropertyCell(Heap::the_hole_value());
7754 if (cell->IsFailure()) return cell;
7755 PropertyDetails details(NONE, NORMAL);
7756 details = details.AsDeleted();
7757 Object* dictionary = property_dictionary()->Add(name, cell, details);
7758 if (dictionary->IsFailure()) return dictionary;
7759 set_properties(StringDictionary::cast(dictionary));
7760 return cell;
7761 } else {
7762 Object* value = property_dictionary()->ValueAt(entry);
7763 ASSERT(value->IsJSGlobalPropertyCell());
7764 return value;
7765 }
7766}
7767
7768
7769Object* SymbolTable::LookupString(String* string, Object** s) {
7770 SymbolKey key(string);
7771 return LookupKey(&key, s);
7772}
7773
7774
Steve Blockd0582a62009-12-15 09:54:21 +00007775// This class is used for looking up two character strings in the symbol table.
7776// If we don't have a hit we don't want to waste much time so we unroll the
7777// string hash calculation loop here for speed. Doesn't work if the two
7778// characters form a decimal integer, since such strings have a different hash
7779// algorithm.
7780class TwoCharHashTableKey : public HashTableKey {
7781 public:
7782 TwoCharHashTableKey(uint32_t c1, uint32_t c2)
7783 : c1_(c1), c2_(c2) {
7784 // Char 1.
7785 uint32_t hash = c1 + (c1 << 10);
7786 hash ^= hash >> 6;
7787 // Char 2.
7788 hash += c2;
7789 hash += hash << 10;
7790 hash ^= hash >> 6;
7791 // GetHash.
7792 hash += hash << 3;
7793 hash ^= hash >> 11;
7794 hash += hash << 15;
7795 if (hash == 0) hash = 27;
7796#ifdef DEBUG
7797 StringHasher hasher(2);
7798 hasher.AddCharacter(c1);
7799 hasher.AddCharacter(c2);
7800 // If this assert fails then we failed to reproduce the two-character
7801 // version of the string hashing algorithm above. One reason could be
7802 // that we were passed two digits as characters, since the hash
7803 // algorithm is different in that case.
7804 ASSERT_EQ(static_cast<int>(hasher.GetHash()), static_cast<int>(hash));
7805#endif
7806 hash_ = hash;
7807 }
7808
7809 bool IsMatch(Object* o) {
7810 if (!o->IsString()) return false;
7811 String* other = String::cast(o);
7812 if (other->length() != 2) return false;
7813 if (other->Get(0) != c1_) return false;
7814 return other->Get(1) == c2_;
7815 }
7816
7817 uint32_t Hash() { return hash_; }
7818 uint32_t HashForObject(Object* key) {
7819 if (!key->IsString()) return 0;
7820 return String::cast(key)->Hash();
7821 }
7822
7823 Object* AsObject() {
7824 // The TwoCharHashTableKey is only used for looking in the symbol
7825 // table, not for adding to it.
7826 UNREACHABLE();
7827 return NULL;
7828 }
7829 private:
7830 uint32_t c1_;
7831 uint32_t c2_;
7832 uint32_t hash_;
7833};
7834
7835
Steve Blocka7e24c12009-10-30 11:49:00 +00007836bool SymbolTable::LookupSymbolIfExists(String* string, String** symbol) {
7837 SymbolKey key(string);
7838 int entry = FindEntry(&key);
7839 if (entry == kNotFound) {
7840 return false;
7841 } else {
7842 String* result = String::cast(KeyAt(entry));
7843 ASSERT(StringShape(result).IsSymbol());
7844 *symbol = result;
7845 return true;
7846 }
7847}
7848
7849
Steve Blockd0582a62009-12-15 09:54:21 +00007850bool SymbolTable::LookupTwoCharsSymbolIfExists(uint32_t c1,
7851 uint32_t c2,
7852 String** symbol) {
7853 TwoCharHashTableKey key(c1, c2);
7854 int entry = FindEntry(&key);
7855 if (entry == kNotFound) {
7856 return false;
7857 } else {
7858 String* result = String::cast(KeyAt(entry));
7859 ASSERT(StringShape(result).IsSymbol());
7860 *symbol = result;
7861 return true;
7862 }
7863}
7864
7865
Steve Blocka7e24c12009-10-30 11:49:00 +00007866Object* SymbolTable::LookupSymbol(Vector<const char> str, Object** s) {
7867 Utf8SymbolKey key(str);
7868 return LookupKey(&key, s);
7869}
7870
7871
7872Object* SymbolTable::LookupKey(HashTableKey* key, Object** s) {
7873 int entry = FindEntry(key);
7874
7875 // Symbol already in table.
7876 if (entry != kNotFound) {
7877 *s = KeyAt(entry);
7878 return this;
7879 }
7880
7881 // Adding new symbol. Grow table if needed.
7882 Object* obj = EnsureCapacity(1, key);
7883 if (obj->IsFailure()) return obj;
7884
7885 // Create symbol object.
7886 Object* symbol = key->AsObject();
7887 if (symbol->IsFailure()) return symbol;
7888
7889 // If the symbol table grew as part of EnsureCapacity, obj is not
7890 // the current symbol table and therefore we cannot use
7891 // SymbolTable::cast here.
7892 SymbolTable* table = reinterpret_cast<SymbolTable*>(obj);
7893
7894 // Add the new symbol and return it along with the symbol table.
7895 entry = table->FindInsertionEntry(key->Hash());
7896 table->set(EntryToIndex(entry), symbol);
7897 table->ElementAdded();
7898 *s = symbol;
7899 return table;
7900}
7901
7902
7903Object* CompilationCacheTable::Lookup(String* src) {
7904 StringKey key(src);
7905 int entry = FindEntry(&key);
7906 if (entry == kNotFound) return Heap::undefined_value();
7907 return get(EntryToIndex(entry) + 1);
7908}
7909
7910
7911Object* CompilationCacheTable::LookupEval(String* src, Context* context) {
7912 StringSharedKey key(src, context->closure()->shared());
7913 int entry = FindEntry(&key);
7914 if (entry == kNotFound) return Heap::undefined_value();
7915 return get(EntryToIndex(entry) + 1);
7916}
7917
7918
7919Object* CompilationCacheTable::LookupRegExp(String* src,
7920 JSRegExp::Flags flags) {
7921 RegExpKey key(src, flags);
7922 int entry = FindEntry(&key);
7923 if (entry == kNotFound) return Heap::undefined_value();
7924 return get(EntryToIndex(entry) + 1);
7925}
7926
7927
7928Object* CompilationCacheTable::Put(String* src, Object* value) {
7929 StringKey key(src);
7930 Object* obj = EnsureCapacity(1, &key);
7931 if (obj->IsFailure()) return obj;
7932
7933 CompilationCacheTable* cache =
7934 reinterpret_cast<CompilationCacheTable*>(obj);
7935 int entry = cache->FindInsertionEntry(key.Hash());
7936 cache->set(EntryToIndex(entry), src);
7937 cache->set(EntryToIndex(entry) + 1, value);
7938 cache->ElementAdded();
7939 return cache;
7940}
7941
7942
7943Object* CompilationCacheTable::PutEval(String* src,
7944 Context* context,
7945 Object* value) {
7946 StringSharedKey key(src, context->closure()->shared());
7947 Object* obj = EnsureCapacity(1, &key);
7948 if (obj->IsFailure()) return obj;
7949
7950 CompilationCacheTable* cache =
7951 reinterpret_cast<CompilationCacheTable*>(obj);
7952 int entry = cache->FindInsertionEntry(key.Hash());
7953
7954 Object* k = key.AsObject();
7955 if (k->IsFailure()) return k;
7956
7957 cache->set(EntryToIndex(entry), k);
7958 cache->set(EntryToIndex(entry) + 1, value);
7959 cache->ElementAdded();
7960 return cache;
7961}
7962
7963
7964Object* CompilationCacheTable::PutRegExp(String* src,
7965 JSRegExp::Flags flags,
7966 FixedArray* value) {
7967 RegExpKey key(src, flags);
7968 Object* obj = EnsureCapacity(1, &key);
7969 if (obj->IsFailure()) return obj;
7970
7971 CompilationCacheTable* cache =
7972 reinterpret_cast<CompilationCacheTable*>(obj);
7973 int entry = cache->FindInsertionEntry(key.Hash());
Steve Block3ce2e202009-11-05 08:53:23 +00007974 // We store the value in the key slot, and compare the search key
7975 // to the stored value with a custon IsMatch function during lookups.
Steve Blocka7e24c12009-10-30 11:49:00 +00007976 cache->set(EntryToIndex(entry), value);
7977 cache->set(EntryToIndex(entry) + 1, value);
7978 cache->ElementAdded();
7979 return cache;
7980}
7981
7982
7983// SymbolsKey used for HashTable where key is array of symbols.
7984class SymbolsKey : public HashTableKey {
7985 public:
7986 explicit SymbolsKey(FixedArray* symbols) : symbols_(symbols) { }
7987
7988 bool IsMatch(Object* symbols) {
7989 FixedArray* o = FixedArray::cast(symbols);
7990 int len = symbols_->length();
7991 if (o->length() != len) return false;
7992 for (int i = 0; i < len; i++) {
7993 if (o->get(i) != symbols_->get(i)) return false;
7994 }
7995 return true;
7996 }
7997
7998 uint32_t Hash() { return HashForObject(symbols_); }
7999
8000 uint32_t HashForObject(Object* obj) {
8001 FixedArray* symbols = FixedArray::cast(obj);
8002 int len = symbols->length();
8003 uint32_t hash = 0;
8004 for (int i = 0; i < len; i++) {
8005 hash ^= String::cast(symbols->get(i))->Hash();
8006 }
8007 return hash;
8008 }
8009
8010 Object* AsObject() { return symbols_; }
8011
8012 private:
8013 FixedArray* symbols_;
8014};
8015
8016
8017Object* MapCache::Lookup(FixedArray* array) {
8018 SymbolsKey key(array);
8019 int entry = FindEntry(&key);
8020 if (entry == kNotFound) return Heap::undefined_value();
8021 return get(EntryToIndex(entry) + 1);
8022}
8023
8024
8025Object* MapCache::Put(FixedArray* array, Map* value) {
8026 SymbolsKey key(array);
8027 Object* obj = EnsureCapacity(1, &key);
8028 if (obj->IsFailure()) return obj;
8029
8030 MapCache* cache = reinterpret_cast<MapCache*>(obj);
8031 int entry = cache->FindInsertionEntry(key.Hash());
8032 cache->set(EntryToIndex(entry), array);
8033 cache->set(EntryToIndex(entry) + 1, value);
8034 cache->ElementAdded();
8035 return cache;
8036}
8037
8038
8039template<typename Shape, typename Key>
8040Object* Dictionary<Shape, Key>::Allocate(int at_least_space_for) {
8041 Object* obj = HashTable<Shape, Key>::Allocate(at_least_space_for);
8042 // Initialize the next enumeration index.
8043 if (!obj->IsFailure()) {
8044 Dictionary<Shape, Key>::cast(obj)->
8045 SetNextEnumerationIndex(PropertyDetails::kInitialIndex);
8046 }
8047 return obj;
8048}
8049
8050
8051template<typename Shape, typename Key>
8052Object* Dictionary<Shape, Key>::GenerateNewEnumerationIndices() {
8053 int length = HashTable<Shape, Key>::NumberOfElements();
8054
8055 // Allocate and initialize iteration order array.
8056 Object* obj = Heap::AllocateFixedArray(length);
8057 if (obj->IsFailure()) return obj;
8058 FixedArray* iteration_order = FixedArray::cast(obj);
8059 for (int i = 0; i < length; i++) {
Leon Clarke4515c472010-02-03 11:58:03 +00008060 iteration_order->set(i, Smi::FromInt(i));
Steve Blocka7e24c12009-10-30 11:49:00 +00008061 }
8062
8063 // Allocate array with enumeration order.
8064 obj = Heap::AllocateFixedArray(length);
8065 if (obj->IsFailure()) return obj;
8066 FixedArray* enumeration_order = FixedArray::cast(obj);
8067
8068 // Fill the enumeration order array with property details.
8069 int capacity = HashTable<Shape, Key>::Capacity();
8070 int pos = 0;
8071 for (int i = 0; i < capacity; i++) {
8072 if (Dictionary<Shape, Key>::IsKey(Dictionary<Shape, Key>::KeyAt(i))) {
Leon Clarke4515c472010-02-03 11:58:03 +00008073 enumeration_order->set(pos++, Smi::FromInt(DetailsAt(i).index()));
Steve Blocka7e24c12009-10-30 11:49:00 +00008074 }
8075 }
8076
8077 // Sort the arrays wrt. enumeration order.
8078 iteration_order->SortPairs(enumeration_order, enumeration_order->length());
8079
8080 // Overwrite the enumeration_order with the enumeration indices.
8081 for (int i = 0; i < length; i++) {
8082 int index = Smi::cast(iteration_order->get(i))->value();
8083 int enum_index = PropertyDetails::kInitialIndex + i;
Leon Clarke4515c472010-02-03 11:58:03 +00008084 enumeration_order->set(index, Smi::FromInt(enum_index));
Steve Blocka7e24c12009-10-30 11:49:00 +00008085 }
8086
8087 // Update the dictionary with new indices.
8088 capacity = HashTable<Shape, Key>::Capacity();
8089 pos = 0;
8090 for (int i = 0; i < capacity; i++) {
8091 if (Dictionary<Shape, Key>::IsKey(Dictionary<Shape, Key>::KeyAt(i))) {
8092 int enum_index = Smi::cast(enumeration_order->get(pos++))->value();
8093 PropertyDetails details = DetailsAt(i);
8094 PropertyDetails new_details =
8095 PropertyDetails(details.attributes(), details.type(), enum_index);
8096 DetailsAtPut(i, new_details);
8097 }
8098 }
8099
8100 // Set the next enumeration index.
8101 SetNextEnumerationIndex(PropertyDetails::kInitialIndex+length);
8102 return this;
8103}
8104
8105template<typename Shape, typename Key>
8106Object* Dictionary<Shape, Key>::EnsureCapacity(int n, Key key) {
8107 // Check whether there are enough enumeration indices to add n elements.
8108 if (Shape::kIsEnumerable &&
8109 !PropertyDetails::IsValidIndex(NextEnumerationIndex() + n)) {
8110 // If not, we generate new indices for the properties.
8111 Object* result = GenerateNewEnumerationIndices();
8112 if (result->IsFailure()) return result;
8113 }
8114 return HashTable<Shape, Key>::EnsureCapacity(n, key);
8115}
8116
8117
8118void NumberDictionary::RemoveNumberEntries(uint32_t from, uint32_t to) {
8119 // Do nothing if the interval [from, to) is empty.
8120 if (from >= to) return;
8121
8122 int removed_entries = 0;
8123 Object* sentinel = Heap::null_value();
8124 int capacity = Capacity();
8125 for (int i = 0; i < capacity; i++) {
8126 Object* key = KeyAt(i);
8127 if (key->IsNumber()) {
8128 uint32_t number = static_cast<uint32_t>(key->Number());
8129 if (from <= number && number < to) {
8130 SetEntry(i, sentinel, sentinel, Smi::FromInt(0));
8131 removed_entries++;
8132 }
8133 }
8134 }
8135
8136 // Update the number of elements.
Leon Clarkee46be812010-01-19 14:06:41 +00008137 ElementsRemoved(removed_entries);
Steve Blocka7e24c12009-10-30 11:49:00 +00008138}
8139
8140
8141template<typename Shape, typename Key>
8142Object* Dictionary<Shape, Key>::DeleteProperty(int entry,
8143 JSObject::DeleteMode mode) {
8144 PropertyDetails details = DetailsAt(entry);
8145 // Ignore attributes if forcing a deletion.
8146 if (details.IsDontDelete() && mode == JSObject::NORMAL_DELETION) {
8147 return Heap::false_value();
8148 }
8149 SetEntry(entry, Heap::null_value(), Heap::null_value(), Smi::FromInt(0));
8150 HashTable<Shape, Key>::ElementRemoved();
8151 return Heap::true_value();
8152}
8153
8154
8155template<typename Shape, typename Key>
8156Object* Dictionary<Shape, Key>::AtPut(Key key, Object* value) {
8157 int entry = FindEntry(key);
8158
8159 // If the entry is present set the value;
8160 if (entry != Dictionary<Shape, Key>::kNotFound) {
8161 ValueAtPut(entry, value);
8162 return this;
8163 }
8164
8165 // Check whether the dictionary should be extended.
8166 Object* obj = EnsureCapacity(1, key);
8167 if (obj->IsFailure()) return obj;
8168
8169 Object* k = Shape::AsObject(key);
8170 if (k->IsFailure()) return k;
8171 PropertyDetails details = PropertyDetails(NONE, NORMAL);
8172 return Dictionary<Shape, Key>::cast(obj)->
8173 AddEntry(key, value, details, Shape::Hash(key));
8174}
8175
8176
8177template<typename Shape, typename Key>
8178Object* Dictionary<Shape, Key>::Add(Key key,
8179 Object* value,
8180 PropertyDetails details) {
8181 // Valdate key is absent.
8182 SLOW_ASSERT((FindEntry(key) == Dictionary<Shape, Key>::kNotFound));
8183 // Check whether the dictionary should be extended.
8184 Object* obj = EnsureCapacity(1, key);
8185 if (obj->IsFailure()) return obj;
8186 return Dictionary<Shape, Key>::cast(obj)->
8187 AddEntry(key, value, details, Shape::Hash(key));
8188}
8189
8190
8191// Add a key, value pair to the dictionary.
8192template<typename Shape, typename Key>
8193Object* Dictionary<Shape, Key>::AddEntry(Key key,
8194 Object* value,
8195 PropertyDetails details,
8196 uint32_t hash) {
8197 // Compute the key object.
8198 Object* k = Shape::AsObject(key);
8199 if (k->IsFailure()) return k;
8200
8201 uint32_t entry = Dictionary<Shape, Key>::FindInsertionEntry(hash);
8202 // Insert element at empty or deleted entry
8203 if (!details.IsDeleted() && details.index() == 0 && Shape::kIsEnumerable) {
8204 // Assign an enumeration index to the property and update
8205 // SetNextEnumerationIndex.
8206 int index = NextEnumerationIndex();
8207 details = PropertyDetails(details.attributes(), details.type(), index);
8208 SetNextEnumerationIndex(index + 1);
8209 }
8210 SetEntry(entry, k, value, details);
8211 ASSERT((Dictionary<Shape, Key>::KeyAt(entry)->IsNumber()
8212 || Dictionary<Shape, Key>::KeyAt(entry)->IsString()));
8213 HashTable<Shape, Key>::ElementAdded();
8214 return this;
8215}
8216
8217
8218void NumberDictionary::UpdateMaxNumberKey(uint32_t key) {
8219 // If the dictionary requires slow elements an element has already
8220 // been added at a high index.
8221 if (requires_slow_elements()) return;
8222 // Check if this index is high enough that we should require slow
8223 // elements.
8224 if (key > kRequiresSlowElementsLimit) {
8225 set_requires_slow_elements();
8226 return;
8227 }
8228 // Update max key value.
8229 Object* max_index_object = get(kMaxNumberKeyIndex);
8230 if (!max_index_object->IsSmi() || max_number_key() < key) {
8231 FixedArray::set(kMaxNumberKeyIndex,
Leon Clarke4515c472010-02-03 11:58:03 +00008232 Smi::FromInt(key << kRequiresSlowElementsTagSize));
Steve Blocka7e24c12009-10-30 11:49:00 +00008233 }
8234}
8235
8236
8237Object* NumberDictionary::AddNumberEntry(uint32_t key,
8238 Object* value,
8239 PropertyDetails details) {
8240 UpdateMaxNumberKey(key);
8241 SLOW_ASSERT(FindEntry(key) == kNotFound);
8242 return Add(key, value, details);
8243}
8244
8245
8246Object* NumberDictionary::AtNumberPut(uint32_t key, Object* value) {
8247 UpdateMaxNumberKey(key);
8248 return AtPut(key, value);
8249}
8250
8251
8252Object* NumberDictionary::Set(uint32_t key,
8253 Object* value,
8254 PropertyDetails details) {
8255 int entry = FindEntry(key);
8256 if (entry == kNotFound) return AddNumberEntry(key, value, details);
8257 // Preserve enumeration index.
8258 details = PropertyDetails(details.attributes(),
8259 details.type(),
8260 DetailsAt(entry).index());
8261 SetEntry(entry, NumberDictionaryShape::AsObject(key), value, details);
8262 return this;
8263}
8264
8265
8266
8267template<typename Shape, typename Key>
8268int Dictionary<Shape, Key>::NumberOfElementsFilterAttributes(
8269 PropertyAttributes filter) {
8270 int capacity = HashTable<Shape, Key>::Capacity();
8271 int result = 0;
8272 for (int i = 0; i < capacity; i++) {
8273 Object* k = HashTable<Shape, Key>::KeyAt(i);
8274 if (HashTable<Shape, Key>::IsKey(k)) {
8275 PropertyDetails details = DetailsAt(i);
8276 if (details.IsDeleted()) continue;
8277 PropertyAttributes attr = details.attributes();
8278 if ((attr & filter) == 0) result++;
8279 }
8280 }
8281 return result;
8282}
8283
8284
8285template<typename Shape, typename Key>
8286int Dictionary<Shape, Key>::NumberOfEnumElements() {
8287 return NumberOfElementsFilterAttributes(
8288 static_cast<PropertyAttributes>(DONT_ENUM));
8289}
8290
8291
8292template<typename Shape, typename Key>
8293void Dictionary<Shape, Key>::CopyKeysTo(FixedArray* storage,
8294 PropertyAttributes filter) {
8295 ASSERT(storage->length() >= NumberOfEnumElements());
8296 int capacity = HashTable<Shape, Key>::Capacity();
8297 int index = 0;
8298 for (int i = 0; i < capacity; i++) {
8299 Object* k = HashTable<Shape, Key>::KeyAt(i);
8300 if (HashTable<Shape, Key>::IsKey(k)) {
8301 PropertyDetails details = DetailsAt(i);
8302 if (details.IsDeleted()) continue;
8303 PropertyAttributes attr = details.attributes();
8304 if ((attr & filter) == 0) storage->set(index++, k);
8305 }
8306 }
8307 storage->SortPairs(storage, index);
8308 ASSERT(storage->length() >= index);
8309}
8310
8311
8312void StringDictionary::CopyEnumKeysTo(FixedArray* storage,
8313 FixedArray* sort_array) {
8314 ASSERT(storage->length() >= NumberOfEnumElements());
8315 int capacity = Capacity();
8316 int index = 0;
8317 for (int i = 0; i < capacity; i++) {
8318 Object* k = KeyAt(i);
8319 if (IsKey(k)) {
8320 PropertyDetails details = DetailsAt(i);
8321 if (details.IsDeleted() || details.IsDontEnum()) continue;
8322 storage->set(index, k);
Leon Clarke4515c472010-02-03 11:58:03 +00008323 sort_array->set(index, Smi::FromInt(details.index()));
Steve Blocka7e24c12009-10-30 11:49:00 +00008324 index++;
8325 }
8326 }
8327 storage->SortPairs(sort_array, sort_array->length());
8328 ASSERT(storage->length() >= index);
8329}
8330
8331
8332template<typename Shape, typename Key>
8333void Dictionary<Shape, Key>::CopyKeysTo(FixedArray* storage) {
8334 ASSERT(storage->length() >= NumberOfElementsFilterAttributes(
8335 static_cast<PropertyAttributes>(NONE)));
8336 int capacity = HashTable<Shape, Key>::Capacity();
8337 int index = 0;
8338 for (int i = 0; i < capacity; i++) {
8339 Object* k = HashTable<Shape, Key>::KeyAt(i);
8340 if (HashTable<Shape, Key>::IsKey(k)) {
8341 PropertyDetails details = DetailsAt(i);
8342 if (details.IsDeleted()) continue;
8343 storage->set(index++, k);
8344 }
8345 }
8346 ASSERT(storage->length() >= index);
8347}
8348
8349
8350// Backwards lookup (slow).
8351template<typename Shape, typename Key>
8352Object* Dictionary<Shape, Key>::SlowReverseLookup(Object* value) {
8353 int capacity = HashTable<Shape, Key>::Capacity();
8354 for (int i = 0; i < capacity; i++) {
8355 Object* k = HashTable<Shape, Key>::KeyAt(i);
8356 if (Dictionary<Shape, Key>::IsKey(k)) {
8357 Object* e = ValueAt(i);
8358 if (e->IsJSGlobalPropertyCell()) {
8359 e = JSGlobalPropertyCell::cast(e)->value();
8360 }
8361 if (e == value) return k;
8362 }
8363 }
8364 return Heap::undefined_value();
8365}
8366
8367
8368Object* StringDictionary::TransformPropertiesToFastFor(
8369 JSObject* obj, int unused_property_fields) {
8370 // Make sure we preserve dictionary representation if there are too many
8371 // descriptors.
8372 if (NumberOfElements() > DescriptorArray::kMaxNumberOfDescriptors) return obj;
8373
8374 // Figure out if it is necessary to generate new enumeration indices.
8375 int max_enumeration_index =
8376 NextEnumerationIndex() +
8377 (DescriptorArray::kMaxNumberOfDescriptors -
8378 NumberOfElements());
8379 if (!PropertyDetails::IsValidIndex(max_enumeration_index)) {
8380 Object* result = GenerateNewEnumerationIndices();
8381 if (result->IsFailure()) return result;
8382 }
8383
8384 int instance_descriptor_length = 0;
8385 int number_of_fields = 0;
8386
8387 // Compute the length of the instance descriptor.
8388 int capacity = Capacity();
8389 for (int i = 0; i < capacity; i++) {
8390 Object* k = KeyAt(i);
8391 if (IsKey(k)) {
8392 Object* value = ValueAt(i);
8393 PropertyType type = DetailsAt(i).type();
8394 ASSERT(type != FIELD);
8395 instance_descriptor_length++;
Leon Clarkee46be812010-01-19 14:06:41 +00008396 if (type == NORMAL &&
8397 (!value->IsJSFunction() || Heap::InNewSpace(value))) {
8398 number_of_fields += 1;
8399 }
Steve Blocka7e24c12009-10-30 11:49:00 +00008400 }
8401 }
8402
8403 // Allocate the instance descriptor.
8404 Object* descriptors_unchecked =
8405 DescriptorArray::Allocate(instance_descriptor_length);
8406 if (descriptors_unchecked->IsFailure()) return descriptors_unchecked;
8407 DescriptorArray* descriptors = DescriptorArray::cast(descriptors_unchecked);
8408
8409 int inobject_props = obj->map()->inobject_properties();
8410 int number_of_allocated_fields =
8411 number_of_fields + unused_property_fields - inobject_props;
8412
8413 // Allocate the fixed array for the fields.
8414 Object* fields = Heap::AllocateFixedArray(number_of_allocated_fields);
8415 if (fields->IsFailure()) return fields;
8416
8417 // Fill in the instance descriptor and the fields.
8418 int next_descriptor = 0;
8419 int current_offset = 0;
8420 for (int i = 0; i < capacity; i++) {
8421 Object* k = KeyAt(i);
8422 if (IsKey(k)) {
8423 Object* value = ValueAt(i);
8424 // Ensure the key is a symbol before writing into the instance descriptor.
8425 Object* key = Heap::LookupSymbol(String::cast(k));
8426 if (key->IsFailure()) return key;
8427 PropertyDetails details = DetailsAt(i);
8428 PropertyType type = details.type();
8429
Leon Clarkee46be812010-01-19 14:06:41 +00008430 if (value->IsJSFunction() && !Heap::InNewSpace(value)) {
Steve Blocka7e24c12009-10-30 11:49:00 +00008431 ConstantFunctionDescriptor d(String::cast(key),
8432 JSFunction::cast(value),
8433 details.attributes(),
8434 details.index());
8435 descriptors->Set(next_descriptor++, &d);
8436 } else if (type == NORMAL) {
8437 if (current_offset < inobject_props) {
8438 obj->InObjectPropertyAtPut(current_offset,
8439 value,
8440 UPDATE_WRITE_BARRIER);
8441 } else {
8442 int offset = current_offset - inobject_props;
8443 FixedArray::cast(fields)->set(offset, value);
8444 }
8445 FieldDescriptor d(String::cast(key),
8446 current_offset++,
8447 details.attributes(),
8448 details.index());
8449 descriptors->Set(next_descriptor++, &d);
8450 } else if (type == CALLBACKS) {
8451 CallbacksDescriptor d(String::cast(key),
8452 value,
8453 details.attributes(),
8454 details.index());
8455 descriptors->Set(next_descriptor++, &d);
8456 } else {
8457 UNREACHABLE();
8458 }
8459 }
8460 }
8461 ASSERT(current_offset == number_of_fields);
8462
8463 descriptors->Sort();
8464 // Allocate new map.
8465 Object* new_map = obj->map()->CopyDropDescriptors();
8466 if (new_map->IsFailure()) return new_map;
8467
8468 // Transform the object.
8469 obj->set_map(Map::cast(new_map));
8470 obj->map()->set_instance_descriptors(descriptors);
8471 obj->map()->set_unused_property_fields(unused_property_fields);
8472
8473 obj->set_properties(FixedArray::cast(fields));
8474 ASSERT(obj->IsJSObject());
8475
8476 descriptors->SetNextEnumerationIndex(NextEnumerationIndex());
8477 // Check that it really works.
8478 ASSERT(obj->HasFastProperties());
8479
8480 return obj;
8481}
8482
8483
8484#ifdef ENABLE_DEBUGGER_SUPPORT
8485// Check if there is a break point at this code position.
8486bool DebugInfo::HasBreakPoint(int code_position) {
8487 // Get the break point info object for this code position.
8488 Object* break_point_info = GetBreakPointInfo(code_position);
8489
8490 // If there is no break point info object or no break points in the break
8491 // point info object there is no break point at this code position.
8492 if (break_point_info->IsUndefined()) return false;
8493 return BreakPointInfo::cast(break_point_info)->GetBreakPointCount() > 0;
8494}
8495
8496
8497// Get the break point info object for this code position.
8498Object* DebugInfo::GetBreakPointInfo(int code_position) {
8499 // Find the index of the break point info object for this code position.
8500 int index = GetBreakPointInfoIndex(code_position);
8501
8502 // Return the break point info object if any.
8503 if (index == kNoBreakPointInfo) return Heap::undefined_value();
8504 return BreakPointInfo::cast(break_points()->get(index));
8505}
8506
8507
8508// Clear a break point at the specified code position.
8509void DebugInfo::ClearBreakPoint(Handle<DebugInfo> debug_info,
8510 int code_position,
8511 Handle<Object> break_point_object) {
8512 Handle<Object> break_point_info(debug_info->GetBreakPointInfo(code_position));
8513 if (break_point_info->IsUndefined()) return;
8514 BreakPointInfo::ClearBreakPoint(
8515 Handle<BreakPointInfo>::cast(break_point_info),
8516 break_point_object);
8517}
8518
8519
8520void DebugInfo::SetBreakPoint(Handle<DebugInfo> debug_info,
8521 int code_position,
8522 int source_position,
8523 int statement_position,
8524 Handle<Object> break_point_object) {
8525 Handle<Object> break_point_info(debug_info->GetBreakPointInfo(code_position));
8526 if (!break_point_info->IsUndefined()) {
8527 BreakPointInfo::SetBreakPoint(
8528 Handle<BreakPointInfo>::cast(break_point_info),
8529 break_point_object);
8530 return;
8531 }
8532
8533 // Adding a new break point for a code position which did not have any
8534 // break points before. Try to find a free slot.
8535 int index = kNoBreakPointInfo;
8536 for (int i = 0; i < debug_info->break_points()->length(); i++) {
8537 if (debug_info->break_points()->get(i)->IsUndefined()) {
8538 index = i;
8539 break;
8540 }
8541 }
8542 if (index == kNoBreakPointInfo) {
8543 // No free slot - extend break point info array.
8544 Handle<FixedArray> old_break_points =
8545 Handle<FixedArray>(FixedArray::cast(debug_info->break_points()));
8546 debug_info->set_break_points(*Factory::NewFixedArray(
8547 old_break_points->length() +
8548 Debug::kEstimatedNofBreakPointsInFunction));
8549 Handle<FixedArray> new_break_points =
8550 Handle<FixedArray>(FixedArray::cast(debug_info->break_points()));
8551 for (int i = 0; i < old_break_points->length(); i++) {
8552 new_break_points->set(i, old_break_points->get(i));
8553 }
8554 index = old_break_points->length();
8555 }
8556 ASSERT(index != kNoBreakPointInfo);
8557
8558 // Allocate new BreakPointInfo object and set the break point.
8559 Handle<BreakPointInfo> new_break_point_info =
8560 Handle<BreakPointInfo>::cast(Factory::NewStruct(BREAK_POINT_INFO_TYPE));
8561 new_break_point_info->set_code_position(Smi::FromInt(code_position));
8562 new_break_point_info->set_source_position(Smi::FromInt(source_position));
8563 new_break_point_info->
8564 set_statement_position(Smi::FromInt(statement_position));
8565 new_break_point_info->set_break_point_objects(Heap::undefined_value());
8566 BreakPointInfo::SetBreakPoint(new_break_point_info, break_point_object);
8567 debug_info->break_points()->set(index, *new_break_point_info);
8568}
8569
8570
8571// Get the break point objects for a code position.
8572Object* DebugInfo::GetBreakPointObjects(int code_position) {
8573 Object* break_point_info = GetBreakPointInfo(code_position);
8574 if (break_point_info->IsUndefined()) {
8575 return Heap::undefined_value();
8576 }
8577 return BreakPointInfo::cast(break_point_info)->break_point_objects();
8578}
8579
8580
8581// Get the total number of break points.
8582int DebugInfo::GetBreakPointCount() {
8583 if (break_points()->IsUndefined()) return 0;
8584 int count = 0;
8585 for (int i = 0; i < break_points()->length(); i++) {
8586 if (!break_points()->get(i)->IsUndefined()) {
8587 BreakPointInfo* break_point_info =
8588 BreakPointInfo::cast(break_points()->get(i));
8589 count += break_point_info->GetBreakPointCount();
8590 }
8591 }
8592 return count;
8593}
8594
8595
8596Object* DebugInfo::FindBreakPointInfo(Handle<DebugInfo> debug_info,
8597 Handle<Object> break_point_object) {
8598 if (debug_info->break_points()->IsUndefined()) return Heap::undefined_value();
8599 for (int i = 0; i < debug_info->break_points()->length(); i++) {
8600 if (!debug_info->break_points()->get(i)->IsUndefined()) {
8601 Handle<BreakPointInfo> break_point_info =
8602 Handle<BreakPointInfo>(BreakPointInfo::cast(
8603 debug_info->break_points()->get(i)));
8604 if (BreakPointInfo::HasBreakPointObject(break_point_info,
8605 break_point_object)) {
8606 return *break_point_info;
8607 }
8608 }
8609 }
8610 return Heap::undefined_value();
8611}
8612
8613
8614// Find the index of the break point info object for the specified code
8615// position.
8616int DebugInfo::GetBreakPointInfoIndex(int code_position) {
8617 if (break_points()->IsUndefined()) return kNoBreakPointInfo;
8618 for (int i = 0; i < break_points()->length(); i++) {
8619 if (!break_points()->get(i)->IsUndefined()) {
8620 BreakPointInfo* break_point_info =
8621 BreakPointInfo::cast(break_points()->get(i));
8622 if (break_point_info->code_position()->value() == code_position) {
8623 return i;
8624 }
8625 }
8626 }
8627 return kNoBreakPointInfo;
8628}
8629
8630
8631// Remove the specified break point object.
8632void BreakPointInfo::ClearBreakPoint(Handle<BreakPointInfo> break_point_info,
8633 Handle<Object> break_point_object) {
8634 // If there are no break points just ignore.
8635 if (break_point_info->break_point_objects()->IsUndefined()) return;
8636 // If there is a single break point clear it if it is the same.
8637 if (!break_point_info->break_point_objects()->IsFixedArray()) {
8638 if (break_point_info->break_point_objects() == *break_point_object) {
8639 break_point_info->set_break_point_objects(Heap::undefined_value());
8640 }
8641 return;
8642 }
8643 // If there are multiple break points shrink the array
8644 ASSERT(break_point_info->break_point_objects()->IsFixedArray());
8645 Handle<FixedArray> old_array =
8646 Handle<FixedArray>(
8647 FixedArray::cast(break_point_info->break_point_objects()));
8648 Handle<FixedArray> new_array =
8649 Factory::NewFixedArray(old_array->length() - 1);
8650 int found_count = 0;
8651 for (int i = 0; i < old_array->length(); i++) {
8652 if (old_array->get(i) == *break_point_object) {
8653 ASSERT(found_count == 0);
8654 found_count++;
8655 } else {
8656 new_array->set(i - found_count, old_array->get(i));
8657 }
8658 }
8659 // If the break point was found in the list change it.
8660 if (found_count > 0) break_point_info->set_break_point_objects(*new_array);
8661}
8662
8663
8664// Add the specified break point object.
8665void BreakPointInfo::SetBreakPoint(Handle<BreakPointInfo> break_point_info,
8666 Handle<Object> break_point_object) {
8667 // If there was no break point objects before just set it.
8668 if (break_point_info->break_point_objects()->IsUndefined()) {
8669 break_point_info->set_break_point_objects(*break_point_object);
8670 return;
8671 }
8672 // If the break point object is the same as before just ignore.
8673 if (break_point_info->break_point_objects() == *break_point_object) return;
8674 // If there was one break point object before replace with array.
8675 if (!break_point_info->break_point_objects()->IsFixedArray()) {
8676 Handle<FixedArray> array = Factory::NewFixedArray(2);
8677 array->set(0, break_point_info->break_point_objects());
8678 array->set(1, *break_point_object);
8679 break_point_info->set_break_point_objects(*array);
8680 return;
8681 }
8682 // If there was more than one break point before extend array.
8683 Handle<FixedArray> old_array =
8684 Handle<FixedArray>(
8685 FixedArray::cast(break_point_info->break_point_objects()));
8686 Handle<FixedArray> new_array =
8687 Factory::NewFixedArray(old_array->length() + 1);
8688 for (int i = 0; i < old_array->length(); i++) {
8689 // If the break point was there before just ignore.
8690 if (old_array->get(i) == *break_point_object) return;
8691 new_array->set(i, old_array->get(i));
8692 }
8693 // Add the new break point.
8694 new_array->set(old_array->length(), *break_point_object);
8695 break_point_info->set_break_point_objects(*new_array);
8696}
8697
8698
8699bool BreakPointInfo::HasBreakPointObject(
8700 Handle<BreakPointInfo> break_point_info,
8701 Handle<Object> break_point_object) {
8702 // No break point.
8703 if (break_point_info->break_point_objects()->IsUndefined()) return false;
8704 // Single beak point.
8705 if (!break_point_info->break_point_objects()->IsFixedArray()) {
8706 return break_point_info->break_point_objects() == *break_point_object;
8707 }
8708 // Multiple break points.
8709 FixedArray* array = FixedArray::cast(break_point_info->break_point_objects());
8710 for (int i = 0; i < array->length(); i++) {
8711 if (array->get(i) == *break_point_object) {
8712 return true;
8713 }
8714 }
8715 return false;
8716}
8717
8718
8719// Get the number of break points.
8720int BreakPointInfo::GetBreakPointCount() {
8721 // No break point.
8722 if (break_point_objects()->IsUndefined()) return 0;
8723 // Single beak point.
8724 if (!break_point_objects()->IsFixedArray()) return 1;
8725 // Multiple break points.
8726 return FixedArray::cast(break_point_objects())->length();
8727}
8728#endif
8729
8730
8731} } // namespace v8::internal