blob: 737bf5726a52c09c907afa92d093c372f2c9c783 [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"
Iain Merrick75681382010-08-19 15:07:18 +010036#include "objects-visiting.h"
Steve Blocka7e24c12009-10-30 11:49:00 +000037#include "macro-assembler.h"
38#include "scanner.h"
39#include "scopeinfo.h"
40#include "string-stream.h"
Steve Blockd0582a62009-12-15 09:54:21 +000041#include "utils.h"
Steve Blocka7e24c12009-10-30 11:49:00 +000042
43#ifdef ENABLE_DISASSEMBLER
44#include "disassembler.h"
45#endif
46
47
48namespace v8 {
49namespace internal {
50
51// Getters and setters are stored in a fixed array property. These are
52// constants for their indices.
53const int kGetterIndex = 0;
54const int kSetterIndex = 1;
55
56
Kristian Monsen80d68ea2010-09-08 11:05:35 +010057MUST_USE_RESULT static Object* CreateJSValue(JSFunction* constructor,
58 Object* value) {
Steve Blocka7e24c12009-10-30 11:49:00 +000059 Object* result = Heap::AllocateJSObject(constructor);
60 if (result->IsFailure()) return result;
61 JSValue::cast(result)->set_value(value);
62 return result;
63}
64
65
66Object* Object::ToObject(Context* global_context) {
67 if (IsNumber()) {
68 return CreateJSValue(global_context->number_function(), this);
69 } else if (IsBoolean()) {
70 return CreateJSValue(global_context->boolean_function(), this);
71 } else if (IsString()) {
72 return CreateJSValue(global_context->string_function(), this);
73 }
74 ASSERT(IsJSObject());
75 return this;
76}
77
78
79Object* Object::ToObject() {
80 Context* global_context = Top::context()->global_context();
81 if (IsJSObject()) {
82 return this;
83 } else if (IsNumber()) {
84 return CreateJSValue(global_context->number_function(), this);
85 } else if (IsBoolean()) {
86 return CreateJSValue(global_context->boolean_function(), this);
87 } else if (IsString()) {
88 return CreateJSValue(global_context->string_function(), this);
89 }
90
91 // Throw a type error.
92 return Failure::InternalError();
93}
94
95
96Object* Object::ToBoolean() {
97 if (IsTrue()) return Heap::true_value();
98 if (IsFalse()) return Heap::false_value();
99 if (IsSmi()) {
100 return Heap::ToBoolean(Smi::cast(this)->value() != 0);
101 }
102 if (IsUndefined() || IsNull()) return Heap::false_value();
103 // Undetectable object is false
104 if (IsUndetectableObject()) {
105 return Heap::false_value();
106 }
107 if (IsString()) {
108 return Heap::ToBoolean(String::cast(this)->length() != 0);
109 }
110 if (IsHeapNumber()) {
111 return HeapNumber::cast(this)->HeapNumberToBoolean();
112 }
113 return Heap::true_value();
114}
115
116
117void Object::Lookup(String* name, LookupResult* result) {
118 if (IsJSObject()) return JSObject::cast(this)->Lookup(name, result);
119 Object* holder = NULL;
120 Context* global_context = Top::context()->global_context();
121 if (IsString()) {
122 holder = global_context->string_function()->instance_prototype();
123 } else if (IsNumber()) {
124 holder = global_context->number_function()->instance_prototype();
125 } else if (IsBoolean()) {
126 holder = global_context->boolean_function()->instance_prototype();
127 }
128 ASSERT(holder != NULL); // Cannot handle null or undefined.
129 JSObject::cast(holder)->Lookup(name, result);
130}
131
132
133Object* Object::GetPropertyWithReceiver(Object* receiver,
134 String* name,
135 PropertyAttributes* attributes) {
136 LookupResult result;
137 Lookup(name, &result);
138 Object* value = GetProperty(receiver, &result, name, attributes);
139 ASSERT(*attributes <= ABSENT);
140 return value;
141}
142
143
144Object* Object::GetPropertyWithCallback(Object* receiver,
145 Object* structure,
146 String* name,
147 Object* holder) {
148 // To accommodate both the old and the new api we switch on the
149 // data structure used to store the callbacks. Eventually proxy
150 // callbacks should be phased out.
151 if (structure->IsProxy()) {
152 AccessorDescriptor* callback =
153 reinterpret_cast<AccessorDescriptor*>(Proxy::cast(structure)->proxy());
154 Object* value = (callback->getter)(receiver, callback->data);
155 RETURN_IF_SCHEDULED_EXCEPTION();
156 return value;
157 }
158
159 // api style callbacks.
160 if (structure->IsAccessorInfo()) {
161 AccessorInfo* data = AccessorInfo::cast(structure);
162 Object* fun_obj = data->getter();
163 v8::AccessorGetter call_fun = v8::ToCData<v8::AccessorGetter>(fun_obj);
164 HandleScope scope;
165 JSObject* self = JSObject::cast(receiver);
166 JSObject* holder_handle = JSObject::cast(holder);
167 Handle<String> key(name);
168 LOG(ApiNamedPropertyAccess("load", self, name));
169 CustomArguments args(data->data(), self, holder_handle);
170 v8::AccessorInfo info(args.end());
171 v8::Handle<v8::Value> result;
172 {
173 // Leaving JavaScript.
174 VMState state(EXTERNAL);
175 result = call_fun(v8::Utils::ToLocal(key), info);
176 }
177 RETURN_IF_SCHEDULED_EXCEPTION();
178 if (result.IsEmpty()) return Heap::undefined_value();
179 return *v8::Utils::OpenHandle(*result);
180 }
181
182 // __defineGetter__ callback
183 if (structure->IsFixedArray()) {
184 Object* getter = FixedArray::cast(structure)->get(kGetterIndex);
185 if (getter->IsJSFunction()) {
186 return Object::GetPropertyWithDefinedGetter(receiver,
187 JSFunction::cast(getter));
188 }
189 // Getter is not a function.
190 return Heap::undefined_value();
191 }
192
193 UNREACHABLE();
Leon Clarkef7060e22010-06-03 12:02:55 +0100194 return NULL;
Steve Blocka7e24c12009-10-30 11:49:00 +0000195}
196
197
198Object* Object::GetPropertyWithDefinedGetter(Object* receiver,
199 JSFunction* getter) {
200 HandleScope scope;
201 Handle<JSFunction> fun(JSFunction::cast(getter));
202 Handle<Object> self(receiver);
203#ifdef ENABLE_DEBUGGER_SUPPORT
204 // Handle stepping into a getter if step into is active.
205 if (Debug::StepInActive()) {
206 Debug::HandleStepIn(fun, Handle<Object>::null(), 0, false);
207 }
208#endif
209 bool has_pending_exception;
210 Handle<Object> result =
211 Execution::Call(fun, self, 0, NULL, &has_pending_exception);
212 // Check for pending exception and return the result.
213 if (has_pending_exception) return Failure::Exception();
214 return *result;
215}
216
217
218// Only deal with CALLBACKS and INTERCEPTOR
219Object* JSObject::GetPropertyWithFailedAccessCheck(
220 Object* receiver,
221 LookupResult* result,
222 String* name,
223 PropertyAttributes* attributes) {
Andrei Popescu402d9372010-02-26 13:31:12 +0000224 if (result->IsProperty()) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000225 switch (result->type()) {
226 case CALLBACKS: {
227 // Only allow API accessors.
228 Object* obj = result->GetCallbackObject();
229 if (obj->IsAccessorInfo()) {
230 AccessorInfo* info = AccessorInfo::cast(obj);
231 if (info->all_can_read()) {
232 *attributes = result->GetAttributes();
233 return GetPropertyWithCallback(receiver,
234 result->GetCallbackObject(),
235 name,
236 result->holder());
237 }
238 }
239 break;
240 }
241 case NORMAL:
242 case FIELD:
243 case CONSTANT_FUNCTION: {
244 // Search ALL_CAN_READ accessors in prototype chain.
245 LookupResult r;
246 result->holder()->LookupRealNamedPropertyInPrototypes(name, &r);
Andrei Popescu402d9372010-02-26 13:31:12 +0000247 if (r.IsProperty()) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000248 return GetPropertyWithFailedAccessCheck(receiver,
249 &r,
250 name,
251 attributes);
252 }
253 break;
254 }
255 case INTERCEPTOR: {
256 // If the object has an interceptor, try real named properties.
257 // No access check in GetPropertyAttributeWithInterceptor.
258 LookupResult r;
259 result->holder()->LookupRealNamedProperty(name, &r);
Andrei Popescu402d9372010-02-26 13:31:12 +0000260 if (r.IsProperty()) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000261 return GetPropertyWithFailedAccessCheck(receiver,
262 &r,
263 name,
264 attributes);
265 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000266 break;
267 }
Andrei Popescu402d9372010-02-26 13:31:12 +0000268 default:
269 UNREACHABLE();
Steve Blocka7e24c12009-10-30 11:49:00 +0000270 }
271 }
272
273 // No accessible property found.
274 *attributes = ABSENT;
275 Top::ReportFailedAccessCheck(this, v8::ACCESS_GET);
276 return Heap::undefined_value();
277}
278
279
280PropertyAttributes JSObject::GetPropertyAttributeWithFailedAccessCheck(
281 Object* receiver,
282 LookupResult* result,
283 String* name,
284 bool continue_search) {
Andrei Popescu402d9372010-02-26 13:31:12 +0000285 if (result->IsProperty()) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000286 switch (result->type()) {
287 case CALLBACKS: {
288 // Only allow API accessors.
289 Object* obj = result->GetCallbackObject();
290 if (obj->IsAccessorInfo()) {
291 AccessorInfo* info = AccessorInfo::cast(obj);
292 if (info->all_can_read()) {
293 return result->GetAttributes();
294 }
295 }
296 break;
297 }
298
299 case NORMAL:
300 case FIELD:
301 case CONSTANT_FUNCTION: {
302 if (!continue_search) break;
303 // Search ALL_CAN_READ accessors in prototype chain.
304 LookupResult r;
305 result->holder()->LookupRealNamedPropertyInPrototypes(name, &r);
Andrei Popescu402d9372010-02-26 13:31:12 +0000306 if (r.IsProperty()) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000307 return GetPropertyAttributeWithFailedAccessCheck(receiver,
308 &r,
309 name,
310 continue_search);
311 }
312 break;
313 }
314
315 case INTERCEPTOR: {
316 // If the object has an interceptor, try real named properties.
317 // No access check in GetPropertyAttributeWithInterceptor.
318 LookupResult r;
319 if (continue_search) {
320 result->holder()->LookupRealNamedProperty(name, &r);
321 } else {
322 result->holder()->LocalLookupRealNamedProperty(name, &r);
323 }
Andrei Popescu402d9372010-02-26 13:31:12 +0000324 if (r.IsProperty()) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000325 return GetPropertyAttributeWithFailedAccessCheck(receiver,
326 &r,
327 name,
328 continue_search);
329 }
330 break;
331 }
332
Andrei Popescu402d9372010-02-26 13:31:12 +0000333 default:
334 UNREACHABLE();
Steve Blocka7e24c12009-10-30 11:49:00 +0000335 }
336 }
337
338 Top::ReportFailedAccessCheck(this, v8::ACCESS_HAS);
339 return ABSENT;
340}
341
342
Steve Blocka7e24c12009-10-30 11:49:00 +0000343Object* JSObject::GetNormalizedProperty(LookupResult* result) {
344 ASSERT(!HasFastProperties());
345 Object* value = property_dictionary()->ValueAt(result->GetDictionaryEntry());
346 if (IsGlobalObject()) {
347 value = JSGlobalPropertyCell::cast(value)->value();
348 }
349 ASSERT(!value->IsJSGlobalPropertyCell());
350 return value;
351}
352
353
354Object* JSObject::SetNormalizedProperty(LookupResult* result, Object* value) {
355 ASSERT(!HasFastProperties());
356 if (IsGlobalObject()) {
357 JSGlobalPropertyCell* cell =
358 JSGlobalPropertyCell::cast(
359 property_dictionary()->ValueAt(result->GetDictionaryEntry()));
360 cell->set_value(value);
361 } else {
362 property_dictionary()->ValueAtPut(result->GetDictionaryEntry(), value);
363 }
364 return value;
365}
366
367
368Object* JSObject::SetNormalizedProperty(String* name,
369 Object* value,
370 PropertyDetails details) {
371 ASSERT(!HasFastProperties());
372 int entry = property_dictionary()->FindEntry(name);
373 if (entry == StringDictionary::kNotFound) {
374 Object* store_value = value;
375 if (IsGlobalObject()) {
376 store_value = Heap::AllocateJSGlobalPropertyCell(value);
377 if (store_value->IsFailure()) return store_value;
378 }
379 Object* dict = property_dictionary()->Add(name, store_value, details);
380 if (dict->IsFailure()) return dict;
381 set_properties(StringDictionary::cast(dict));
382 return value;
383 }
384 // Preserve enumeration index.
385 details = PropertyDetails(details.attributes(),
386 details.type(),
387 property_dictionary()->DetailsAt(entry).index());
388 if (IsGlobalObject()) {
389 JSGlobalPropertyCell* cell =
390 JSGlobalPropertyCell::cast(property_dictionary()->ValueAt(entry));
391 cell->set_value(value);
392 // Please note we have to update the property details.
393 property_dictionary()->DetailsAtPut(entry, details);
394 } else {
395 property_dictionary()->SetEntry(entry, name, value, details);
396 }
397 return value;
398}
399
400
401Object* JSObject::DeleteNormalizedProperty(String* name, DeleteMode mode) {
402 ASSERT(!HasFastProperties());
403 StringDictionary* dictionary = property_dictionary();
404 int entry = dictionary->FindEntry(name);
405 if (entry != StringDictionary::kNotFound) {
406 // If we have a global object set the cell to the hole.
407 if (IsGlobalObject()) {
408 PropertyDetails details = dictionary->DetailsAt(entry);
409 if (details.IsDontDelete()) {
410 if (mode != FORCE_DELETION) return Heap::false_value();
411 // When forced to delete global properties, we have to make a
412 // map change to invalidate any ICs that think they can load
413 // from the DontDelete cell without checking if it contains
414 // the hole value.
415 Object* new_map = map()->CopyDropDescriptors();
416 if (new_map->IsFailure()) return new_map;
417 set_map(Map::cast(new_map));
418 }
419 JSGlobalPropertyCell* cell =
420 JSGlobalPropertyCell::cast(dictionary->ValueAt(entry));
421 cell->set_value(Heap::the_hole_value());
422 dictionary->DetailsAtPut(entry, details.AsDeleted());
423 } else {
424 return dictionary->DeleteProperty(entry, mode);
425 }
426 }
427 return Heap::true_value();
428}
429
430
431bool JSObject::IsDirty() {
432 Object* cons_obj = map()->constructor();
433 if (!cons_obj->IsJSFunction())
434 return true;
435 JSFunction* fun = JSFunction::cast(cons_obj);
Steve Block6ded16b2010-05-10 14:33:55 +0100436 if (!fun->shared()->IsApiFunction())
Steve Blocka7e24c12009-10-30 11:49:00 +0000437 return true;
438 // If the object is fully fast case and has the same map it was
439 // created with then no changes can have been made to it.
440 return map() != fun->initial_map()
441 || !HasFastElements()
442 || !HasFastProperties();
443}
444
445
446Object* Object::GetProperty(Object* receiver,
447 LookupResult* result,
448 String* name,
449 PropertyAttributes* attributes) {
450 // Make sure that the top context does not change when doing
451 // callbacks or interceptor calls.
452 AssertNoContextChange ncc;
453
454 // Traverse the prototype chain from the current object (this) to
455 // the holder and check for access rights. This avoid traversing the
456 // objects more than once in case of interceptors, because the
457 // holder will always be the interceptor holder and the search may
458 // only continue with a current object just after the interceptor
459 // holder in the prototype chain.
Andrei Popescu402d9372010-02-26 13:31:12 +0000460 Object* last = result->IsProperty() ? result->holder() : Heap::null_value();
Steve Blocka7e24c12009-10-30 11:49:00 +0000461 for (Object* current = this; true; current = current->GetPrototype()) {
462 if (current->IsAccessCheckNeeded()) {
463 // Check if we're allowed to read from the current object. Note
464 // that even though we may not actually end up loading the named
465 // property from the current object, we still check that we have
466 // access to it.
467 JSObject* checked = JSObject::cast(current);
468 if (!Top::MayNamedAccess(checked, name, v8::ACCESS_GET)) {
469 return checked->GetPropertyWithFailedAccessCheck(receiver,
470 result,
471 name,
472 attributes);
473 }
474 }
475 // Stop traversing the chain once we reach the last object in the
476 // chain; either the holder of the result or null in case of an
477 // absent property.
478 if (current == last) break;
479 }
480
481 if (!result->IsProperty()) {
482 *attributes = ABSENT;
483 return Heap::undefined_value();
484 }
485 *attributes = result->GetAttributes();
Steve Blocka7e24c12009-10-30 11:49:00 +0000486 Object* value;
487 JSObject* holder = result->holder();
488 switch (result->type()) {
489 case NORMAL:
490 value = holder->GetNormalizedProperty(result);
491 ASSERT(!value->IsTheHole() || result->IsReadOnly());
492 return value->IsTheHole() ? Heap::undefined_value() : value;
493 case FIELD:
494 value = holder->FastPropertyAt(result->GetFieldIndex());
495 ASSERT(!value->IsTheHole() || result->IsReadOnly());
496 return value->IsTheHole() ? Heap::undefined_value() : value;
497 case CONSTANT_FUNCTION:
498 return result->GetConstantFunction();
499 case CALLBACKS:
500 return GetPropertyWithCallback(receiver,
501 result->GetCallbackObject(),
502 name,
503 holder);
504 case INTERCEPTOR: {
505 JSObject* recvr = JSObject::cast(receiver);
506 return holder->GetPropertyWithInterceptor(recvr, name, attributes);
507 }
508 default:
509 UNREACHABLE();
510 return NULL;
511 }
512}
513
514
515Object* Object::GetElementWithReceiver(Object* receiver, uint32_t index) {
516 // Non-JS objects do not have integer indexed properties.
517 if (!IsJSObject()) return Heap::undefined_value();
518 return JSObject::cast(this)->GetElementWithReceiver(JSObject::cast(receiver),
519 index);
520}
521
522
523Object* Object::GetPrototype() {
524 // The object is either a number, a string, a boolean, or a real JS object.
525 if (IsJSObject()) return JSObject::cast(this)->map()->prototype();
526 Context* context = Top::context()->global_context();
527
528 if (IsNumber()) return context->number_function()->instance_prototype();
529 if (IsString()) return context->string_function()->instance_prototype();
530 if (IsBoolean()) {
531 return context->boolean_function()->instance_prototype();
532 } else {
533 return Heap::null_value();
534 }
535}
536
537
538void Object::ShortPrint() {
539 HeapStringAllocator allocator;
540 StringStream accumulator(&allocator);
541 ShortPrint(&accumulator);
542 accumulator.OutputToStdOut();
543}
544
545
546void Object::ShortPrint(StringStream* accumulator) {
547 if (IsSmi()) {
548 Smi::cast(this)->SmiPrint(accumulator);
549 } else if (IsFailure()) {
550 Failure::cast(this)->FailurePrint(accumulator);
551 } else {
552 HeapObject::cast(this)->HeapObjectShortPrint(accumulator);
553 }
554}
555
556
557void Smi::SmiPrint() {
558 PrintF("%d", value());
559}
560
561
562void Smi::SmiPrint(StringStream* accumulator) {
563 accumulator->Add("%d", value());
564}
565
566
567void Failure::FailurePrint(StringStream* accumulator) {
Steve Block3ce2e202009-11-05 08:53:23 +0000568 accumulator->Add("Failure(%p)", reinterpret_cast<void*>(value()));
Steve Blocka7e24c12009-10-30 11:49:00 +0000569}
570
571
572void Failure::FailurePrint() {
Steve Block3ce2e202009-11-05 08:53:23 +0000573 PrintF("Failure(%p)", reinterpret_cast<void*>(value()));
Steve Blocka7e24c12009-10-30 11:49:00 +0000574}
575
576
577Failure* Failure::RetryAfterGC(int requested_bytes, AllocationSpace space) {
578 ASSERT((space & ~kSpaceTagMask) == 0);
579 // TODO(X64): Stop using Smi validation for non-smi checks, even if they
580 // happen to be identical at the moment.
581
582 int requested = requested_bytes >> kObjectAlignmentBits;
583 int value = (requested << kSpaceTagSize) | space;
584 // We can't very well allocate a heap number in this situation, and if the
585 // requested memory is so large it seems reasonable to say that this is an
586 // out of memory situation. This fixes a crash in
587 // js1_5/Regress/regress-303213.js.
588 if (value >> kSpaceTagSize != requested ||
589 !Smi::IsValid(value) ||
590 value != ((value << kFailureTypeTagSize) >> kFailureTypeTagSize) ||
591 !Smi::IsValid(value << kFailureTypeTagSize)) {
592 Top::context()->mark_out_of_memory();
593 return Failure::OutOfMemoryException();
594 }
595 return Construct(RETRY_AFTER_GC, value);
596}
597
598
599// Should a word be prefixed by 'a' or 'an' in order to read naturally in
600// English? Returns false for non-ASCII or words that don't start with
601// a capital letter. The a/an rule follows pronunciation in English.
602// We don't use the BBC's overcorrect "an historic occasion" though if
603// you speak a dialect you may well say "an 'istoric occasion".
604static bool AnWord(String* str) {
605 if (str->length() == 0) return false; // A nothing.
606 int c0 = str->Get(0);
607 int c1 = str->length() > 1 ? str->Get(1) : 0;
608 if (c0 == 'U') {
609 if (c1 > 'Z') {
610 return true; // An Umpire, but a UTF8String, a U.
611 }
612 } else if (c0 == 'A' || c0 == 'E' || c0 == 'I' || c0 == 'O') {
613 return true; // An Ape, an ABCBook.
614 } else if ((c1 == 0 || (c1 >= 'A' && c1 <= 'Z')) &&
615 (c0 == 'F' || c0 == 'H' || c0 == 'M' || c0 == 'N' || c0 == 'R' ||
616 c0 == 'S' || c0 == 'X')) {
617 return true; // An MP3File, an M.
618 }
619 return false;
620}
621
622
Steve Block6ded16b2010-05-10 14:33:55 +0100623Object* String::SlowTryFlatten(PretenureFlag pretenure) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000624#ifdef DEBUG
625 // Do not attempt to flatten in debug mode when allocation is not
626 // allowed. This is to avoid an assertion failure when allocating.
627 // Flattening strings is the only case where we always allow
628 // allocation because no GC is performed if the allocation fails.
629 if (!Heap::IsAllocationAllowed()) return this;
630#endif
631
632 switch (StringShape(this).representation_tag()) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000633 case kConsStringTag: {
634 ConsString* cs = ConsString::cast(this);
635 if (cs->second()->length() == 0) {
Leon Clarkef7060e22010-06-03 12:02:55 +0100636 return cs->first();
Steve Blocka7e24c12009-10-30 11:49:00 +0000637 }
638 // There's little point in putting the flat string in new space if the
639 // cons string is in old space. It can never get GCed until there is
640 // an old space GC.
Steve Block6ded16b2010-05-10 14:33:55 +0100641 PretenureFlag tenure = Heap::InNewSpace(this) ? pretenure : TENURED;
Steve Blocka7e24c12009-10-30 11:49:00 +0000642 int len = length();
643 Object* object;
644 String* result;
645 if (IsAsciiRepresentation()) {
646 object = Heap::AllocateRawAsciiString(len, tenure);
647 if (object->IsFailure()) return object;
648 result = String::cast(object);
649 String* first = cs->first();
650 int first_length = first->length();
651 char* dest = SeqAsciiString::cast(result)->GetChars();
652 WriteToFlat(first, dest, 0, first_length);
653 String* second = cs->second();
654 WriteToFlat(second,
655 dest + first_length,
656 0,
657 len - first_length);
658 } else {
659 object = Heap::AllocateRawTwoByteString(len, tenure);
660 if (object->IsFailure()) return object;
661 result = String::cast(object);
662 uc16* dest = SeqTwoByteString::cast(result)->GetChars();
663 String* first = cs->first();
664 int first_length = first->length();
665 WriteToFlat(first, dest, 0, first_length);
666 String* second = cs->second();
667 WriteToFlat(second,
668 dest + first_length,
669 0,
670 len - first_length);
671 }
672 cs->set_first(result);
673 cs->set_second(Heap::empty_string());
Leon Clarkef7060e22010-06-03 12:02:55 +0100674 return result;
Steve Blocka7e24c12009-10-30 11:49:00 +0000675 }
676 default:
677 return this;
678 }
679}
680
681
682bool String::MakeExternal(v8::String::ExternalStringResource* resource) {
Steve Block8defd9f2010-07-08 12:39:36 +0100683 // Externalizing twice leaks the external resource, so it's
Kristian Monsen9dcf7e22010-06-28 14:14:28 +0100684 // prohibited by the API.
685 ASSERT(!this->IsExternalString());
Steve Blocka7e24c12009-10-30 11:49:00 +0000686#ifdef DEBUG
Steve Block3ce2e202009-11-05 08:53:23 +0000687 if (FLAG_enable_slow_asserts) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000688 // Assert that the resource and the string are equivalent.
689 ASSERT(static_cast<size_t>(this->length()) == resource->length());
Kristian Monsen25f61362010-05-21 11:50:48 +0100690 ScopedVector<uc16> smart_chars(this->length());
691 String::WriteToFlat(this, smart_chars.start(), 0, this->length());
692 ASSERT(memcmp(smart_chars.start(),
Steve Blocka7e24c12009-10-30 11:49:00 +0000693 resource->data(),
Kristian Monsen25f61362010-05-21 11:50:48 +0100694 resource->length() * sizeof(smart_chars[0])) == 0);
Steve Blocka7e24c12009-10-30 11:49:00 +0000695 }
696#endif // DEBUG
697
698 int size = this->Size(); // Byte size of the original string.
699 if (size < ExternalString::kSize) {
700 // The string is too small to fit an external String in its place. This can
701 // only happen for zero length strings.
702 return false;
703 }
704 ASSERT(size >= ExternalString::kSize);
Kristian Monsen9dcf7e22010-06-28 14:14:28 +0100705 bool is_ascii = this->IsAsciiRepresentation();
Steve Blocka7e24c12009-10-30 11:49:00 +0000706 bool is_symbol = this->IsSymbol();
707 int length = this->length();
Steve Blockd0582a62009-12-15 09:54:21 +0000708 int hash_field = this->hash_field();
Steve Blocka7e24c12009-10-30 11:49:00 +0000709
710 // Morph the object to an external string by adjusting the map and
711 // reinitializing the fields.
Kristian Monsen9dcf7e22010-06-28 14:14:28 +0100712 this->set_map(is_ascii ?
713 Heap::external_string_with_ascii_data_map() :
714 Heap::external_string_map());
Steve Blocka7e24c12009-10-30 11:49:00 +0000715 ExternalTwoByteString* self = ExternalTwoByteString::cast(this);
716 self->set_length(length);
Steve Blockd0582a62009-12-15 09:54:21 +0000717 self->set_hash_field(hash_field);
Steve Blocka7e24c12009-10-30 11:49:00 +0000718 self->set_resource(resource);
719 // Additionally make the object into an external symbol if the original string
720 // was a symbol to start with.
721 if (is_symbol) {
722 self->Hash(); // Force regeneration of the hash value.
723 // Now morph this external string into a external symbol.
Kristian Monsen9dcf7e22010-06-28 14:14:28 +0100724 this->set_map(is_ascii ?
725 Heap::external_symbol_with_ascii_data_map() :
726 Heap::external_symbol_map());
Steve Blocka7e24c12009-10-30 11:49:00 +0000727 }
728
729 // Fill the remainder of the string with dead wood.
730 int new_size = this->Size(); // Byte size of the external String object.
731 Heap::CreateFillerObjectAt(this->address() + new_size, size - new_size);
732 return true;
733}
734
735
736bool String::MakeExternal(v8::String::ExternalAsciiStringResource* resource) {
737#ifdef DEBUG
Steve Block3ce2e202009-11-05 08:53:23 +0000738 if (FLAG_enable_slow_asserts) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000739 // Assert that the resource and the string are equivalent.
740 ASSERT(static_cast<size_t>(this->length()) == resource->length());
Kristian Monsen25f61362010-05-21 11:50:48 +0100741 ScopedVector<char> smart_chars(this->length());
742 String::WriteToFlat(this, smart_chars.start(), 0, this->length());
743 ASSERT(memcmp(smart_chars.start(),
Steve Blocka7e24c12009-10-30 11:49:00 +0000744 resource->data(),
Kristian Monsen25f61362010-05-21 11:50:48 +0100745 resource->length() * sizeof(smart_chars[0])) == 0);
Steve Blocka7e24c12009-10-30 11:49:00 +0000746 }
747#endif // DEBUG
748
749 int size = this->Size(); // Byte size of the original string.
750 if (size < ExternalString::kSize) {
751 // The string is too small to fit an external String in its place. This can
752 // only happen for zero length strings.
753 return false;
754 }
755 ASSERT(size >= ExternalString::kSize);
756 bool is_symbol = this->IsSymbol();
757 int length = this->length();
Steve Blockd0582a62009-12-15 09:54:21 +0000758 int hash_field = this->hash_field();
Steve Blocka7e24c12009-10-30 11:49:00 +0000759
760 // Morph the object to an external string by adjusting the map and
761 // reinitializing the fields.
Steve Blockd0582a62009-12-15 09:54:21 +0000762 this->set_map(Heap::external_ascii_string_map());
Steve Blocka7e24c12009-10-30 11:49:00 +0000763 ExternalAsciiString* self = ExternalAsciiString::cast(this);
764 self->set_length(length);
Steve Blockd0582a62009-12-15 09:54:21 +0000765 self->set_hash_field(hash_field);
Steve Blocka7e24c12009-10-30 11:49:00 +0000766 self->set_resource(resource);
767 // Additionally make the object into an external symbol if the original string
768 // was a symbol to start with.
769 if (is_symbol) {
770 self->Hash(); // Force regeneration of the hash value.
771 // Now morph this external string into a external symbol.
Steve Blockd0582a62009-12-15 09:54:21 +0000772 this->set_map(Heap::external_ascii_symbol_map());
Steve Blocka7e24c12009-10-30 11:49:00 +0000773 }
774
775 // Fill the remainder of the string with dead wood.
776 int new_size = this->Size(); // Byte size of the external String object.
777 Heap::CreateFillerObjectAt(this->address() + new_size, size - new_size);
778 return true;
779}
780
781
782void String::StringShortPrint(StringStream* accumulator) {
783 int len = length();
Steve Blockd0582a62009-12-15 09:54:21 +0000784 if (len > kMaxShortPrintLength) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000785 accumulator->Add("<Very long string[%u]>", len);
786 return;
787 }
788
789 if (!LooksValid()) {
790 accumulator->Add("<Invalid String>");
791 return;
792 }
793
794 StringInputBuffer buf(this);
795
796 bool truncated = false;
797 if (len > kMaxShortPrintLength) {
798 len = kMaxShortPrintLength;
799 truncated = true;
800 }
801 bool ascii = true;
802 for (int i = 0; i < len; i++) {
803 int c = buf.GetNext();
804
805 if (c < 32 || c >= 127) {
806 ascii = false;
807 }
808 }
809 buf.Reset(this);
810 if (ascii) {
811 accumulator->Add("<String[%u]: ", length());
812 for (int i = 0; i < len; i++) {
813 accumulator->Put(buf.GetNext());
814 }
815 accumulator->Put('>');
816 } else {
817 // Backslash indicates that the string contains control
818 // characters and that backslashes are therefore escaped.
819 accumulator->Add("<String[%u]\\: ", length());
820 for (int i = 0; i < len; i++) {
821 int c = buf.GetNext();
822 if (c == '\n') {
823 accumulator->Add("\\n");
824 } else if (c == '\r') {
825 accumulator->Add("\\r");
826 } else if (c == '\\') {
827 accumulator->Add("\\\\");
828 } else if (c < 32 || c > 126) {
829 accumulator->Add("\\x%02x", c);
830 } else {
831 accumulator->Put(c);
832 }
833 }
834 if (truncated) {
835 accumulator->Put('.');
836 accumulator->Put('.');
837 accumulator->Put('.');
838 }
839 accumulator->Put('>');
840 }
841 return;
842}
843
844
845void JSObject::JSObjectShortPrint(StringStream* accumulator) {
846 switch (map()->instance_type()) {
847 case JS_ARRAY_TYPE: {
848 double length = JSArray::cast(this)->length()->Number();
849 accumulator->Add("<JS array[%u]>", static_cast<uint32_t>(length));
850 break;
851 }
852 case JS_REGEXP_TYPE: {
853 accumulator->Add("<JS RegExp>");
854 break;
855 }
856 case JS_FUNCTION_TYPE: {
857 Object* fun_name = JSFunction::cast(this)->shared()->name();
858 bool printed = false;
859 if (fun_name->IsString()) {
860 String* str = String::cast(fun_name);
861 if (str->length() > 0) {
862 accumulator->Add("<JS Function ");
863 accumulator->Put(str);
864 accumulator->Put('>');
865 printed = true;
866 }
867 }
868 if (!printed) {
869 accumulator->Add("<JS Function>");
870 }
871 break;
872 }
873 // All other JSObjects are rather similar to each other (JSObject,
874 // JSGlobalProxy, JSGlobalObject, JSUndetectableObject, JSValue).
875 default: {
876 Object* constructor = map()->constructor();
877 bool printed = false;
878 if (constructor->IsHeapObject() &&
879 !Heap::Contains(HeapObject::cast(constructor))) {
880 accumulator->Add("!!!INVALID CONSTRUCTOR!!!");
881 } else {
882 bool global_object = IsJSGlobalProxy();
883 if (constructor->IsJSFunction()) {
884 if (!Heap::Contains(JSFunction::cast(constructor)->shared())) {
885 accumulator->Add("!!!INVALID SHARED ON CONSTRUCTOR!!!");
886 } else {
887 Object* constructor_name =
888 JSFunction::cast(constructor)->shared()->name();
889 if (constructor_name->IsString()) {
890 String* str = String::cast(constructor_name);
891 if (str->length() > 0) {
892 bool vowel = AnWord(str);
893 accumulator->Add("<%sa%s ",
894 global_object ? "Global Object: " : "",
895 vowel ? "n" : "");
896 accumulator->Put(str);
897 accumulator->Put('>');
898 printed = true;
899 }
900 }
901 }
902 }
903 if (!printed) {
904 accumulator->Add("<JS %sObject", global_object ? "Global " : "");
905 }
906 }
907 if (IsJSValue()) {
908 accumulator->Add(" value = ");
909 JSValue::cast(this)->value()->ShortPrint(accumulator);
910 }
911 accumulator->Put('>');
912 break;
913 }
914 }
915}
916
917
918void HeapObject::HeapObjectShortPrint(StringStream* accumulator) {
919 // if (!Heap::InNewSpace(this)) PrintF("*", this);
920 if (!Heap::Contains(this)) {
921 accumulator->Add("!!!INVALID POINTER!!!");
922 return;
923 }
924 if (!Heap::Contains(map())) {
925 accumulator->Add("!!!INVALID MAP!!!");
926 return;
927 }
928
929 accumulator->Add("%p ", this);
930
931 if (IsString()) {
932 String::cast(this)->StringShortPrint(accumulator);
933 return;
934 }
935 if (IsJSObject()) {
936 JSObject::cast(this)->JSObjectShortPrint(accumulator);
937 return;
938 }
939 switch (map()->instance_type()) {
940 case MAP_TYPE:
941 accumulator->Add("<Map>");
942 break;
943 case FIXED_ARRAY_TYPE:
944 accumulator->Add("<FixedArray[%u]>", FixedArray::cast(this)->length());
945 break;
946 case BYTE_ARRAY_TYPE:
947 accumulator->Add("<ByteArray[%u]>", ByteArray::cast(this)->length());
948 break;
949 case PIXEL_ARRAY_TYPE:
950 accumulator->Add("<PixelArray[%u]>", PixelArray::cast(this)->length());
951 break;
Steve Block3ce2e202009-11-05 08:53:23 +0000952 case EXTERNAL_BYTE_ARRAY_TYPE:
953 accumulator->Add("<ExternalByteArray[%u]>",
954 ExternalByteArray::cast(this)->length());
955 break;
956 case EXTERNAL_UNSIGNED_BYTE_ARRAY_TYPE:
957 accumulator->Add("<ExternalUnsignedByteArray[%u]>",
958 ExternalUnsignedByteArray::cast(this)->length());
959 break;
960 case EXTERNAL_SHORT_ARRAY_TYPE:
961 accumulator->Add("<ExternalShortArray[%u]>",
962 ExternalShortArray::cast(this)->length());
963 break;
964 case EXTERNAL_UNSIGNED_SHORT_ARRAY_TYPE:
965 accumulator->Add("<ExternalUnsignedShortArray[%u]>",
966 ExternalUnsignedShortArray::cast(this)->length());
967 break;
968 case EXTERNAL_INT_ARRAY_TYPE:
969 accumulator->Add("<ExternalIntArray[%u]>",
970 ExternalIntArray::cast(this)->length());
971 break;
972 case EXTERNAL_UNSIGNED_INT_ARRAY_TYPE:
973 accumulator->Add("<ExternalUnsignedIntArray[%u]>",
974 ExternalUnsignedIntArray::cast(this)->length());
975 break;
976 case EXTERNAL_FLOAT_ARRAY_TYPE:
977 accumulator->Add("<ExternalFloatArray[%u]>",
978 ExternalFloatArray::cast(this)->length());
979 break;
Steve Blocka7e24c12009-10-30 11:49:00 +0000980 case SHARED_FUNCTION_INFO_TYPE:
981 accumulator->Add("<SharedFunctionInfo>");
982 break;
983#define MAKE_STRUCT_CASE(NAME, Name, name) \
984 case NAME##_TYPE: \
985 accumulator->Put('<'); \
986 accumulator->Add(#Name); \
987 accumulator->Put('>'); \
988 break;
989 STRUCT_LIST(MAKE_STRUCT_CASE)
990#undef MAKE_STRUCT_CASE
991 case CODE_TYPE:
992 accumulator->Add("<Code>");
993 break;
994 case ODDBALL_TYPE: {
995 if (IsUndefined())
996 accumulator->Add("<undefined>");
997 else if (IsTheHole())
998 accumulator->Add("<the hole>");
999 else if (IsNull())
1000 accumulator->Add("<null>");
1001 else if (IsTrue())
1002 accumulator->Add("<true>");
1003 else if (IsFalse())
1004 accumulator->Add("<false>");
1005 else
1006 accumulator->Add("<Odd Oddball>");
1007 break;
1008 }
1009 case HEAP_NUMBER_TYPE:
1010 accumulator->Add("<Number: ");
1011 HeapNumber::cast(this)->HeapNumberPrint(accumulator);
1012 accumulator->Put('>');
1013 break;
1014 case PROXY_TYPE:
1015 accumulator->Add("<Proxy>");
1016 break;
1017 case JS_GLOBAL_PROPERTY_CELL_TYPE:
1018 accumulator->Add("Cell for ");
1019 JSGlobalPropertyCell::cast(this)->value()->ShortPrint(accumulator);
1020 break;
1021 default:
1022 accumulator->Add("<Other heap object (%d)>", map()->instance_type());
1023 break;
1024 }
1025}
1026
1027
Steve Blocka7e24c12009-10-30 11:49:00 +00001028void HeapObject::Iterate(ObjectVisitor* v) {
1029 // Handle header
1030 IteratePointer(v, kMapOffset);
1031 // Handle object body
1032 Map* m = map();
1033 IterateBody(m->instance_type(), SizeFromMap(m), v);
1034}
1035
1036
1037void HeapObject::IterateBody(InstanceType type, int object_size,
1038 ObjectVisitor* v) {
1039 // Avoiding <Type>::cast(this) because it accesses the map pointer field.
1040 // During GC, the map pointer field is encoded.
1041 if (type < FIRST_NONSTRING_TYPE) {
1042 switch (type & kStringRepresentationMask) {
1043 case kSeqStringTag:
1044 break;
1045 case kConsStringTag:
Iain Merrick75681382010-08-19 15:07:18 +01001046 ConsString::BodyDescriptor::IterateBody(this, v);
Steve Blocka7e24c12009-10-30 11:49:00 +00001047 break;
Steve Blockd0582a62009-12-15 09:54:21 +00001048 case kExternalStringTag:
1049 if ((type & kStringEncodingMask) == kAsciiStringTag) {
1050 reinterpret_cast<ExternalAsciiString*>(this)->
1051 ExternalAsciiStringIterateBody(v);
1052 } else {
1053 reinterpret_cast<ExternalTwoByteString*>(this)->
1054 ExternalTwoByteStringIterateBody(v);
1055 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001056 break;
1057 }
1058 return;
1059 }
1060
1061 switch (type) {
1062 case FIXED_ARRAY_TYPE:
Iain Merrick75681382010-08-19 15:07:18 +01001063 FixedArray::BodyDescriptor::IterateBody(this, object_size, v);
Steve Blocka7e24c12009-10-30 11:49:00 +00001064 break;
1065 case JS_OBJECT_TYPE:
1066 case JS_CONTEXT_EXTENSION_OBJECT_TYPE:
1067 case JS_VALUE_TYPE:
1068 case JS_ARRAY_TYPE:
1069 case JS_REGEXP_TYPE:
Steve Blocka7e24c12009-10-30 11:49:00 +00001070 case JS_GLOBAL_PROXY_TYPE:
1071 case JS_GLOBAL_OBJECT_TYPE:
1072 case JS_BUILTINS_OBJECT_TYPE:
Iain Merrick75681382010-08-19 15:07:18 +01001073 JSObject::BodyDescriptor::IterateBody(this, object_size, v);
Steve Blocka7e24c12009-10-30 11:49:00 +00001074 break;
Steve Block791712a2010-08-27 10:21:07 +01001075 case JS_FUNCTION_TYPE:
1076 reinterpret_cast<JSFunction*>(this)
1077 ->JSFunctionIterateBody(object_size, v);
1078 break;
Steve Blocka7e24c12009-10-30 11:49:00 +00001079 case ODDBALL_TYPE:
Iain Merrick75681382010-08-19 15:07:18 +01001080 Oddball::BodyDescriptor::IterateBody(this, v);
Steve Blocka7e24c12009-10-30 11:49:00 +00001081 break;
1082 case PROXY_TYPE:
1083 reinterpret_cast<Proxy*>(this)->ProxyIterateBody(v);
1084 break;
1085 case MAP_TYPE:
Iain Merrick75681382010-08-19 15:07:18 +01001086 Map::BodyDescriptor::IterateBody(this, v);
Steve Blocka7e24c12009-10-30 11:49:00 +00001087 break;
1088 case CODE_TYPE:
1089 reinterpret_cast<Code*>(this)->CodeIterateBody(v);
1090 break;
1091 case JS_GLOBAL_PROPERTY_CELL_TYPE:
Iain Merrick75681382010-08-19 15:07:18 +01001092 JSGlobalPropertyCell::BodyDescriptor::IterateBody(this, v);
Steve Blocka7e24c12009-10-30 11:49:00 +00001093 break;
1094 case HEAP_NUMBER_TYPE:
1095 case FILLER_TYPE:
1096 case BYTE_ARRAY_TYPE:
1097 case PIXEL_ARRAY_TYPE:
Steve Block3ce2e202009-11-05 08:53:23 +00001098 case EXTERNAL_BYTE_ARRAY_TYPE:
1099 case EXTERNAL_UNSIGNED_BYTE_ARRAY_TYPE:
1100 case EXTERNAL_SHORT_ARRAY_TYPE:
1101 case EXTERNAL_UNSIGNED_SHORT_ARRAY_TYPE:
1102 case EXTERNAL_INT_ARRAY_TYPE:
1103 case EXTERNAL_UNSIGNED_INT_ARRAY_TYPE:
1104 case EXTERNAL_FLOAT_ARRAY_TYPE:
Steve Blocka7e24c12009-10-30 11:49:00 +00001105 break;
Iain Merrick75681382010-08-19 15:07:18 +01001106 case SHARED_FUNCTION_INFO_TYPE:
1107 SharedFunctionInfo::BodyDescriptor::IterateBody(this, v);
Steve Blocka7e24c12009-10-30 11:49:00 +00001108 break;
Iain Merrick75681382010-08-19 15:07:18 +01001109
Steve Blocka7e24c12009-10-30 11:49:00 +00001110#define MAKE_STRUCT_CASE(NAME, Name, name) \
1111 case NAME##_TYPE:
1112 STRUCT_LIST(MAKE_STRUCT_CASE)
1113#undef MAKE_STRUCT_CASE
Iain Merrick75681382010-08-19 15:07:18 +01001114 StructBodyDescriptor::IterateBody(this, object_size, v);
Steve Blocka7e24c12009-10-30 11:49:00 +00001115 break;
1116 default:
1117 PrintF("Unknown type: %d\n", type);
1118 UNREACHABLE();
1119 }
1120}
1121
1122
Steve Blocka7e24c12009-10-30 11:49:00 +00001123Object* HeapNumber::HeapNumberToBoolean() {
1124 // NaN, +0, and -0 should return the false object
Iain Merrick75681382010-08-19 15:07:18 +01001125#if __BYTE_ORDER == __LITTLE_ENDIAN
1126 union IeeeDoubleLittleEndianArchType u;
1127#elif __BYTE_ORDER == __BIG_ENDIAN
1128 union IeeeDoubleBigEndianArchType u;
1129#endif
1130 u.d = value();
1131 if (u.bits.exp == 2047) {
1132 // Detect NaN for IEEE double precision floating point.
1133 if ((u.bits.man_low | u.bits.man_high) != 0)
1134 return Heap::false_value();
Steve Blocka7e24c12009-10-30 11:49:00 +00001135 }
Iain Merrick75681382010-08-19 15:07:18 +01001136 if (u.bits.exp == 0) {
1137 // Detect +0, and -0 for IEEE double precision floating point.
1138 if ((u.bits.man_low | u.bits.man_high) == 0)
1139 return Heap::false_value();
1140 }
1141 return Heap::true_value();
Steve Blocka7e24c12009-10-30 11:49:00 +00001142}
1143
1144
1145void HeapNumber::HeapNumberPrint() {
1146 PrintF("%.16g", Number());
1147}
1148
1149
1150void HeapNumber::HeapNumberPrint(StringStream* accumulator) {
1151 // The Windows version of vsnprintf can allocate when printing a %g string
1152 // into a buffer that may not be big enough. We don't want random memory
1153 // allocation when producing post-crash stack traces, so we print into a
1154 // buffer that is plenty big enough for any floating point number, then
1155 // print that using vsnprintf (which may truncate but never allocate if
1156 // there is no more space in the buffer).
1157 EmbeddedVector<char, 100> buffer;
1158 OS::SNPrintF(buffer, "%.16g", Number());
1159 accumulator->Add("%s", buffer.start());
1160}
1161
1162
1163String* JSObject::class_name() {
1164 if (IsJSFunction()) {
1165 return Heap::function_class_symbol();
1166 }
1167 if (map()->constructor()->IsJSFunction()) {
1168 JSFunction* constructor = JSFunction::cast(map()->constructor());
1169 return String::cast(constructor->shared()->instance_class_name());
1170 }
1171 // If the constructor is not present, return "Object".
1172 return Heap::Object_symbol();
1173}
1174
1175
1176String* JSObject::constructor_name() {
1177 if (IsJSFunction()) {
Steve Block6ded16b2010-05-10 14:33:55 +01001178 return Heap::closure_symbol();
Steve Blocka7e24c12009-10-30 11:49:00 +00001179 }
1180 if (map()->constructor()->IsJSFunction()) {
1181 JSFunction* constructor = JSFunction::cast(map()->constructor());
1182 String* name = String::cast(constructor->shared()->name());
1183 return name->length() > 0 ? name : constructor->shared()->inferred_name();
1184 }
1185 // If the constructor is not present, return "Object".
1186 return Heap::Object_symbol();
1187}
1188
1189
Steve Blocka7e24c12009-10-30 11:49:00 +00001190Object* JSObject::AddFastPropertyUsingMap(Map* new_map,
1191 String* name,
1192 Object* value) {
1193 int index = new_map->PropertyIndexFor(name);
1194 if (map()->unused_property_fields() == 0) {
1195 ASSERT(map()->unused_property_fields() == 0);
1196 int new_unused = new_map->unused_property_fields();
1197 Object* values =
1198 properties()->CopySize(properties()->length() + new_unused + 1);
1199 if (values->IsFailure()) return values;
1200 set_properties(FixedArray::cast(values));
1201 }
1202 set_map(new_map);
1203 return FastPropertyAtPut(index, value);
1204}
1205
1206
1207Object* JSObject::AddFastProperty(String* name,
1208 Object* value,
1209 PropertyAttributes attributes) {
1210 // Normalize the object if the name is an actual string (not the
1211 // hidden symbols) and is not a real identifier.
1212 StringInputBuffer buffer(name);
1213 if (!Scanner::IsIdentifier(&buffer) && name != Heap::hidden_symbol()) {
1214 Object* obj = NormalizeProperties(CLEAR_INOBJECT_PROPERTIES, 0);
1215 if (obj->IsFailure()) return obj;
1216 return AddSlowProperty(name, value, attributes);
1217 }
1218
1219 DescriptorArray* old_descriptors = map()->instance_descriptors();
1220 // Compute the new index for new field.
1221 int index = map()->NextFreePropertyIndex();
1222
1223 // Allocate new instance descriptors with (name, index) added
1224 FieldDescriptor new_field(name, index, attributes);
1225 Object* new_descriptors =
1226 old_descriptors->CopyInsert(&new_field, REMOVE_TRANSITIONS);
1227 if (new_descriptors->IsFailure()) return new_descriptors;
1228
1229 // Only allow map transition if the object's map is NOT equal to the
1230 // global object_function's map and there is not a transition for name.
1231 bool allow_map_transition =
1232 !old_descriptors->Contains(name) &&
1233 (Top::context()->global_context()->object_function()->map() != map());
1234
1235 ASSERT(index < map()->inobject_properties() ||
1236 (index - map()->inobject_properties()) < properties()->length() ||
1237 map()->unused_property_fields() == 0);
1238 // Allocate a new map for the object.
1239 Object* r = map()->CopyDropDescriptors();
1240 if (r->IsFailure()) return r;
1241 Map* new_map = Map::cast(r);
1242 if (allow_map_transition) {
1243 // Allocate new instance descriptors for the old map with map transition.
1244 MapTransitionDescriptor d(name, Map::cast(new_map), attributes);
1245 Object* r = old_descriptors->CopyInsert(&d, KEEP_TRANSITIONS);
1246 if (r->IsFailure()) return r;
1247 old_descriptors = DescriptorArray::cast(r);
1248 }
1249
1250 if (map()->unused_property_fields() == 0) {
Steve Block8defd9f2010-07-08 12:39:36 +01001251 if (properties()->length() > MaxFastProperties()) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001252 Object* obj = NormalizeProperties(CLEAR_INOBJECT_PROPERTIES, 0);
1253 if (obj->IsFailure()) return obj;
1254 return AddSlowProperty(name, value, attributes);
1255 }
1256 // Make room for the new value
1257 Object* values =
1258 properties()->CopySize(properties()->length() + kFieldsAdded);
1259 if (values->IsFailure()) return values;
1260 set_properties(FixedArray::cast(values));
1261 new_map->set_unused_property_fields(kFieldsAdded - 1);
1262 } else {
1263 new_map->set_unused_property_fields(map()->unused_property_fields() - 1);
1264 }
1265 // We have now allocated all the necessary objects.
1266 // All the changes can be applied at once, so they are atomic.
1267 map()->set_instance_descriptors(old_descriptors);
1268 new_map->set_instance_descriptors(DescriptorArray::cast(new_descriptors));
1269 set_map(new_map);
1270 return FastPropertyAtPut(index, value);
1271}
1272
1273
1274Object* JSObject::AddConstantFunctionProperty(String* name,
1275 JSFunction* function,
1276 PropertyAttributes attributes) {
Leon Clarkee46be812010-01-19 14:06:41 +00001277 ASSERT(!Heap::InNewSpace(function));
1278
Steve Blocka7e24c12009-10-30 11:49:00 +00001279 // Allocate new instance descriptors with (name, function) added
1280 ConstantFunctionDescriptor d(name, function, attributes);
1281 Object* new_descriptors =
1282 map()->instance_descriptors()->CopyInsert(&d, REMOVE_TRANSITIONS);
1283 if (new_descriptors->IsFailure()) return new_descriptors;
1284
1285 // Allocate a new map for the object.
1286 Object* new_map = map()->CopyDropDescriptors();
1287 if (new_map->IsFailure()) return new_map;
1288
1289 DescriptorArray* descriptors = DescriptorArray::cast(new_descriptors);
1290 Map::cast(new_map)->set_instance_descriptors(descriptors);
1291 Map* old_map = map();
1292 set_map(Map::cast(new_map));
1293
1294 // If the old map is the global object map (from new Object()),
1295 // then transitions are not added to it, so we are done.
1296 if (old_map == Top::context()->global_context()->object_function()->map()) {
1297 return function;
1298 }
1299
1300 // Do not add CONSTANT_TRANSITIONS to global objects
1301 if (IsGlobalObject()) {
1302 return function;
1303 }
1304
1305 // Add a CONSTANT_TRANSITION descriptor to the old map,
1306 // so future assignments to this property on other objects
1307 // of the same type will create a normal field, not a constant function.
1308 // Don't do this for special properties, with non-trival attributes.
1309 if (attributes != NONE) {
1310 return function;
1311 }
Iain Merrick75681382010-08-19 15:07:18 +01001312 ConstTransitionDescriptor mark(name, Map::cast(new_map));
Steve Blocka7e24c12009-10-30 11:49:00 +00001313 new_descriptors =
1314 old_map->instance_descriptors()->CopyInsert(&mark, KEEP_TRANSITIONS);
1315 if (new_descriptors->IsFailure()) {
1316 return function; // We have accomplished the main goal, so return success.
1317 }
1318 old_map->set_instance_descriptors(DescriptorArray::cast(new_descriptors));
1319
1320 return function;
1321}
1322
1323
1324// Add property in slow mode
1325Object* JSObject::AddSlowProperty(String* name,
1326 Object* value,
1327 PropertyAttributes attributes) {
1328 ASSERT(!HasFastProperties());
1329 StringDictionary* dict = property_dictionary();
1330 Object* store_value = value;
1331 if (IsGlobalObject()) {
1332 // In case name is an orphaned property reuse the cell.
1333 int entry = dict->FindEntry(name);
1334 if (entry != StringDictionary::kNotFound) {
1335 store_value = dict->ValueAt(entry);
1336 JSGlobalPropertyCell::cast(store_value)->set_value(value);
1337 // Assign an enumeration index to the property and update
1338 // SetNextEnumerationIndex.
1339 int index = dict->NextEnumerationIndex();
1340 PropertyDetails details = PropertyDetails(attributes, NORMAL, index);
1341 dict->SetNextEnumerationIndex(index + 1);
1342 dict->SetEntry(entry, name, store_value, details);
1343 return value;
1344 }
1345 store_value = Heap::AllocateJSGlobalPropertyCell(value);
1346 if (store_value->IsFailure()) return store_value;
1347 JSGlobalPropertyCell::cast(store_value)->set_value(value);
1348 }
1349 PropertyDetails details = PropertyDetails(attributes, NORMAL);
1350 Object* result = dict->Add(name, store_value, details);
1351 if (result->IsFailure()) return result;
1352 if (dict != result) set_properties(StringDictionary::cast(result));
1353 return value;
1354}
1355
1356
1357Object* JSObject::AddProperty(String* name,
1358 Object* value,
1359 PropertyAttributes attributes) {
1360 ASSERT(!IsJSGlobalProxy());
Steve Block8defd9f2010-07-08 12:39:36 +01001361 if (!map()->is_extensible()) {
1362 Handle<Object> args[1] = {Handle<String>(name)};
1363 return Top::Throw(*Factory::NewTypeError("object_not_extensible",
1364 HandleVector(args, 1)));
1365 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001366 if (HasFastProperties()) {
1367 // Ensure the descriptor array does not get too big.
1368 if (map()->instance_descriptors()->number_of_descriptors() <
1369 DescriptorArray::kMaxNumberOfDescriptors) {
Leon Clarkee46be812010-01-19 14:06:41 +00001370 if (value->IsJSFunction() && !Heap::InNewSpace(value)) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001371 return AddConstantFunctionProperty(name,
1372 JSFunction::cast(value),
1373 attributes);
1374 } else {
1375 return AddFastProperty(name, value, attributes);
1376 }
1377 } else {
1378 // Normalize the object to prevent very large instance descriptors.
1379 // This eliminates unwanted N^2 allocation and lookup behavior.
1380 Object* obj = NormalizeProperties(CLEAR_INOBJECT_PROPERTIES, 0);
1381 if (obj->IsFailure()) return obj;
1382 }
1383 }
1384 return AddSlowProperty(name, value, attributes);
1385}
1386
1387
1388Object* JSObject::SetPropertyPostInterceptor(String* name,
1389 Object* value,
1390 PropertyAttributes attributes) {
1391 // Check local property, ignore interceptor.
1392 LookupResult result;
1393 LocalLookupRealNamedProperty(name, &result);
Andrei Popescu402d9372010-02-26 13:31:12 +00001394 if (result.IsFound()) {
1395 // An existing property, a map transition or a null descriptor was
1396 // found. Use set property to handle all these cases.
1397 return SetProperty(&result, name, value, attributes);
1398 }
1399 // Add a new real property.
Steve Blocka7e24c12009-10-30 11:49:00 +00001400 return AddProperty(name, value, attributes);
1401}
1402
1403
1404Object* JSObject::ReplaceSlowProperty(String* name,
Steve Blockd0582a62009-12-15 09:54:21 +00001405 Object* value,
1406 PropertyAttributes attributes) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001407 StringDictionary* dictionary = property_dictionary();
1408 int old_index = dictionary->FindEntry(name);
1409 int new_enumeration_index = 0; // 0 means "Use the next available index."
1410 if (old_index != -1) {
1411 // All calls to ReplaceSlowProperty have had all transitions removed.
1412 ASSERT(!dictionary->DetailsAt(old_index).IsTransition());
1413 new_enumeration_index = dictionary->DetailsAt(old_index).index();
1414 }
1415
1416 PropertyDetails new_details(attributes, NORMAL, new_enumeration_index);
1417 return SetNormalizedProperty(name, value, new_details);
1418}
1419
Steve Blockd0582a62009-12-15 09:54:21 +00001420
Steve Blocka7e24c12009-10-30 11:49:00 +00001421Object* JSObject::ConvertDescriptorToFieldAndMapTransition(
1422 String* name,
1423 Object* new_value,
1424 PropertyAttributes attributes) {
1425 Map* old_map = map();
1426 Object* result = ConvertDescriptorToField(name, new_value, attributes);
1427 if (result->IsFailure()) return result;
1428 // If we get to this point we have succeeded - do not return failure
1429 // after this point. Later stuff is optional.
1430 if (!HasFastProperties()) {
1431 return result;
1432 }
1433 // Do not add transitions to the map of "new Object()".
1434 if (map() == Top::context()->global_context()->object_function()->map()) {
1435 return result;
1436 }
1437
1438 MapTransitionDescriptor transition(name,
1439 map(),
1440 attributes);
1441 Object* new_descriptors =
1442 old_map->instance_descriptors()->
1443 CopyInsert(&transition, KEEP_TRANSITIONS);
1444 if (new_descriptors->IsFailure()) return result; // Yes, return _result_.
1445 old_map->set_instance_descriptors(DescriptorArray::cast(new_descriptors));
1446 return result;
1447}
1448
1449
1450Object* JSObject::ConvertDescriptorToField(String* name,
1451 Object* new_value,
1452 PropertyAttributes attributes) {
1453 if (map()->unused_property_fields() == 0 &&
Steve Block8defd9f2010-07-08 12:39:36 +01001454 properties()->length() > MaxFastProperties()) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001455 Object* obj = NormalizeProperties(CLEAR_INOBJECT_PROPERTIES, 0);
1456 if (obj->IsFailure()) return obj;
1457 return ReplaceSlowProperty(name, new_value, attributes);
1458 }
1459
1460 int index = map()->NextFreePropertyIndex();
1461 FieldDescriptor new_field(name, index, attributes);
1462 // Make a new DescriptorArray replacing an entry with FieldDescriptor.
1463 Object* descriptors_unchecked = map()->instance_descriptors()->
1464 CopyInsert(&new_field, REMOVE_TRANSITIONS);
1465 if (descriptors_unchecked->IsFailure()) return descriptors_unchecked;
1466 DescriptorArray* new_descriptors =
1467 DescriptorArray::cast(descriptors_unchecked);
1468
1469 // Make a new map for the object.
1470 Object* new_map_unchecked = map()->CopyDropDescriptors();
1471 if (new_map_unchecked->IsFailure()) return new_map_unchecked;
1472 Map* new_map = Map::cast(new_map_unchecked);
1473 new_map->set_instance_descriptors(new_descriptors);
1474
1475 // Make new properties array if necessary.
1476 FixedArray* new_properties = 0; // Will always be NULL or a valid pointer.
1477 int new_unused_property_fields = map()->unused_property_fields() - 1;
1478 if (map()->unused_property_fields() == 0) {
Kristian Monsen0d5e1162010-09-30 15:31:59 +01001479 new_unused_property_fields = kFieldsAdded - 1;
1480 Object* new_properties_unchecked =
Steve Blocka7e24c12009-10-30 11:49:00 +00001481 properties()->CopySize(properties()->length() + kFieldsAdded);
1482 if (new_properties_unchecked->IsFailure()) return new_properties_unchecked;
1483 new_properties = FixedArray::cast(new_properties_unchecked);
1484 }
1485
1486 // Update pointers to commit changes.
1487 // Object points to the new map.
1488 new_map->set_unused_property_fields(new_unused_property_fields);
1489 set_map(new_map);
1490 if (new_properties) {
1491 set_properties(FixedArray::cast(new_properties));
1492 }
1493 return FastPropertyAtPut(index, new_value);
1494}
1495
1496
1497
1498Object* JSObject::SetPropertyWithInterceptor(String* name,
1499 Object* value,
1500 PropertyAttributes attributes) {
1501 HandleScope scope;
1502 Handle<JSObject> this_handle(this);
1503 Handle<String> name_handle(name);
1504 Handle<Object> value_handle(value);
1505 Handle<InterceptorInfo> interceptor(GetNamedInterceptor());
1506 if (!interceptor->setter()->IsUndefined()) {
1507 LOG(ApiNamedPropertyAccess("interceptor-named-set", this, name));
1508 CustomArguments args(interceptor->data(), this, this);
1509 v8::AccessorInfo info(args.end());
1510 v8::NamedPropertySetter setter =
1511 v8::ToCData<v8::NamedPropertySetter>(interceptor->setter());
1512 v8::Handle<v8::Value> result;
1513 {
1514 // Leaving JavaScript.
1515 VMState state(EXTERNAL);
1516 Handle<Object> value_unhole(value->IsTheHole() ?
1517 Heap::undefined_value() :
1518 value);
1519 result = setter(v8::Utils::ToLocal(name_handle),
1520 v8::Utils::ToLocal(value_unhole),
1521 info);
1522 }
1523 RETURN_IF_SCHEDULED_EXCEPTION();
1524 if (!result.IsEmpty()) return *value_handle;
1525 }
1526 Object* raw_result = this_handle->SetPropertyPostInterceptor(*name_handle,
1527 *value_handle,
1528 attributes);
1529 RETURN_IF_SCHEDULED_EXCEPTION();
1530 return raw_result;
1531}
1532
1533
1534Object* JSObject::SetProperty(String* name,
1535 Object* value,
1536 PropertyAttributes attributes) {
1537 LookupResult result;
1538 LocalLookup(name, &result);
1539 return SetProperty(&result, name, value, attributes);
1540}
1541
1542
1543Object* JSObject::SetPropertyWithCallback(Object* structure,
1544 String* name,
1545 Object* value,
1546 JSObject* holder) {
1547 HandleScope scope;
1548
1549 // We should never get here to initialize a const with the hole
1550 // value since a const declaration would conflict with the setter.
1551 ASSERT(!value->IsTheHole());
1552 Handle<Object> value_handle(value);
1553
1554 // To accommodate both the old and the new api we switch on the
1555 // data structure used to store the callbacks. Eventually proxy
1556 // callbacks should be phased out.
1557 if (structure->IsProxy()) {
1558 AccessorDescriptor* callback =
1559 reinterpret_cast<AccessorDescriptor*>(Proxy::cast(structure)->proxy());
1560 Object* obj = (callback->setter)(this, value, callback->data);
1561 RETURN_IF_SCHEDULED_EXCEPTION();
1562 if (obj->IsFailure()) return obj;
1563 return *value_handle;
1564 }
1565
1566 if (structure->IsAccessorInfo()) {
1567 // api style callbacks
1568 AccessorInfo* data = AccessorInfo::cast(structure);
1569 Object* call_obj = data->setter();
1570 v8::AccessorSetter call_fun = v8::ToCData<v8::AccessorSetter>(call_obj);
1571 if (call_fun == NULL) return value;
1572 Handle<String> key(name);
1573 LOG(ApiNamedPropertyAccess("store", this, name));
1574 CustomArguments args(data->data(), this, JSObject::cast(holder));
1575 v8::AccessorInfo info(args.end());
1576 {
1577 // Leaving JavaScript.
1578 VMState state(EXTERNAL);
1579 call_fun(v8::Utils::ToLocal(key),
1580 v8::Utils::ToLocal(value_handle),
1581 info);
1582 }
1583 RETURN_IF_SCHEDULED_EXCEPTION();
1584 return *value_handle;
1585 }
1586
1587 if (structure->IsFixedArray()) {
1588 Object* setter = FixedArray::cast(structure)->get(kSetterIndex);
1589 if (setter->IsJSFunction()) {
1590 return SetPropertyWithDefinedSetter(JSFunction::cast(setter), value);
1591 } else {
1592 Handle<String> key(name);
1593 Handle<Object> holder_handle(holder);
1594 Handle<Object> args[2] = { key, holder_handle };
1595 return Top::Throw(*Factory::NewTypeError("no_setter_in_callback",
1596 HandleVector(args, 2)));
1597 }
1598 }
1599
1600 UNREACHABLE();
Leon Clarkef7060e22010-06-03 12:02:55 +01001601 return NULL;
Steve Blocka7e24c12009-10-30 11:49:00 +00001602}
1603
1604
1605Object* JSObject::SetPropertyWithDefinedSetter(JSFunction* setter,
1606 Object* value) {
1607 Handle<Object> value_handle(value);
1608 Handle<JSFunction> fun(JSFunction::cast(setter));
1609 Handle<JSObject> self(this);
1610#ifdef ENABLE_DEBUGGER_SUPPORT
1611 // Handle stepping into a setter if step into is active.
1612 if (Debug::StepInActive()) {
1613 Debug::HandleStepIn(fun, Handle<Object>::null(), 0, false);
1614 }
1615#endif
1616 bool has_pending_exception;
1617 Object** argv[] = { value_handle.location() };
1618 Execution::Call(fun, self, 1, argv, &has_pending_exception);
1619 // Check for pending exception and return the result.
1620 if (has_pending_exception) return Failure::Exception();
1621 return *value_handle;
1622}
1623
1624
1625void JSObject::LookupCallbackSetterInPrototypes(String* name,
1626 LookupResult* result) {
1627 for (Object* pt = GetPrototype();
1628 pt != Heap::null_value();
1629 pt = pt->GetPrototype()) {
1630 JSObject::cast(pt)->LocalLookupRealNamedProperty(name, result);
Andrei Popescu402d9372010-02-26 13:31:12 +00001631 if (result->IsProperty()) {
1632 if (result->IsReadOnly()) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001633 result->NotFound();
1634 return;
1635 }
1636 if (result->type() == CALLBACKS) {
1637 return;
1638 }
1639 }
1640 }
1641 result->NotFound();
1642}
1643
1644
Leon Clarkef7060e22010-06-03 12:02:55 +01001645bool JSObject::SetElementWithCallbackSetterInPrototypes(uint32_t index,
1646 Object* value) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001647 for (Object* pt = GetPrototype();
1648 pt != Heap::null_value();
1649 pt = pt->GetPrototype()) {
1650 if (!JSObject::cast(pt)->HasDictionaryElements()) {
1651 continue;
1652 }
1653 NumberDictionary* dictionary = JSObject::cast(pt)->element_dictionary();
1654 int entry = dictionary->FindEntry(index);
1655 if (entry != NumberDictionary::kNotFound) {
1656 Object* element = dictionary->ValueAt(entry);
1657 PropertyDetails details = dictionary->DetailsAt(entry);
1658 if (details.type() == CALLBACKS) {
Leon Clarkef7060e22010-06-03 12:02:55 +01001659 SetElementWithCallback(element, index, value, JSObject::cast(pt));
1660 return true;
Steve Blocka7e24c12009-10-30 11:49:00 +00001661 }
1662 }
1663 }
Leon Clarkef7060e22010-06-03 12:02:55 +01001664 return false;
Steve Blocka7e24c12009-10-30 11:49:00 +00001665}
1666
1667
1668void JSObject::LookupInDescriptor(String* name, LookupResult* result) {
1669 DescriptorArray* descriptors = map()->instance_descriptors();
Iain Merrick75681382010-08-19 15:07:18 +01001670 int number = descriptors->SearchWithCache(name);
Steve Blocka7e24c12009-10-30 11:49:00 +00001671 if (number != DescriptorArray::kNotFound) {
1672 result->DescriptorResult(this, descriptors->GetDetails(number), number);
1673 } else {
1674 result->NotFound();
1675 }
1676}
1677
1678
1679void JSObject::LocalLookupRealNamedProperty(String* name,
1680 LookupResult* result) {
1681 if (IsJSGlobalProxy()) {
1682 Object* proto = GetPrototype();
1683 if (proto->IsNull()) return result->NotFound();
1684 ASSERT(proto->IsJSGlobalObject());
1685 return JSObject::cast(proto)->LocalLookupRealNamedProperty(name, result);
1686 }
1687
1688 if (HasFastProperties()) {
1689 LookupInDescriptor(name, result);
Andrei Popescu402d9372010-02-26 13:31:12 +00001690 if (result->IsFound()) {
1691 // A property, a map transition or a null descriptor was found.
1692 // We return all of these result types because
1693 // LocalLookupRealNamedProperty is used when setting properties
1694 // where map transitions and null descriptors are handled.
Steve Blocka7e24c12009-10-30 11:49:00 +00001695 ASSERT(result->holder() == this && result->type() != NORMAL);
1696 // Disallow caching for uninitialized constants. These can only
1697 // occur as fields.
1698 if (result->IsReadOnly() && result->type() == FIELD &&
1699 FastPropertyAt(result->GetFieldIndex())->IsTheHole()) {
1700 result->DisallowCaching();
1701 }
1702 return;
1703 }
1704 } else {
1705 int entry = property_dictionary()->FindEntry(name);
1706 if (entry != StringDictionary::kNotFound) {
1707 Object* value = property_dictionary()->ValueAt(entry);
1708 if (IsGlobalObject()) {
1709 PropertyDetails d = property_dictionary()->DetailsAt(entry);
1710 if (d.IsDeleted()) {
1711 result->NotFound();
1712 return;
1713 }
1714 value = JSGlobalPropertyCell::cast(value)->value();
Steve Blocka7e24c12009-10-30 11:49:00 +00001715 }
1716 // Make sure to disallow caching for uninitialized constants
1717 // found in the dictionary-mode objects.
1718 if (value->IsTheHole()) result->DisallowCaching();
1719 result->DictionaryResult(this, entry);
1720 return;
1721 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001722 }
1723 result->NotFound();
1724}
1725
1726
1727void JSObject::LookupRealNamedProperty(String* name, LookupResult* result) {
1728 LocalLookupRealNamedProperty(name, result);
1729 if (result->IsProperty()) return;
1730
1731 LookupRealNamedPropertyInPrototypes(name, result);
1732}
1733
1734
1735void JSObject::LookupRealNamedPropertyInPrototypes(String* name,
1736 LookupResult* result) {
1737 for (Object* pt = GetPrototype();
1738 pt != Heap::null_value();
1739 pt = JSObject::cast(pt)->GetPrototype()) {
1740 JSObject::cast(pt)->LocalLookupRealNamedProperty(name, result);
Andrei Popescu402d9372010-02-26 13:31:12 +00001741 if (result->IsProperty() && (result->type() != INTERCEPTOR)) return;
Steve Blocka7e24c12009-10-30 11:49:00 +00001742 }
1743 result->NotFound();
1744}
1745
1746
1747// We only need to deal with CALLBACKS and INTERCEPTORS
1748Object* JSObject::SetPropertyWithFailedAccessCheck(LookupResult* result,
1749 String* name,
1750 Object* value) {
1751 if (!result->IsProperty()) {
1752 LookupCallbackSetterInPrototypes(name, result);
1753 }
1754
1755 if (result->IsProperty()) {
1756 if (!result->IsReadOnly()) {
1757 switch (result->type()) {
1758 case CALLBACKS: {
1759 Object* obj = result->GetCallbackObject();
1760 if (obj->IsAccessorInfo()) {
1761 AccessorInfo* info = AccessorInfo::cast(obj);
1762 if (info->all_can_write()) {
1763 return SetPropertyWithCallback(result->GetCallbackObject(),
1764 name,
1765 value,
1766 result->holder());
1767 }
1768 }
1769 break;
1770 }
1771 case INTERCEPTOR: {
1772 // Try lookup real named properties. Note that only property can be
1773 // set is callbacks marked as ALL_CAN_WRITE on the prototype chain.
1774 LookupResult r;
1775 LookupRealNamedProperty(name, &r);
1776 if (r.IsProperty()) {
1777 return SetPropertyWithFailedAccessCheck(&r, name, value);
1778 }
1779 break;
1780 }
1781 default: {
1782 break;
1783 }
1784 }
1785 }
1786 }
1787
Iain Merrick75681382010-08-19 15:07:18 +01001788 HandleScope scope;
1789 Handle<Object> value_handle(value);
Steve Blocka7e24c12009-10-30 11:49:00 +00001790 Top::ReportFailedAccessCheck(this, v8::ACCESS_SET);
Iain Merrick75681382010-08-19 15:07:18 +01001791 return *value_handle;
Steve Blocka7e24c12009-10-30 11:49:00 +00001792}
1793
1794
1795Object* JSObject::SetProperty(LookupResult* result,
1796 String* name,
1797 Object* value,
1798 PropertyAttributes attributes) {
1799 // Make sure that the top context does not change when doing callbacks or
1800 // interceptor calls.
1801 AssertNoContextChange ncc;
1802
Steve Blockd0582a62009-12-15 09:54:21 +00001803 // Optimization for 2-byte strings often used as keys in a decompression
1804 // dictionary. We make these short keys into symbols to avoid constantly
1805 // reallocating them.
1806 if (!name->IsSymbol() && name->length() <= 2) {
1807 Object* symbol_version = Heap::LookupSymbol(name);
1808 if (!symbol_version->IsFailure()) name = String::cast(symbol_version);
1809 }
1810
Steve Blocka7e24c12009-10-30 11:49:00 +00001811 // Check access rights if needed.
1812 if (IsAccessCheckNeeded()
1813 && !Top::MayNamedAccess(this, name, v8::ACCESS_SET)) {
1814 return SetPropertyWithFailedAccessCheck(result, name, value);
1815 }
1816
1817 if (IsJSGlobalProxy()) {
1818 Object* proto = GetPrototype();
1819 if (proto->IsNull()) return value;
1820 ASSERT(proto->IsJSGlobalObject());
1821 return JSObject::cast(proto)->SetProperty(result, name, value, attributes);
1822 }
1823
1824 if (!result->IsProperty() && !IsJSContextExtensionObject()) {
1825 // We could not find a local property so let's check whether there is an
1826 // accessor that wants to handle the property.
1827 LookupResult accessor_result;
1828 LookupCallbackSetterInPrototypes(name, &accessor_result);
Andrei Popescu402d9372010-02-26 13:31:12 +00001829 if (accessor_result.IsProperty()) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001830 return SetPropertyWithCallback(accessor_result.GetCallbackObject(),
1831 name,
1832 value,
1833 accessor_result.holder());
1834 }
1835 }
Andrei Popescu402d9372010-02-26 13:31:12 +00001836 if (!result->IsFound()) {
1837 // Neither properties nor transitions found.
Steve Blocka7e24c12009-10-30 11:49:00 +00001838 return AddProperty(name, value, attributes);
1839 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001840 if (result->IsReadOnly() && result->IsProperty()) return value;
1841 // This is a real property that is not read-only, or it is a
1842 // transition or null descriptor and there are no setters in the prototypes.
1843 switch (result->type()) {
1844 case NORMAL:
1845 return SetNormalizedProperty(result, value);
1846 case FIELD:
1847 return FastPropertyAtPut(result->GetFieldIndex(), value);
1848 case MAP_TRANSITION:
1849 if (attributes == result->GetAttributes()) {
1850 // Only use map transition if the attributes match.
1851 return AddFastPropertyUsingMap(result->GetTransitionMap(),
1852 name,
1853 value);
1854 }
1855 return ConvertDescriptorToField(name, value, attributes);
1856 case CONSTANT_FUNCTION:
1857 // Only replace the function if necessary.
1858 if (value == result->GetConstantFunction()) return value;
1859 // Preserve the attributes of this existing property.
1860 attributes = result->GetAttributes();
1861 return ConvertDescriptorToField(name, value, attributes);
1862 case CALLBACKS:
1863 return SetPropertyWithCallback(result->GetCallbackObject(),
1864 name,
1865 value,
1866 result->holder());
1867 case INTERCEPTOR:
1868 return SetPropertyWithInterceptor(name, value, attributes);
Iain Merrick75681382010-08-19 15:07:18 +01001869 case CONSTANT_TRANSITION: {
1870 // If the same constant function is being added we can simply
1871 // transition to the target map.
1872 Map* target_map = result->GetTransitionMap();
1873 DescriptorArray* target_descriptors = target_map->instance_descriptors();
1874 int number = target_descriptors->SearchWithCache(name);
1875 ASSERT(number != DescriptorArray::kNotFound);
1876 ASSERT(target_descriptors->GetType(number) == CONSTANT_FUNCTION);
1877 JSFunction* function =
1878 JSFunction::cast(target_descriptors->GetValue(number));
1879 ASSERT(!Heap::InNewSpace(function));
1880 if (value == function) {
1881 set_map(target_map);
1882 return value;
1883 }
1884 // Otherwise, replace with a MAP_TRANSITION to a new map with a
1885 // FIELD, even if the value is a constant function.
Steve Blocka7e24c12009-10-30 11:49:00 +00001886 return ConvertDescriptorToFieldAndMapTransition(name, value, attributes);
Iain Merrick75681382010-08-19 15:07:18 +01001887 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001888 case NULL_DESCRIPTOR:
1889 return ConvertDescriptorToFieldAndMapTransition(name, value, attributes);
1890 default:
1891 UNREACHABLE();
1892 }
1893 UNREACHABLE();
1894 return value;
1895}
1896
1897
1898// Set a real local property, even if it is READ_ONLY. If the property is not
1899// present, add it with attributes NONE. This code is an exact clone of
1900// SetProperty, with the check for IsReadOnly and the check for a
1901// callback setter removed. The two lines looking up the LookupResult
1902// result are also added. If one of the functions is changed, the other
1903// should be.
1904Object* JSObject::IgnoreAttributesAndSetLocalProperty(
1905 String* name,
1906 Object* value,
1907 PropertyAttributes attributes) {
1908 // Make sure that the top context does not change when doing callbacks or
1909 // interceptor calls.
1910 AssertNoContextChange ncc;
Andrei Popescu402d9372010-02-26 13:31:12 +00001911 LookupResult result;
1912 LocalLookup(name, &result);
Steve Blocka7e24c12009-10-30 11:49:00 +00001913 // Check access rights if needed.
1914 if (IsAccessCheckNeeded()
Andrei Popescu402d9372010-02-26 13:31:12 +00001915 && !Top::MayNamedAccess(this, name, v8::ACCESS_SET)) {
1916 return SetPropertyWithFailedAccessCheck(&result, name, value);
Steve Blocka7e24c12009-10-30 11:49:00 +00001917 }
1918
1919 if (IsJSGlobalProxy()) {
1920 Object* proto = GetPrototype();
1921 if (proto->IsNull()) return value;
1922 ASSERT(proto->IsJSGlobalObject());
1923 return JSObject::cast(proto)->IgnoreAttributesAndSetLocalProperty(
1924 name,
1925 value,
1926 attributes);
1927 }
1928
1929 // Check for accessor in prototype chain removed here in clone.
Andrei Popescu402d9372010-02-26 13:31:12 +00001930 if (!result.IsFound()) {
1931 // Neither properties nor transitions found.
Steve Blocka7e24c12009-10-30 11:49:00 +00001932 return AddProperty(name, value, attributes);
1933 }
Steve Block6ded16b2010-05-10 14:33:55 +01001934
Andrei Popescu402d9372010-02-26 13:31:12 +00001935 PropertyDetails details = PropertyDetails(attributes, NORMAL);
1936
Steve Blocka7e24c12009-10-30 11:49:00 +00001937 // Check of IsReadOnly removed from here in clone.
Andrei Popescu402d9372010-02-26 13:31:12 +00001938 switch (result.type()) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001939 case NORMAL:
Andrei Popescu402d9372010-02-26 13:31:12 +00001940 return SetNormalizedProperty(name, value, details);
Steve Blocka7e24c12009-10-30 11:49:00 +00001941 case FIELD:
Andrei Popescu402d9372010-02-26 13:31:12 +00001942 return FastPropertyAtPut(result.GetFieldIndex(), value);
Steve Blocka7e24c12009-10-30 11:49:00 +00001943 case MAP_TRANSITION:
Andrei Popescu402d9372010-02-26 13:31:12 +00001944 if (attributes == result.GetAttributes()) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001945 // Only use map transition if the attributes match.
Andrei Popescu402d9372010-02-26 13:31:12 +00001946 return AddFastPropertyUsingMap(result.GetTransitionMap(),
Steve Blocka7e24c12009-10-30 11:49:00 +00001947 name,
1948 value);
1949 }
1950 return ConvertDescriptorToField(name, value, attributes);
1951 case CONSTANT_FUNCTION:
1952 // Only replace the function if necessary.
Andrei Popescu402d9372010-02-26 13:31:12 +00001953 if (value == result.GetConstantFunction()) return value;
Steve Blocka7e24c12009-10-30 11:49:00 +00001954 // Preserve the attributes of this existing property.
Andrei Popescu402d9372010-02-26 13:31:12 +00001955 attributes = result.GetAttributes();
Steve Blocka7e24c12009-10-30 11:49:00 +00001956 return ConvertDescriptorToField(name, value, attributes);
1957 case CALLBACKS:
1958 case INTERCEPTOR:
1959 // Override callback in clone
1960 return ConvertDescriptorToField(name, value, attributes);
1961 case CONSTANT_TRANSITION:
1962 // Replace with a MAP_TRANSITION to a new map with a FIELD, even
1963 // if the value is a function.
1964 return ConvertDescriptorToFieldAndMapTransition(name, value, attributes);
1965 case NULL_DESCRIPTOR:
1966 return ConvertDescriptorToFieldAndMapTransition(name, value, attributes);
1967 default:
1968 UNREACHABLE();
1969 }
1970 UNREACHABLE();
1971 return value;
1972}
1973
1974
1975PropertyAttributes JSObject::GetPropertyAttributePostInterceptor(
1976 JSObject* receiver,
1977 String* name,
1978 bool continue_search) {
1979 // Check local property, ignore interceptor.
1980 LookupResult result;
1981 LocalLookupRealNamedProperty(name, &result);
1982 if (result.IsProperty()) return result.GetAttributes();
1983
1984 if (continue_search) {
1985 // Continue searching via the prototype chain.
1986 Object* pt = GetPrototype();
1987 if (pt != Heap::null_value()) {
1988 return JSObject::cast(pt)->
1989 GetPropertyAttributeWithReceiver(receiver, name);
1990 }
1991 }
1992 return ABSENT;
1993}
1994
1995
1996PropertyAttributes JSObject::GetPropertyAttributeWithInterceptor(
1997 JSObject* receiver,
1998 String* name,
1999 bool continue_search) {
2000 // Make sure that the top context does not change when doing
2001 // callbacks or interceptor calls.
2002 AssertNoContextChange ncc;
2003
2004 HandleScope scope;
2005 Handle<InterceptorInfo> interceptor(GetNamedInterceptor());
2006 Handle<JSObject> receiver_handle(receiver);
2007 Handle<JSObject> holder_handle(this);
2008 Handle<String> name_handle(name);
2009 CustomArguments args(interceptor->data(), receiver, this);
2010 v8::AccessorInfo info(args.end());
2011 if (!interceptor->query()->IsUndefined()) {
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01002012 v8::NamedPropertyQuery query =
2013 v8::ToCData<v8::NamedPropertyQuery>(interceptor->query());
Steve Blocka7e24c12009-10-30 11:49:00 +00002014 LOG(ApiNamedPropertyAccess("interceptor-named-has", *holder_handle, name));
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01002015 v8::Handle<v8::Integer> result;
Steve Blocka7e24c12009-10-30 11:49:00 +00002016 {
2017 // Leaving JavaScript.
2018 VMState state(EXTERNAL);
2019 result = query(v8::Utils::ToLocal(name_handle), info);
2020 }
2021 if (!result.IsEmpty()) {
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01002022 ASSERT(result->IsInt32());
2023 return static_cast<PropertyAttributes>(result->Int32Value());
Steve Blocka7e24c12009-10-30 11:49:00 +00002024 }
2025 } else if (!interceptor->getter()->IsUndefined()) {
2026 v8::NamedPropertyGetter getter =
2027 v8::ToCData<v8::NamedPropertyGetter>(interceptor->getter());
2028 LOG(ApiNamedPropertyAccess("interceptor-named-get-has", this, name));
2029 v8::Handle<v8::Value> result;
2030 {
2031 // Leaving JavaScript.
2032 VMState state(EXTERNAL);
2033 result = getter(v8::Utils::ToLocal(name_handle), info);
2034 }
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01002035 if (!result.IsEmpty()) return DONT_ENUM;
Steve Blocka7e24c12009-10-30 11:49:00 +00002036 }
2037 return holder_handle->GetPropertyAttributePostInterceptor(*receiver_handle,
2038 *name_handle,
2039 continue_search);
2040}
2041
2042
2043PropertyAttributes JSObject::GetPropertyAttributeWithReceiver(
2044 JSObject* receiver,
2045 String* key) {
2046 uint32_t index = 0;
2047 if (key->AsArrayIndex(&index)) {
2048 if (HasElementWithReceiver(receiver, index)) return NONE;
2049 return ABSENT;
2050 }
2051 // Named property.
2052 LookupResult result;
2053 Lookup(key, &result);
2054 return GetPropertyAttribute(receiver, &result, key, true);
2055}
2056
2057
2058PropertyAttributes JSObject::GetPropertyAttribute(JSObject* receiver,
2059 LookupResult* result,
2060 String* name,
2061 bool continue_search) {
2062 // Check access rights if needed.
2063 if (IsAccessCheckNeeded() &&
2064 !Top::MayNamedAccess(this, name, v8::ACCESS_HAS)) {
2065 return GetPropertyAttributeWithFailedAccessCheck(receiver,
2066 result,
2067 name,
2068 continue_search);
2069 }
Andrei Popescu402d9372010-02-26 13:31:12 +00002070 if (result->IsProperty()) {
Steve Blocka7e24c12009-10-30 11:49:00 +00002071 switch (result->type()) {
2072 case NORMAL: // fall through
2073 case FIELD:
2074 case CONSTANT_FUNCTION:
2075 case CALLBACKS:
2076 return result->GetAttributes();
2077 case INTERCEPTOR:
2078 return result->holder()->
2079 GetPropertyAttributeWithInterceptor(receiver, name, continue_search);
Steve Blocka7e24c12009-10-30 11:49:00 +00002080 default:
2081 UNREACHABLE();
Steve Blocka7e24c12009-10-30 11:49:00 +00002082 }
2083 }
2084 return ABSENT;
2085}
2086
2087
2088PropertyAttributes JSObject::GetLocalPropertyAttribute(String* name) {
2089 // Check whether the name is an array index.
2090 uint32_t index = 0;
2091 if (name->AsArrayIndex(&index)) {
2092 if (HasLocalElement(index)) return NONE;
2093 return ABSENT;
2094 }
2095 // Named property.
2096 LookupResult result;
2097 LocalLookup(name, &result);
2098 return GetPropertyAttribute(this, &result, name, false);
2099}
2100
2101
Kristian Monsen80d68ea2010-09-08 11:05:35 +01002102Object* NormalizedMapCache::Get(JSObject* obj, PropertyNormalizationMode mode) {
Kristian Monsen80d68ea2010-09-08 11:05:35 +01002103 Map* fast = obj->map();
Kristian Monsen0d5e1162010-09-30 15:31:59 +01002104 int index = Hash(fast) % kEntries;
2105 Object* result = get(index);
2106 if (result->IsMap() && CheckHit(Map::cast(result), fast, mode)) {
Kristian Monsen80d68ea2010-09-08 11:05:35 +01002107#ifdef DEBUG
Kristian Monsen0d5e1162010-09-30 15:31:59 +01002108 if (FLAG_enable_slow_asserts) {
2109 // The cached map should match newly created normalized map bit-by-bit.
2110 Object* fresh = fast->CopyNormalized(mode, SHARED_NORMALIZED_MAP);
2111 if (!fresh->IsFailure()) {
2112 ASSERT(memcmp(Map::cast(fresh)->address(),
2113 Map::cast(result)->address(),
2114 Map::kSize) == 0);
Kristian Monsen80d68ea2010-09-08 11:05:35 +01002115 }
Kristian Monsen80d68ea2010-09-08 11:05:35 +01002116 }
Kristian Monsen0d5e1162010-09-30 15:31:59 +01002117#endif
2118 return result;
Kristian Monsen80d68ea2010-09-08 11:05:35 +01002119 }
Kristian Monsen0d5e1162010-09-30 15:31:59 +01002120
2121 result = fast->CopyNormalized(mode, SHARED_NORMALIZED_MAP);
2122 if (result->IsFailure()) return result;
2123 set(index, result);
Kristian Monsen80d68ea2010-09-08 11:05:35 +01002124 Counters::normalized_maps.Increment();
2125
2126 return result;
2127}
2128
2129
Kristian Monsen80d68ea2010-09-08 11:05:35 +01002130void NormalizedMapCache::Clear() {
2131 int entries = length();
2132 for (int i = 0; i != entries; i++) {
2133 set_undefined(i);
2134 }
2135}
2136
2137
2138int NormalizedMapCache::Hash(Map* fast) {
2139 // For performance reasons we only hash the 3 most variable fields of a map:
2140 // constructor, prototype and bit_field2.
2141
2142 // Shift away the tag.
2143 int hash = (static_cast<uint32_t>(
2144 reinterpret_cast<uintptr_t>(fast->constructor())) >> 2);
2145
2146 // XOR-ing the prototype and constructor directly yields too many zero bits
2147 // when the two pointers are close (which is fairly common).
2148 // To avoid this we shift the prototype 4 bits relatively to the constructor.
2149 hash ^= (static_cast<uint32_t>(
2150 reinterpret_cast<uintptr_t>(fast->prototype())) << 2);
2151
2152 return hash ^ (hash >> 16) ^ fast->bit_field2();
2153}
2154
2155
2156bool NormalizedMapCache::CheckHit(Map* slow,
2157 Map* fast,
2158 PropertyNormalizationMode mode) {
2159#ifdef DEBUG
Kristian Monsen0d5e1162010-09-30 15:31:59 +01002160 slow->SharedMapVerify();
Kristian Monsen80d68ea2010-09-08 11:05:35 +01002161#endif
2162 return
2163 slow->constructor() == fast->constructor() &&
2164 slow->prototype() == fast->prototype() &&
2165 slow->inobject_properties() == ((mode == CLEAR_INOBJECT_PROPERTIES) ?
2166 0 :
2167 fast->inobject_properties()) &&
2168 slow->instance_type() == fast->instance_type() &&
2169 slow->bit_field() == fast->bit_field() &&
Kristian Monsen0d5e1162010-09-30 15:31:59 +01002170 (slow->bit_field2() & ~(1<<Map::kIsShared)) == fast->bit_field2();
Kristian Monsen80d68ea2010-09-08 11:05:35 +01002171}
2172
2173
2174Object* JSObject::UpdateMapCodeCache(String* name, Code* code) {
Kristian Monsen0d5e1162010-09-30 15:31:59 +01002175 if (map()->is_shared()) {
2176 // Fast case maps are never marked as shared.
2177 ASSERT(!HasFastProperties());
2178 // Replace the map with an identical copy that can be safely modified.
2179 Object* obj = map()->CopyNormalized(KEEP_INOBJECT_PROPERTIES,
2180 UNIQUE_NORMALIZED_MAP);
Kristian Monsen80d68ea2010-09-08 11:05:35 +01002181 if (obj->IsFailure()) return obj;
2182 Counters::normalized_maps.Increment();
2183
2184 set_map(Map::cast(obj));
2185 }
2186 return map()->UpdateCodeCache(name, code);
2187}
2188
2189
Steve Blocka7e24c12009-10-30 11:49:00 +00002190Object* JSObject::NormalizeProperties(PropertyNormalizationMode mode,
2191 int expected_additional_properties) {
2192 if (!HasFastProperties()) return this;
2193
2194 // The global object is always normalized.
2195 ASSERT(!IsGlobalObject());
2196
2197 // Allocate new content.
2198 int property_count = map()->NumberOfDescribedProperties();
2199 if (expected_additional_properties > 0) {
2200 property_count += expected_additional_properties;
2201 } else {
2202 property_count += 2; // Make space for two more properties.
2203 }
2204 Object* obj =
Steve Block6ded16b2010-05-10 14:33:55 +01002205 StringDictionary::Allocate(property_count);
Steve Blocka7e24c12009-10-30 11:49:00 +00002206 if (obj->IsFailure()) return obj;
2207 StringDictionary* dictionary = StringDictionary::cast(obj);
2208
2209 DescriptorArray* descs = map()->instance_descriptors();
2210 for (int i = 0; i < descs->number_of_descriptors(); i++) {
2211 PropertyDetails details = descs->GetDetails(i);
2212 switch (details.type()) {
2213 case CONSTANT_FUNCTION: {
2214 PropertyDetails d =
2215 PropertyDetails(details.attributes(), NORMAL, details.index());
2216 Object* value = descs->GetConstantFunction(i);
2217 Object* result = dictionary->Add(descs->GetKey(i), value, d);
2218 if (result->IsFailure()) return result;
2219 dictionary = StringDictionary::cast(result);
2220 break;
2221 }
2222 case FIELD: {
2223 PropertyDetails d =
2224 PropertyDetails(details.attributes(), NORMAL, details.index());
2225 Object* value = FastPropertyAt(descs->GetFieldIndex(i));
2226 Object* result = dictionary->Add(descs->GetKey(i), value, d);
2227 if (result->IsFailure()) return result;
2228 dictionary = StringDictionary::cast(result);
2229 break;
2230 }
2231 case CALLBACKS: {
2232 PropertyDetails d =
2233 PropertyDetails(details.attributes(), CALLBACKS, details.index());
2234 Object* value = descs->GetCallbacksObject(i);
2235 Object* result = dictionary->Add(descs->GetKey(i), value, d);
2236 if (result->IsFailure()) return result;
2237 dictionary = StringDictionary::cast(result);
2238 break;
2239 }
2240 case MAP_TRANSITION:
2241 case CONSTANT_TRANSITION:
2242 case NULL_DESCRIPTOR:
2243 case INTERCEPTOR:
2244 break;
2245 default:
2246 UNREACHABLE();
2247 }
2248 }
2249
2250 // Copy the next enumeration index from instance descriptor.
2251 int index = map()->instance_descriptors()->NextEnumerationIndex();
2252 dictionary->SetNextEnumerationIndex(index);
2253
Kristian Monsen80d68ea2010-09-08 11:05:35 +01002254 obj = Top::context()->global_context()->
2255 normalized_map_cache()->Get(this, mode);
Steve Blocka7e24c12009-10-30 11:49:00 +00002256 if (obj->IsFailure()) return obj;
2257 Map* new_map = Map::cast(obj);
2258
Steve Blocka7e24c12009-10-30 11:49:00 +00002259 // We have now successfully allocated all the necessary objects.
2260 // Changes can now be made with the guarantee that all of them take effect.
Kristian Monsen80d68ea2010-09-08 11:05:35 +01002261
2262 // Resize the object in the heap if necessary.
2263 int new_instance_size = new_map->instance_size();
2264 int instance_size_delta = map()->instance_size() - new_instance_size;
2265 ASSERT(instance_size_delta >= 0);
2266 Heap::CreateFillerObjectAt(this->address() + new_instance_size,
2267 instance_size_delta);
2268
Steve Blocka7e24c12009-10-30 11:49:00 +00002269 set_map(new_map);
Steve Blocka7e24c12009-10-30 11:49:00 +00002270
2271 set_properties(dictionary);
2272
2273 Counters::props_to_dictionary.Increment();
2274
2275#ifdef DEBUG
2276 if (FLAG_trace_normalization) {
2277 PrintF("Object properties have been normalized:\n");
2278 Print();
2279 }
2280#endif
2281 return this;
2282}
2283
2284
2285Object* JSObject::TransformToFastProperties(int unused_property_fields) {
2286 if (HasFastProperties()) return this;
2287 ASSERT(!IsGlobalObject());
2288 return property_dictionary()->
2289 TransformPropertiesToFastFor(this, unused_property_fields);
2290}
2291
2292
2293Object* JSObject::NormalizeElements() {
Steve Block3ce2e202009-11-05 08:53:23 +00002294 ASSERT(!HasPixelElements() && !HasExternalArrayElements());
Steve Blocka7e24c12009-10-30 11:49:00 +00002295 if (HasDictionaryElements()) return this;
Steve Block8defd9f2010-07-08 12:39:36 +01002296 ASSERT(map()->has_fast_elements());
2297
2298 Object* obj = map()->GetSlowElementsMap();
2299 if (obj->IsFailure()) return obj;
2300 Map* new_map = Map::cast(obj);
Steve Blocka7e24c12009-10-30 11:49:00 +00002301
2302 // Get number of entries.
2303 FixedArray* array = FixedArray::cast(elements());
2304
2305 // Compute the effective length.
2306 int length = IsJSArray() ?
2307 Smi::cast(JSArray::cast(this)->length())->value() :
2308 array->length();
Steve Block8defd9f2010-07-08 12:39:36 +01002309 obj = NumberDictionary::Allocate(length);
Steve Blocka7e24c12009-10-30 11:49:00 +00002310 if (obj->IsFailure()) return obj;
2311 NumberDictionary* dictionary = NumberDictionary::cast(obj);
2312 // Copy entries.
2313 for (int i = 0; i < length; i++) {
2314 Object* value = array->get(i);
2315 if (!value->IsTheHole()) {
2316 PropertyDetails details = PropertyDetails(NONE, NORMAL);
2317 Object* result = dictionary->AddNumberEntry(i, array->get(i), details);
2318 if (result->IsFailure()) return result;
2319 dictionary = NumberDictionary::cast(result);
2320 }
2321 }
Steve Block8defd9f2010-07-08 12:39:36 +01002322 // Switch to using the dictionary as the backing storage for
2323 // elements. Set the new map first to satify the elements type
2324 // assert in set_elements().
2325 set_map(new_map);
Steve Blocka7e24c12009-10-30 11:49:00 +00002326 set_elements(dictionary);
2327
2328 Counters::elements_to_dictionary.Increment();
2329
2330#ifdef DEBUG
2331 if (FLAG_trace_normalization) {
2332 PrintF("Object elements have been normalized:\n");
2333 Print();
2334 }
2335#endif
2336
2337 return this;
2338}
2339
2340
2341Object* JSObject::DeletePropertyPostInterceptor(String* name, DeleteMode mode) {
2342 // Check local property, ignore interceptor.
2343 LookupResult result;
2344 LocalLookupRealNamedProperty(name, &result);
Andrei Popescu402d9372010-02-26 13:31:12 +00002345 if (!result.IsProperty()) return Heap::true_value();
Steve Blocka7e24c12009-10-30 11:49:00 +00002346
2347 // Normalize object if needed.
2348 Object* obj = NormalizeProperties(CLEAR_INOBJECT_PROPERTIES, 0);
2349 if (obj->IsFailure()) return obj;
2350
2351 return DeleteNormalizedProperty(name, mode);
2352}
2353
2354
2355Object* JSObject::DeletePropertyWithInterceptor(String* name) {
2356 HandleScope scope;
2357 Handle<InterceptorInfo> interceptor(GetNamedInterceptor());
2358 Handle<String> name_handle(name);
2359 Handle<JSObject> this_handle(this);
2360 if (!interceptor->deleter()->IsUndefined()) {
2361 v8::NamedPropertyDeleter deleter =
2362 v8::ToCData<v8::NamedPropertyDeleter>(interceptor->deleter());
2363 LOG(ApiNamedPropertyAccess("interceptor-named-delete", *this_handle, name));
2364 CustomArguments args(interceptor->data(), this, this);
2365 v8::AccessorInfo info(args.end());
2366 v8::Handle<v8::Boolean> result;
2367 {
2368 // Leaving JavaScript.
2369 VMState state(EXTERNAL);
2370 result = deleter(v8::Utils::ToLocal(name_handle), info);
2371 }
2372 RETURN_IF_SCHEDULED_EXCEPTION();
2373 if (!result.IsEmpty()) {
2374 ASSERT(result->IsBoolean());
2375 return *v8::Utils::OpenHandle(*result);
2376 }
2377 }
2378 Object* raw_result =
2379 this_handle->DeletePropertyPostInterceptor(*name_handle, NORMAL_DELETION);
2380 RETURN_IF_SCHEDULED_EXCEPTION();
2381 return raw_result;
2382}
2383
2384
2385Object* JSObject::DeleteElementPostInterceptor(uint32_t index,
2386 DeleteMode mode) {
Steve Block3ce2e202009-11-05 08:53:23 +00002387 ASSERT(!HasPixelElements() && !HasExternalArrayElements());
Steve Blocka7e24c12009-10-30 11:49:00 +00002388 switch (GetElementsKind()) {
2389 case FAST_ELEMENTS: {
Iain Merrick75681382010-08-19 15:07:18 +01002390 Object* obj = EnsureWritableFastElements();
2391 if (obj->IsFailure()) return obj;
Steve Blocka7e24c12009-10-30 11:49:00 +00002392 uint32_t length = IsJSArray() ?
2393 static_cast<uint32_t>(Smi::cast(JSArray::cast(this)->length())->value()) :
2394 static_cast<uint32_t>(FixedArray::cast(elements())->length());
2395 if (index < length) {
2396 FixedArray::cast(elements())->set_the_hole(index);
2397 }
2398 break;
2399 }
2400 case DICTIONARY_ELEMENTS: {
2401 NumberDictionary* dictionary = element_dictionary();
2402 int entry = dictionary->FindEntry(index);
2403 if (entry != NumberDictionary::kNotFound) {
2404 return dictionary->DeleteProperty(entry, mode);
2405 }
2406 break;
2407 }
2408 default:
2409 UNREACHABLE();
2410 break;
2411 }
2412 return Heap::true_value();
2413}
2414
2415
2416Object* JSObject::DeleteElementWithInterceptor(uint32_t index) {
2417 // Make sure that the top context does not change when doing
2418 // callbacks or interceptor calls.
2419 AssertNoContextChange ncc;
2420 HandleScope scope;
2421 Handle<InterceptorInfo> interceptor(GetIndexedInterceptor());
2422 if (interceptor->deleter()->IsUndefined()) return Heap::false_value();
2423 v8::IndexedPropertyDeleter deleter =
2424 v8::ToCData<v8::IndexedPropertyDeleter>(interceptor->deleter());
2425 Handle<JSObject> this_handle(this);
2426 LOG(ApiIndexedPropertyAccess("interceptor-indexed-delete", this, index));
2427 CustomArguments args(interceptor->data(), this, this);
2428 v8::AccessorInfo info(args.end());
2429 v8::Handle<v8::Boolean> result;
2430 {
2431 // Leaving JavaScript.
2432 VMState state(EXTERNAL);
2433 result = deleter(index, info);
2434 }
2435 RETURN_IF_SCHEDULED_EXCEPTION();
2436 if (!result.IsEmpty()) {
2437 ASSERT(result->IsBoolean());
2438 return *v8::Utils::OpenHandle(*result);
2439 }
2440 Object* raw_result =
2441 this_handle->DeleteElementPostInterceptor(index, NORMAL_DELETION);
2442 RETURN_IF_SCHEDULED_EXCEPTION();
2443 return raw_result;
2444}
2445
2446
2447Object* JSObject::DeleteElement(uint32_t index, DeleteMode mode) {
2448 // Check access rights if needed.
2449 if (IsAccessCheckNeeded() &&
2450 !Top::MayIndexedAccess(this, index, v8::ACCESS_DELETE)) {
2451 Top::ReportFailedAccessCheck(this, v8::ACCESS_DELETE);
2452 return Heap::false_value();
2453 }
2454
2455 if (IsJSGlobalProxy()) {
2456 Object* proto = GetPrototype();
2457 if (proto->IsNull()) return Heap::false_value();
2458 ASSERT(proto->IsJSGlobalObject());
2459 return JSGlobalObject::cast(proto)->DeleteElement(index, mode);
2460 }
2461
2462 if (HasIndexedInterceptor()) {
2463 // Skip interceptor if forcing deletion.
2464 if (mode == FORCE_DELETION) {
2465 return DeleteElementPostInterceptor(index, mode);
2466 }
2467 return DeleteElementWithInterceptor(index);
2468 }
2469
2470 switch (GetElementsKind()) {
2471 case FAST_ELEMENTS: {
Iain Merrick75681382010-08-19 15:07:18 +01002472 Object* obj = EnsureWritableFastElements();
2473 if (obj->IsFailure()) return obj;
Steve Blocka7e24c12009-10-30 11:49:00 +00002474 uint32_t length = IsJSArray() ?
2475 static_cast<uint32_t>(Smi::cast(JSArray::cast(this)->length())->value()) :
2476 static_cast<uint32_t>(FixedArray::cast(elements())->length());
2477 if (index < length) {
2478 FixedArray::cast(elements())->set_the_hole(index);
2479 }
2480 break;
2481 }
Steve Block3ce2e202009-11-05 08:53:23 +00002482 case PIXEL_ELEMENTS:
2483 case EXTERNAL_BYTE_ELEMENTS:
2484 case EXTERNAL_UNSIGNED_BYTE_ELEMENTS:
2485 case EXTERNAL_SHORT_ELEMENTS:
2486 case EXTERNAL_UNSIGNED_SHORT_ELEMENTS:
2487 case EXTERNAL_INT_ELEMENTS:
2488 case EXTERNAL_UNSIGNED_INT_ELEMENTS:
2489 case EXTERNAL_FLOAT_ELEMENTS:
2490 // Pixel and external array elements cannot be deleted. Just
2491 // silently ignore here.
Steve Blocka7e24c12009-10-30 11:49:00 +00002492 break;
Steve Blocka7e24c12009-10-30 11:49:00 +00002493 case DICTIONARY_ELEMENTS: {
2494 NumberDictionary* dictionary = element_dictionary();
2495 int entry = dictionary->FindEntry(index);
2496 if (entry != NumberDictionary::kNotFound) {
2497 return dictionary->DeleteProperty(entry, mode);
2498 }
2499 break;
2500 }
2501 default:
2502 UNREACHABLE();
2503 break;
2504 }
2505 return Heap::true_value();
2506}
2507
2508
2509Object* JSObject::DeleteProperty(String* name, DeleteMode mode) {
2510 // ECMA-262, 3rd, 8.6.2.5
2511 ASSERT(name->IsString());
2512
2513 // Check access rights if needed.
2514 if (IsAccessCheckNeeded() &&
2515 !Top::MayNamedAccess(this, name, v8::ACCESS_DELETE)) {
2516 Top::ReportFailedAccessCheck(this, v8::ACCESS_DELETE);
2517 return Heap::false_value();
2518 }
2519
2520 if (IsJSGlobalProxy()) {
2521 Object* proto = GetPrototype();
2522 if (proto->IsNull()) return Heap::false_value();
2523 ASSERT(proto->IsJSGlobalObject());
2524 return JSGlobalObject::cast(proto)->DeleteProperty(name, mode);
2525 }
2526
2527 uint32_t index = 0;
2528 if (name->AsArrayIndex(&index)) {
2529 return DeleteElement(index, mode);
2530 } else {
2531 LookupResult result;
2532 LocalLookup(name, &result);
Andrei Popescu402d9372010-02-26 13:31:12 +00002533 if (!result.IsProperty()) return Heap::true_value();
Steve Blocka7e24c12009-10-30 11:49:00 +00002534 // Ignore attributes if forcing a deletion.
2535 if (result.IsDontDelete() && mode != FORCE_DELETION) {
2536 return Heap::false_value();
2537 }
2538 // Check for interceptor.
2539 if (result.type() == INTERCEPTOR) {
2540 // Skip interceptor if forcing a deletion.
2541 if (mode == FORCE_DELETION) {
2542 return DeletePropertyPostInterceptor(name, mode);
2543 }
2544 return DeletePropertyWithInterceptor(name);
2545 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002546 // Normalize object if needed.
2547 Object* obj = NormalizeProperties(CLEAR_INOBJECT_PROPERTIES, 0);
2548 if (obj->IsFailure()) return obj;
2549 // Make sure the properties are normalized before removing the entry.
2550 return DeleteNormalizedProperty(name, mode);
2551 }
2552}
2553
2554
2555// Check whether this object references another object.
2556bool JSObject::ReferencesObject(Object* obj) {
2557 AssertNoAllocation no_alloc;
2558
2559 // Is the object the constructor for this object?
2560 if (map()->constructor() == obj) {
2561 return true;
2562 }
2563
2564 // Is the object the prototype for this object?
2565 if (map()->prototype() == obj) {
2566 return true;
2567 }
2568
2569 // Check if the object is among the named properties.
2570 Object* key = SlowReverseLookup(obj);
2571 if (key != Heap::undefined_value()) {
2572 return true;
2573 }
2574
2575 // Check if the object is among the indexed properties.
2576 switch (GetElementsKind()) {
2577 case PIXEL_ELEMENTS:
Steve Block3ce2e202009-11-05 08:53:23 +00002578 case EXTERNAL_BYTE_ELEMENTS:
2579 case EXTERNAL_UNSIGNED_BYTE_ELEMENTS:
2580 case EXTERNAL_SHORT_ELEMENTS:
2581 case EXTERNAL_UNSIGNED_SHORT_ELEMENTS:
2582 case EXTERNAL_INT_ELEMENTS:
2583 case EXTERNAL_UNSIGNED_INT_ELEMENTS:
2584 case EXTERNAL_FLOAT_ELEMENTS:
2585 // Raw pixels and external arrays do not reference other
2586 // objects.
Steve Blocka7e24c12009-10-30 11:49:00 +00002587 break;
2588 case FAST_ELEMENTS: {
2589 int length = IsJSArray() ?
2590 Smi::cast(JSArray::cast(this)->length())->value() :
2591 FixedArray::cast(elements())->length();
2592 for (int i = 0; i < length; i++) {
2593 Object* element = FixedArray::cast(elements())->get(i);
2594 if (!element->IsTheHole() && element == obj) {
2595 return true;
2596 }
2597 }
2598 break;
2599 }
2600 case DICTIONARY_ELEMENTS: {
2601 key = element_dictionary()->SlowReverseLookup(obj);
2602 if (key != Heap::undefined_value()) {
2603 return true;
2604 }
2605 break;
2606 }
2607 default:
2608 UNREACHABLE();
2609 break;
2610 }
2611
Steve Block6ded16b2010-05-10 14:33:55 +01002612 // For functions check the context.
2613 if (IsJSFunction()) {
Steve Blocka7e24c12009-10-30 11:49:00 +00002614 // Get the constructor function for arguments array.
2615 JSObject* arguments_boilerplate =
2616 Top::context()->global_context()->arguments_boilerplate();
2617 JSFunction* arguments_function =
2618 JSFunction::cast(arguments_boilerplate->map()->constructor());
2619
2620 // Get the context and don't check if it is the global context.
2621 JSFunction* f = JSFunction::cast(this);
2622 Context* context = f->context();
2623 if (context->IsGlobalContext()) {
2624 return false;
2625 }
2626
2627 // Check the non-special context slots.
2628 for (int i = Context::MIN_CONTEXT_SLOTS; i < context->length(); i++) {
2629 // Only check JS objects.
2630 if (context->get(i)->IsJSObject()) {
2631 JSObject* ctxobj = JSObject::cast(context->get(i));
2632 // If it is an arguments array check the content.
2633 if (ctxobj->map()->constructor() == arguments_function) {
2634 if (ctxobj->ReferencesObject(obj)) {
2635 return true;
2636 }
2637 } else if (ctxobj == obj) {
2638 return true;
2639 }
2640 }
2641 }
2642
2643 // Check the context extension if any.
2644 if (context->has_extension()) {
2645 return context->extension()->ReferencesObject(obj);
2646 }
2647 }
2648
2649 // No references to object.
2650 return false;
2651}
2652
2653
Steve Block8defd9f2010-07-08 12:39:36 +01002654Object* JSObject::PreventExtensions() {
2655 // If there are fast elements we normalize.
2656 if (HasFastElements()) {
Kristian Monsen80d68ea2010-09-08 11:05:35 +01002657 Object* ok = NormalizeElements();
2658 if (ok->IsFailure()) return ok;
Steve Block8defd9f2010-07-08 12:39:36 +01002659 }
2660 // Make sure that we never go back to fast case.
2661 element_dictionary()->set_requires_slow_elements();
2662
2663 // Do a map transition, other objects with this map may still
2664 // be extensible.
2665 Object* new_map = map()->CopyDropTransitions();
2666 if (new_map->IsFailure()) return new_map;
2667 Map::cast(new_map)->set_is_extensible(false);
2668 set_map(Map::cast(new_map));
2669 ASSERT(!map()->is_extensible());
2670 return new_map;
2671}
2672
2673
Steve Blocka7e24c12009-10-30 11:49:00 +00002674// Tests for the fast common case for property enumeration:
Steve Blockd0582a62009-12-15 09:54:21 +00002675// - This object and all prototypes has an enum cache (which means that it has
2676// no interceptors and needs no access checks).
2677// - This object has no elements.
2678// - No prototype has enumerable properties/elements.
Steve Blocka7e24c12009-10-30 11:49:00 +00002679bool JSObject::IsSimpleEnum() {
Steve Blocka7e24c12009-10-30 11:49:00 +00002680 for (Object* o = this;
2681 o != Heap::null_value();
2682 o = JSObject::cast(o)->GetPrototype()) {
2683 JSObject* curr = JSObject::cast(o);
Steve Blocka7e24c12009-10-30 11:49:00 +00002684 if (!curr->map()->instance_descriptors()->HasEnumCache()) return false;
Steve Blockd0582a62009-12-15 09:54:21 +00002685 ASSERT(!curr->HasNamedInterceptor());
2686 ASSERT(!curr->HasIndexedInterceptor());
2687 ASSERT(!curr->IsAccessCheckNeeded());
Steve Blocka7e24c12009-10-30 11:49:00 +00002688 if (curr->NumberOfEnumElements() > 0) return false;
Steve Blocka7e24c12009-10-30 11:49:00 +00002689 if (curr != this) {
2690 FixedArray* curr_fixed_array =
2691 FixedArray::cast(curr->map()->instance_descriptors()->GetEnumCache());
Steve Blockd0582a62009-12-15 09:54:21 +00002692 if (curr_fixed_array->length() > 0) return false;
Steve Blocka7e24c12009-10-30 11:49:00 +00002693 }
2694 }
2695 return true;
2696}
2697
2698
2699int Map::NumberOfDescribedProperties() {
2700 int result = 0;
2701 DescriptorArray* descs = instance_descriptors();
2702 for (int i = 0; i < descs->number_of_descriptors(); i++) {
2703 if (descs->IsProperty(i)) result++;
2704 }
2705 return result;
2706}
2707
2708
2709int Map::PropertyIndexFor(String* name) {
2710 DescriptorArray* descs = instance_descriptors();
2711 for (int i = 0; i < descs->number_of_descriptors(); i++) {
2712 if (name->Equals(descs->GetKey(i)) && !descs->IsNullDescriptor(i)) {
2713 return descs->GetFieldIndex(i);
2714 }
2715 }
2716 return -1;
2717}
2718
2719
2720int Map::NextFreePropertyIndex() {
2721 int max_index = -1;
2722 DescriptorArray* descs = instance_descriptors();
2723 for (int i = 0; i < descs->number_of_descriptors(); i++) {
2724 if (descs->GetType(i) == FIELD) {
2725 int current_index = descs->GetFieldIndex(i);
2726 if (current_index > max_index) max_index = current_index;
2727 }
2728 }
2729 return max_index + 1;
2730}
2731
2732
2733AccessorDescriptor* Map::FindAccessor(String* name) {
2734 DescriptorArray* descs = instance_descriptors();
2735 for (int i = 0; i < descs->number_of_descriptors(); i++) {
2736 if (name->Equals(descs->GetKey(i)) && descs->GetType(i) == CALLBACKS) {
2737 return descs->GetCallbacks(i);
2738 }
2739 }
2740 return NULL;
2741}
2742
2743
2744void JSObject::LocalLookup(String* name, LookupResult* result) {
2745 ASSERT(name->IsString());
2746
2747 if (IsJSGlobalProxy()) {
2748 Object* proto = GetPrototype();
2749 if (proto->IsNull()) return result->NotFound();
2750 ASSERT(proto->IsJSGlobalObject());
2751 return JSObject::cast(proto)->LocalLookup(name, result);
2752 }
2753
2754 // Do not use inline caching if the object is a non-global object
2755 // that requires access checks.
2756 if (!IsJSGlobalProxy() && IsAccessCheckNeeded()) {
2757 result->DisallowCaching();
2758 }
2759
2760 // Check __proto__ before interceptor.
2761 if (name->Equals(Heap::Proto_symbol()) && !IsJSContextExtensionObject()) {
2762 result->ConstantResult(this);
2763 return;
2764 }
2765
2766 // Check for lookup interceptor except when bootstrapping.
2767 if (HasNamedInterceptor() && !Bootstrapper::IsActive()) {
2768 result->InterceptorResult(this);
2769 return;
2770 }
2771
2772 LocalLookupRealNamedProperty(name, result);
2773}
2774
2775
2776void JSObject::Lookup(String* name, LookupResult* result) {
2777 // Ecma-262 3rd 8.6.2.4
2778 for (Object* current = this;
2779 current != Heap::null_value();
2780 current = JSObject::cast(current)->GetPrototype()) {
2781 JSObject::cast(current)->LocalLookup(name, result);
Andrei Popescu402d9372010-02-26 13:31:12 +00002782 if (result->IsProperty()) return;
Steve Blocka7e24c12009-10-30 11:49:00 +00002783 }
2784 result->NotFound();
2785}
2786
2787
2788// Search object and it's prototype chain for callback properties.
2789void JSObject::LookupCallback(String* name, LookupResult* result) {
2790 for (Object* current = this;
2791 current != Heap::null_value();
2792 current = JSObject::cast(current)->GetPrototype()) {
2793 JSObject::cast(current)->LocalLookupRealNamedProperty(name, result);
Andrei Popescu402d9372010-02-26 13:31:12 +00002794 if (result->IsProperty() && result->type() == CALLBACKS) return;
Steve Blocka7e24c12009-10-30 11:49:00 +00002795 }
2796 result->NotFound();
2797}
2798
2799
2800Object* JSObject::DefineGetterSetter(String* name,
2801 PropertyAttributes attributes) {
2802 // Make sure that the top context does not change when doing callbacks or
2803 // interceptor calls.
2804 AssertNoContextChange ncc;
2805
Steve Blocka7e24c12009-10-30 11:49:00 +00002806 // Try to flatten before operating on the string.
Steve Block6ded16b2010-05-10 14:33:55 +01002807 name->TryFlatten();
Steve Blocka7e24c12009-10-30 11:49:00 +00002808
Leon Clarkef7060e22010-06-03 12:02:55 +01002809 if (!CanSetCallback(name)) {
2810 return Heap::undefined_value();
Steve Blocka7e24c12009-10-30 11:49:00 +00002811 }
2812
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01002813 uint32_t index = 0;
Steve Blocka7e24c12009-10-30 11:49:00 +00002814 bool is_element = name->AsArrayIndex(&index);
2815 if (is_element && IsJSArray()) return Heap::undefined_value();
2816
2817 if (is_element) {
2818 switch (GetElementsKind()) {
2819 case FAST_ELEMENTS:
2820 break;
2821 case PIXEL_ELEMENTS:
Steve Block3ce2e202009-11-05 08:53:23 +00002822 case EXTERNAL_BYTE_ELEMENTS:
2823 case EXTERNAL_UNSIGNED_BYTE_ELEMENTS:
2824 case EXTERNAL_SHORT_ELEMENTS:
2825 case EXTERNAL_UNSIGNED_SHORT_ELEMENTS:
2826 case EXTERNAL_INT_ELEMENTS:
2827 case EXTERNAL_UNSIGNED_INT_ELEMENTS:
2828 case EXTERNAL_FLOAT_ELEMENTS:
2829 // Ignore getters and setters on pixel and external array
2830 // elements.
Steve Blocka7e24c12009-10-30 11:49:00 +00002831 return Heap::undefined_value();
2832 case DICTIONARY_ELEMENTS: {
2833 // Lookup the index.
2834 NumberDictionary* dictionary = element_dictionary();
2835 int entry = dictionary->FindEntry(index);
2836 if (entry != NumberDictionary::kNotFound) {
2837 Object* result = dictionary->ValueAt(entry);
2838 PropertyDetails details = dictionary->DetailsAt(entry);
2839 if (details.IsReadOnly()) return Heap::undefined_value();
2840 if (details.type() == CALLBACKS) {
Leon Clarkef7060e22010-06-03 12:02:55 +01002841 if (result->IsFixedArray()) {
2842 return result;
2843 }
2844 // Otherwise allow to override it.
Steve Blocka7e24c12009-10-30 11:49:00 +00002845 }
2846 }
2847 break;
2848 }
2849 default:
2850 UNREACHABLE();
2851 break;
2852 }
2853 } else {
2854 // Lookup the name.
2855 LookupResult result;
2856 LocalLookup(name, &result);
Andrei Popescu402d9372010-02-26 13:31:12 +00002857 if (result.IsProperty()) {
Steve Blocka7e24c12009-10-30 11:49:00 +00002858 if (result.IsReadOnly()) return Heap::undefined_value();
2859 if (result.type() == CALLBACKS) {
2860 Object* obj = result.GetCallbackObject();
Leon Clarkef7060e22010-06-03 12:02:55 +01002861 // Need to preserve old getters/setters.
Leon Clarked91b9f72010-01-27 17:25:45 +00002862 if (obj->IsFixedArray()) {
Leon Clarkef7060e22010-06-03 12:02:55 +01002863 // Use set to update attributes.
2864 return SetPropertyCallback(name, obj, attributes);
Leon Clarked91b9f72010-01-27 17:25:45 +00002865 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002866 }
2867 }
2868 }
2869
2870 // Allocate the fixed array to hold getter and setter.
2871 Object* structure = Heap::AllocateFixedArray(2, TENURED);
2872 if (structure->IsFailure()) return structure;
Steve Blocka7e24c12009-10-30 11:49:00 +00002873
2874 if (is_element) {
Leon Clarkef7060e22010-06-03 12:02:55 +01002875 return SetElementCallback(index, structure, attributes);
Steve Blocka7e24c12009-10-30 11:49:00 +00002876 } else {
Leon Clarkef7060e22010-06-03 12:02:55 +01002877 return SetPropertyCallback(name, structure, attributes);
Steve Blocka7e24c12009-10-30 11:49:00 +00002878 }
Leon Clarkef7060e22010-06-03 12:02:55 +01002879}
2880
2881
2882bool JSObject::CanSetCallback(String* name) {
2883 ASSERT(!IsAccessCheckNeeded()
2884 || Top::MayNamedAccess(this, name, v8::ACCESS_SET));
2885
2886 // Check if there is an API defined callback object which prohibits
2887 // callback overwriting in this object or it's prototype chain.
2888 // This mechanism is needed for instance in a browser setting, where
2889 // certain accessors such as window.location should not be allowed
2890 // to be overwritten because allowing overwriting could potentially
2891 // cause security problems.
2892 LookupResult callback_result;
2893 LookupCallback(name, &callback_result);
2894 if (callback_result.IsProperty()) {
2895 Object* obj = callback_result.GetCallbackObject();
2896 if (obj->IsAccessorInfo() &&
2897 AccessorInfo::cast(obj)->prohibits_overwriting()) {
2898 return false;
2899 }
2900 }
2901
2902 return true;
2903}
2904
2905
2906Object* JSObject::SetElementCallback(uint32_t index,
2907 Object* structure,
2908 PropertyAttributes attributes) {
2909 PropertyDetails details = PropertyDetails(attributes, CALLBACKS);
2910
2911 // Normalize elements to make this operation simple.
2912 Object* ok = NormalizeElements();
2913 if (ok->IsFailure()) return ok;
2914
2915 // Update the dictionary with the new CALLBACKS property.
2916 Object* dict =
2917 element_dictionary()->Set(index, structure, details);
2918 if (dict->IsFailure()) return dict;
2919
2920 NumberDictionary* elements = NumberDictionary::cast(dict);
2921 elements->set_requires_slow_elements();
2922 // Set the potential new dictionary on the object.
2923 set_elements(elements);
Steve Blocka7e24c12009-10-30 11:49:00 +00002924
2925 return structure;
2926}
2927
2928
Leon Clarkef7060e22010-06-03 12:02:55 +01002929Object* JSObject::SetPropertyCallback(String* name,
2930 Object* structure,
2931 PropertyAttributes attributes) {
2932 PropertyDetails details = PropertyDetails(attributes, CALLBACKS);
2933
2934 bool convert_back_to_fast = HasFastProperties() &&
2935 (map()->instance_descriptors()->number_of_descriptors()
2936 < DescriptorArray::kMaxNumberOfDescriptors);
2937
2938 // Normalize object to make this operation simple.
2939 Object* ok = NormalizeProperties(CLEAR_INOBJECT_PROPERTIES, 0);
2940 if (ok->IsFailure()) return ok;
2941
2942 // For the global object allocate a new map to invalidate the global inline
2943 // caches which have a global property cell reference directly in the code.
2944 if (IsGlobalObject()) {
2945 Object* new_map = map()->CopyDropDescriptors();
2946 if (new_map->IsFailure()) return new_map;
2947 set_map(Map::cast(new_map));
2948 }
2949
2950 // Update the dictionary with the new CALLBACKS property.
2951 Object* result = SetNormalizedProperty(name, structure, details);
2952 if (result->IsFailure()) return result;
2953
2954 if (convert_back_to_fast) {
2955 ok = TransformToFastProperties(0);
2956 if (ok->IsFailure()) return ok;
2957 }
2958 return result;
2959}
2960
Steve Blocka7e24c12009-10-30 11:49:00 +00002961Object* JSObject::DefineAccessor(String* name, bool is_getter, JSFunction* fun,
2962 PropertyAttributes attributes) {
2963 // Check access rights if needed.
2964 if (IsAccessCheckNeeded() &&
Leon Clarkef7060e22010-06-03 12:02:55 +01002965 !Top::MayNamedAccess(this, name, v8::ACCESS_SET)) {
2966 Top::ReportFailedAccessCheck(this, v8::ACCESS_SET);
Steve Blocka7e24c12009-10-30 11:49:00 +00002967 return Heap::undefined_value();
2968 }
2969
2970 if (IsJSGlobalProxy()) {
2971 Object* proto = GetPrototype();
2972 if (proto->IsNull()) return this;
2973 ASSERT(proto->IsJSGlobalObject());
2974 return JSObject::cast(proto)->DefineAccessor(name, is_getter,
2975 fun, attributes);
2976 }
2977
2978 Object* array = DefineGetterSetter(name, attributes);
2979 if (array->IsFailure() || array->IsUndefined()) return array;
2980 FixedArray::cast(array)->set(is_getter ? 0 : 1, fun);
2981 return this;
2982}
2983
2984
Leon Clarkef7060e22010-06-03 12:02:55 +01002985Object* JSObject::DefineAccessor(AccessorInfo* info) {
2986 String* name = String::cast(info->name());
2987 // Check access rights if needed.
2988 if (IsAccessCheckNeeded() &&
2989 !Top::MayNamedAccess(this, name, v8::ACCESS_SET)) {
2990 Top::ReportFailedAccessCheck(this, v8::ACCESS_SET);
2991 return Heap::undefined_value();
2992 }
2993
2994 if (IsJSGlobalProxy()) {
2995 Object* proto = GetPrototype();
2996 if (proto->IsNull()) return this;
2997 ASSERT(proto->IsJSGlobalObject());
2998 return JSObject::cast(proto)->DefineAccessor(info);
2999 }
3000
3001 // Make sure that the top context does not change when doing callbacks or
3002 // interceptor calls.
3003 AssertNoContextChange ncc;
3004
3005 // Try to flatten before operating on the string.
3006 name->TryFlatten();
3007
3008 if (!CanSetCallback(name)) {
3009 return Heap::undefined_value();
3010 }
3011
3012 uint32_t index = 0;
3013 bool is_element = name->AsArrayIndex(&index);
3014
3015 if (is_element) {
3016 if (IsJSArray()) return Heap::undefined_value();
3017
3018 // Accessors overwrite previous callbacks (cf. with getters/setters).
3019 switch (GetElementsKind()) {
3020 case FAST_ELEMENTS:
3021 break;
3022 case PIXEL_ELEMENTS:
3023 case EXTERNAL_BYTE_ELEMENTS:
3024 case EXTERNAL_UNSIGNED_BYTE_ELEMENTS:
3025 case EXTERNAL_SHORT_ELEMENTS:
3026 case EXTERNAL_UNSIGNED_SHORT_ELEMENTS:
3027 case EXTERNAL_INT_ELEMENTS:
3028 case EXTERNAL_UNSIGNED_INT_ELEMENTS:
3029 case EXTERNAL_FLOAT_ELEMENTS:
3030 // Ignore getters and setters on pixel and external array
3031 // elements.
3032 return Heap::undefined_value();
3033 case DICTIONARY_ELEMENTS:
3034 break;
3035 default:
3036 UNREACHABLE();
3037 break;
3038 }
3039
Kristian Monsen50ef84f2010-07-29 15:18:00 +01003040 Object* ok = SetElementCallback(index, info, info->property_attributes());
3041 if (ok->IsFailure()) return ok;
Leon Clarkef7060e22010-06-03 12:02:55 +01003042 } else {
3043 // Lookup the name.
3044 LookupResult result;
3045 LocalLookup(name, &result);
3046 // ES5 forbids turning a property into an accessor if it's not
3047 // configurable (that is IsDontDelete in ES3 and v8), see 8.6.1 (Table 5).
3048 if (result.IsProperty() && (result.IsReadOnly() || result.IsDontDelete())) {
3049 return Heap::undefined_value();
3050 }
Kristian Monsen50ef84f2010-07-29 15:18:00 +01003051 Object* ok = SetPropertyCallback(name, info, info->property_attributes());
3052 if (ok->IsFailure()) return ok;
Leon Clarkef7060e22010-06-03 12:02:55 +01003053 }
3054
3055 return this;
3056}
3057
3058
Steve Blocka7e24c12009-10-30 11:49:00 +00003059Object* JSObject::LookupAccessor(String* name, bool is_getter) {
3060 // Make sure that the top context does not change when doing callbacks or
3061 // interceptor calls.
3062 AssertNoContextChange ncc;
3063
3064 // Check access rights if needed.
3065 if (IsAccessCheckNeeded() &&
3066 !Top::MayNamedAccess(this, name, v8::ACCESS_HAS)) {
3067 Top::ReportFailedAccessCheck(this, v8::ACCESS_HAS);
3068 return Heap::undefined_value();
3069 }
3070
3071 // Make the lookup and include prototypes.
3072 int accessor_index = is_getter ? kGetterIndex : kSetterIndex;
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01003073 uint32_t index = 0;
Steve Blocka7e24c12009-10-30 11:49:00 +00003074 if (name->AsArrayIndex(&index)) {
3075 for (Object* obj = this;
3076 obj != Heap::null_value();
3077 obj = JSObject::cast(obj)->GetPrototype()) {
3078 JSObject* js_object = JSObject::cast(obj);
3079 if (js_object->HasDictionaryElements()) {
3080 NumberDictionary* dictionary = js_object->element_dictionary();
3081 int entry = dictionary->FindEntry(index);
3082 if (entry != NumberDictionary::kNotFound) {
3083 Object* element = dictionary->ValueAt(entry);
3084 PropertyDetails details = dictionary->DetailsAt(entry);
3085 if (details.type() == CALLBACKS) {
Leon Clarkef7060e22010-06-03 12:02:55 +01003086 if (element->IsFixedArray()) {
3087 return FixedArray::cast(element)->get(accessor_index);
3088 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003089 }
3090 }
3091 }
3092 }
3093 } else {
3094 for (Object* obj = this;
3095 obj != Heap::null_value();
3096 obj = JSObject::cast(obj)->GetPrototype()) {
3097 LookupResult result;
3098 JSObject::cast(obj)->LocalLookup(name, &result);
Andrei Popescu402d9372010-02-26 13:31:12 +00003099 if (result.IsProperty()) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003100 if (result.IsReadOnly()) return Heap::undefined_value();
3101 if (result.type() == CALLBACKS) {
3102 Object* obj = result.GetCallbackObject();
3103 if (obj->IsFixedArray()) {
3104 return FixedArray::cast(obj)->get(accessor_index);
3105 }
3106 }
3107 }
3108 }
3109 }
3110 return Heap::undefined_value();
3111}
3112
3113
3114Object* JSObject::SlowReverseLookup(Object* value) {
3115 if (HasFastProperties()) {
3116 DescriptorArray* descs = map()->instance_descriptors();
3117 for (int i = 0; i < descs->number_of_descriptors(); i++) {
3118 if (descs->GetType(i) == FIELD) {
3119 if (FastPropertyAt(descs->GetFieldIndex(i)) == value) {
3120 return descs->GetKey(i);
3121 }
3122 } else if (descs->GetType(i) == CONSTANT_FUNCTION) {
3123 if (descs->GetConstantFunction(i) == value) {
3124 return descs->GetKey(i);
3125 }
3126 }
3127 }
3128 return Heap::undefined_value();
3129 } else {
3130 return property_dictionary()->SlowReverseLookup(value);
3131 }
3132}
3133
3134
3135Object* Map::CopyDropDescriptors() {
3136 Object* result = Heap::AllocateMap(instance_type(), instance_size());
3137 if (result->IsFailure()) return result;
3138 Map::cast(result)->set_prototype(prototype());
3139 Map::cast(result)->set_constructor(constructor());
3140 // Don't copy descriptors, so map transitions always remain a forest.
3141 // If we retained the same descriptors we would have two maps
3142 // pointing to the same transition which is bad because the garbage
3143 // collector relies on being able to reverse pointers from transitions
3144 // to maps. If properties need to be retained use CopyDropTransitions.
3145 Map::cast(result)->set_instance_descriptors(Heap::empty_descriptor_array());
3146 // Please note instance_type and instance_size are set when allocated.
3147 Map::cast(result)->set_inobject_properties(inobject_properties());
3148 Map::cast(result)->set_unused_property_fields(unused_property_fields());
3149
3150 // If the map has pre-allocated properties always start out with a descriptor
3151 // array describing these properties.
3152 if (pre_allocated_property_fields() > 0) {
3153 ASSERT(constructor()->IsJSFunction());
3154 JSFunction* ctor = JSFunction::cast(constructor());
3155 Object* descriptors =
3156 ctor->initial_map()->instance_descriptors()->RemoveTransitions();
3157 if (descriptors->IsFailure()) return descriptors;
3158 Map::cast(result)->set_instance_descriptors(
3159 DescriptorArray::cast(descriptors));
3160 Map::cast(result)->set_pre_allocated_property_fields(
3161 pre_allocated_property_fields());
3162 }
3163 Map::cast(result)->set_bit_field(bit_field());
3164 Map::cast(result)->set_bit_field2(bit_field2());
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003165 Map::cast(result)->set_is_shared(false);
Steve Blocka7e24c12009-10-30 11:49:00 +00003166 Map::cast(result)->ClearCodeCache();
3167 return result;
3168}
3169
3170
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003171Object* Map::CopyNormalized(PropertyNormalizationMode mode,
3172 NormalizedMapSharingMode sharing) {
Kristian Monsen80d68ea2010-09-08 11:05:35 +01003173 int new_instance_size = instance_size();
3174 if (mode == CLEAR_INOBJECT_PROPERTIES) {
3175 new_instance_size -= inobject_properties() * kPointerSize;
3176 }
3177
3178 Object* result = Heap::AllocateMap(instance_type(), new_instance_size);
3179 if (result->IsFailure()) return result;
3180
3181 if (mode != CLEAR_INOBJECT_PROPERTIES) {
3182 Map::cast(result)->set_inobject_properties(inobject_properties());
3183 }
3184
3185 Map::cast(result)->set_prototype(prototype());
3186 Map::cast(result)->set_constructor(constructor());
3187
3188 Map::cast(result)->set_bit_field(bit_field());
3189 Map::cast(result)->set_bit_field2(bit_field2());
3190
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003191 Map::cast(result)->set_is_shared(sharing == SHARED_NORMALIZED_MAP);
3192
Kristian Monsen80d68ea2010-09-08 11:05:35 +01003193#ifdef DEBUG
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003194 if (Map::cast(result)->is_shared()) {
3195 Map::cast(result)->SharedMapVerify();
3196 }
Kristian Monsen80d68ea2010-09-08 11:05:35 +01003197#endif
3198
3199 return result;
3200}
3201
3202
Steve Blocka7e24c12009-10-30 11:49:00 +00003203Object* Map::CopyDropTransitions() {
3204 Object* new_map = CopyDropDescriptors();
3205 if (new_map->IsFailure()) return new_map;
3206 Object* descriptors = instance_descriptors()->RemoveTransitions();
3207 if (descriptors->IsFailure()) return descriptors;
3208 cast(new_map)->set_instance_descriptors(DescriptorArray::cast(descriptors));
Steve Block8defd9f2010-07-08 12:39:36 +01003209 return new_map;
Steve Blocka7e24c12009-10-30 11:49:00 +00003210}
3211
3212
3213Object* Map::UpdateCodeCache(String* name, Code* code) {
Steve Block6ded16b2010-05-10 14:33:55 +01003214 // Allocate the code cache if not present.
3215 if (code_cache()->IsFixedArray()) {
3216 Object* result = Heap::AllocateCodeCache();
3217 if (result->IsFailure()) return result;
3218 set_code_cache(result);
3219 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003220
Steve Block6ded16b2010-05-10 14:33:55 +01003221 // Update the code cache.
3222 return CodeCache::cast(code_cache())->Update(name, code);
3223}
3224
3225
3226Object* Map::FindInCodeCache(String* name, Code::Flags flags) {
3227 // Do a lookup if a code cache exists.
3228 if (!code_cache()->IsFixedArray()) {
3229 return CodeCache::cast(code_cache())->Lookup(name, flags);
3230 } else {
3231 return Heap::undefined_value();
3232 }
3233}
3234
3235
3236int Map::IndexInCodeCache(Object* name, Code* code) {
3237 // Get the internal index if a code cache exists.
3238 if (!code_cache()->IsFixedArray()) {
3239 return CodeCache::cast(code_cache())->GetIndex(name, code);
3240 }
3241 return -1;
3242}
3243
3244
3245void Map::RemoveFromCodeCache(String* name, Code* code, int index) {
3246 // No GC is supposed to happen between a call to IndexInCodeCache and
3247 // RemoveFromCodeCache so the code cache must be there.
3248 ASSERT(!code_cache()->IsFixedArray());
3249 CodeCache::cast(code_cache())->RemoveByIndex(name, code, index);
3250}
3251
3252
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003253void Map::TraverseTransitionTree(TraverseCallback callback, void* data) {
3254 Map* current = this;
3255 while (current != Heap::meta_map()) {
3256 DescriptorArray* d = reinterpret_cast<DescriptorArray*>(
3257 *RawField(current, Map::kInstanceDescriptorsOffset));
3258 if (d == Heap::empty_descriptor_array()) {
3259 Map* prev = current->map();
3260 current->set_map(Heap::meta_map());
3261 callback(current, data);
3262 current = prev;
3263 continue;
3264 }
3265
3266 FixedArray* contents = reinterpret_cast<FixedArray*>(
3267 d->get(DescriptorArray::kContentArrayIndex));
3268 Object** map_or_index_field = RawField(contents, HeapObject::kMapOffset);
3269 Object* map_or_index = *map_or_index_field;
3270 bool map_done = true;
3271 for (int i = map_or_index->IsSmi() ? Smi::cast(map_or_index)->value() : 0;
3272 i < contents->length();
3273 i += 2) {
3274 PropertyDetails details(Smi::cast(contents->get(i + 1)));
3275 if (details.IsTransition()) {
3276 Map* next = reinterpret_cast<Map*>(contents->get(i));
3277 next->set_map(current);
3278 *map_or_index_field = Smi::FromInt(i + 2);
3279 current = next;
3280 map_done = false;
3281 break;
3282 }
3283 }
3284 if (!map_done) continue;
3285 *map_or_index_field = Heap::fixed_array_map();
3286 Map* prev = current->map();
3287 current->set_map(Heap::meta_map());
3288 callback(current, data);
3289 current = prev;
3290 }
3291}
3292
3293
Steve Block6ded16b2010-05-10 14:33:55 +01003294Object* CodeCache::Update(String* name, Code* code) {
3295 ASSERT(code->ic_state() == MONOMORPHIC);
3296
3297 // The number of monomorphic stubs for normal load/store/call IC's can grow to
3298 // a large number and therefore they need to go into a hash table. They are
3299 // used to load global properties from cells.
3300 if (code->type() == NORMAL) {
3301 // Make sure that a hash table is allocated for the normal load code cache.
3302 if (normal_type_cache()->IsUndefined()) {
3303 Object* result =
3304 CodeCacheHashTable::Allocate(CodeCacheHashTable::kInitialSize);
3305 if (result->IsFailure()) return result;
3306 set_normal_type_cache(result);
3307 }
3308 return UpdateNormalTypeCache(name, code);
3309 } else {
3310 ASSERT(default_cache()->IsFixedArray());
3311 return UpdateDefaultCache(name, code);
3312 }
3313}
3314
3315
3316Object* CodeCache::UpdateDefaultCache(String* name, Code* code) {
3317 // When updating the default code cache we disregard the type encoded in the
Steve Blocka7e24c12009-10-30 11:49:00 +00003318 // flags. This allows call constant stubs to overwrite call field
3319 // stubs, etc.
3320 Code::Flags flags = Code::RemoveTypeFromFlags(code->flags());
3321
3322 // First check whether we can update existing code cache without
3323 // extending it.
Steve Block6ded16b2010-05-10 14:33:55 +01003324 FixedArray* cache = default_cache();
Steve Blocka7e24c12009-10-30 11:49:00 +00003325 int length = cache->length();
3326 int deleted_index = -1;
Steve Block6ded16b2010-05-10 14:33:55 +01003327 for (int i = 0; i < length; i += kCodeCacheEntrySize) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003328 Object* key = cache->get(i);
3329 if (key->IsNull()) {
3330 if (deleted_index < 0) deleted_index = i;
3331 continue;
3332 }
3333 if (key->IsUndefined()) {
3334 if (deleted_index >= 0) i = deleted_index;
Steve Block6ded16b2010-05-10 14:33:55 +01003335 cache->set(i + kCodeCacheEntryNameOffset, name);
3336 cache->set(i + kCodeCacheEntryCodeOffset, code);
Steve Blocka7e24c12009-10-30 11:49:00 +00003337 return this;
3338 }
3339 if (name->Equals(String::cast(key))) {
Steve Block6ded16b2010-05-10 14:33:55 +01003340 Code::Flags found =
3341 Code::cast(cache->get(i + kCodeCacheEntryCodeOffset))->flags();
Steve Blocka7e24c12009-10-30 11:49:00 +00003342 if (Code::RemoveTypeFromFlags(found) == flags) {
Steve Block6ded16b2010-05-10 14:33:55 +01003343 cache->set(i + kCodeCacheEntryCodeOffset, code);
Steve Blocka7e24c12009-10-30 11:49:00 +00003344 return this;
3345 }
3346 }
3347 }
3348
3349 // Reached the end of the code cache. If there were deleted
3350 // elements, reuse the space for the first of them.
3351 if (deleted_index >= 0) {
Steve Block6ded16b2010-05-10 14:33:55 +01003352 cache->set(deleted_index + kCodeCacheEntryNameOffset, name);
3353 cache->set(deleted_index + kCodeCacheEntryCodeOffset, code);
Steve Blocka7e24c12009-10-30 11:49:00 +00003354 return this;
3355 }
3356
Steve Block6ded16b2010-05-10 14:33:55 +01003357 // Extend the code cache with some new entries (at least one). Must be a
3358 // multiple of the entry size.
3359 int new_length = length + ((length >> 1)) + kCodeCacheEntrySize;
3360 new_length = new_length - new_length % kCodeCacheEntrySize;
3361 ASSERT((new_length % kCodeCacheEntrySize) == 0);
Steve Blocka7e24c12009-10-30 11:49:00 +00003362 Object* result = cache->CopySize(new_length);
3363 if (result->IsFailure()) return result;
3364
3365 // Add the (name, code) pair to the new cache.
3366 cache = FixedArray::cast(result);
Steve Block6ded16b2010-05-10 14:33:55 +01003367 cache->set(length + kCodeCacheEntryNameOffset, name);
3368 cache->set(length + kCodeCacheEntryCodeOffset, code);
3369 set_default_cache(cache);
Steve Blocka7e24c12009-10-30 11:49:00 +00003370 return this;
3371}
3372
3373
Steve Block6ded16b2010-05-10 14:33:55 +01003374Object* CodeCache::UpdateNormalTypeCache(String* name, Code* code) {
3375 // Adding a new entry can cause a new cache to be allocated.
3376 CodeCacheHashTable* cache = CodeCacheHashTable::cast(normal_type_cache());
3377 Object* new_cache = cache->Put(name, code);
3378 if (new_cache->IsFailure()) return new_cache;
3379 set_normal_type_cache(new_cache);
3380 return this;
3381}
3382
3383
3384Object* CodeCache::Lookup(String* name, Code::Flags flags) {
3385 if (Code::ExtractTypeFromFlags(flags) == NORMAL) {
3386 return LookupNormalTypeCache(name, flags);
3387 } else {
3388 return LookupDefaultCache(name, flags);
3389 }
3390}
3391
3392
3393Object* CodeCache::LookupDefaultCache(String* name, Code::Flags flags) {
3394 FixedArray* cache = default_cache();
Steve Blocka7e24c12009-10-30 11:49:00 +00003395 int length = cache->length();
Steve Block6ded16b2010-05-10 14:33:55 +01003396 for (int i = 0; i < length; i += kCodeCacheEntrySize) {
3397 Object* key = cache->get(i + kCodeCacheEntryNameOffset);
Steve Blocka7e24c12009-10-30 11:49:00 +00003398 // Skip deleted elements.
3399 if (key->IsNull()) continue;
3400 if (key->IsUndefined()) return key;
3401 if (name->Equals(String::cast(key))) {
Steve Block6ded16b2010-05-10 14:33:55 +01003402 Code* code = Code::cast(cache->get(i + kCodeCacheEntryCodeOffset));
3403 if (code->flags() == flags) {
3404 return code;
3405 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003406 }
3407 }
3408 return Heap::undefined_value();
3409}
3410
3411
Steve Block6ded16b2010-05-10 14:33:55 +01003412Object* CodeCache::LookupNormalTypeCache(String* name, Code::Flags flags) {
3413 if (!normal_type_cache()->IsUndefined()) {
3414 CodeCacheHashTable* cache = CodeCacheHashTable::cast(normal_type_cache());
3415 return cache->Lookup(name, flags);
3416 } else {
3417 return Heap::undefined_value();
3418 }
3419}
3420
3421
3422int CodeCache::GetIndex(Object* name, Code* code) {
3423 if (code->type() == NORMAL) {
3424 if (normal_type_cache()->IsUndefined()) return -1;
3425 CodeCacheHashTable* cache = CodeCacheHashTable::cast(normal_type_cache());
3426 return cache->GetIndex(String::cast(name), code->flags());
3427 }
3428
3429 FixedArray* array = default_cache();
Steve Blocka7e24c12009-10-30 11:49:00 +00003430 int len = array->length();
Steve Block6ded16b2010-05-10 14:33:55 +01003431 for (int i = 0; i < len; i += kCodeCacheEntrySize) {
3432 if (array->get(i + kCodeCacheEntryCodeOffset) == code) return i + 1;
Steve Blocka7e24c12009-10-30 11:49:00 +00003433 }
3434 return -1;
3435}
3436
3437
Steve Block6ded16b2010-05-10 14:33:55 +01003438void CodeCache::RemoveByIndex(Object* name, Code* code, int index) {
3439 if (code->type() == NORMAL) {
3440 ASSERT(!normal_type_cache()->IsUndefined());
3441 CodeCacheHashTable* cache = CodeCacheHashTable::cast(normal_type_cache());
3442 ASSERT(cache->GetIndex(String::cast(name), code->flags()) == index);
3443 cache->RemoveByIndex(index);
3444 } else {
3445 FixedArray* array = default_cache();
3446 ASSERT(array->length() >= index && array->get(index)->IsCode());
3447 // Use null instead of undefined for deleted elements to distinguish
3448 // deleted elements from unused elements. This distinction is used
3449 // when looking up in the cache and when updating the cache.
3450 ASSERT_EQ(1, kCodeCacheEntryCodeOffset - kCodeCacheEntryNameOffset);
3451 array->set_null(index - 1); // Name.
3452 array->set_null(index); // Code.
3453 }
3454}
3455
3456
3457// The key in the code cache hash table consists of the property name and the
3458// code object. The actual match is on the name and the code flags. If a key
3459// is created using the flags and not a code object it can only be used for
3460// lookup not to create a new entry.
3461class CodeCacheHashTableKey : public HashTableKey {
3462 public:
3463 CodeCacheHashTableKey(String* name, Code::Flags flags)
3464 : name_(name), flags_(flags), code_(NULL) { }
3465
3466 CodeCacheHashTableKey(String* name, Code* code)
3467 : name_(name),
3468 flags_(code->flags()),
3469 code_(code) { }
3470
3471
3472 bool IsMatch(Object* other) {
3473 if (!other->IsFixedArray()) return false;
3474 FixedArray* pair = FixedArray::cast(other);
3475 String* name = String::cast(pair->get(0));
3476 Code::Flags flags = Code::cast(pair->get(1))->flags();
3477 if (flags != flags_) {
3478 return false;
3479 }
3480 return name_->Equals(name);
3481 }
3482
3483 static uint32_t NameFlagsHashHelper(String* name, Code::Flags flags) {
3484 return name->Hash() ^ flags;
3485 }
3486
3487 uint32_t Hash() { return NameFlagsHashHelper(name_, flags_); }
3488
3489 uint32_t HashForObject(Object* obj) {
3490 FixedArray* pair = FixedArray::cast(obj);
3491 String* name = String::cast(pair->get(0));
3492 Code* code = Code::cast(pair->get(1));
3493 return NameFlagsHashHelper(name, code->flags());
3494 }
3495
3496 Object* AsObject() {
3497 ASSERT(code_ != NULL);
3498 Object* obj = Heap::AllocateFixedArray(2);
3499 if (obj->IsFailure()) return obj;
3500 FixedArray* pair = FixedArray::cast(obj);
3501 pair->set(0, name_);
3502 pair->set(1, code_);
3503 return pair;
3504 }
3505
3506 private:
3507 String* name_;
3508 Code::Flags flags_;
3509 Code* code_;
3510};
3511
3512
3513Object* CodeCacheHashTable::Lookup(String* name, Code::Flags flags) {
3514 CodeCacheHashTableKey key(name, flags);
3515 int entry = FindEntry(&key);
3516 if (entry == kNotFound) return Heap::undefined_value();
3517 return get(EntryToIndex(entry) + 1);
3518}
3519
3520
3521Object* CodeCacheHashTable::Put(String* name, Code* code) {
3522 CodeCacheHashTableKey key(name, code);
3523 Object* obj = EnsureCapacity(1, &key);
3524 if (obj->IsFailure()) return obj;
3525
3526 // Don't use this, as the table might have grown.
3527 CodeCacheHashTable* cache = reinterpret_cast<CodeCacheHashTable*>(obj);
3528
3529 int entry = cache->FindInsertionEntry(key.Hash());
3530 Object* k = key.AsObject();
3531 if (k->IsFailure()) return k;
3532
3533 cache->set(EntryToIndex(entry), k);
3534 cache->set(EntryToIndex(entry) + 1, code);
3535 cache->ElementAdded();
3536 return cache;
3537}
3538
3539
3540int CodeCacheHashTable::GetIndex(String* name, Code::Flags flags) {
3541 CodeCacheHashTableKey key(name, flags);
3542 int entry = FindEntry(&key);
3543 return (entry == kNotFound) ? -1 : entry;
3544}
3545
3546
3547void CodeCacheHashTable::RemoveByIndex(int index) {
3548 ASSERT(index >= 0);
3549 set(EntryToIndex(index), Heap::null_value());
3550 set(EntryToIndex(index) + 1, Heap::null_value());
3551 ElementRemoved();
Steve Blocka7e24c12009-10-30 11:49:00 +00003552}
3553
3554
Steve Blocka7e24c12009-10-30 11:49:00 +00003555static bool HasKey(FixedArray* array, Object* key) {
3556 int len0 = array->length();
3557 for (int i = 0; i < len0; i++) {
3558 Object* element = array->get(i);
3559 if (element->IsSmi() && key->IsSmi() && (element == key)) return true;
3560 if (element->IsString() &&
3561 key->IsString() && String::cast(element)->Equals(String::cast(key))) {
3562 return true;
3563 }
3564 }
3565 return false;
3566}
3567
3568
3569Object* FixedArray::AddKeysFromJSArray(JSArray* array) {
Steve Block3ce2e202009-11-05 08:53:23 +00003570 ASSERT(!array->HasPixelElements() && !array->HasExternalArrayElements());
Steve Blocka7e24c12009-10-30 11:49:00 +00003571 switch (array->GetElementsKind()) {
3572 case JSObject::FAST_ELEMENTS:
3573 return UnionOfKeys(FixedArray::cast(array->elements()));
3574 case JSObject::DICTIONARY_ELEMENTS: {
3575 NumberDictionary* dict = array->element_dictionary();
3576 int size = dict->NumberOfElements();
3577
3578 // Allocate a temporary fixed array.
3579 Object* object = Heap::AllocateFixedArray(size);
3580 if (object->IsFailure()) return object;
3581 FixedArray* key_array = FixedArray::cast(object);
3582
3583 int capacity = dict->Capacity();
3584 int pos = 0;
3585 // Copy the elements from the JSArray to the temporary fixed array.
3586 for (int i = 0; i < capacity; i++) {
3587 if (dict->IsKey(dict->KeyAt(i))) {
3588 key_array->set(pos++, dict->ValueAt(i));
3589 }
3590 }
3591 // Compute the union of this and the temporary fixed array.
3592 return UnionOfKeys(key_array);
3593 }
3594 default:
3595 UNREACHABLE();
3596 }
3597 UNREACHABLE();
3598 return Heap::null_value(); // Failure case needs to "return" a value.
3599}
3600
3601
3602Object* FixedArray::UnionOfKeys(FixedArray* other) {
3603 int len0 = length();
3604 int len1 = other->length();
3605 // Optimize if either is empty.
3606 if (len0 == 0) return other;
3607 if (len1 == 0) return this;
3608
3609 // Compute how many elements are not in this.
3610 int extra = 0;
3611 for (int y = 0; y < len1; y++) {
3612 Object* value = other->get(y);
3613 if (!value->IsTheHole() && !HasKey(this, value)) extra++;
3614 }
3615
3616 if (extra == 0) return this;
3617
3618 // Allocate the result
3619 Object* obj = Heap::AllocateFixedArray(len0 + extra);
3620 if (obj->IsFailure()) return obj;
3621 // Fill in the content
Leon Clarke4515c472010-02-03 11:58:03 +00003622 AssertNoAllocation no_gc;
Steve Blocka7e24c12009-10-30 11:49:00 +00003623 FixedArray* result = FixedArray::cast(obj);
Leon Clarke4515c472010-02-03 11:58:03 +00003624 WriteBarrierMode mode = result->GetWriteBarrierMode(no_gc);
Steve Blocka7e24c12009-10-30 11:49:00 +00003625 for (int i = 0; i < len0; i++) {
3626 result->set(i, get(i), mode);
3627 }
3628 // Fill in the extra keys.
3629 int index = 0;
3630 for (int y = 0; y < len1; y++) {
3631 Object* value = other->get(y);
3632 if (!value->IsTheHole() && !HasKey(this, value)) {
3633 result->set(len0 + index, other->get(y), mode);
3634 index++;
3635 }
3636 }
3637 ASSERT(extra == index);
3638 return result;
3639}
3640
3641
3642Object* FixedArray::CopySize(int new_length) {
3643 if (new_length == 0) return Heap::empty_fixed_array();
3644 Object* obj = Heap::AllocateFixedArray(new_length);
3645 if (obj->IsFailure()) return obj;
3646 FixedArray* result = FixedArray::cast(obj);
3647 // Copy the content
Leon Clarke4515c472010-02-03 11:58:03 +00003648 AssertNoAllocation no_gc;
Steve Blocka7e24c12009-10-30 11:49:00 +00003649 int len = length();
3650 if (new_length < len) len = new_length;
3651 result->set_map(map());
Leon Clarke4515c472010-02-03 11:58:03 +00003652 WriteBarrierMode mode = result->GetWriteBarrierMode(no_gc);
Steve Blocka7e24c12009-10-30 11:49:00 +00003653 for (int i = 0; i < len; i++) {
3654 result->set(i, get(i), mode);
3655 }
3656 return result;
3657}
3658
3659
3660void FixedArray::CopyTo(int pos, FixedArray* dest, int dest_pos, int len) {
Leon Clarke4515c472010-02-03 11:58:03 +00003661 AssertNoAllocation no_gc;
3662 WriteBarrierMode mode = dest->GetWriteBarrierMode(no_gc);
Steve Blocka7e24c12009-10-30 11:49:00 +00003663 for (int index = 0; index < len; index++) {
3664 dest->set(dest_pos+index, get(pos+index), mode);
3665 }
3666}
3667
3668
3669#ifdef DEBUG
3670bool FixedArray::IsEqualTo(FixedArray* other) {
3671 if (length() != other->length()) return false;
3672 for (int i = 0 ; i < length(); ++i) {
3673 if (get(i) != other->get(i)) return false;
3674 }
3675 return true;
3676}
3677#endif
3678
3679
3680Object* DescriptorArray::Allocate(int number_of_descriptors) {
3681 if (number_of_descriptors == 0) {
3682 return Heap::empty_descriptor_array();
3683 }
3684 // Allocate the array of keys.
Leon Clarkee46be812010-01-19 14:06:41 +00003685 Object* array =
3686 Heap::AllocateFixedArray(ToKeyIndex(number_of_descriptors));
Steve Blocka7e24c12009-10-30 11:49:00 +00003687 if (array->IsFailure()) return array;
3688 // Do not use DescriptorArray::cast on incomplete object.
3689 FixedArray* result = FixedArray::cast(array);
3690
3691 // Allocate the content array and set it in the descriptor array.
3692 array = Heap::AllocateFixedArray(number_of_descriptors << 1);
3693 if (array->IsFailure()) return array;
3694 result->set(kContentArrayIndex, array);
3695 result->set(kEnumerationIndexIndex,
Leon Clarke4515c472010-02-03 11:58:03 +00003696 Smi::FromInt(PropertyDetails::kInitialIndex));
Steve Blocka7e24c12009-10-30 11:49:00 +00003697 return result;
3698}
3699
3700
3701void DescriptorArray::SetEnumCache(FixedArray* bridge_storage,
3702 FixedArray* new_cache) {
3703 ASSERT(bridge_storage->length() >= kEnumCacheBridgeLength);
3704 if (HasEnumCache()) {
3705 FixedArray::cast(get(kEnumerationIndexIndex))->
3706 set(kEnumCacheBridgeCacheIndex, new_cache);
3707 } else {
3708 if (IsEmpty()) return; // Do nothing for empty descriptor array.
3709 FixedArray::cast(bridge_storage)->
3710 set(kEnumCacheBridgeCacheIndex, new_cache);
3711 fast_set(FixedArray::cast(bridge_storage),
3712 kEnumCacheBridgeEnumIndex,
3713 get(kEnumerationIndexIndex));
3714 set(kEnumerationIndexIndex, bridge_storage);
3715 }
3716}
3717
3718
3719Object* DescriptorArray::CopyInsert(Descriptor* descriptor,
3720 TransitionFlag transition_flag) {
3721 // Transitions are only kept when inserting another transition.
3722 // This precondition is not required by this function's implementation, but
3723 // is currently required by the semantics of maps, so we check it.
3724 // Conversely, we filter after replacing, so replacing a transition and
3725 // removing all other transitions is not supported.
3726 bool remove_transitions = transition_flag == REMOVE_TRANSITIONS;
3727 ASSERT(remove_transitions == !descriptor->GetDetails().IsTransition());
3728 ASSERT(descriptor->GetDetails().type() != NULL_DESCRIPTOR);
3729
3730 // Ensure the key is a symbol.
3731 Object* result = descriptor->KeyToSymbol();
3732 if (result->IsFailure()) return result;
3733
3734 int transitions = 0;
3735 int null_descriptors = 0;
3736 if (remove_transitions) {
3737 for (int i = 0; i < number_of_descriptors(); i++) {
3738 if (IsTransition(i)) transitions++;
3739 if (IsNullDescriptor(i)) null_descriptors++;
3740 }
3741 } else {
3742 for (int i = 0; i < number_of_descriptors(); i++) {
3743 if (IsNullDescriptor(i)) null_descriptors++;
3744 }
3745 }
3746 int new_size = number_of_descriptors() - transitions - null_descriptors;
3747
3748 // If key is in descriptor, we replace it in-place when filtering.
3749 // Count a null descriptor for key as inserted, not replaced.
3750 int index = Search(descriptor->GetKey());
3751 const bool inserting = (index == kNotFound);
3752 const bool replacing = !inserting;
3753 bool keep_enumeration_index = false;
3754 if (inserting) {
3755 ++new_size;
3756 }
3757 if (replacing) {
3758 // We are replacing an existing descriptor. We keep the enumeration
3759 // index of a visible property.
3760 PropertyType t = PropertyDetails(GetDetails(index)).type();
3761 if (t == CONSTANT_FUNCTION ||
3762 t == FIELD ||
3763 t == CALLBACKS ||
3764 t == INTERCEPTOR) {
3765 keep_enumeration_index = true;
3766 } else if (remove_transitions) {
3767 // Replaced descriptor has been counted as removed if it is
3768 // a transition that will be replaced. Adjust count in this case.
3769 ++new_size;
3770 }
3771 }
3772 result = Allocate(new_size);
3773 if (result->IsFailure()) return result;
3774 DescriptorArray* new_descriptors = DescriptorArray::cast(result);
3775 // Set the enumeration index in the descriptors and set the enumeration index
3776 // in the result.
3777 int enumeration_index = NextEnumerationIndex();
3778 if (!descriptor->GetDetails().IsTransition()) {
3779 if (keep_enumeration_index) {
3780 descriptor->SetEnumerationIndex(
3781 PropertyDetails(GetDetails(index)).index());
3782 } else {
3783 descriptor->SetEnumerationIndex(enumeration_index);
3784 ++enumeration_index;
3785 }
3786 }
3787 new_descriptors->SetNextEnumerationIndex(enumeration_index);
3788
3789 // Copy the descriptors, filtering out transitions and null descriptors,
3790 // and inserting or replacing a descriptor.
3791 uint32_t descriptor_hash = descriptor->GetKey()->Hash();
3792 int from_index = 0;
3793 int to_index = 0;
3794
3795 for (; from_index < number_of_descriptors(); from_index++) {
3796 String* key = GetKey(from_index);
3797 if (key->Hash() > descriptor_hash || key == descriptor->GetKey()) {
3798 break;
3799 }
3800 if (IsNullDescriptor(from_index)) continue;
3801 if (remove_transitions && IsTransition(from_index)) continue;
3802 new_descriptors->CopyFrom(to_index++, this, from_index);
3803 }
3804
3805 new_descriptors->Set(to_index++, descriptor);
3806 if (replacing) from_index++;
3807
3808 for (; from_index < number_of_descriptors(); from_index++) {
3809 if (IsNullDescriptor(from_index)) continue;
3810 if (remove_transitions && IsTransition(from_index)) continue;
3811 new_descriptors->CopyFrom(to_index++, this, from_index);
3812 }
3813
3814 ASSERT(to_index == new_descriptors->number_of_descriptors());
3815 SLOW_ASSERT(new_descriptors->IsSortedNoDuplicates());
3816
3817 return new_descriptors;
3818}
3819
3820
3821Object* DescriptorArray::RemoveTransitions() {
3822 // Remove all transitions and null descriptors. Return a copy of the array
3823 // with all transitions removed, or a Failure object if the new array could
3824 // not be allocated.
3825
3826 // Compute the size of the map transition entries to be removed.
3827 int num_removed = 0;
3828 for (int i = 0; i < number_of_descriptors(); i++) {
3829 if (!IsProperty(i)) num_removed++;
3830 }
3831
3832 // Allocate the new descriptor array.
3833 Object* result = Allocate(number_of_descriptors() - num_removed);
3834 if (result->IsFailure()) return result;
3835 DescriptorArray* new_descriptors = DescriptorArray::cast(result);
3836
3837 // Copy the content.
3838 int next_descriptor = 0;
3839 for (int i = 0; i < number_of_descriptors(); i++) {
3840 if (IsProperty(i)) new_descriptors->CopyFrom(next_descriptor++, this, i);
3841 }
3842 ASSERT(next_descriptor == new_descriptors->number_of_descriptors());
3843
3844 return new_descriptors;
3845}
3846
3847
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003848void DescriptorArray::SortUnchecked() {
Steve Blocka7e24c12009-10-30 11:49:00 +00003849 // In-place heap sort.
3850 int len = number_of_descriptors();
3851
3852 // Bottom-up max-heap construction.
Steve Block6ded16b2010-05-10 14:33:55 +01003853 // Index of the last node with children
3854 const int max_parent_index = (len / 2) - 1;
3855 for (int i = max_parent_index; i >= 0; --i) {
3856 int parent_index = i;
3857 const uint32_t parent_hash = GetKey(i)->Hash();
3858 while (parent_index <= max_parent_index) {
3859 int child_index = 2 * parent_index + 1;
Steve Blocka7e24c12009-10-30 11:49:00 +00003860 uint32_t child_hash = GetKey(child_index)->Hash();
Steve Block6ded16b2010-05-10 14:33:55 +01003861 if (child_index + 1 < len) {
3862 uint32_t right_child_hash = GetKey(child_index + 1)->Hash();
3863 if (right_child_hash > child_hash) {
3864 child_index++;
3865 child_hash = right_child_hash;
3866 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003867 }
Steve Block6ded16b2010-05-10 14:33:55 +01003868 if (child_hash <= parent_hash) break;
3869 Swap(parent_index, child_index);
3870 // Now element at child_index could be < its children.
3871 parent_index = child_index; // parent_hash remains correct.
Steve Blocka7e24c12009-10-30 11:49:00 +00003872 }
3873 }
3874
3875 // Extract elements and create sorted array.
3876 for (int i = len - 1; i > 0; --i) {
3877 // Put max element at the back of the array.
3878 Swap(0, i);
3879 // Sift down the new top element.
3880 int parent_index = 0;
Steve Block6ded16b2010-05-10 14:33:55 +01003881 const uint32_t parent_hash = GetKey(parent_index)->Hash();
3882 const int max_parent_index = (i / 2) - 1;
3883 while (parent_index <= max_parent_index) {
3884 int child_index = parent_index * 2 + 1;
3885 uint32_t child_hash = GetKey(child_index)->Hash();
3886 if (child_index + 1 < i) {
3887 uint32_t right_child_hash = GetKey(child_index + 1)->Hash();
3888 if (right_child_hash > child_hash) {
3889 child_index++;
3890 child_hash = right_child_hash;
3891 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003892 }
Steve Block6ded16b2010-05-10 14:33:55 +01003893 if (child_hash <= parent_hash) break;
3894 Swap(parent_index, child_index);
3895 parent_index = child_index;
Steve Blocka7e24c12009-10-30 11:49:00 +00003896 }
3897 }
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003898}
Steve Blocka7e24c12009-10-30 11:49:00 +00003899
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003900
3901void DescriptorArray::Sort() {
3902 SortUnchecked();
Steve Blocka7e24c12009-10-30 11:49:00 +00003903 SLOW_ASSERT(IsSortedNoDuplicates());
3904}
3905
3906
3907int DescriptorArray::BinarySearch(String* name, int low, int high) {
3908 uint32_t hash = name->Hash();
3909
3910 while (low <= high) {
3911 int mid = (low + high) / 2;
3912 String* mid_name = GetKey(mid);
3913 uint32_t mid_hash = mid_name->Hash();
3914
3915 if (mid_hash > hash) {
3916 high = mid - 1;
3917 continue;
3918 }
3919 if (mid_hash < hash) {
3920 low = mid + 1;
3921 continue;
3922 }
3923 // Found an element with the same hash-code.
3924 ASSERT(hash == mid_hash);
3925 // There might be more, so we find the first one and
3926 // check them all to see if we have a match.
3927 if (name == mid_name && !is_null_descriptor(mid)) return mid;
3928 while ((mid > low) && (GetKey(mid - 1)->Hash() == hash)) mid--;
3929 for (; (mid <= high) && (GetKey(mid)->Hash() == hash); mid++) {
3930 if (GetKey(mid)->Equals(name) && !is_null_descriptor(mid)) return mid;
3931 }
3932 break;
3933 }
3934 return kNotFound;
3935}
3936
3937
3938int DescriptorArray::LinearSearch(String* name, int len) {
3939 uint32_t hash = name->Hash();
3940 for (int number = 0; number < len; number++) {
3941 String* entry = GetKey(number);
3942 if ((entry->Hash() == hash) &&
3943 name->Equals(entry) &&
3944 !is_null_descriptor(number)) {
3945 return number;
3946 }
3947 }
3948 return kNotFound;
3949}
3950
3951
3952#ifdef DEBUG
3953bool DescriptorArray::IsEqualTo(DescriptorArray* other) {
3954 if (IsEmpty()) return other->IsEmpty();
3955 if (other->IsEmpty()) return false;
3956 if (length() != other->length()) return false;
3957 for (int i = 0; i < length(); ++i) {
3958 if (get(i) != other->get(i) && i != kContentArrayIndex) return false;
3959 }
3960 return GetContentArray()->IsEqualTo(other->GetContentArray());
3961}
3962#endif
3963
3964
3965static StaticResource<StringInputBuffer> string_input_buffer;
3966
3967
3968bool String::LooksValid() {
3969 if (!Heap::Contains(this)) return false;
3970 return true;
3971}
3972
3973
3974int String::Utf8Length() {
3975 if (IsAsciiRepresentation()) return length();
3976 // Attempt to flatten before accessing the string. It probably
3977 // doesn't make Utf8Length faster, but it is very likely that
3978 // the string will be accessed later (for example by WriteUtf8)
3979 // so it's still a good idea.
Steve Block6ded16b2010-05-10 14:33:55 +01003980 TryFlatten();
Steve Blocka7e24c12009-10-30 11:49:00 +00003981 Access<StringInputBuffer> buffer(&string_input_buffer);
3982 buffer->Reset(0, this);
3983 int result = 0;
3984 while (buffer->has_more())
3985 result += unibrow::Utf8::Length(buffer->GetNext());
3986 return result;
3987}
3988
3989
3990Vector<const char> String::ToAsciiVector() {
3991 ASSERT(IsAsciiRepresentation());
3992 ASSERT(IsFlat());
3993
3994 int offset = 0;
3995 int length = this->length();
3996 StringRepresentationTag string_tag = StringShape(this).representation_tag();
3997 String* string = this;
Steve Blockd0582a62009-12-15 09:54:21 +00003998 if (string_tag == kConsStringTag) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003999 ConsString* cons = ConsString::cast(string);
4000 ASSERT(cons->second()->length() == 0);
4001 string = cons->first();
4002 string_tag = StringShape(string).representation_tag();
4003 }
4004 if (string_tag == kSeqStringTag) {
4005 SeqAsciiString* seq = SeqAsciiString::cast(string);
4006 char* start = seq->GetChars();
4007 return Vector<const char>(start + offset, length);
4008 }
4009 ASSERT(string_tag == kExternalStringTag);
4010 ExternalAsciiString* ext = ExternalAsciiString::cast(string);
4011 const char* start = ext->resource()->data();
4012 return Vector<const char>(start + offset, length);
4013}
4014
4015
4016Vector<const uc16> String::ToUC16Vector() {
4017 ASSERT(IsTwoByteRepresentation());
4018 ASSERT(IsFlat());
4019
4020 int offset = 0;
4021 int length = this->length();
4022 StringRepresentationTag string_tag = StringShape(this).representation_tag();
4023 String* string = this;
Steve Blockd0582a62009-12-15 09:54:21 +00004024 if (string_tag == kConsStringTag) {
Steve Blocka7e24c12009-10-30 11:49:00 +00004025 ConsString* cons = ConsString::cast(string);
4026 ASSERT(cons->second()->length() == 0);
4027 string = cons->first();
4028 string_tag = StringShape(string).representation_tag();
4029 }
4030 if (string_tag == kSeqStringTag) {
4031 SeqTwoByteString* seq = SeqTwoByteString::cast(string);
4032 return Vector<const uc16>(seq->GetChars() + offset, length);
4033 }
4034 ASSERT(string_tag == kExternalStringTag);
4035 ExternalTwoByteString* ext = ExternalTwoByteString::cast(string);
4036 const uc16* start =
4037 reinterpret_cast<const uc16*>(ext->resource()->data());
4038 return Vector<const uc16>(start + offset, length);
4039}
4040
4041
4042SmartPointer<char> String::ToCString(AllowNullsFlag allow_nulls,
4043 RobustnessFlag robust_flag,
4044 int offset,
4045 int length,
4046 int* length_return) {
4047 ASSERT(NativeAllocationChecker::allocation_allowed());
4048 if (robust_flag == ROBUST_STRING_TRAVERSAL && !LooksValid()) {
4049 return SmartPointer<char>(NULL);
4050 }
4051
4052 // Negative length means the to the end of the string.
4053 if (length < 0) length = kMaxInt - offset;
4054
4055 // Compute the size of the UTF-8 string. Start at the specified offset.
4056 Access<StringInputBuffer> buffer(&string_input_buffer);
4057 buffer->Reset(offset, this);
4058 int character_position = offset;
4059 int utf8_bytes = 0;
4060 while (buffer->has_more()) {
4061 uint16_t character = buffer->GetNext();
4062 if (character_position < offset + length) {
4063 utf8_bytes += unibrow::Utf8::Length(character);
4064 }
4065 character_position++;
4066 }
4067
4068 if (length_return) {
4069 *length_return = utf8_bytes;
4070 }
4071
4072 char* result = NewArray<char>(utf8_bytes + 1);
4073
4074 // Convert the UTF-16 string to a UTF-8 buffer. Start at the specified offset.
4075 buffer->Rewind();
4076 buffer->Seek(offset);
4077 character_position = offset;
4078 int utf8_byte_position = 0;
4079 while (buffer->has_more()) {
4080 uint16_t character = buffer->GetNext();
4081 if (character_position < offset + length) {
4082 if (allow_nulls == DISALLOW_NULLS && character == 0) {
4083 character = ' ';
4084 }
4085 utf8_byte_position +=
4086 unibrow::Utf8::Encode(result + utf8_byte_position, character);
4087 }
4088 character_position++;
4089 }
4090 result[utf8_byte_position] = 0;
4091 return SmartPointer<char>(result);
4092}
4093
4094
4095SmartPointer<char> String::ToCString(AllowNullsFlag allow_nulls,
4096 RobustnessFlag robust_flag,
4097 int* length_return) {
4098 return ToCString(allow_nulls, robust_flag, 0, -1, length_return);
4099}
4100
4101
4102const uc16* String::GetTwoByteData() {
4103 return GetTwoByteData(0);
4104}
4105
4106
4107const uc16* String::GetTwoByteData(unsigned start) {
4108 ASSERT(!IsAsciiRepresentation());
4109 switch (StringShape(this).representation_tag()) {
4110 case kSeqStringTag:
4111 return SeqTwoByteString::cast(this)->SeqTwoByteStringGetData(start);
4112 case kExternalStringTag:
4113 return ExternalTwoByteString::cast(this)->
4114 ExternalTwoByteStringGetData(start);
Steve Blocka7e24c12009-10-30 11:49:00 +00004115 case kConsStringTag:
4116 UNREACHABLE();
4117 return NULL;
4118 }
4119 UNREACHABLE();
4120 return NULL;
4121}
4122
4123
4124SmartPointer<uc16> String::ToWideCString(RobustnessFlag robust_flag) {
4125 ASSERT(NativeAllocationChecker::allocation_allowed());
4126
4127 if (robust_flag == ROBUST_STRING_TRAVERSAL && !LooksValid()) {
4128 return SmartPointer<uc16>();
4129 }
4130
4131 Access<StringInputBuffer> buffer(&string_input_buffer);
4132 buffer->Reset(this);
4133
4134 uc16* result = NewArray<uc16>(length() + 1);
4135
4136 int i = 0;
4137 while (buffer->has_more()) {
4138 uint16_t character = buffer->GetNext();
4139 result[i++] = character;
4140 }
4141 result[i] = 0;
4142 return SmartPointer<uc16>(result);
4143}
4144
4145
4146const uc16* SeqTwoByteString::SeqTwoByteStringGetData(unsigned start) {
4147 return reinterpret_cast<uc16*>(
4148 reinterpret_cast<char*>(this) - kHeapObjectTag + kHeaderSize) + start;
4149}
4150
4151
4152void SeqTwoByteString::SeqTwoByteStringReadBlockIntoBuffer(ReadBlockBuffer* rbb,
4153 unsigned* offset_ptr,
4154 unsigned max_chars) {
4155 unsigned chars_read = 0;
4156 unsigned offset = *offset_ptr;
4157 while (chars_read < max_chars) {
4158 uint16_t c = *reinterpret_cast<uint16_t*>(
4159 reinterpret_cast<char*>(this) -
4160 kHeapObjectTag + kHeaderSize + offset * kShortSize);
4161 if (c <= kMaxAsciiCharCode) {
4162 // Fast case for ASCII characters. Cursor is an input output argument.
4163 if (!unibrow::CharacterStream::EncodeAsciiCharacter(c,
4164 rbb->util_buffer,
4165 rbb->capacity,
4166 rbb->cursor)) {
4167 break;
4168 }
4169 } else {
4170 if (!unibrow::CharacterStream::EncodeNonAsciiCharacter(c,
4171 rbb->util_buffer,
4172 rbb->capacity,
4173 rbb->cursor)) {
4174 break;
4175 }
4176 }
4177 offset++;
4178 chars_read++;
4179 }
4180 *offset_ptr = offset;
4181 rbb->remaining += chars_read;
4182}
4183
4184
4185const unibrow::byte* SeqAsciiString::SeqAsciiStringReadBlock(
4186 unsigned* remaining,
4187 unsigned* offset_ptr,
4188 unsigned max_chars) {
4189 const unibrow::byte* b = reinterpret_cast<unibrow::byte*>(this) -
4190 kHeapObjectTag + kHeaderSize + *offset_ptr * kCharSize;
4191 *remaining = max_chars;
4192 *offset_ptr += max_chars;
4193 return b;
4194}
4195
4196
4197// This will iterate unless the block of string data spans two 'halves' of
4198// a ConsString, in which case it will recurse. Since the block of string
4199// data to be read has a maximum size this limits the maximum recursion
4200// depth to something sane. Since C++ does not have tail call recursion
4201// elimination, the iteration must be explicit. Since this is not an
4202// -IntoBuffer method it can delegate to one of the efficient
4203// *AsciiStringReadBlock routines.
4204const unibrow::byte* ConsString::ConsStringReadBlock(ReadBlockBuffer* rbb,
4205 unsigned* offset_ptr,
4206 unsigned max_chars) {
4207 ConsString* current = this;
4208 unsigned offset = *offset_ptr;
4209 int offset_correction = 0;
4210
4211 while (true) {
4212 String* left = current->first();
4213 unsigned left_length = (unsigned)left->length();
4214 if (left_length > offset &&
4215 (max_chars <= left_length - offset ||
4216 (rbb->capacity <= left_length - offset &&
4217 (max_chars = left_length - offset, true)))) { // comma operator!
4218 // Left hand side only - iterate unless we have reached the bottom of
4219 // the cons tree. The assignment on the left of the comma operator is
4220 // in order to make use of the fact that the -IntoBuffer routines can
4221 // produce at most 'capacity' characters. This enables us to postpone
4222 // the point where we switch to the -IntoBuffer routines (below) in order
4223 // to maximize the chances of delegating a big chunk of work to the
4224 // efficient *AsciiStringReadBlock routines.
4225 if (StringShape(left).IsCons()) {
4226 current = ConsString::cast(left);
4227 continue;
4228 } else {
4229 const unibrow::byte* answer =
4230 String::ReadBlock(left, rbb, &offset, max_chars);
4231 *offset_ptr = offset + offset_correction;
4232 return answer;
4233 }
4234 } else if (left_length <= offset) {
4235 // Right hand side only - iterate unless we have reached the bottom of
4236 // the cons tree.
4237 String* right = current->second();
4238 offset -= left_length;
4239 offset_correction += left_length;
4240 if (StringShape(right).IsCons()) {
4241 current = ConsString::cast(right);
4242 continue;
4243 } else {
4244 const unibrow::byte* answer =
4245 String::ReadBlock(right, rbb, &offset, max_chars);
4246 *offset_ptr = offset + offset_correction;
4247 return answer;
4248 }
4249 } else {
4250 // The block to be read spans two sides of the ConsString, so we call the
4251 // -IntoBuffer version, which will recurse. The -IntoBuffer methods
4252 // are able to assemble data from several part strings because they use
4253 // the util_buffer to store their data and never return direct pointers
4254 // to their storage. We don't try to read more than the buffer capacity
4255 // here or we can get too much recursion.
4256 ASSERT(rbb->remaining == 0);
4257 ASSERT(rbb->cursor == 0);
4258 current->ConsStringReadBlockIntoBuffer(
4259 rbb,
4260 &offset,
4261 max_chars > rbb->capacity ? rbb->capacity : max_chars);
4262 *offset_ptr = offset + offset_correction;
4263 return rbb->util_buffer;
4264 }
4265 }
4266}
4267
4268
Steve Blocka7e24c12009-10-30 11:49:00 +00004269uint16_t ExternalAsciiString::ExternalAsciiStringGet(int index) {
4270 ASSERT(index >= 0 && index < length());
4271 return resource()->data()[index];
4272}
4273
4274
4275const unibrow::byte* ExternalAsciiString::ExternalAsciiStringReadBlock(
4276 unsigned* remaining,
4277 unsigned* offset_ptr,
4278 unsigned max_chars) {
4279 // Cast const char* to unibrow::byte* (signedness difference).
4280 const unibrow::byte* b =
4281 reinterpret_cast<const unibrow::byte*>(resource()->data()) + *offset_ptr;
4282 *remaining = max_chars;
4283 *offset_ptr += max_chars;
4284 return b;
4285}
4286
4287
4288const uc16* ExternalTwoByteString::ExternalTwoByteStringGetData(
4289 unsigned start) {
4290 return resource()->data() + start;
4291}
4292
4293
4294uint16_t ExternalTwoByteString::ExternalTwoByteStringGet(int index) {
4295 ASSERT(index >= 0 && index < length());
4296 return resource()->data()[index];
4297}
4298
4299
4300void ExternalTwoByteString::ExternalTwoByteStringReadBlockIntoBuffer(
4301 ReadBlockBuffer* rbb,
4302 unsigned* offset_ptr,
4303 unsigned max_chars) {
4304 unsigned chars_read = 0;
4305 unsigned offset = *offset_ptr;
4306 const uint16_t* data = resource()->data();
4307 while (chars_read < max_chars) {
4308 uint16_t c = data[offset];
4309 if (c <= kMaxAsciiCharCode) {
4310 // Fast case for ASCII characters. Cursor is an input output argument.
4311 if (!unibrow::CharacterStream::EncodeAsciiCharacter(c,
4312 rbb->util_buffer,
4313 rbb->capacity,
4314 rbb->cursor))
4315 break;
4316 } else {
4317 if (!unibrow::CharacterStream::EncodeNonAsciiCharacter(c,
4318 rbb->util_buffer,
4319 rbb->capacity,
4320 rbb->cursor))
4321 break;
4322 }
4323 offset++;
4324 chars_read++;
4325 }
4326 *offset_ptr = offset;
4327 rbb->remaining += chars_read;
4328}
4329
4330
4331void SeqAsciiString::SeqAsciiStringReadBlockIntoBuffer(ReadBlockBuffer* rbb,
4332 unsigned* offset_ptr,
4333 unsigned max_chars) {
4334 unsigned capacity = rbb->capacity - rbb->cursor;
4335 if (max_chars > capacity) max_chars = capacity;
4336 memcpy(rbb->util_buffer + rbb->cursor,
4337 reinterpret_cast<char*>(this) - kHeapObjectTag + kHeaderSize +
4338 *offset_ptr * kCharSize,
4339 max_chars);
4340 rbb->remaining += max_chars;
4341 *offset_ptr += max_chars;
4342 rbb->cursor += max_chars;
4343}
4344
4345
4346void ExternalAsciiString::ExternalAsciiStringReadBlockIntoBuffer(
4347 ReadBlockBuffer* rbb,
4348 unsigned* offset_ptr,
4349 unsigned max_chars) {
4350 unsigned capacity = rbb->capacity - rbb->cursor;
4351 if (max_chars > capacity) max_chars = capacity;
4352 memcpy(rbb->util_buffer + rbb->cursor,
4353 resource()->data() + *offset_ptr,
4354 max_chars);
4355 rbb->remaining += max_chars;
4356 *offset_ptr += max_chars;
4357 rbb->cursor += max_chars;
4358}
4359
4360
4361// This method determines the type of string involved and then copies
4362// a whole chunk of characters into a buffer, or returns a pointer to a buffer
4363// where they can be found. The pointer is not necessarily valid across a GC
4364// (see AsciiStringReadBlock).
4365const unibrow::byte* String::ReadBlock(String* input,
4366 ReadBlockBuffer* rbb,
4367 unsigned* offset_ptr,
4368 unsigned max_chars) {
4369 ASSERT(*offset_ptr <= static_cast<unsigned>(input->length()));
4370 if (max_chars == 0) {
4371 rbb->remaining = 0;
4372 return NULL;
4373 }
4374 switch (StringShape(input).representation_tag()) {
4375 case kSeqStringTag:
4376 if (input->IsAsciiRepresentation()) {
4377 SeqAsciiString* str = SeqAsciiString::cast(input);
4378 return str->SeqAsciiStringReadBlock(&rbb->remaining,
4379 offset_ptr,
4380 max_chars);
4381 } else {
4382 SeqTwoByteString* str = SeqTwoByteString::cast(input);
4383 str->SeqTwoByteStringReadBlockIntoBuffer(rbb,
4384 offset_ptr,
4385 max_chars);
4386 return rbb->util_buffer;
4387 }
4388 case kConsStringTag:
4389 return ConsString::cast(input)->ConsStringReadBlock(rbb,
4390 offset_ptr,
4391 max_chars);
Steve Blocka7e24c12009-10-30 11:49:00 +00004392 case kExternalStringTag:
4393 if (input->IsAsciiRepresentation()) {
4394 return ExternalAsciiString::cast(input)->ExternalAsciiStringReadBlock(
4395 &rbb->remaining,
4396 offset_ptr,
4397 max_chars);
4398 } else {
4399 ExternalTwoByteString::cast(input)->
4400 ExternalTwoByteStringReadBlockIntoBuffer(rbb,
4401 offset_ptr,
4402 max_chars);
4403 return rbb->util_buffer;
4404 }
4405 default:
4406 break;
4407 }
4408
4409 UNREACHABLE();
4410 return 0;
4411}
4412
4413
4414Relocatable* Relocatable::top_ = NULL;
4415
4416
4417void Relocatable::PostGarbageCollectionProcessing() {
4418 Relocatable* current = top_;
4419 while (current != NULL) {
4420 current->PostGarbageCollection();
4421 current = current->prev_;
4422 }
4423}
4424
4425
4426// Reserve space for statics needing saving and restoring.
4427int Relocatable::ArchiveSpacePerThread() {
4428 return sizeof(top_);
4429}
4430
4431
4432// Archive statics that are thread local.
4433char* Relocatable::ArchiveState(char* to) {
4434 *reinterpret_cast<Relocatable**>(to) = top_;
4435 top_ = NULL;
4436 return to + ArchiveSpacePerThread();
4437}
4438
4439
4440// Restore statics that are thread local.
4441char* Relocatable::RestoreState(char* from) {
4442 top_ = *reinterpret_cast<Relocatable**>(from);
4443 return from + ArchiveSpacePerThread();
4444}
4445
4446
4447char* Relocatable::Iterate(ObjectVisitor* v, char* thread_storage) {
4448 Relocatable* top = *reinterpret_cast<Relocatable**>(thread_storage);
4449 Iterate(v, top);
4450 return thread_storage + ArchiveSpacePerThread();
4451}
4452
4453
4454void Relocatable::Iterate(ObjectVisitor* v) {
4455 Iterate(v, top_);
4456}
4457
4458
4459void Relocatable::Iterate(ObjectVisitor* v, Relocatable* top) {
4460 Relocatable* current = top;
4461 while (current != NULL) {
4462 current->IterateInstance(v);
4463 current = current->prev_;
4464 }
4465}
4466
4467
4468FlatStringReader::FlatStringReader(Handle<String> str)
4469 : str_(str.location()),
4470 length_(str->length()) {
4471 PostGarbageCollection();
4472}
4473
4474
4475FlatStringReader::FlatStringReader(Vector<const char> input)
4476 : str_(0),
4477 is_ascii_(true),
4478 length_(input.length()),
4479 start_(input.start()) { }
4480
4481
4482void FlatStringReader::PostGarbageCollection() {
4483 if (str_ == NULL) return;
4484 Handle<String> str(str_);
4485 ASSERT(str->IsFlat());
4486 is_ascii_ = str->IsAsciiRepresentation();
4487 if (is_ascii_) {
4488 start_ = str->ToAsciiVector().start();
4489 } else {
4490 start_ = str->ToUC16Vector().start();
4491 }
4492}
4493
4494
4495void StringInputBuffer::Seek(unsigned pos) {
4496 Reset(pos, input_);
4497}
4498
4499
4500void SafeStringInputBuffer::Seek(unsigned pos) {
4501 Reset(pos, input_);
4502}
4503
4504
4505// This method determines the type of string involved and then copies
4506// a whole chunk of characters into a buffer. It can be used with strings
4507// that have been glued together to form a ConsString and which must cooperate
4508// to fill up a buffer.
4509void String::ReadBlockIntoBuffer(String* input,
4510 ReadBlockBuffer* rbb,
4511 unsigned* offset_ptr,
4512 unsigned max_chars) {
4513 ASSERT(*offset_ptr <= (unsigned)input->length());
4514 if (max_chars == 0) return;
4515
4516 switch (StringShape(input).representation_tag()) {
4517 case kSeqStringTag:
4518 if (input->IsAsciiRepresentation()) {
4519 SeqAsciiString::cast(input)->SeqAsciiStringReadBlockIntoBuffer(rbb,
4520 offset_ptr,
4521 max_chars);
4522 return;
4523 } else {
4524 SeqTwoByteString::cast(input)->SeqTwoByteStringReadBlockIntoBuffer(rbb,
4525 offset_ptr,
4526 max_chars);
4527 return;
4528 }
4529 case kConsStringTag:
4530 ConsString::cast(input)->ConsStringReadBlockIntoBuffer(rbb,
4531 offset_ptr,
4532 max_chars);
4533 return;
Steve Blocka7e24c12009-10-30 11:49:00 +00004534 case kExternalStringTag:
4535 if (input->IsAsciiRepresentation()) {
Steve Blockd0582a62009-12-15 09:54:21 +00004536 ExternalAsciiString::cast(input)->
4537 ExternalAsciiStringReadBlockIntoBuffer(rbb, offset_ptr, max_chars);
4538 } else {
4539 ExternalTwoByteString::cast(input)->
4540 ExternalTwoByteStringReadBlockIntoBuffer(rbb,
4541 offset_ptr,
4542 max_chars);
Steve Blocka7e24c12009-10-30 11:49:00 +00004543 }
4544 return;
4545 default:
4546 break;
4547 }
4548
4549 UNREACHABLE();
4550 return;
4551}
4552
4553
4554const unibrow::byte* String::ReadBlock(String* input,
4555 unibrow::byte* util_buffer,
4556 unsigned capacity,
4557 unsigned* remaining,
4558 unsigned* offset_ptr) {
4559 ASSERT(*offset_ptr <= (unsigned)input->length());
4560 unsigned chars = input->length() - *offset_ptr;
4561 ReadBlockBuffer rbb(util_buffer, 0, capacity, 0);
4562 const unibrow::byte* answer = ReadBlock(input, &rbb, offset_ptr, chars);
4563 ASSERT(rbb.remaining <= static_cast<unsigned>(input->length()));
4564 *remaining = rbb.remaining;
4565 return answer;
4566}
4567
4568
4569const unibrow::byte* String::ReadBlock(String** raw_input,
4570 unibrow::byte* util_buffer,
4571 unsigned capacity,
4572 unsigned* remaining,
4573 unsigned* offset_ptr) {
4574 Handle<String> input(raw_input);
4575 ASSERT(*offset_ptr <= (unsigned)input->length());
4576 unsigned chars = input->length() - *offset_ptr;
4577 if (chars > capacity) chars = capacity;
4578 ReadBlockBuffer rbb(util_buffer, 0, capacity, 0);
4579 ReadBlockIntoBuffer(*input, &rbb, offset_ptr, chars);
4580 ASSERT(rbb.remaining <= static_cast<unsigned>(input->length()));
4581 *remaining = rbb.remaining;
4582 return rbb.util_buffer;
4583}
4584
4585
4586// This will iterate unless the block of string data spans two 'halves' of
4587// a ConsString, in which case it will recurse. Since the block of string
4588// data to be read has a maximum size this limits the maximum recursion
4589// depth to something sane. Since C++ does not have tail call recursion
4590// elimination, the iteration must be explicit.
4591void ConsString::ConsStringReadBlockIntoBuffer(ReadBlockBuffer* rbb,
4592 unsigned* offset_ptr,
4593 unsigned max_chars) {
4594 ConsString* current = this;
4595 unsigned offset = *offset_ptr;
4596 int offset_correction = 0;
4597
4598 while (true) {
4599 String* left = current->first();
4600 unsigned left_length = (unsigned)left->length();
4601 if (left_length > offset &&
4602 max_chars <= left_length - offset) {
4603 // Left hand side only - iterate unless we have reached the bottom of
4604 // the cons tree.
4605 if (StringShape(left).IsCons()) {
4606 current = ConsString::cast(left);
4607 continue;
4608 } else {
4609 String::ReadBlockIntoBuffer(left, rbb, &offset, max_chars);
4610 *offset_ptr = offset + offset_correction;
4611 return;
4612 }
4613 } else if (left_length <= offset) {
4614 // Right hand side only - iterate unless we have reached the bottom of
4615 // the cons tree.
4616 offset -= left_length;
4617 offset_correction += left_length;
4618 String* right = current->second();
4619 if (StringShape(right).IsCons()) {
4620 current = ConsString::cast(right);
4621 continue;
4622 } else {
4623 String::ReadBlockIntoBuffer(right, rbb, &offset, max_chars);
4624 *offset_ptr = offset + offset_correction;
4625 return;
4626 }
4627 } else {
4628 // The block to be read spans two sides of the ConsString, so we recurse.
4629 // First recurse on the left.
4630 max_chars -= left_length - offset;
4631 String::ReadBlockIntoBuffer(left, rbb, &offset, left_length - offset);
4632 // We may have reached the max or there may not have been enough space
4633 // in the buffer for the characters in the left hand side.
4634 if (offset == left_length) {
4635 // Recurse on the right.
4636 String* right = String::cast(current->second());
4637 offset -= left_length;
4638 offset_correction += left_length;
4639 String::ReadBlockIntoBuffer(right, rbb, &offset, max_chars);
4640 }
4641 *offset_ptr = offset + offset_correction;
4642 return;
4643 }
4644 }
4645}
4646
4647
Steve Blocka7e24c12009-10-30 11:49:00 +00004648uint16_t ConsString::ConsStringGet(int index) {
4649 ASSERT(index >= 0 && index < this->length());
4650
4651 // Check for a flattened cons string
4652 if (second()->length() == 0) {
4653 String* left = first();
4654 return left->Get(index);
4655 }
4656
4657 String* string = String::cast(this);
4658
4659 while (true) {
4660 if (StringShape(string).IsCons()) {
4661 ConsString* cons_string = ConsString::cast(string);
4662 String* left = cons_string->first();
4663 if (left->length() > index) {
4664 string = left;
4665 } else {
4666 index -= left->length();
4667 string = cons_string->second();
4668 }
4669 } else {
4670 return string->Get(index);
4671 }
4672 }
4673
4674 UNREACHABLE();
4675 return 0;
4676}
4677
4678
4679template <typename sinkchar>
4680void String::WriteToFlat(String* src,
4681 sinkchar* sink,
4682 int f,
4683 int t) {
4684 String* source = src;
4685 int from = f;
4686 int to = t;
4687 while (true) {
4688 ASSERT(0 <= from && from <= to && to <= source->length());
4689 switch (StringShape(source).full_representation_tag()) {
4690 case kAsciiStringTag | kExternalStringTag: {
4691 CopyChars(sink,
4692 ExternalAsciiString::cast(source)->resource()->data() + from,
4693 to - from);
4694 return;
4695 }
4696 case kTwoByteStringTag | kExternalStringTag: {
4697 const uc16* data =
4698 ExternalTwoByteString::cast(source)->resource()->data();
4699 CopyChars(sink,
4700 data + from,
4701 to - from);
4702 return;
4703 }
4704 case kAsciiStringTag | kSeqStringTag: {
4705 CopyChars(sink,
4706 SeqAsciiString::cast(source)->GetChars() + from,
4707 to - from);
4708 return;
4709 }
4710 case kTwoByteStringTag | kSeqStringTag: {
4711 CopyChars(sink,
4712 SeqTwoByteString::cast(source)->GetChars() + from,
4713 to - from);
4714 return;
4715 }
Steve Blocka7e24c12009-10-30 11:49:00 +00004716 case kAsciiStringTag | kConsStringTag:
4717 case kTwoByteStringTag | kConsStringTag: {
4718 ConsString* cons_string = ConsString::cast(source);
4719 String* first = cons_string->first();
4720 int boundary = first->length();
4721 if (to - boundary >= boundary - from) {
4722 // Right hand side is longer. Recurse over left.
4723 if (from < boundary) {
4724 WriteToFlat(first, sink, from, boundary);
4725 sink += boundary - from;
4726 from = 0;
4727 } else {
4728 from -= boundary;
4729 }
4730 to -= boundary;
4731 source = cons_string->second();
4732 } else {
4733 // Left hand side is longer. Recurse over right.
4734 if (to > boundary) {
4735 String* second = cons_string->second();
4736 WriteToFlat(second,
4737 sink + boundary - from,
4738 0,
4739 to - boundary);
4740 to = boundary;
4741 }
4742 source = first;
4743 }
4744 break;
4745 }
4746 }
4747 }
4748}
4749
4750
Steve Blocka7e24c12009-10-30 11:49:00 +00004751template <typename IteratorA, typename IteratorB>
4752static inline bool CompareStringContents(IteratorA* ia, IteratorB* ib) {
4753 // General slow case check. We know that the ia and ib iterators
4754 // have the same length.
4755 while (ia->has_more()) {
4756 uc32 ca = ia->GetNext();
4757 uc32 cb = ib->GetNext();
4758 if (ca != cb)
4759 return false;
4760 }
4761 return true;
4762}
4763
4764
4765// Compares the contents of two strings by reading and comparing
4766// int-sized blocks of characters.
4767template <typename Char>
4768static inline bool CompareRawStringContents(Vector<Char> a, Vector<Char> b) {
4769 int length = a.length();
4770 ASSERT_EQ(length, b.length());
4771 const Char* pa = a.start();
4772 const Char* pb = b.start();
4773 int i = 0;
4774#ifndef V8_HOST_CAN_READ_UNALIGNED
4775 // If this architecture isn't comfortable reading unaligned ints
4776 // then we have to check that the strings are aligned before
4777 // comparing them blockwise.
4778 const int kAlignmentMask = sizeof(uint32_t) - 1; // NOLINT
4779 uint32_t pa_addr = reinterpret_cast<uint32_t>(pa);
4780 uint32_t pb_addr = reinterpret_cast<uint32_t>(pb);
4781 if (((pa_addr & kAlignmentMask) | (pb_addr & kAlignmentMask)) == 0) {
4782#endif
4783 const int kStepSize = sizeof(int) / sizeof(Char); // NOLINT
4784 int endpoint = length - kStepSize;
4785 // Compare blocks until we reach near the end of the string.
4786 for (; i <= endpoint; i += kStepSize) {
4787 uint32_t wa = *reinterpret_cast<const uint32_t*>(pa + i);
4788 uint32_t wb = *reinterpret_cast<const uint32_t*>(pb + i);
4789 if (wa != wb) {
4790 return false;
4791 }
4792 }
4793#ifndef V8_HOST_CAN_READ_UNALIGNED
4794 }
4795#endif
4796 // Compare the remaining characters that didn't fit into a block.
4797 for (; i < length; i++) {
4798 if (a[i] != b[i]) {
4799 return false;
4800 }
4801 }
4802 return true;
4803}
4804
4805
4806static StringInputBuffer string_compare_buffer_b;
4807
4808
4809template <typename IteratorA>
4810static inline bool CompareStringContentsPartial(IteratorA* ia, String* b) {
4811 if (b->IsFlat()) {
4812 if (b->IsAsciiRepresentation()) {
4813 VectorIterator<char> ib(b->ToAsciiVector());
4814 return CompareStringContents(ia, &ib);
4815 } else {
4816 VectorIterator<uc16> ib(b->ToUC16Vector());
4817 return CompareStringContents(ia, &ib);
4818 }
4819 } else {
4820 string_compare_buffer_b.Reset(0, b);
4821 return CompareStringContents(ia, &string_compare_buffer_b);
4822 }
4823}
4824
4825
4826static StringInputBuffer string_compare_buffer_a;
4827
4828
4829bool String::SlowEquals(String* other) {
4830 // Fast check: negative check with lengths.
4831 int len = length();
4832 if (len != other->length()) return false;
4833 if (len == 0) return true;
4834
4835 // Fast check: if hash code is computed for both strings
4836 // a fast negative check can be performed.
4837 if (HasHashCode() && other->HasHashCode()) {
4838 if (Hash() != other->Hash()) return false;
4839 }
4840
Leon Clarkef7060e22010-06-03 12:02:55 +01004841 // We know the strings are both non-empty. Compare the first chars
4842 // before we try to flatten the strings.
4843 if (this->Get(0) != other->Get(0)) return false;
4844
4845 String* lhs = this->TryFlattenGetString();
4846 String* rhs = other->TryFlattenGetString();
4847
4848 if (StringShape(lhs).IsSequentialAscii() &&
4849 StringShape(rhs).IsSequentialAscii()) {
4850 const char* str1 = SeqAsciiString::cast(lhs)->GetChars();
4851 const char* str2 = SeqAsciiString::cast(rhs)->GetChars();
Steve Blocka7e24c12009-10-30 11:49:00 +00004852 return CompareRawStringContents(Vector<const char>(str1, len),
4853 Vector<const char>(str2, len));
4854 }
4855
Leon Clarkef7060e22010-06-03 12:02:55 +01004856 if (lhs->IsFlat()) {
Ben Murdochbb769b22010-08-11 14:56:33 +01004857 if (lhs->IsAsciiRepresentation()) {
Leon Clarkef7060e22010-06-03 12:02:55 +01004858 Vector<const char> vec1 = lhs->ToAsciiVector();
4859 if (rhs->IsFlat()) {
4860 if (rhs->IsAsciiRepresentation()) {
4861 Vector<const char> vec2 = rhs->ToAsciiVector();
Steve Blocka7e24c12009-10-30 11:49:00 +00004862 return CompareRawStringContents(vec1, vec2);
4863 } else {
4864 VectorIterator<char> buf1(vec1);
Leon Clarkef7060e22010-06-03 12:02:55 +01004865 VectorIterator<uc16> ib(rhs->ToUC16Vector());
Steve Blocka7e24c12009-10-30 11:49:00 +00004866 return CompareStringContents(&buf1, &ib);
4867 }
4868 } else {
4869 VectorIterator<char> buf1(vec1);
Leon Clarkef7060e22010-06-03 12:02:55 +01004870 string_compare_buffer_b.Reset(0, rhs);
Steve Blocka7e24c12009-10-30 11:49:00 +00004871 return CompareStringContents(&buf1, &string_compare_buffer_b);
4872 }
4873 } else {
Leon Clarkef7060e22010-06-03 12:02:55 +01004874 Vector<const uc16> vec1 = lhs->ToUC16Vector();
4875 if (rhs->IsFlat()) {
4876 if (rhs->IsAsciiRepresentation()) {
Steve Blocka7e24c12009-10-30 11:49:00 +00004877 VectorIterator<uc16> buf1(vec1);
Leon Clarkef7060e22010-06-03 12:02:55 +01004878 VectorIterator<char> ib(rhs->ToAsciiVector());
Steve Blocka7e24c12009-10-30 11:49:00 +00004879 return CompareStringContents(&buf1, &ib);
4880 } else {
Leon Clarkef7060e22010-06-03 12:02:55 +01004881 Vector<const uc16> vec2(rhs->ToUC16Vector());
Steve Blocka7e24c12009-10-30 11:49:00 +00004882 return CompareRawStringContents(vec1, vec2);
4883 }
4884 } else {
4885 VectorIterator<uc16> buf1(vec1);
Leon Clarkef7060e22010-06-03 12:02:55 +01004886 string_compare_buffer_b.Reset(0, rhs);
Steve Blocka7e24c12009-10-30 11:49:00 +00004887 return CompareStringContents(&buf1, &string_compare_buffer_b);
4888 }
4889 }
4890 } else {
Leon Clarkef7060e22010-06-03 12:02:55 +01004891 string_compare_buffer_a.Reset(0, lhs);
4892 return CompareStringContentsPartial(&string_compare_buffer_a, rhs);
Steve Blocka7e24c12009-10-30 11:49:00 +00004893 }
4894}
4895
4896
4897bool String::MarkAsUndetectable() {
4898 if (StringShape(this).IsSymbol()) return false;
4899
4900 Map* map = this->map();
Steve Blockd0582a62009-12-15 09:54:21 +00004901 if (map == Heap::string_map()) {
4902 this->set_map(Heap::undetectable_string_map());
Steve Blocka7e24c12009-10-30 11:49:00 +00004903 return true;
Steve Blockd0582a62009-12-15 09:54:21 +00004904 } else if (map == Heap::ascii_string_map()) {
4905 this->set_map(Heap::undetectable_ascii_string_map());
Steve Blocka7e24c12009-10-30 11:49:00 +00004906 return true;
4907 }
4908 // Rest cannot be marked as undetectable
4909 return false;
4910}
4911
4912
4913bool String::IsEqualTo(Vector<const char> str) {
4914 int slen = length();
4915 Access<Scanner::Utf8Decoder> decoder(Scanner::utf8_decoder());
4916 decoder->Reset(str.start(), str.length());
4917 int i;
4918 for (i = 0; i < slen && decoder->has_more(); i++) {
4919 uc32 r = decoder->GetNext();
4920 if (Get(i) != r) return false;
4921 }
4922 return i == slen && !decoder->has_more();
4923}
4924
4925
Steve Block6ded16b2010-05-10 14:33:55 +01004926template <typename schar>
4927static inline uint32_t HashSequentialString(const schar* chars, int length) {
4928 StringHasher hasher(length);
4929 if (!hasher.has_trivial_hash()) {
4930 int i;
4931 for (i = 0; hasher.is_array_index() && (i < length); i++) {
4932 hasher.AddCharacter(chars[i]);
4933 }
4934 for (; i < length; i++) {
4935 hasher.AddCharacterNoIndex(chars[i]);
4936 }
4937 }
4938 return hasher.GetHashField();
4939}
4940
4941
Steve Blocka7e24c12009-10-30 11:49:00 +00004942uint32_t String::ComputeAndSetHash() {
4943 // Should only be called if hash code has not yet been computed.
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01004944 ASSERT(!HasHashCode());
Steve Blocka7e24c12009-10-30 11:49:00 +00004945
Steve Block6ded16b2010-05-10 14:33:55 +01004946 const int len = length();
4947
Steve Blocka7e24c12009-10-30 11:49:00 +00004948 // Compute the hash code.
Steve Block6ded16b2010-05-10 14:33:55 +01004949 uint32_t field = 0;
4950 if (StringShape(this).IsSequentialAscii()) {
4951 field = HashSequentialString(SeqAsciiString::cast(this)->GetChars(), len);
4952 } else if (StringShape(this).IsSequentialTwoByte()) {
4953 field = HashSequentialString(SeqTwoByteString::cast(this)->GetChars(), len);
4954 } else {
4955 StringInputBuffer buffer(this);
4956 field = ComputeHashField(&buffer, len);
4957 }
Steve Blocka7e24c12009-10-30 11:49:00 +00004958
4959 // Store the hash code in the object.
Steve Blockd0582a62009-12-15 09:54:21 +00004960 set_hash_field(field);
Steve Blocka7e24c12009-10-30 11:49:00 +00004961
4962 // Check the hash code is there.
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01004963 ASSERT(HasHashCode());
Steve Blocka7e24c12009-10-30 11:49:00 +00004964 uint32_t result = field >> kHashShift;
4965 ASSERT(result != 0); // Ensure that the hash value of 0 is never computed.
4966 return result;
4967}
4968
4969
4970bool String::ComputeArrayIndex(unibrow::CharacterStream* buffer,
4971 uint32_t* index,
4972 int length) {
4973 if (length == 0 || length > kMaxArrayIndexSize) return false;
4974 uc32 ch = buffer->GetNext();
4975
4976 // If the string begins with a '0' character, it must only consist
4977 // of it to be a legal array index.
4978 if (ch == '0') {
4979 *index = 0;
4980 return length == 1;
4981 }
4982
4983 // Convert string to uint32 array index; character by character.
4984 int d = ch - '0';
4985 if (d < 0 || d > 9) return false;
4986 uint32_t result = d;
4987 while (buffer->has_more()) {
4988 d = buffer->GetNext() - '0';
4989 if (d < 0 || d > 9) return false;
4990 // Check that the new result is below the 32 bit limit.
4991 if (result > 429496729U - ((d > 5) ? 1 : 0)) return false;
4992 result = (result * 10) + d;
4993 }
4994
4995 *index = result;
4996 return true;
4997}
4998
4999
5000bool String::SlowAsArrayIndex(uint32_t* index) {
5001 if (length() <= kMaxCachedArrayIndexLength) {
5002 Hash(); // force computation of hash code
Steve Blockd0582a62009-12-15 09:54:21 +00005003 uint32_t field = hash_field();
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01005004 if ((field & kIsNotArrayIndexMask) != 0) return false;
Steve Blockd0582a62009-12-15 09:54:21 +00005005 // Isolate the array index form the full hash field.
5006 *index = (kArrayIndexHashMask & field) >> kHashShift;
Steve Blocka7e24c12009-10-30 11:49:00 +00005007 return true;
5008 } else {
5009 StringInputBuffer buffer(this);
5010 return ComputeArrayIndex(&buffer, index, length());
5011 }
5012}
5013
5014
Iain Merrick9ac36c92010-09-13 15:29:50 +01005015uint32_t StringHasher::MakeArrayIndexHash(uint32_t value, int length) {
Kristian Monsen80d68ea2010-09-08 11:05:35 +01005016 // For array indexes mix the length into the hash as an array index could
5017 // be zero.
5018 ASSERT(length > 0);
5019 ASSERT(length <= String::kMaxArrayIndexSize);
5020 ASSERT(TenToThe(String::kMaxCachedArrayIndexLength) <
5021 (1 << String::kArrayIndexValueBits));
Iain Merrick9ac36c92010-09-13 15:29:50 +01005022
5023 value <<= String::kHashShift;
Kristian Monsen80d68ea2010-09-08 11:05:35 +01005024 value |= length << String::kArrayIndexHashLengthShift;
Iain Merrick9ac36c92010-09-13 15:29:50 +01005025
5026 ASSERT((value & String::kIsNotArrayIndexMask) == 0);
5027 ASSERT((length > String::kMaxCachedArrayIndexLength) ||
5028 (value & String::kContainsCachedArrayIndexMask) == 0);
Kristian Monsen80d68ea2010-09-08 11:05:35 +01005029 return value;
Steve Blocka7e24c12009-10-30 11:49:00 +00005030}
5031
5032
5033uint32_t StringHasher::GetHashField() {
5034 ASSERT(is_valid());
Steve Blockd0582a62009-12-15 09:54:21 +00005035 if (length_ <= String::kMaxHashCalcLength) {
Steve Blocka7e24c12009-10-30 11:49:00 +00005036 if (is_array_index()) {
Iain Merrick9ac36c92010-09-13 15:29:50 +01005037 return MakeArrayIndexHash(array_index(), length_);
Steve Blocka7e24c12009-10-30 11:49:00 +00005038 }
Kristian Monsen80d68ea2010-09-08 11:05:35 +01005039 return (GetHash() << String::kHashShift) | String::kIsNotArrayIndexMask;
Steve Blocka7e24c12009-10-30 11:49:00 +00005040 } else {
Kristian Monsen80d68ea2010-09-08 11:05:35 +01005041 return (length_ << String::kHashShift) | String::kIsNotArrayIndexMask;
Steve Blocka7e24c12009-10-30 11:49:00 +00005042 }
5043}
5044
5045
Steve Blockd0582a62009-12-15 09:54:21 +00005046uint32_t String::ComputeHashField(unibrow::CharacterStream* buffer,
5047 int length) {
Steve Blocka7e24c12009-10-30 11:49:00 +00005048 StringHasher hasher(length);
5049
5050 // Very long strings have a trivial hash that doesn't inspect the
5051 // string contents.
5052 if (hasher.has_trivial_hash()) {
5053 return hasher.GetHashField();
5054 }
5055
5056 // Do the iterative array index computation as long as there is a
5057 // chance this is an array index.
5058 while (buffer->has_more() && hasher.is_array_index()) {
5059 hasher.AddCharacter(buffer->GetNext());
5060 }
5061
5062 // Process the remaining characters without updating the array
5063 // index.
5064 while (buffer->has_more()) {
5065 hasher.AddCharacterNoIndex(buffer->GetNext());
5066 }
5067
5068 return hasher.GetHashField();
5069}
5070
5071
Steve Block6ded16b2010-05-10 14:33:55 +01005072Object* String::SubString(int start, int end, PretenureFlag pretenure) {
Steve Blocka7e24c12009-10-30 11:49:00 +00005073 if (start == 0 && end == length()) return this;
Steve Block6ded16b2010-05-10 14:33:55 +01005074 Object* result = Heap::AllocateSubString(this, start, end, pretenure);
Steve Blockd0582a62009-12-15 09:54:21 +00005075 return result;
Steve Blocka7e24c12009-10-30 11:49:00 +00005076}
5077
5078
5079void String::PrintOn(FILE* file) {
5080 int length = this->length();
5081 for (int i = 0; i < length; i++) {
5082 fprintf(file, "%c", Get(i));
5083 }
5084}
5085
5086
5087void Map::CreateBackPointers() {
5088 DescriptorArray* descriptors = instance_descriptors();
5089 for (int i = 0; i < descriptors->number_of_descriptors(); i++) {
Iain Merrick75681382010-08-19 15:07:18 +01005090 if (descriptors->GetType(i) == MAP_TRANSITION ||
5091 descriptors->GetType(i) == CONSTANT_TRANSITION) {
Steve Blocka7e24c12009-10-30 11:49:00 +00005092 // Get target.
5093 Map* target = Map::cast(descriptors->GetValue(i));
5094#ifdef DEBUG
5095 // Verify target.
5096 Object* source_prototype = prototype();
5097 Object* target_prototype = target->prototype();
5098 ASSERT(source_prototype->IsJSObject() ||
5099 source_prototype->IsMap() ||
5100 source_prototype->IsNull());
5101 ASSERT(target_prototype->IsJSObject() ||
5102 target_prototype->IsNull());
5103 ASSERT(source_prototype->IsMap() ||
5104 source_prototype == target_prototype);
5105#endif
5106 // Point target back to source. set_prototype() will not let us set
5107 // the prototype to a map, as we do here.
5108 *RawField(target, kPrototypeOffset) = this;
5109 }
5110 }
5111}
5112
5113
5114void Map::ClearNonLiveTransitions(Object* real_prototype) {
5115 // Live DescriptorArray objects will be marked, so we must use
5116 // low-level accessors to get and modify their data.
5117 DescriptorArray* d = reinterpret_cast<DescriptorArray*>(
5118 *RawField(this, Map::kInstanceDescriptorsOffset));
5119 if (d == Heap::raw_unchecked_empty_descriptor_array()) return;
5120 Smi* NullDescriptorDetails =
5121 PropertyDetails(NONE, NULL_DESCRIPTOR).AsSmi();
5122 FixedArray* contents = reinterpret_cast<FixedArray*>(
5123 d->get(DescriptorArray::kContentArrayIndex));
5124 ASSERT(contents->length() >= 2);
5125 for (int i = 0; i < contents->length(); i += 2) {
5126 // If the pair (value, details) is a map transition,
5127 // check if the target is live. If not, null the descriptor.
5128 // Also drop the back pointer for that map transition, so that this
5129 // map is not reached again by following a back pointer from a
5130 // non-live object.
5131 PropertyDetails details(Smi::cast(contents->get(i + 1)));
Iain Merrick75681382010-08-19 15:07:18 +01005132 if (details.type() == MAP_TRANSITION ||
5133 details.type() == CONSTANT_TRANSITION) {
Steve Blocka7e24c12009-10-30 11:49:00 +00005134 Map* target = reinterpret_cast<Map*>(contents->get(i));
5135 ASSERT(target->IsHeapObject());
5136 if (!target->IsMarked()) {
5137 ASSERT(target->IsMap());
Iain Merrick75681382010-08-19 15:07:18 +01005138 contents->set_unchecked(i + 1, NullDescriptorDetails);
5139 contents->set_null_unchecked(i);
Steve Blocka7e24c12009-10-30 11:49:00 +00005140 ASSERT(target->prototype() == this ||
5141 target->prototype() == real_prototype);
5142 // Getter prototype() is read-only, set_prototype() has side effects.
5143 *RawField(target, Map::kPrototypeOffset) = real_prototype;
5144 }
5145 }
5146 }
5147}
5148
5149
Steve Block791712a2010-08-27 10:21:07 +01005150void JSFunction::JSFunctionIterateBody(int object_size, ObjectVisitor* v) {
5151 // Iterate over all fields in the body but take care in dealing with
5152 // the code entry.
5153 IteratePointers(v, kPropertiesOffset, kCodeEntryOffset);
5154 v->VisitCodeEntry(this->address() + kCodeEntryOffset);
5155 IteratePointers(v, kCodeEntryOffset + kPointerSize, object_size);
5156}
5157
5158
Steve Blocka7e24c12009-10-30 11:49:00 +00005159Object* JSFunction::SetInstancePrototype(Object* value) {
5160 ASSERT(value->IsJSObject());
5161
5162 if (has_initial_map()) {
5163 initial_map()->set_prototype(value);
5164 } else {
5165 // Put the value in the initial map field until an initial map is
5166 // needed. At that point, a new initial map is created and the
5167 // prototype is put into the initial map where it belongs.
5168 set_prototype_or_initial_map(value);
5169 }
Kristian Monsen25f61362010-05-21 11:50:48 +01005170 Heap::ClearInstanceofCache();
Steve Blocka7e24c12009-10-30 11:49:00 +00005171 return value;
5172}
5173
5174
Steve Blocka7e24c12009-10-30 11:49:00 +00005175Object* JSFunction::SetPrototype(Object* value) {
Steve Block6ded16b2010-05-10 14:33:55 +01005176 ASSERT(should_have_prototype());
Steve Blocka7e24c12009-10-30 11:49:00 +00005177 Object* construct_prototype = value;
5178
5179 // If the value is not a JSObject, store the value in the map's
5180 // constructor field so it can be accessed. Also, set the prototype
5181 // used for constructing objects to the original object prototype.
5182 // See ECMA-262 13.2.2.
5183 if (!value->IsJSObject()) {
5184 // Copy the map so this does not affect unrelated functions.
5185 // Remove map transitions because they point to maps with a
5186 // different prototype.
5187 Object* new_map = map()->CopyDropTransitions();
5188 if (new_map->IsFailure()) return new_map;
5189 set_map(Map::cast(new_map));
5190 map()->set_constructor(value);
5191 map()->set_non_instance_prototype(true);
5192 construct_prototype =
5193 Top::context()->global_context()->initial_object_prototype();
5194 } else {
5195 map()->set_non_instance_prototype(false);
5196 }
5197
5198 return SetInstancePrototype(construct_prototype);
5199}
5200
5201
Steve Block6ded16b2010-05-10 14:33:55 +01005202Object* JSFunction::RemovePrototype() {
5203 ASSERT(map() == context()->global_context()->function_map());
5204 set_map(context()->global_context()->function_without_prototype_map());
5205 set_prototype_or_initial_map(Heap::the_hole_value());
5206 return this;
5207}
5208
5209
Steve Blocka7e24c12009-10-30 11:49:00 +00005210Object* JSFunction::SetInstanceClassName(String* name) {
5211 shared()->set_instance_class_name(name);
5212 return this;
5213}
5214
5215
5216Context* JSFunction::GlobalContextFromLiterals(FixedArray* literals) {
5217 return Context::cast(literals->get(JSFunction::kLiteralGlobalContextIndex));
5218}
5219
5220
Steve Blocka7e24c12009-10-30 11:49:00 +00005221Object* Oddball::Initialize(const char* to_string, Object* to_number) {
5222 Object* symbol = Heap::LookupAsciiSymbol(to_string);
5223 if (symbol->IsFailure()) return symbol;
5224 set_to_string(String::cast(symbol));
5225 set_to_number(to_number);
5226 return this;
5227}
5228
5229
5230bool SharedFunctionInfo::HasSourceCode() {
5231 return !script()->IsUndefined() &&
Iain Merrick75681382010-08-19 15:07:18 +01005232 !reinterpret_cast<Script*>(script())->source()->IsUndefined();
Steve Blocka7e24c12009-10-30 11:49:00 +00005233}
5234
5235
5236Object* SharedFunctionInfo::GetSourceCode() {
5237 HandleScope scope;
5238 if (script()->IsUndefined()) return Heap::undefined_value();
5239 Object* source = Script::cast(script())->source();
5240 if (source->IsUndefined()) return Heap::undefined_value();
5241 return *SubString(Handle<String>(String::cast(source)),
5242 start_position(), end_position());
5243}
5244
5245
5246int SharedFunctionInfo::CalculateInstanceSize() {
5247 int instance_size =
5248 JSObject::kHeaderSize +
5249 expected_nof_properties() * kPointerSize;
5250 if (instance_size > JSObject::kMaxInstanceSize) {
5251 instance_size = JSObject::kMaxInstanceSize;
5252 }
5253 return instance_size;
5254}
5255
5256
5257int SharedFunctionInfo::CalculateInObjectProperties() {
5258 return (CalculateInstanceSize() - JSObject::kHeaderSize) / kPointerSize;
5259}
5260
5261
Andrei Popescu402d9372010-02-26 13:31:12 +00005262bool SharedFunctionInfo::CanGenerateInlineConstructor(Object* prototype) {
5263 // Check the basic conditions for generating inline constructor code.
5264 if (!FLAG_inline_new
5265 || !has_only_simple_this_property_assignments()
5266 || this_property_assignments_count() == 0) {
5267 return false;
5268 }
5269
5270 // If the prototype is null inline constructors cause no problems.
5271 if (!prototype->IsJSObject()) {
5272 ASSERT(prototype->IsNull());
5273 return true;
5274 }
5275
5276 // Traverse the proposed prototype chain looking for setters for properties of
5277 // the same names as are set by the inline constructor.
5278 for (Object* obj = prototype;
5279 obj != Heap::null_value();
5280 obj = obj->GetPrototype()) {
5281 JSObject* js_object = JSObject::cast(obj);
5282 for (int i = 0; i < this_property_assignments_count(); i++) {
5283 LookupResult result;
5284 String* name = GetThisPropertyAssignmentName(i);
5285 js_object->LocalLookupRealNamedProperty(name, &result);
5286 if (result.IsProperty() && result.type() == CALLBACKS) {
5287 return false;
5288 }
5289 }
5290 }
5291
5292 return true;
5293}
5294
5295
Kristian Monsen0d5e1162010-09-30 15:31:59 +01005296void SharedFunctionInfo::ForbidInlineConstructor() {
5297 set_compiler_hints(BooleanBit::set(compiler_hints(),
5298 kHasOnlySimpleThisPropertyAssignments,
5299 false));
5300}
5301
5302
Steve Blocka7e24c12009-10-30 11:49:00 +00005303void SharedFunctionInfo::SetThisPropertyAssignmentsInfo(
Steve Blocka7e24c12009-10-30 11:49:00 +00005304 bool only_simple_this_property_assignments,
5305 FixedArray* assignments) {
5306 set_compiler_hints(BooleanBit::set(compiler_hints(),
Steve Blocka7e24c12009-10-30 11:49:00 +00005307 kHasOnlySimpleThisPropertyAssignments,
5308 only_simple_this_property_assignments));
5309 set_this_property_assignments(assignments);
5310 set_this_property_assignments_count(assignments->length() / 3);
5311}
5312
5313
5314void SharedFunctionInfo::ClearThisPropertyAssignmentsInfo() {
5315 set_compiler_hints(BooleanBit::set(compiler_hints(),
Steve Blocka7e24c12009-10-30 11:49:00 +00005316 kHasOnlySimpleThisPropertyAssignments,
5317 false));
5318 set_this_property_assignments(Heap::undefined_value());
5319 set_this_property_assignments_count(0);
5320}
5321
5322
5323String* SharedFunctionInfo::GetThisPropertyAssignmentName(int index) {
5324 Object* obj = this_property_assignments();
5325 ASSERT(obj->IsFixedArray());
5326 ASSERT(index < this_property_assignments_count());
5327 obj = FixedArray::cast(obj)->get(index * 3);
5328 ASSERT(obj->IsString());
5329 return String::cast(obj);
5330}
5331
5332
5333bool SharedFunctionInfo::IsThisPropertyAssignmentArgument(int index) {
5334 Object* obj = this_property_assignments();
5335 ASSERT(obj->IsFixedArray());
5336 ASSERT(index < this_property_assignments_count());
5337 obj = FixedArray::cast(obj)->get(index * 3 + 1);
5338 return Smi::cast(obj)->value() != -1;
5339}
5340
5341
5342int SharedFunctionInfo::GetThisPropertyAssignmentArgument(int index) {
5343 ASSERT(IsThisPropertyAssignmentArgument(index));
5344 Object* obj =
5345 FixedArray::cast(this_property_assignments())->get(index * 3 + 1);
5346 return Smi::cast(obj)->value();
5347}
5348
5349
5350Object* SharedFunctionInfo::GetThisPropertyAssignmentConstant(int index) {
5351 ASSERT(!IsThisPropertyAssignmentArgument(index));
5352 Object* obj =
5353 FixedArray::cast(this_property_assignments())->get(index * 3 + 2);
5354 return obj;
5355}
5356
5357
Steve Blocka7e24c12009-10-30 11:49:00 +00005358// Support function for printing the source code to a StringStream
5359// without any allocation in the heap.
5360void SharedFunctionInfo::SourceCodePrint(StringStream* accumulator,
5361 int max_length) {
5362 // For some native functions there is no source.
5363 if (script()->IsUndefined() ||
5364 Script::cast(script())->source()->IsUndefined()) {
5365 accumulator->Add("<No Source>");
5366 return;
5367 }
5368
Steve Blockd0582a62009-12-15 09:54:21 +00005369 // Get the source for the script which this function came from.
Steve Blocka7e24c12009-10-30 11:49:00 +00005370 // Don't use String::cast because we don't want more assertion errors while
5371 // we are already creating a stack dump.
5372 String* script_source =
5373 reinterpret_cast<String*>(Script::cast(script())->source());
5374
5375 if (!script_source->LooksValid()) {
5376 accumulator->Add("<Invalid Source>");
5377 return;
5378 }
5379
5380 if (!is_toplevel()) {
5381 accumulator->Add("function ");
5382 Object* name = this->name();
5383 if (name->IsString() && String::cast(name)->length() > 0) {
5384 accumulator->PrintName(name);
5385 }
5386 }
5387
5388 int len = end_position() - start_position();
5389 if (len > max_length) {
5390 accumulator->Put(script_source,
5391 start_position(),
5392 start_position() + max_length);
5393 accumulator->Add("...\n");
5394 } else {
5395 accumulator->Put(script_source, start_position(), end_position());
5396 }
5397}
5398
5399
Kristian Monsen0d5e1162010-09-30 15:31:59 +01005400void SharedFunctionInfo::StartInobjectSlackTracking(Map* map) {
5401 ASSERT(!IsInobjectSlackTrackingInProgress());
5402
5403 // Only initiate the tracking the first time.
5404 if (live_objects_may_exist()) return;
5405 set_live_objects_may_exist(true);
5406
5407 // No tracking during the snapshot construction phase.
5408 if (Serializer::enabled()) return;
5409
5410 if (map->unused_property_fields() == 0) return;
5411
5412 // Nonzero counter is a leftover from the previous attempt interrupted
5413 // by GC, keep it.
5414 if (construction_count() == 0) {
5415 set_construction_count(kGenerousAllocationCount);
5416 }
5417 set_initial_map(map);
5418 ASSERT_EQ(Builtins::builtin(Builtins::JSConstructStubGeneric),
5419 construct_stub());
5420 set_construct_stub(Builtins::builtin(Builtins::JSConstructStubCountdown));
5421}
5422
5423
5424// Called from GC, hence reinterpret_cast and unchecked accessors.
5425void SharedFunctionInfo::DetachInitialMap() {
5426 Map* map = reinterpret_cast<Map*>(initial_map());
5427
5428 // Make the map remember to restore the link if it survives the GC.
5429 map->set_bit_field2(
5430 map->bit_field2() | (1 << Map::kAttachedToSharedFunctionInfo));
5431
5432 // Undo state changes made by StartInobjectTracking (except the
5433 // construction_count). This way if the initial map does not survive the GC
5434 // then StartInobjectTracking will be called again the next time the
5435 // constructor is called. The countdown will continue and (possibly after
5436 // several more GCs) CompleteInobjectSlackTracking will eventually be called.
5437 set_initial_map(Heap::raw_unchecked_undefined_value());
5438 ASSERT_EQ(Builtins::builtin(Builtins::JSConstructStubCountdown),
5439 *RawField(this, kConstructStubOffset));
5440 set_construct_stub(Builtins::builtin(Builtins::JSConstructStubGeneric));
5441 // It is safe to clear the flag: it will be set again if the map is live.
5442 set_live_objects_may_exist(false);
5443}
5444
5445
5446// Called from GC, hence reinterpret_cast and unchecked accessors.
5447void SharedFunctionInfo::AttachInitialMap(Map* map) {
5448 map->set_bit_field2(
5449 map->bit_field2() & ~(1 << Map::kAttachedToSharedFunctionInfo));
5450
5451 // Resume inobject slack tracking.
5452 set_initial_map(map);
5453 ASSERT_EQ(Builtins::builtin(Builtins::JSConstructStubGeneric),
5454 *RawField(this, kConstructStubOffset));
5455 set_construct_stub(Builtins::builtin(Builtins::JSConstructStubCountdown));
5456 // The map survived the gc, so there may be objects referencing it.
5457 set_live_objects_may_exist(true);
5458}
5459
5460
5461static void GetMinInobjectSlack(Map* map, void* data) {
5462 int slack = map->unused_property_fields();
5463 if (*reinterpret_cast<int*>(data) > slack) {
5464 *reinterpret_cast<int*>(data) = slack;
5465 }
5466}
5467
5468
5469static void ShrinkInstanceSize(Map* map, void* data) {
5470 int slack = *reinterpret_cast<int*>(data);
5471 map->set_inobject_properties(map->inobject_properties() - slack);
5472 map->set_unused_property_fields(map->unused_property_fields() - slack);
5473 map->set_instance_size(map->instance_size() - slack * kPointerSize);
5474
5475 // Visitor id might depend on the instance size, recalculate it.
5476 map->set_visitor_id(StaticVisitorBase::GetVisitorId(map));
5477}
5478
5479
5480void SharedFunctionInfo::CompleteInobjectSlackTracking() {
5481 ASSERT(live_objects_may_exist() && IsInobjectSlackTrackingInProgress());
5482 Map* map = Map::cast(initial_map());
5483
5484 set_initial_map(Heap::undefined_value());
5485 ASSERT_EQ(Builtins::builtin(Builtins::JSConstructStubCountdown),
5486 construct_stub());
5487 set_construct_stub(Builtins::builtin(Builtins::JSConstructStubGeneric));
5488
5489 int slack = map->unused_property_fields();
5490 map->TraverseTransitionTree(&GetMinInobjectSlack, &slack);
5491 if (slack != 0) {
5492 // Resize the initial map and all maps in its transition tree.
5493 map->TraverseTransitionTree(&ShrinkInstanceSize, &slack);
5494 // Give the correct expected_nof_properties to initial maps created later.
5495 ASSERT(expected_nof_properties() >= slack);
5496 set_expected_nof_properties(expected_nof_properties() - slack);
5497 }
5498}
5499
5500
Steve Blocka7e24c12009-10-30 11:49:00 +00005501void ObjectVisitor::VisitCodeTarget(RelocInfo* rinfo) {
5502 ASSERT(RelocInfo::IsCodeTarget(rinfo->rmode()));
5503 Object* target = Code::GetCodeFromTargetAddress(rinfo->target_address());
5504 Object* old_target = target;
5505 VisitPointer(&target);
5506 CHECK_EQ(target, old_target); // VisitPointer doesn't change Code* *target.
5507}
5508
5509
Steve Block791712a2010-08-27 10:21:07 +01005510void ObjectVisitor::VisitCodeEntry(Address entry_address) {
5511 Object* code = Code::GetObjectFromEntryAddress(entry_address);
5512 Object* old_code = code;
5513 VisitPointer(&code);
5514 if (code != old_code) {
5515 Memory::Address_at(entry_address) = reinterpret_cast<Code*>(code)->entry();
5516 }
5517}
5518
5519
Steve Blocka7e24c12009-10-30 11:49:00 +00005520void ObjectVisitor::VisitDebugTarget(RelocInfo* rinfo) {
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01005521 ASSERT((RelocInfo::IsJSReturn(rinfo->rmode()) &&
5522 rinfo->IsPatchedReturnSequence()) ||
5523 (RelocInfo::IsDebugBreakSlot(rinfo->rmode()) &&
5524 rinfo->IsPatchedDebugBreakSlotSequence()));
Steve Blocka7e24c12009-10-30 11:49:00 +00005525 Object* target = Code::GetCodeFromTargetAddress(rinfo->call_address());
5526 Object* old_target = target;
5527 VisitPointer(&target);
5528 CHECK_EQ(target, old_target); // VisitPointer doesn't change Code* *target.
5529}
5530
5531
Steve Blockd0582a62009-12-15 09:54:21 +00005532void Code::Relocate(intptr_t delta) {
Steve Blocka7e24c12009-10-30 11:49:00 +00005533 for (RelocIterator it(this, RelocInfo::kApplyMask); !it.done(); it.next()) {
5534 it.rinfo()->apply(delta);
5535 }
5536 CPU::FlushICache(instruction_start(), instruction_size());
5537}
5538
5539
5540void Code::CopyFrom(const CodeDesc& desc) {
5541 // copy code
5542 memmove(instruction_start(), desc.buffer, desc.instr_size);
5543
Steve Blocka7e24c12009-10-30 11:49:00 +00005544 // copy reloc info
5545 memmove(relocation_start(),
5546 desc.buffer + desc.buffer_size - desc.reloc_size,
5547 desc.reloc_size);
5548
5549 // unbox handles and relocate
Steve Block3ce2e202009-11-05 08:53:23 +00005550 intptr_t delta = instruction_start() - desc.buffer;
Steve Blocka7e24c12009-10-30 11:49:00 +00005551 int mode_mask = RelocInfo::kCodeTargetMask |
5552 RelocInfo::ModeMask(RelocInfo::EMBEDDED_OBJECT) |
5553 RelocInfo::kApplyMask;
Steve Block3ce2e202009-11-05 08:53:23 +00005554 Assembler* origin = desc.origin; // Needed to find target_object on X64.
Steve Blocka7e24c12009-10-30 11:49:00 +00005555 for (RelocIterator it(this, mode_mask); !it.done(); it.next()) {
5556 RelocInfo::Mode mode = it.rinfo()->rmode();
5557 if (mode == RelocInfo::EMBEDDED_OBJECT) {
Steve Block3ce2e202009-11-05 08:53:23 +00005558 Handle<Object> p = it.rinfo()->target_object_handle(origin);
Steve Blocka7e24c12009-10-30 11:49:00 +00005559 it.rinfo()->set_target_object(*p);
5560 } else if (RelocInfo::IsCodeTarget(mode)) {
5561 // rewrite code handles in inline cache targets to direct
5562 // pointers to the first instruction in the code object
Steve Block3ce2e202009-11-05 08:53:23 +00005563 Handle<Object> p = it.rinfo()->target_object_handle(origin);
Steve Blocka7e24c12009-10-30 11:49:00 +00005564 Code* code = Code::cast(*p);
5565 it.rinfo()->set_target_address(code->instruction_start());
5566 } else {
5567 it.rinfo()->apply(delta);
5568 }
5569 }
5570 CPU::FlushICache(instruction_start(), instruction_size());
5571}
5572
5573
5574// Locate the source position which is closest to the address in the code. This
5575// is using the source position information embedded in the relocation info.
5576// The position returned is relative to the beginning of the script where the
5577// source for this function is found.
5578int Code::SourcePosition(Address pc) {
5579 int distance = kMaxInt;
5580 int position = RelocInfo::kNoPosition; // Initially no position found.
5581 // Run through all the relocation info to find the best matching source
5582 // position. All the code needs to be considered as the sequence of the
5583 // instructions in the code does not necessarily follow the same order as the
5584 // source.
5585 RelocIterator it(this, RelocInfo::kPositionMask);
5586 while (!it.done()) {
5587 // Only look at positions after the current pc.
5588 if (it.rinfo()->pc() < pc) {
5589 // Get position and distance.
Steve Blockd0582a62009-12-15 09:54:21 +00005590
5591 int dist = static_cast<int>(pc - it.rinfo()->pc());
5592 int pos = static_cast<int>(it.rinfo()->data());
Steve Blocka7e24c12009-10-30 11:49:00 +00005593 // If this position is closer than the current candidate or if it has the
5594 // same distance as the current candidate and the position is higher then
5595 // this position is the new candidate.
5596 if ((dist < distance) ||
5597 (dist == distance && pos > position)) {
5598 position = pos;
5599 distance = dist;
5600 }
5601 }
5602 it.next();
5603 }
5604 return position;
5605}
5606
5607
5608// Same as Code::SourcePosition above except it only looks for statement
5609// positions.
5610int Code::SourceStatementPosition(Address pc) {
5611 // First find the position as close as possible using all position
5612 // information.
5613 int position = SourcePosition(pc);
5614 // Now find the closest statement position before the position.
5615 int statement_position = 0;
5616 RelocIterator it(this, RelocInfo::kPositionMask);
5617 while (!it.done()) {
5618 if (RelocInfo::IsStatementPosition(it.rinfo()->rmode())) {
Steve Blockd0582a62009-12-15 09:54:21 +00005619 int p = static_cast<int>(it.rinfo()->data());
Steve Blocka7e24c12009-10-30 11:49:00 +00005620 if (statement_position < p && p <= position) {
5621 statement_position = p;
5622 }
5623 }
5624 it.next();
5625 }
5626 return statement_position;
5627}
5628
5629
5630#ifdef ENABLE_DISASSEMBLER
5631// Identify kind of code.
5632const char* Code::Kind2String(Kind kind) {
5633 switch (kind) {
5634 case FUNCTION: return "FUNCTION";
5635 case STUB: return "STUB";
5636 case BUILTIN: return "BUILTIN";
5637 case LOAD_IC: return "LOAD_IC";
5638 case KEYED_LOAD_IC: return "KEYED_LOAD_IC";
5639 case STORE_IC: return "STORE_IC";
5640 case KEYED_STORE_IC: return "KEYED_STORE_IC";
5641 case CALL_IC: return "CALL_IC";
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01005642 case KEYED_CALL_IC: return "KEYED_CALL_IC";
Steve Block6ded16b2010-05-10 14:33:55 +01005643 case BINARY_OP_IC: return "BINARY_OP_IC";
Steve Blocka7e24c12009-10-30 11:49:00 +00005644 }
5645 UNREACHABLE();
5646 return NULL;
5647}
5648
5649
5650const char* Code::ICState2String(InlineCacheState state) {
5651 switch (state) {
5652 case UNINITIALIZED: return "UNINITIALIZED";
5653 case PREMONOMORPHIC: return "PREMONOMORPHIC";
5654 case MONOMORPHIC: return "MONOMORPHIC";
5655 case MONOMORPHIC_PROTOTYPE_FAILURE: return "MONOMORPHIC_PROTOTYPE_FAILURE";
5656 case MEGAMORPHIC: return "MEGAMORPHIC";
5657 case DEBUG_BREAK: return "DEBUG_BREAK";
5658 case DEBUG_PREPARE_STEP_IN: return "DEBUG_PREPARE_STEP_IN";
5659 }
5660 UNREACHABLE();
5661 return NULL;
5662}
5663
5664
5665const char* Code::PropertyType2String(PropertyType type) {
5666 switch (type) {
5667 case NORMAL: return "NORMAL";
5668 case FIELD: return "FIELD";
5669 case CONSTANT_FUNCTION: return "CONSTANT_FUNCTION";
5670 case CALLBACKS: return "CALLBACKS";
5671 case INTERCEPTOR: return "INTERCEPTOR";
5672 case MAP_TRANSITION: return "MAP_TRANSITION";
5673 case CONSTANT_TRANSITION: return "CONSTANT_TRANSITION";
5674 case NULL_DESCRIPTOR: return "NULL_DESCRIPTOR";
5675 }
5676 UNREACHABLE();
5677 return NULL;
5678}
5679
5680void Code::Disassemble(const char* name) {
5681 PrintF("kind = %s\n", Kind2String(kind()));
5682 if (is_inline_cache_stub()) {
5683 PrintF("ic_state = %s\n", ICState2String(ic_state()));
5684 PrintF("ic_in_loop = %d\n", ic_in_loop() == IN_LOOP);
5685 if (ic_state() == MONOMORPHIC) {
5686 PrintF("type = %s\n", PropertyType2String(type()));
5687 }
5688 }
5689 if ((name != NULL) && (name[0] != '\0')) {
5690 PrintF("name = %s\n", name);
5691 }
5692
5693 PrintF("Instructions (size = %d)\n", instruction_size());
5694 Disassembler::Decode(NULL, this);
5695 PrintF("\n");
5696
5697 PrintF("RelocInfo (size = %d)\n", relocation_size());
5698 for (RelocIterator it(this); !it.done(); it.next())
5699 it.rinfo()->Print();
5700 PrintF("\n");
5701}
5702#endif // ENABLE_DISASSEMBLER
5703
5704
Steve Block8defd9f2010-07-08 12:39:36 +01005705Object* JSObject::SetFastElementsCapacityAndLength(int capacity, int length) {
Steve Block3ce2e202009-11-05 08:53:23 +00005706 // We should never end in here with a pixel or external array.
5707 ASSERT(!HasPixelElements() && !HasExternalArrayElements());
Steve Block8defd9f2010-07-08 12:39:36 +01005708
5709 Object* obj = Heap::AllocateFixedArrayWithHoles(capacity);
5710 if (obj->IsFailure()) return obj;
5711 FixedArray* elems = FixedArray::cast(obj);
5712
5713 obj = map()->GetFastElementsMap();
5714 if (obj->IsFailure()) return obj;
5715 Map* new_map = Map::cast(obj);
5716
Leon Clarke4515c472010-02-03 11:58:03 +00005717 AssertNoAllocation no_gc;
5718 WriteBarrierMode mode = elems->GetWriteBarrierMode(no_gc);
Steve Blocka7e24c12009-10-30 11:49:00 +00005719 switch (GetElementsKind()) {
5720 case FAST_ELEMENTS: {
5721 FixedArray* old_elements = FixedArray::cast(elements());
5722 uint32_t old_length = static_cast<uint32_t>(old_elements->length());
5723 // Fill out the new array with this content and array holes.
5724 for (uint32_t i = 0; i < old_length; i++) {
5725 elems->set(i, old_elements->get(i), mode);
5726 }
5727 break;
5728 }
5729 case DICTIONARY_ELEMENTS: {
5730 NumberDictionary* dictionary = NumberDictionary::cast(elements());
5731 for (int i = 0; i < dictionary->Capacity(); i++) {
5732 Object* key = dictionary->KeyAt(i);
5733 if (key->IsNumber()) {
5734 uint32_t entry = static_cast<uint32_t>(key->Number());
5735 elems->set(entry, dictionary->ValueAt(i), mode);
5736 }
5737 }
5738 break;
5739 }
5740 default:
5741 UNREACHABLE();
5742 break;
5743 }
Steve Block8defd9f2010-07-08 12:39:36 +01005744
5745 set_map(new_map);
Steve Blocka7e24c12009-10-30 11:49:00 +00005746 set_elements(elems);
Steve Block8defd9f2010-07-08 12:39:36 +01005747
5748 if (IsJSArray()) {
5749 JSArray::cast(this)->set_length(Smi::FromInt(length));
5750 }
5751
5752 return this;
Steve Blocka7e24c12009-10-30 11:49:00 +00005753}
5754
5755
5756Object* JSObject::SetSlowElements(Object* len) {
Steve Block3ce2e202009-11-05 08:53:23 +00005757 // We should never end in here with a pixel or external array.
5758 ASSERT(!HasPixelElements() && !HasExternalArrayElements());
Steve Blocka7e24c12009-10-30 11:49:00 +00005759
5760 uint32_t new_length = static_cast<uint32_t>(len->Number());
5761
5762 switch (GetElementsKind()) {
5763 case FAST_ELEMENTS: {
5764 // Make sure we never try to shrink dense arrays into sparse arrays.
5765 ASSERT(static_cast<uint32_t>(FixedArray::cast(elements())->length()) <=
5766 new_length);
5767 Object* obj = NormalizeElements();
5768 if (obj->IsFailure()) return obj;
5769
5770 // Update length for JSArrays.
5771 if (IsJSArray()) JSArray::cast(this)->set_length(len);
5772 break;
5773 }
5774 case DICTIONARY_ELEMENTS: {
5775 if (IsJSArray()) {
5776 uint32_t old_length =
Steve Block6ded16b2010-05-10 14:33:55 +01005777 static_cast<uint32_t>(JSArray::cast(this)->length()->Number());
Steve Blocka7e24c12009-10-30 11:49:00 +00005778 element_dictionary()->RemoveNumberEntries(new_length, old_length),
5779 JSArray::cast(this)->set_length(len);
5780 }
5781 break;
5782 }
5783 default:
5784 UNREACHABLE();
5785 break;
5786 }
5787 return this;
5788}
5789
5790
5791Object* JSArray::Initialize(int capacity) {
5792 ASSERT(capacity >= 0);
Leon Clarke4515c472010-02-03 11:58:03 +00005793 set_length(Smi::FromInt(0));
Steve Blocka7e24c12009-10-30 11:49:00 +00005794 FixedArray* new_elements;
5795 if (capacity == 0) {
5796 new_elements = Heap::empty_fixed_array();
5797 } else {
5798 Object* obj = Heap::AllocateFixedArrayWithHoles(capacity);
5799 if (obj->IsFailure()) return obj;
5800 new_elements = FixedArray::cast(obj);
5801 }
5802 set_elements(new_elements);
5803 return this;
5804}
5805
5806
5807void JSArray::Expand(int required_size) {
5808 Handle<JSArray> self(this);
5809 Handle<FixedArray> old_backing(FixedArray::cast(elements()));
5810 int old_size = old_backing->length();
Steve Blockd0582a62009-12-15 09:54:21 +00005811 int new_size = required_size > old_size ? required_size : old_size;
Steve Blocka7e24c12009-10-30 11:49:00 +00005812 Handle<FixedArray> new_backing = Factory::NewFixedArray(new_size);
5813 // Can't use this any more now because we may have had a GC!
5814 for (int i = 0; i < old_size; i++) new_backing->set(i, old_backing->get(i));
5815 self->SetContent(*new_backing);
5816}
5817
5818
5819// Computes the new capacity when expanding the elements of a JSObject.
5820static int NewElementsCapacity(int old_capacity) {
5821 // (old_capacity + 50%) + 16
5822 return old_capacity + (old_capacity >> 1) + 16;
5823}
5824
5825
5826static Object* ArrayLengthRangeError() {
5827 HandleScope scope;
5828 return Top::Throw(*Factory::NewRangeError("invalid_array_length",
5829 HandleVector<Object>(NULL, 0)));
5830}
5831
5832
5833Object* JSObject::SetElementsLength(Object* len) {
Steve Block3ce2e202009-11-05 08:53:23 +00005834 // We should never end in here with a pixel or external array.
Steve Block6ded16b2010-05-10 14:33:55 +01005835 ASSERT(AllowsSetElementsLength());
Steve Blocka7e24c12009-10-30 11:49:00 +00005836
5837 Object* smi_length = len->ToSmi();
5838 if (smi_length->IsSmi()) {
Steve Block8defd9f2010-07-08 12:39:36 +01005839 const int value = Smi::cast(smi_length)->value();
Steve Blocka7e24c12009-10-30 11:49:00 +00005840 if (value < 0) return ArrayLengthRangeError();
5841 switch (GetElementsKind()) {
5842 case FAST_ELEMENTS: {
5843 int old_capacity = FixedArray::cast(elements())->length();
5844 if (value <= old_capacity) {
5845 if (IsJSArray()) {
Iain Merrick75681382010-08-19 15:07:18 +01005846 Object* obj = EnsureWritableFastElements();
5847 if (obj->IsFailure()) return obj;
Steve Blocka7e24c12009-10-30 11:49:00 +00005848 int old_length = FastD2I(JSArray::cast(this)->length()->Number());
5849 // NOTE: We may be able to optimize this by removing the
5850 // last part of the elements backing storage array and
5851 // setting the capacity to the new size.
5852 for (int i = value; i < old_length; i++) {
5853 FixedArray::cast(elements())->set_the_hole(i);
5854 }
Leon Clarke4515c472010-02-03 11:58:03 +00005855 JSArray::cast(this)->set_length(Smi::cast(smi_length));
Steve Blocka7e24c12009-10-30 11:49:00 +00005856 }
5857 return this;
5858 }
5859 int min = NewElementsCapacity(old_capacity);
5860 int new_capacity = value > min ? value : min;
5861 if (new_capacity <= kMaxFastElementsLength ||
5862 !ShouldConvertToSlowElements(new_capacity)) {
Steve Block8defd9f2010-07-08 12:39:36 +01005863 Object* obj = SetFastElementsCapacityAndLength(new_capacity, value);
Steve Blocka7e24c12009-10-30 11:49:00 +00005864 if (obj->IsFailure()) return obj;
Steve Blocka7e24c12009-10-30 11:49:00 +00005865 return this;
5866 }
5867 break;
5868 }
5869 case DICTIONARY_ELEMENTS: {
5870 if (IsJSArray()) {
5871 if (value == 0) {
5872 // If the length of a slow array is reset to zero, we clear
5873 // the array and flush backing storage. This has the added
5874 // benefit that the array returns to fast mode.
Steve Block8defd9f2010-07-08 12:39:36 +01005875 Object* obj = ResetElements();
5876 if (obj->IsFailure()) return obj;
Steve Blocka7e24c12009-10-30 11:49:00 +00005877 } else {
5878 // Remove deleted elements.
5879 uint32_t old_length =
5880 static_cast<uint32_t>(JSArray::cast(this)->length()->Number());
5881 element_dictionary()->RemoveNumberEntries(value, old_length);
5882 }
Leon Clarke4515c472010-02-03 11:58:03 +00005883 JSArray::cast(this)->set_length(Smi::cast(smi_length));
Steve Blocka7e24c12009-10-30 11:49:00 +00005884 }
5885 return this;
5886 }
5887 default:
5888 UNREACHABLE();
5889 break;
5890 }
5891 }
5892
5893 // General slow case.
5894 if (len->IsNumber()) {
5895 uint32_t length;
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01005896 if (len->ToArrayIndex(&length)) {
Steve Blocka7e24c12009-10-30 11:49:00 +00005897 return SetSlowElements(len);
5898 } else {
5899 return ArrayLengthRangeError();
5900 }
5901 }
5902
5903 // len is not a number so make the array size one and
5904 // set only element to len.
5905 Object* obj = Heap::AllocateFixedArray(1);
5906 if (obj->IsFailure()) return obj;
5907 FixedArray::cast(obj)->set(0, len);
Leon Clarke4515c472010-02-03 11:58:03 +00005908 if (IsJSArray()) JSArray::cast(this)->set_length(Smi::FromInt(1));
Steve Blocka7e24c12009-10-30 11:49:00 +00005909 set_elements(FixedArray::cast(obj));
5910 return this;
5911}
5912
5913
Andrei Popescu402d9372010-02-26 13:31:12 +00005914Object* JSObject::SetPrototype(Object* value,
5915 bool skip_hidden_prototypes) {
5916 // Silently ignore the change if value is not a JSObject or null.
5917 // SpiderMonkey behaves this way.
5918 if (!value->IsJSObject() && !value->IsNull()) return value;
5919
5920 // Before we can set the prototype we need to be sure
5921 // prototype cycles are prevented.
5922 // It is sufficient to validate that the receiver is not in the new prototype
5923 // chain.
5924 for (Object* pt = value; pt != Heap::null_value(); pt = pt->GetPrototype()) {
5925 if (JSObject::cast(pt) == this) {
5926 // Cycle detected.
5927 HandleScope scope;
5928 return Top::Throw(*Factory::NewError("cyclic_proto",
5929 HandleVector<Object>(NULL, 0)));
5930 }
5931 }
5932
5933 JSObject* real_receiver = this;
5934
5935 if (skip_hidden_prototypes) {
5936 // Find the first object in the chain whose prototype object is not
5937 // hidden and set the new prototype on that object.
5938 Object* current_proto = real_receiver->GetPrototype();
5939 while (current_proto->IsJSObject() &&
5940 JSObject::cast(current_proto)->map()->is_hidden_prototype()) {
5941 real_receiver = JSObject::cast(current_proto);
5942 current_proto = current_proto->GetPrototype();
5943 }
5944 }
5945
5946 // Set the new prototype of the object.
5947 Object* new_map = real_receiver->map()->CopyDropTransitions();
5948 if (new_map->IsFailure()) return new_map;
5949 Map::cast(new_map)->set_prototype(value);
5950 real_receiver->set_map(Map::cast(new_map));
5951
Kristian Monsen25f61362010-05-21 11:50:48 +01005952 Heap::ClearInstanceofCache();
5953
Andrei Popescu402d9372010-02-26 13:31:12 +00005954 return value;
5955}
5956
5957
Steve Blocka7e24c12009-10-30 11:49:00 +00005958bool JSObject::HasElementPostInterceptor(JSObject* receiver, uint32_t index) {
5959 switch (GetElementsKind()) {
5960 case FAST_ELEMENTS: {
5961 uint32_t length = IsJSArray() ?
5962 static_cast<uint32_t>
5963 (Smi::cast(JSArray::cast(this)->length())->value()) :
5964 static_cast<uint32_t>(FixedArray::cast(elements())->length());
5965 if ((index < length) &&
5966 !FixedArray::cast(elements())->get(index)->IsTheHole()) {
5967 return true;
5968 }
5969 break;
5970 }
5971 case PIXEL_ELEMENTS: {
5972 // TODO(iposva): Add testcase.
5973 PixelArray* pixels = PixelArray::cast(elements());
5974 if (index < static_cast<uint32_t>(pixels->length())) {
5975 return true;
5976 }
5977 break;
5978 }
Steve Block3ce2e202009-11-05 08:53:23 +00005979 case EXTERNAL_BYTE_ELEMENTS:
5980 case EXTERNAL_UNSIGNED_BYTE_ELEMENTS:
5981 case EXTERNAL_SHORT_ELEMENTS:
5982 case EXTERNAL_UNSIGNED_SHORT_ELEMENTS:
5983 case EXTERNAL_INT_ELEMENTS:
5984 case EXTERNAL_UNSIGNED_INT_ELEMENTS:
5985 case EXTERNAL_FLOAT_ELEMENTS: {
5986 // TODO(kbr): Add testcase.
5987 ExternalArray* array = ExternalArray::cast(elements());
5988 if (index < static_cast<uint32_t>(array->length())) {
5989 return true;
5990 }
5991 break;
5992 }
Steve Blocka7e24c12009-10-30 11:49:00 +00005993 case DICTIONARY_ELEMENTS: {
5994 if (element_dictionary()->FindEntry(index)
5995 != NumberDictionary::kNotFound) {
5996 return true;
5997 }
5998 break;
5999 }
6000 default:
6001 UNREACHABLE();
6002 break;
6003 }
6004
6005 // Handle [] on String objects.
6006 if (this->IsStringObjectWithCharacterAt(index)) return true;
6007
6008 Object* pt = GetPrototype();
6009 if (pt == Heap::null_value()) return false;
6010 return JSObject::cast(pt)->HasElementWithReceiver(receiver, index);
6011}
6012
6013
6014bool JSObject::HasElementWithInterceptor(JSObject* receiver, uint32_t index) {
6015 // Make sure that the top context does not change when doing
6016 // callbacks or interceptor calls.
6017 AssertNoContextChange ncc;
6018 HandleScope scope;
6019 Handle<InterceptorInfo> interceptor(GetIndexedInterceptor());
6020 Handle<JSObject> receiver_handle(receiver);
6021 Handle<JSObject> holder_handle(this);
6022 CustomArguments args(interceptor->data(), receiver, this);
6023 v8::AccessorInfo info(args.end());
6024 if (!interceptor->query()->IsUndefined()) {
6025 v8::IndexedPropertyQuery query =
6026 v8::ToCData<v8::IndexedPropertyQuery>(interceptor->query());
6027 LOG(ApiIndexedPropertyAccess("interceptor-indexed-has", this, index));
Iain Merrick75681382010-08-19 15:07:18 +01006028 v8::Handle<v8::Integer> result;
Steve Blocka7e24c12009-10-30 11:49:00 +00006029 {
6030 // Leaving JavaScript.
6031 VMState state(EXTERNAL);
6032 result = query(index, info);
6033 }
Iain Merrick75681382010-08-19 15:07:18 +01006034 if (!result.IsEmpty()) {
6035 ASSERT(result->IsInt32());
6036 return true; // absence of property is signaled by empty handle.
6037 }
Steve Blocka7e24c12009-10-30 11:49:00 +00006038 } else if (!interceptor->getter()->IsUndefined()) {
6039 v8::IndexedPropertyGetter getter =
6040 v8::ToCData<v8::IndexedPropertyGetter>(interceptor->getter());
6041 LOG(ApiIndexedPropertyAccess("interceptor-indexed-has-get", this, index));
6042 v8::Handle<v8::Value> result;
6043 {
6044 // Leaving JavaScript.
6045 VMState state(EXTERNAL);
6046 result = getter(index, info);
6047 }
6048 if (!result.IsEmpty()) return true;
6049 }
6050 return holder_handle->HasElementPostInterceptor(*receiver_handle, index);
6051}
6052
6053
Kristian Monsen0d5e1162010-09-30 15:31:59 +01006054JSObject::LocalElementType JSObject::HasLocalElement(uint32_t index) {
Steve Blocka7e24c12009-10-30 11:49:00 +00006055 // Check access rights if needed.
6056 if (IsAccessCheckNeeded() &&
6057 !Top::MayIndexedAccess(this, index, v8::ACCESS_HAS)) {
6058 Top::ReportFailedAccessCheck(this, v8::ACCESS_HAS);
Kristian Monsen0d5e1162010-09-30 15:31:59 +01006059 return UNDEFINED_ELEMENT;
Steve Blocka7e24c12009-10-30 11:49:00 +00006060 }
6061
6062 // Check for lookup interceptor
6063 if (HasIndexedInterceptor()) {
Kristian Monsen0d5e1162010-09-30 15:31:59 +01006064 return HasElementWithInterceptor(this, index) ? INTERCEPTED_ELEMENT
6065 : UNDEFINED_ELEMENT;
Steve Blocka7e24c12009-10-30 11:49:00 +00006066 }
6067
6068 // Handle [] on String objects.
Kristian Monsen0d5e1162010-09-30 15:31:59 +01006069 if (this->IsStringObjectWithCharacterAt(index)) {
6070 return STRING_CHARACTER_ELEMENT;
6071 }
Steve Blocka7e24c12009-10-30 11:49:00 +00006072
6073 switch (GetElementsKind()) {
6074 case FAST_ELEMENTS: {
6075 uint32_t length = IsJSArray() ?
6076 static_cast<uint32_t>
6077 (Smi::cast(JSArray::cast(this)->length())->value()) :
6078 static_cast<uint32_t>(FixedArray::cast(elements())->length());
Kristian Monsen0d5e1162010-09-30 15:31:59 +01006079 if ((index < length) &&
6080 !FixedArray::cast(elements())->get(index)->IsTheHole()) {
6081 return FAST_ELEMENT;
6082 }
6083 break;
Steve Blocka7e24c12009-10-30 11:49:00 +00006084 }
6085 case PIXEL_ELEMENTS: {
6086 PixelArray* pixels = PixelArray::cast(elements());
Kristian Monsen0d5e1162010-09-30 15:31:59 +01006087 if (index < static_cast<uint32_t>(pixels->length())) return FAST_ELEMENT;
6088 break;
Steve Blocka7e24c12009-10-30 11:49:00 +00006089 }
Steve Block3ce2e202009-11-05 08:53:23 +00006090 case EXTERNAL_BYTE_ELEMENTS:
6091 case EXTERNAL_UNSIGNED_BYTE_ELEMENTS:
6092 case EXTERNAL_SHORT_ELEMENTS:
6093 case EXTERNAL_UNSIGNED_SHORT_ELEMENTS:
6094 case EXTERNAL_INT_ELEMENTS:
6095 case EXTERNAL_UNSIGNED_INT_ELEMENTS:
6096 case EXTERNAL_FLOAT_ELEMENTS: {
6097 ExternalArray* array = ExternalArray::cast(elements());
Kristian Monsen0d5e1162010-09-30 15:31:59 +01006098 if (index < static_cast<uint32_t>(array->length())) return FAST_ELEMENT;
6099 break;
Steve Block3ce2e202009-11-05 08:53:23 +00006100 }
Steve Blocka7e24c12009-10-30 11:49:00 +00006101 case DICTIONARY_ELEMENTS: {
Kristian Monsen0d5e1162010-09-30 15:31:59 +01006102 if (element_dictionary()->FindEntry(index) !=
6103 NumberDictionary::kNotFound) {
6104 return DICTIONARY_ELEMENT;
6105 }
6106 break;
Steve Blocka7e24c12009-10-30 11:49:00 +00006107 }
6108 default:
6109 UNREACHABLE();
6110 break;
6111 }
Kristian Monsen0d5e1162010-09-30 15:31:59 +01006112
6113 return UNDEFINED_ELEMENT;
Steve Blocka7e24c12009-10-30 11:49:00 +00006114}
6115
6116
6117bool JSObject::HasElementWithReceiver(JSObject* receiver, uint32_t index) {
6118 // Check access rights if needed.
6119 if (IsAccessCheckNeeded() &&
6120 !Top::MayIndexedAccess(this, index, v8::ACCESS_HAS)) {
6121 Top::ReportFailedAccessCheck(this, v8::ACCESS_HAS);
6122 return false;
6123 }
6124
6125 // Check for lookup interceptor
6126 if (HasIndexedInterceptor()) {
6127 return HasElementWithInterceptor(receiver, index);
6128 }
6129
6130 switch (GetElementsKind()) {
6131 case FAST_ELEMENTS: {
6132 uint32_t length = IsJSArray() ?
6133 static_cast<uint32_t>
6134 (Smi::cast(JSArray::cast(this)->length())->value()) :
6135 static_cast<uint32_t>(FixedArray::cast(elements())->length());
6136 if ((index < length) &&
6137 !FixedArray::cast(elements())->get(index)->IsTheHole()) return true;
6138 break;
6139 }
6140 case PIXEL_ELEMENTS: {
6141 PixelArray* pixels = PixelArray::cast(elements());
6142 if (index < static_cast<uint32_t>(pixels->length())) {
6143 return true;
6144 }
6145 break;
6146 }
Steve Block3ce2e202009-11-05 08:53:23 +00006147 case EXTERNAL_BYTE_ELEMENTS:
6148 case EXTERNAL_UNSIGNED_BYTE_ELEMENTS:
6149 case EXTERNAL_SHORT_ELEMENTS:
6150 case EXTERNAL_UNSIGNED_SHORT_ELEMENTS:
6151 case EXTERNAL_INT_ELEMENTS:
6152 case EXTERNAL_UNSIGNED_INT_ELEMENTS:
6153 case EXTERNAL_FLOAT_ELEMENTS: {
6154 ExternalArray* array = ExternalArray::cast(elements());
6155 if (index < static_cast<uint32_t>(array->length())) {
6156 return true;
6157 }
6158 break;
6159 }
Steve Blocka7e24c12009-10-30 11:49:00 +00006160 case DICTIONARY_ELEMENTS: {
6161 if (element_dictionary()->FindEntry(index)
6162 != NumberDictionary::kNotFound) {
6163 return true;
6164 }
6165 break;
6166 }
6167 default:
6168 UNREACHABLE();
6169 break;
6170 }
6171
6172 // Handle [] on String objects.
6173 if (this->IsStringObjectWithCharacterAt(index)) return true;
6174
6175 Object* pt = GetPrototype();
6176 if (pt == Heap::null_value()) return false;
6177 return JSObject::cast(pt)->HasElementWithReceiver(receiver, index);
6178}
6179
6180
6181Object* JSObject::SetElementWithInterceptor(uint32_t index, Object* value) {
6182 // Make sure that the top context does not change when doing
6183 // callbacks or interceptor calls.
6184 AssertNoContextChange ncc;
6185 HandleScope scope;
6186 Handle<InterceptorInfo> interceptor(GetIndexedInterceptor());
6187 Handle<JSObject> this_handle(this);
6188 Handle<Object> value_handle(value);
6189 if (!interceptor->setter()->IsUndefined()) {
6190 v8::IndexedPropertySetter setter =
6191 v8::ToCData<v8::IndexedPropertySetter>(interceptor->setter());
6192 LOG(ApiIndexedPropertyAccess("interceptor-indexed-set", this, index));
6193 CustomArguments args(interceptor->data(), this, this);
6194 v8::AccessorInfo info(args.end());
6195 v8::Handle<v8::Value> result;
6196 {
6197 // Leaving JavaScript.
6198 VMState state(EXTERNAL);
6199 result = setter(index, v8::Utils::ToLocal(value_handle), info);
6200 }
6201 RETURN_IF_SCHEDULED_EXCEPTION();
6202 if (!result.IsEmpty()) return *value_handle;
6203 }
6204 Object* raw_result =
6205 this_handle->SetElementWithoutInterceptor(index, *value_handle);
6206 RETURN_IF_SCHEDULED_EXCEPTION();
6207 return raw_result;
6208}
6209
6210
Leon Clarkef7060e22010-06-03 12:02:55 +01006211Object* JSObject::GetElementWithCallback(Object* receiver,
6212 Object* structure,
6213 uint32_t index,
6214 Object* holder) {
6215 ASSERT(!structure->IsProxy());
6216
6217 // api style callbacks.
6218 if (structure->IsAccessorInfo()) {
6219 AccessorInfo* data = AccessorInfo::cast(structure);
6220 Object* fun_obj = data->getter();
6221 v8::AccessorGetter call_fun = v8::ToCData<v8::AccessorGetter>(fun_obj);
6222 HandleScope scope;
6223 Handle<JSObject> self(JSObject::cast(receiver));
6224 Handle<JSObject> holder_handle(JSObject::cast(holder));
6225 Handle<Object> number = Factory::NewNumberFromUint(index);
6226 Handle<String> key(Factory::NumberToString(number));
6227 LOG(ApiNamedPropertyAccess("load", *self, *key));
6228 CustomArguments args(data->data(), *self, *holder_handle);
6229 v8::AccessorInfo info(args.end());
6230 v8::Handle<v8::Value> result;
6231 {
6232 // Leaving JavaScript.
6233 VMState state(EXTERNAL);
6234 result = call_fun(v8::Utils::ToLocal(key), info);
6235 }
6236 RETURN_IF_SCHEDULED_EXCEPTION();
6237 if (result.IsEmpty()) return Heap::undefined_value();
6238 return *v8::Utils::OpenHandle(*result);
6239 }
6240
6241 // __defineGetter__ callback
6242 if (structure->IsFixedArray()) {
6243 Object* getter = FixedArray::cast(structure)->get(kGetterIndex);
6244 if (getter->IsJSFunction()) {
6245 return Object::GetPropertyWithDefinedGetter(receiver,
6246 JSFunction::cast(getter));
6247 }
6248 // Getter is not a function.
6249 return Heap::undefined_value();
6250 }
6251
6252 UNREACHABLE();
6253 return NULL;
6254}
6255
6256
6257Object* JSObject::SetElementWithCallback(Object* structure,
6258 uint32_t index,
6259 Object* value,
6260 JSObject* holder) {
6261 HandleScope scope;
6262
6263 // We should never get here to initialize a const with the hole
6264 // value since a const declaration would conflict with the setter.
6265 ASSERT(!value->IsTheHole());
6266 Handle<Object> value_handle(value);
6267
6268 // To accommodate both the old and the new api we switch on the
6269 // data structure used to store the callbacks. Eventually proxy
6270 // callbacks should be phased out.
6271 ASSERT(!structure->IsProxy());
6272
6273 if (structure->IsAccessorInfo()) {
6274 // api style callbacks
6275 AccessorInfo* data = AccessorInfo::cast(structure);
6276 Object* call_obj = data->setter();
6277 v8::AccessorSetter call_fun = v8::ToCData<v8::AccessorSetter>(call_obj);
6278 if (call_fun == NULL) return value;
6279 Handle<Object> number = Factory::NewNumberFromUint(index);
6280 Handle<String> key(Factory::NumberToString(number));
6281 LOG(ApiNamedPropertyAccess("store", this, *key));
6282 CustomArguments args(data->data(), this, JSObject::cast(holder));
6283 v8::AccessorInfo info(args.end());
6284 {
6285 // Leaving JavaScript.
6286 VMState state(EXTERNAL);
6287 call_fun(v8::Utils::ToLocal(key),
6288 v8::Utils::ToLocal(value_handle),
6289 info);
6290 }
6291 RETURN_IF_SCHEDULED_EXCEPTION();
6292 return *value_handle;
6293 }
6294
6295 if (structure->IsFixedArray()) {
6296 Object* setter = FixedArray::cast(structure)->get(kSetterIndex);
6297 if (setter->IsJSFunction()) {
6298 return SetPropertyWithDefinedSetter(JSFunction::cast(setter), value);
6299 } else {
6300 Handle<Object> holder_handle(holder);
6301 Handle<Object> key(Factory::NewNumberFromUint(index));
6302 Handle<Object> args[2] = { key, holder_handle };
6303 return Top::Throw(*Factory::NewTypeError("no_setter_in_callback",
6304 HandleVector(args, 2)));
6305 }
6306 }
6307
6308 UNREACHABLE();
6309 return NULL;
6310}
6311
6312
Steve Blocka7e24c12009-10-30 11:49:00 +00006313// Adding n elements in fast case is O(n*n).
6314// Note: revisit design to have dual undefined values to capture absent
6315// elements.
6316Object* JSObject::SetFastElement(uint32_t index, Object* value) {
6317 ASSERT(HasFastElements());
6318
Iain Merrick75681382010-08-19 15:07:18 +01006319 Object* elms_obj = EnsureWritableFastElements();
6320 if (elms_obj->IsFailure()) return elms_obj;
6321 FixedArray* elms = FixedArray::cast(elms_obj);
Steve Blocka7e24c12009-10-30 11:49:00 +00006322 uint32_t elms_length = static_cast<uint32_t>(elms->length());
6323
6324 if (!IsJSArray() && (index >= elms_length || elms->get(index)->IsTheHole())) {
Leon Clarkef7060e22010-06-03 12:02:55 +01006325 if (SetElementWithCallbackSetterInPrototypes(index, value)) {
6326 return value;
Steve Blocka7e24c12009-10-30 11:49:00 +00006327 }
6328 }
6329
6330 // Check whether there is extra space in fixed array..
6331 if (index < elms_length) {
6332 elms->set(index, value);
6333 if (IsJSArray()) {
6334 // Update the length of the array if needed.
6335 uint32_t array_length = 0;
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01006336 CHECK(JSArray::cast(this)->length()->ToArrayIndex(&array_length));
Steve Blocka7e24c12009-10-30 11:49:00 +00006337 if (index >= array_length) {
Leon Clarke4515c472010-02-03 11:58:03 +00006338 JSArray::cast(this)->set_length(Smi::FromInt(index + 1));
Steve Blocka7e24c12009-10-30 11:49:00 +00006339 }
6340 }
6341 return value;
6342 }
6343
6344 // Allow gap in fast case.
6345 if ((index - elms_length) < kMaxGap) {
6346 // Try allocating extra space.
6347 int new_capacity = NewElementsCapacity(index+1);
6348 if (new_capacity <= kMaxFastElementsLength ||
6349 !ShouldConvertToSlowElements(new_capacity)) {
6350 ASSERT(static_cast<uint32_t>(new_capacity) > index);
Steve Block8defd9f2010-07-08 12:39:36 +01006351 Object* obj = SetFastElementsCapacityAndLength(new_capacity, index + 1);
Steve Blocka7e24c12009-10-30 11:49:00 +00006352 if (obj->IsFailure()) return obj;
Steve Blocka7e24c12009-10-30 11:49:00 +00006353 FixedArray::cast(elements())->set(index, value);
6354 return value;
6355 }
6356 }
6357
6358 // Otherwise default to slow case.
6359 Object* obj = NormalizeElements();
6360 if (obj->IsFailure()) return obj;
6361 ASSERT(HasDictionaryElements());
6362 return SetElement(index, value);
6363}
6364
Iain Merrick75681382010-08-19 15:07:18 +01006365
Steve Blocka7e24c12009-10-30 11:49:00 +00006366Object* JSObject::SetElement(uint32_t index, Object* value) {
6367 // Check access rights if needed.
6368 if (IsAccessCheckNeeded() &&
6369 !Top::MayIndexedAccess(this, index, v8::ACCESS_SET)) {
Iain Merrick75681382010-08-19 15:07:18 +01006370 HandleScope scope;
6371 Handle<Object> value_handle(value);
Steve Blocka7e24c12009-10-30 11:49:00 +00006372 Top::ReportFailedAccessCheck(this, v8::ACCESS_SET);
Iain Merrick75681382010-08-19 15:07:18 +01006373 return *value_handle;
Steve Blocka7e24c12009-10-30 11:49:00 +00006374 }
6375
6376 if (IsJSGlobalProxy()) {
6377 Object* proto = GetPrototype();
6378 if (proto->IsNull()) return value;
6379 ASSERT(proto->IsJSGlobalObject());
6380 return JSObject::cast(proto)->SetElement(index, value);
6381 }
6382
6383 // Check for lookup interceptor
6384 if (HasIndexedInterceptor()) {
6385 return SetElementWithInterceptor(index, value);
6386 }
6387
6388 return SetElementWithoutInterceptor(index, value);
6389}
6390
6391
6392Object* JSObject::SetElementWithoutInterceptor(uint32_t index, Object* value) {
6393 switch (GetElementsKind()) {
6394 case FAST_ELEMENTS:
6395 // Fast case.
6396 return SetFastElement(index, value);
6397 case PIXEL_ELEMENTS: {
6398 PixelArray* pixels = PixelArray::cast(elements());
6399 return pixels->SetValue(index, value);
6400 }
Steve Block3ce2e202009-11-05 08:53:23 +00006401 case EXTERNAL_BYTE_ELEMENTS: {
6402 ExternalByteArray* array = ExternalByteArray::cast(elements());
6403 return array->SetValue(index, value);
6404 }
6405 case EXTERNAL_UNSIGNED_BYTE_ELEMENTS: {
6406 ExternalUnsignedByteArray* array =
6407 ExternalUnsignedByteArray::cast(elements());
6408 return array->SetValue(index, value);
6409 }
6410 case EXTERNAL_SHORT_ELEMENTS: {
6411 ExternalShortArray* array = ExternalShortArray::cast(elements());
6412 return array->SetValue(index, value);
6413 }
6414 case EXTERNAL_UNSIGNED_SHORT_ELEMENTS: {
6415 ExternalUnsignedShortArray* array =
6416 ExternalUnsignedShortArray::cast(elements());
6417 return array->SetValue(index, value);
6418 }
6419 case EXTERNAL_INT_ELEMENTS: {
6420 ExternalIntArray* array = ExternalIntArray::cast(elements());
6421 return array->SetValue(index, value);
6422 }
6423 case EXTERNAL_UNSIGNED_INT_ELEMENTS: {
6424 ExternalUnsignedIntArray* array =
6425 ExternalUnsignedIntArray::cast(elements());
6426 return array->SetValue(index, value);
6427 }
6428 case EXTERNAL_FLOAT_ELEMENTS: {
6429 ExternalFloatArray* array = ExternalFloatArray::cast(elements());
6430 return array->SetValue(index, value);
6431 }
Steve Blocka7e24c12009-10-30 11:49:00 +00006432 case DICTIONARY_ELEMENTS: {
6433 // Insert element in the dictionary.
6434 FixedArray* elms = FixedArray::cast(elements());
6435 NumberDictionary* dictionary = NumberDictionary::cast(elms);
6436
6437 int entry = dictionary->FindEntry(index);
6438 if (entry != NumberDictionary::kNotFound) {
6439 Object* element = dictionary->ValueAt(entry);
6440 PropertyDetails details = dictionary->DetailsAt(entry);
6441 if (details.type() == CALLBACKS) {
Leon Clarkef7060e22010-06-03 12:02:55 +01006442 return SetElementWithCallback(element, index, value, this);
Steve Blocka7e24c12009-10-30 11:49:00 +00006443 } else {
6444 dictionary->UpdateMaxNumberKey(index);
6445 dictionary->ValueAtPut(entry, value);
6446 }
6447 } else {
6448 // Index not already used. Look for an accessor in the prototype chain.
6449 if (!IsJSArray()) {
Leon Clarkef7060e22010-06-03 12:02:55 +01006450 if (SetElementWithCallbackSetterInPrototypes(index, value)) {
6451 return value;
Steve Blocka7e24c12009-10-30 11:49:00 +00006452 }
6453 }
Steve Block8defd9f2010-07-08 12:39:36 +01006454 // When we set the is_extensible flag to false we always force
6455 // the element into dictionary mode (and force them to stay there).
6456 if (!map()->is_extensible()) {
6457 Handle<Object> number(Heap::NumberFromUint32(index));
6458 Handle<String> index_string(Factory::NumberToString(number));
6459 Handle<Object> args[1] = { index_string };
6460 return Top::Throw(*Factory::NewTypeError("object_not_extensible",
6461 HandleVector(args, 1)));
6462 }
Steve Blocka7e24c12009-10-30 11:49:00 +00006463 Object* result = dictionary->AtNumberPut(index, value);
6464 if (result->IsFailure()) return result;
6465 if (elms != FixedArray::cast(result)) {
6466 set_elements(FixedArray::cast(result));
6467 }
6468 }
6469
6470 // Update the array length if this JSObject is an array.
6471 if (IsJSArray()) {
6472 JSArray* array = JSArray::cast(this);
6473 Object* return_value = array->JSArrayUpdateLengthFromIndex(index,
6474 value);
6475 if (return_value->IsFailure()) return return_value;
6476 }
6477
6478 // Attempt to put this object back in fast case.
6479 if (ShouldConvertToFastElements()) {
6480 uint32_t new_length = 0;
6481 if (IsJSArray()) {
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01006482 CHECK(JSArray::cast(this)->length()->ToArrayIndex(&new_length));
Steve Blocka7e24c12009-10-30 11:49:00 +00006483 } else {
6484 new_length = NumberDictionary::cast(elements())->max_number_key() + 1;
6485 }
Steve Block8defd9f2010-07-08 12:39:36 +01006486 Object* obj = SetFastElementsCapacityAndLength(new_length, new_length);
Steve Blocka7e24c12009-10-30 11:49:00 +00006487 if (obj->IsFailure()) return obj;
Steve Blocka7e24c12009-10-30 11:49:00 +00006488#ifdef DEBUG
6489 if (FLAG_trace_normalization) {
6490 PrintF("Object elements are fast case again:\n");
6491 Print();
6492 }
6493#endif
6494 }
6495
6496 return value;
6497 }
6498 default:
6499 UNREACHABLE();
6500 break;
6501 }
6502 // All possible cases have been handled above. Add a return to avoid the
6503 // complaints from the compiler.
6504 UNREACHABLE();
6505 return Heap::null_value();
6506}
6507
6508
6509Object* JSArray::JSArrayUpdateLengthFromIndex(uint32_t index, Object* value) {
6510 uint32_t old_len = 0;
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01006511 CHECK(length()->ToArrayIndex(&old_len));
Steve Blocka7e24c12009-10-30 11:49:00 +00006512 // Check to see if we need to update the length. For now, we make
6513 // sure that the length stays within 32-bits (unsigned).
6514 if (index >= old_len && index != 0xffffffff) {
6515 Object* len =
6516 Heap::NumberFromDouble(static_cast<double>(index) + 1);
6517 if (len->IsFailure()) return len;
6518 set_length(len);
6519 }
6520 return value;
6521}
6522
6523
6524Object* JSObject::GetElementPostInterceptor(JSObject* receiver,
6525 uint32_t index) {
6526 // Get element works for both JSObject and JSArray since
6527 // JSArray::length cannot change.
6528 switch (GetElementsKind()) {
6529 case FAST_ELEMENTS: {
6530 FixedArray* elms = FixedArray::cast(elements());
6531 if (index < static_cast<uint32_t>(elms->length())) {
6532 Object* value = elms->get(index);
6533 if (!value->IsTheHole()) return value;
6534 }
6535 break;
6536 }
6537 case PIXEL_ELEMENTS: {
6538 // TODO(iposva): Add testcase and implement.
6539 UNIMPLEMENTED();
6540 break;
6541 }
Steve Block3ce2e202009-11-05 08:53:23 +00006542 case EXTERNAL_BYTE_ELEMENTS:
6543 case EXTERNAL_UNSIGNED_BYTE_ELEMENTS:
6544 case EXTERNAL_SHORT_ELEMENTS:
6545 case EXTERNAL_UNSIGNED_SHORT_ELEMENTS:
6546 case EXTERNAL_INT_ELEMENTS:
6547 case EXTERNAL_UNSIGNED_INT_ELEMENTS:
6548 case EXTERNAL_FLOAT_ELEMENTS: {
6549 // TODO(kbr): Add testcase and implement.
6550 UNIMPLEMENTED();
6551 break;
6552 }
Steve Blocka7e24c12009-10-30 11:49:00 +00006553 case DICTIONARY_ELEMENTS: {
6554 NumberDictionary* dictionary = element_dictionary();
6555 int entry = dictionary->FindEntry(index);
6556 if (entry != NumberDictionary::kNotFound) {
6557 Object* element = dictionary->ValueAt(entry);
6558 PropertyDetails details = dictionary->DetailsAt(entry);
6559 if (details.type() == CALLBACKS) {
Leon Clarkef7060e22010-06-03 12:02:55 +01006560 return GetElementWithCallback(receiver,
6561 element,
6562 index,
6563 this);
Steve Blocka7e24c12009-10-30 11:49:00 +00006564 }
6565 return element;
6566 }
6567 break;
6568 }
6569 default:
6570 UNREACHABLE();
6571 break;
6572 }
6573
6574 // Continue searching via the prototype chain.
6575 Object* pt = GetPrototype();
6576 if (pt == Heap::null_value()) return Heap::undefined_value();
6577 return pt->GetElementWithReceiver(receiver, index);
6578}
6579
6580
6581Object* JSObject::GetElementWithInterceptor(JSObject* receiver,
6582 uint32_t index) {
6583 // Make sure that the top context does not change when doing
6584 // callbacks or interceptor calls.
6585 AssertNoContextChange ncc;
6586 HandleScope scope;
6587 Handle<InterceptorInfo> interceptor(GetIndexedInterceptor());
6588 Handle<JSObject> this_handle(receiver);
6589 Handle<JSObject> holder_handle(this);
6590
6591 if (!interceptor->getter()->IsUndefined()) {
6592 v8::IndexedPropertyGetter getter =
6593 v8::ToCData<v8::IndexedPropertyGetter>(interceptor->getter());
6594 LOG(ApiIndexedPropertyAccess("interceptor-indexed-get", this, index));
6595 CustomArguments args(interceptor->data(), receiver, this);
6596 v8::AccessorInfo info(args.end());
6597 v8::Handle<v8::Value> result;
6598 {
6599 // Leaving JavaScript.
6600 VMState state(EXTERNAL);
6601 result = getter(index, info);
6602 }
6603 RETURN_IF_SCHEDULED_EXCEPTION();
6604 if (!result.IsEmpty()) return *v8::Utils::OpenHandle(*result);
6605 }
6606
6607 Object* raw_result =
6608 holder_handle->GetElementPostInterceptor(*this_handle, index);
6609 RETURN_IF_SCHEDULED_EXCEPTION();
6610 return raw_result;
6611}
6612
6613
6614Object* JSObject::GetElementWithReceiver(JSObject* receiver, uint32_t index) {
6615 // Check access rights if needed.
6616 if (IsAccessCheckNeeded() &&
6617 !Top::MayIndexedAccess(this, index, v8::ACCESS_GET)) {
6618 Top::ReportFailedAccessCheck(this, v8::ACCESS_GET);
6619 return Heap::undefined_value();
6620 }
6621
6622 if (HasIndexedInterceptor()) {
6623 return GetElementWithInterceptor(receiver, index);
6624 }
6625
6626 // Get element works for both JSObject and JSArray since
6627 // JSArray::length cannot change.
6628 switch (GetElementsKind()) {
6629 case FAST_ELEMENTS: {
6630 FixedArray* elms = FixedArray::cast(elements());
6631 if (index < static_cast<uint32_t>(elms->length())) {
6632 Object* value = elms->get(index);
6633 if (!value->IsTheHole()) return value;
6634 }
6635 break;
6636 }
6637 case PIXEL_ELEMENTS: {
6638 PixelArray* pixels = PixelArray::cast(elements());
6639 if (index < static_cast<uint32_t>(pixels->length())) {
6640 uint8_t value = pixels->get(index);
6641 return Smi::FromInt(value);
6642 }
6643 break;
6644 }
Steve Block3ce2e202009-11-05 08:53:23 +00006645 case EXTERNAL_BYTE_ELEMENTS: {
6646 ExternalByteArray* array = ExternalByteArray::cast(elements());
6647 if (index < static_cast<uint32_t>(array->length())) {
6648 int8_t value = array->get(index);
6649 return Smi::FromInt(value);
6650 }
6651 break;
6652 }
6653 case EXTERNAL_UNSIGNED_BYTE_ELEMENTS: {
6654 ExternalUnsignedByteArray* array =
6655 ExternalUnsignedByteArray::cast(elements());
6656 if (index < static_cast<uint32_t>(array->length())) {
6657 uint8_t value = array->get(index);
6658 return Smi::FromInt(value);
6659 }
6660 break;
6661 }
6662 case EXTERNAL_SHORT_ELEMENTS: {
6663 ExternalShortArray* array = ExternalShortArray::cast(elements());
6664 if (index < static_cast<uint32_t>(array->length())) {
6665 int16_t value = array->get(index);
6666 return Smi::FromInt(value);
6667 }
6668 break;
6669 }
6670 case EXTERNAL_UNSIGNED_SHORT_ELEMENTS: {
6671 ExternalUnsignedShortArray* array =
6672 ExternalUnsignedShortArray::cast(elements());
6673 if (index < static_cast<uint32_t>(array->length())) {
6674 uint16_t value = array->get(index);
6675 return Smi::FromInt(value);
6676 }
6677 break;
6678 }
6679 case EXTERNAL_INT_ELEMENTS: {
6680 ExternalIntArray* array = ExternalIntArray::cast(elements());
6681 if (index < static_cast<uint32_t>(array->length())) {
6682 int32_t value = array->get(index);
6683 return Heap::NumberFromInt32(value);
6684 }
6685 break;
6686 }
6687 case EXTERNAL_UNSIGNED_INT_ELEMENTS: {
6688 ExternalUnsignedIntArray* array =
6689 ExternalUnsignedIntArray::cast(elements());
6690 if (index < static_cast<uint32_t>(array->length())) {
6691 uint32_t value = array->get(index);
6692 return Heap::NumberFromUint32(value);
6693 }
6694 break;
6695 }
6696 case EXTERNAL_FLOAT_ELEMENTS: {
6697 ExternalFloatArray* array = ExternalFloatArray::cast(elements());
6698 if (index < static_cast<uint32_t>(array->length())) {
6699 float value = array->get(index);
6700 return Heap::AllocateHeapNumber(value);
6701 }
6702 break;
6703 }
Steve Blocka7e24c12009-10-30 11:49:00 +00006704 case DICTIONARY_ELEMENTS: {
6705 NumberDictionary* dictionary = element_dictionary();
6706 int entry = dictionary->FindEntry(index);
6707 if (entry != NumberDictionary::kNotFound) {
6708 Object* element = dictionary->ValueAt(entry);
6709 PropertyDetails details = dictionary->DetailsAt(entry);
6710 if (details.type() == CALLBACKS) {
Leon Clarkef7060e22010-06-03 12:02:55 +01006711 return GetElementWithCallback(receiver,
6712 element,
6713 index,
6714 this);
Steve Blocka7e24c12009-10-30 11:49:00 +00006715 }
6716 return element;
6717 }
6718 break;
6719 }
6720 }
6721
6722 Object* pt = GetPrototype();
6723 if (pt == Heap::null_value()) return Heap::undefined_value();
6724 return pt->GetElementWithReceiver(receiver, index);
6725}
6726
6727
6728bool JSObject::HasDenseElements() {
6729 int capacity = 0;
6730 int number_of_elements = 0;
6731
6732 switch (GetElementsKind()) {
6733 case FAST_ELEMENTS: {
6734 FixedArray* elms = FixedArray::cast(elements());
6735 capacity = elms->length();
6736 for (int i = 0; i < capacity; i++) {
6737 if (!elms->get(i)->IsTheHole()) number_of_elements++;
6738 }
6739 break;
6740 }
Steve Block3ce2e202009-11-05 08:53:23 +00006741 case PIXEL_ELEMENTS:
6742 case EXTERNAL_BYTE_ELEMENTS:
6743 case EXTERNAL_UNSIGNED_BYTE_ELEMENTS:
6744 case EXTERNAL_SHORT_ELEMENTS:
6745 case EXTERNAL_UNSIGNED_SHORT_ELEMENTS:
6746 case EXTERNAL_INT_ELEMENTS:
6747 case EXTERNAL_UNSIGNED_INT_ELEMENTS:
6748 case EXTERNAL_FLOAT_ELEMENTS: {
Steve Blocka7e24c12009-10-30 11:49:00 +00006749 return true;
6750 }
6751 case DICTIONARY_ELEMENTS: {
6752 NumberDictionary* dictionary = NumberDictionary::cast(elements());
6753 capacity = dictionary->Capacity();
6754 number_of_elements = dictionary->NumberOfElements();
6755 break;
6756 }
6757 default:
6758 UNREACHABLE();
6759 break;
6760 }
6761
6762 if (capacity == 0) return true;
6763 return (number_of_elements > (capacity / 2));
6764}
6765
6766
6767bool JSObject::ShouldConvertToSlowElements(int new_capacity) {
6768 ASSERT(HasFastElements());
6769 // Keep the array in fast case if the current backing storage is
6770 // almost filled and if the new capacity is no more than twice the
6771 // old capacity.
6772 int elements_length = FixedArray::cast(elements())->length();
6773 return !HasDenseElements() || ((new_capacity / 2) > elements_length);
6774}
6775
6776
6777bool JSObject::ShouldConvertToFastElements() {
6778 ASSERT(HasDictionaryElements());
6779 NumberDictionary* dictionary = NumberDictionary::cast(elements());
6780 // If the elements are sparse, we should not go back to fast case.
6781 if (!HasDenseElements()) return false;
6782 // If an element has been added at a very high index in the elements
6783 // dictionary, we cannot go back to fast case.
6784 if (dictionary->requires_slow_elements()) return false;
6785 // An object requiring access checks is never allowed to have fast
6786 // elements. If it had fast elements we would skip security checks.
6787 if (IsAccessCheckNeeded()) return false;
6788 // If the dictionary backing storage takes up roughly half as much
6789 // space as a fast-case backing storage would the array should have
6790 // fast elements.
6791 uint32_t length = 0;
6792 if (IsJSArray()) {
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01006793 CHECK(JSArray::cast(this)->length()->ToArrayIndex(&length));
Steve Blocka7e24c12009-10-30 11:49:00 +00006794 } else {
6795 length = dictionary->max_number_key();
6796 }
6797 return static_cast<uint32_t>(dictionary->Capacity()) >=
6798 (length / (2 * NumberDictionary::kEntrySize));
6799}
6800
6801
6802// Certain compilers request function template instantiation when they
6803// see the definition of the other template functions in the
6804// class. This requires us to have the template functions put
6805// together, so even though this function belongs in objects-debug.cc,
6806// we keep it here instead to satisfy certain compilers.
6807#ifdef DEBUG
6808template<typename Shape, typename Key>
6809void Dictionary<Shape, Key>::Print() {
6810 int capacity = HashTable<Shape, Key>::Capacity();
6811 for (int i = 0; i < capacity; i++) {
6812 Object* k = HashTable<Shape, Key>::KeyAt(i);
6813 if (HashTable<Shape, Key>::IsKey(k)) {
6814 PrintF(" ");
6815 if (k->IsString()) {
6816 String::cast(k)->StringPrint();
6817 } else {
6818 k->ShortPrint();
6819 }
6820 PrintF(": ");
6821 ValueAt(i)->ShortPrint();
6822 PrintF("\n");
6823 }
6824 }
6825}
6826#endif
6827
6828
6829template<typename Shape, typename Key>
6830void Dictionary<Shape, Key>::CopyValuesTo(FixedArray* elements) {
6831 int pos = 0;
6832 int capacity = HashTable<Shape, Key>::Capacity();
Leon Clarke4515c472010-02-03 11:58:03 +00006833 AssertNoAllocation no_gc;
6834 WriteBarrierMode mode = elements->GetWriteBarrierMode(no_gc);
Steve Blocka7e24c12009-10-30 11:49:00 +00006835 for (int i = 0; i < capacity; i++) {
6836 Object* k = Dictionary<Shape, Key>::KeyAt(i);
6837 if (Dictionary<Shape, Key>::IsKey(k)) {
6838 elements->set(pos++, ValueAt(i), mode);
6839 }
6840 }
6841 ASSERT(pos == elements->length());
6842}
6843
6844
6845InterceptorInfo* JSObject::GetNamedInterceptor() {
6846 ASSERT(map()->has_named_interceptor());
6847 JSFunction* constructor = JSFunction::cast(map()->constructor());
Steve Block6ded16b2010-05-10 14:33:55 +01006848 ASSERT(constructor->shared()->IsApiFunction());
Steve Blocka7e24c12009-10-30 11:49:00 +00006849 Object* result =
Steve Block6ded16b2010-05-10 14:33:55 +01006850 constructor->shared()->get_api_func_data()->named_property_handler();
Steve Blocka7e24c12009-10-30 11:49:00 +00006851 return InterceptorInfo::cast(result);
6852}
6853
6854
6855InterceptorInfo* JSObject::GetIndexedInterceptor() {
6856 ASSERT(map()->has_indexed_interceptor());
6857 JSFunction* constructor = JSFunction::cast(map()->constructor());
Steve Block6ded16b2010-05-10 14:33:55 +01006858 ASSERT(constructor->shared()->IsApiFunction());
Steve Blocka7e24c12009-10-30 11:49:00 +00006859 Object* result =
Steve Block6ded16b2010-05-10 14:33:55 +01006860 constructor->shared()->get_api_func_data()->indexed_property_handler();
Steve Blocka7e24c12009-10-30 11:49:00 +00006861 return InterceptorInfo::cast(result);
6862}
6863
6864
6865Object* JSObject::GetPropertyPostInterceptor(JSObject* receiver,
6866 String* name,
6867 PropertyAttributes* attributes) {
6868 // Check local property in holder, ignore interceptor.
6869 LookupResult result;
6870 LocalLookupRealNamedProperty(name, &result);
Andrei Popescu402d9372010-02-26 13:31:12 +00006871 if (result.IsProperty()) {
6872 return GetProperty(receiver, &result, name, attributes);
6873 }
Steve Blocka7e24c12009-10-30 11:49:00 +00006874 // Continue searching via the prototype chain.
6875 Object* pt = GetPrototype();
6876 *attributes = ABSENT;
6877 if (pt == Heap::null_value()) return Heap::undefined_value();
6878 return pt->GetPropertyWithReceiver(receiver, name, attributes);
6879}
6880
6881
Steve Blockd0582a62009-12-15 09:54:21 +00006882Object* JSObject::GetLocalPropertyPostInterceptor(
6883 JSObject* receiver,
6884 String* name,
6885 PropertyAttributes* attributes) {
6886 // Check local property in holder, ignore interceptor.
6887 LookupResult result;
6888 LocalLookupRealNamedProperty(name, &result);
Andrei Popescu402d9372010-02-26 13:31:12 +00006889 if (result.IsProperty()) {
6890 return GetProperty(receiver, &result, name, attributes);
6891 }
6892 return Heap::undefined_value();
Steve Blockd0582a62009-12-15 09:54:21 +00006893}
6894
6895
Steve Blocka7e24c12009-10-30 11:49:00 +00006896Object* JSObject::GetPropertyWithInterceptor(
6897 JSObject* receiver,
6898 String* name,
6899 PropertyAttributes* attributes) {
6900 InterceptorInfo* interceptor = GetNamedInterceptor();
6901 HandleScope scope;
6902 Handle<JSObject> receiver_handle(receiver);
6903 Handle<JSObject> holder_handle(this);
6904 Handle<String> name_handle(name);
6905
6906 if (!interceptor->getter()->IsUndefined()) {
6907 v8::NamedPropertyGetter getter =
6908 v8::ToCData<v8::NamedPropertyGetter>(interceptor->getter());
6909 LOG(ApiNamedPropertyAccess("interceptor-named-get", *holder_handle, name));
6910 CustomArguments args(interceptor->data(), receiver, this);
6911 v8::AccessorInfo info(args.end());
6912 v8::Handle<v8::Value> result;
6913 {
6914 // Leaving JavaScript.
6915 VMState state(EXTERNAL);
6916 result = getter(v8::Utils::ToLocal(name_handle), info);
6917 }
6918 RETURN_IF_SCHEDULED_EXCEPTION();
6919 if (!result.IsEmpty()) {
6920 *attributes = NONE;
6921 return *v8::Utils::OpenHandle(*result);
6922 }
6923 }
6924
6925 Object* result = holder_handle->GetPropertyPostInterceptor(
6926 *receiver_handle,
6927 *name_handle,
6928 attributes);
6929 RETURN_IF_SCHEDULED_EXCEPTION();
6930 return result;
6931}
6932
6933
6934bool JSObject::HasRealNamedProperty(String* key) {
6935 // Check access rights if needed.
6936 if (IsAccessCheckNeeded() &&
6937 !Top::MayNamedAccess(this, key, v8::ACCESS_HAS)) {
6938 Top::ReportFailedAccessCheck(this, v8::ACCESS_HAS);
6939 return false;
6940 }
6941
6942 LookupResult result;
6943 LocalLookupRealNamedProperty(key, &result);
Andrei Popescu402d9372010-02-26 13:31:12 +00006944 return result.IsProperty() && (result.type() != INTERCEPTOR);
Steve Blocka7e24c12009-10-30 11:49:00 +00006945}
6946
6947
6948bool JSObject::HasRealElementProperty(uint32_t index) {
6949 // Check access rights if needed.
6950 if (IsAccessCheckNeeded() &&
6951 !Top::MayIndexedAccess(this, index, v8::ACCESS_HAS)) {
6952 Top::ReportFailedAccessCheck(this, v8::ACCESS_HAS);
6953 return false;
6954 }
6955
6956 // Handle [] on String objects.
6957 if (this->IsStringObjectWithCharacterAt(index)) return true;
6958
6959 switch (GetElementsKind()) {
6960 case FAST_ELEMENTS: {
6961 uint32_t length = IsJSArray() ?
6962 static_cast<uint32_t>(
6963 Smi::cast(JSArray::cast(this)->length())->value()) :
6964 static_cast<uint32_t>(FixedArray::cast(elements())->length());
6965 return (index < length) &&
6966 !FixedArray::cast(elements())->get(index)->IsTheHole();
6967 }
6968 case PIXEL_ELEMENTS: {
6969 PixelArray* pixels = PixelArray::cast(elements());
6970 return index < static_cast<uint32_t>(pixels->length());
6971 }
Steve Block3ce2e202009-11-05 08:53:23 +00006972 case EXTERNAL_BYTE_ELEMENTS:
6973 case EXTERNAL_UNSIGNED_BYTE_ELEMENTS:
6974 case EXTERNAL_SHORT_ELEMENTS:
6975 case EXTERNAL_UNSIGNED_SHORT_ELEMENTS:
6976 case EXTERNAL_INT_ELEMENTS:
6977 case EXTERNAL_UNSIGNED_INT_ELEMENTS:
6978 case EXTERNAL_FLOAT_ELEMENTS: {
6979 ExternalArray* array = ExternalArray::cast(elements());
6980 return index < static_cast<uint32_t>(array->length());
6981 }
Steve Blocka7e24c12009-10-30 11:49:00 +00006982 case DICTIONARY_ELEMENTS: {
6983 return element_dictionary()->FindEntry(index)
6984 != NumberDictionary::kNotFound;
6985 }
6986 default:
6987 UNREACHABLE();
6988 break;
6989 }
6990 // All possibilities have been handled above already.
6991 UNREACHABLE();
6992 return Heap::null_value();
6993}
6994
6995
6996bool JSObject::HasRealNamedCallbackProperty(String* key) {
6997 // Check access rights if needed.
6998 if (IsAccessCheckNeeded() &&
6999 !Top::MayNamedAccess(this, key, v8::ACCESS_HAS)) {
7000 Top::ReportFailedAccessCheck(this, v8::ACCESS_HAS);
7001 return false;
7002 }
7003
7004 LookupResult result;
7005 LocalLookupRealNamedProperty(key, &result);
Andrei Popescu402d9372010-02-26 13:31:12 +00007006 return result.IsProperty() && (result.type() == CALLBACKS);
Steve Blocka7e24c12009-10-30 11:49:00 +00007007}
7008
7009
7010int JSObject::NumberOfLocalProperties(PropertyAttributes filter) {
7011 if (HasFastProperties()) {
7012 DescriptorArray* descs = map()->instance_descriptors();
7013 int result = 0;
7014 for (int i = 0; i < descs->number_of_descriptors(); i++) {
7015 PropertyDetails details = descs->GetDetails(i);
7016 if (details.IsProperty() && (details.attributes() & filter) == 0) {
7017 result++;
7018 }
7019 }
7020 return result;
7021 } else {
7022 return property_dictionary()->NumberOfElementsFilterAttributes(filter);
7023 }
7024}
7025
7026
7027int JSObject::NumberOfEnumProperties() {
7028 return NumberOfLocalProperties(static_cast<PropertyAttributes>(DONT_ENUM));
7029}
7030
7031
7032void FixedArray::SwapPairs(FixedArray* numbers, int i, int j) {
7033 Object* temp = get(i);
7034 set(i, get(j));
7035 set(j, temp);
7036 if (this != numbers) {
7037 temp = numbers->get(i);
7038 numbers->set(i, numbers->get(j));
7039 numbers->set(j, temp);
7040 }
7041}
7042
7043
7044static void InsertionSortPairs(FixedArray* content,
7045 FixedArray* numbers,
7046 int len) {
7047 for (int i = 1; i < len; i++) {
7048 int j = i;
7049 while (j > 0 &&
7050 (NumberToUint32(numbers->get(j - 1)) >
7051 NumberToUint32(numbers->get(j)))) {
7052 content->SwapPairs(numbers, j - 1, j);
7053 j--;
7054 }
7055 }
7056}
7057
7058
7059void HeapSortPairs(FixedArray* content, FixedArray* numbers, int len) {
7060 // In-place heap sort.
7061 ASSERT(content->length() == numbers->length());
7062
7063 // Bottom-up max-heap construction.
7064 for (int i = 1; i < len; ++i) {
7065 int child_index = i;
7066 while (child_index > 0) {
7067 int parent_index = ((child_index + 1) >> 1) - 1;
7068 uint32_t parent_value = NumberToUint32(numbers->get(parent_index));
7069 uint32_t child_value = NumberToUint32(numbers->get(child_index));
7070 if (parent_value < child_value) {
7071 content->SwapPairs(numbers, parent_index, child_index);
7072 } else {
7073 break;
7074 }
7075 child_index = parent_index;
7076 }
7077 }
7078
7079 // Extract elements and create sorted array.
7080 for (int i = len - 1; i > 0; --i) {
7081 // Put max element at the back of the array.
7082 content->SwapPairs(numbers, 0, i);
7083 // Sift down the new top element.
7084 int parent_index = 0;
7085 while (true) {
7086 int child_index = ((parent_index + 1) << 1) - 1;
7087 if (child_index >= i) break;
7088 uint32_t child1_value = NumberToUint32(numbers->get(child_index));
7089 uint32_t child2_value = NumberToUint32(numbers->get(child_index + 1));
7090 uint32_t parent_value = NumberToUint32(numbers->get(parent_index));
7091 if (child_index + 1 >= i || child1_value > child2_value) {
7092 if (parent_value > child1_value) break;
7093 content->SwapPairs(numbers, parent_index, child_index);
7094 parent_index = child_index;
7095 } else {
7096 if (parent_value > child2_value) break;
7097 content->SwapPairs(numbers, parent_index, child_index + 1);
7098 parent_index = child_index + 1;
7099 }
7100 }
7101 }
7102}
7103
7104
7105// Sort this array and the numbers as pairs wrt. the (distinct) numbers.
7106void FixedArray::SortPairs(FixedArray* numbers, uint32_t len) {
7107 ASSERT(this->length() == numbers->length());
7108 // For small arrays, simply use insertion sort.
7109 if (len <= 10) {
7110 InsertionSortPairs(this, numbers, len);
7111 return;
7112 }
7113 // Check the range of indices.
7114 uint32_t min_index = NumberToUint32(numbers->get(0));
7115 uint32_t max_index = min_index;
7116 uint32_t i;
7117 for (i = 1; i < len; i++) {
7118 if (NumberToUint32(numbers->get(i)) < min_index) {
7119 min_index = NumberToUint32(numbers->get(i));
7120 } else if (NumberToUint32(numbers->get(i)) > max_index) {
7121 max_index = NumberToUint32(numbers->get(i));
7122 }
7123 }
7124 if (max_index - min_index + 1 == len) {
7125 // Indices form a contiguous range, unless there are duplicates.
7126 // Do an in-place linear time sort assuming distinct numbers, but
7127 // avoid hanging in case they are not.
7128 for (i = 0; i < len; i++) {
7129 uint32_t p;
7130 uint32_t j = 0;
7131 // While the current element at i is not at its correct position p,
7132 // swap the elements at these two positions.
7133 while ((p = NumberToUint32(numbers->get(i)) - min_index) != i &&
7134 j++ < len) {
7135 SwapPairs(numbers, i, p);
7136 }
7137 }
7138 } else {
7139 HeapSortPairs(this, numbers, len);
7140 return;
7141 }
7142}
7143
7144
7145// Fill in the names of local properties into the supplied storage. The main
7146// purpose of this function is to provide reflection information for the object
7147// mirrors.
7148void JSObject::GetLocalPropertyNames(FixedArray* storage, int index) {
7149 ASSERT(storage->length() >= (NumberOfLocalProperties(NONE) - index));
7150 if (HasFastProperties()) {
7151 DescriptorArray* descs = map()->instance_descriptors();
7152 for (int i = 0; i < descs->number_of_descriptors(); i++) {
7153 if (descs->IsProperty(i)) storage->set(index++, descs->GetKey(i));
7154 }
7155 ASSERT(storage->length() >= index);
7156 } else {
7157 property_dictionary()->CopyKeysTo(storage);
7158 }
7159}
7160
7161
7162int JSObject::NumberOfLocalElements(PropertyAttributes filter) {
7163 return GetLocalElementKeys(NULL, filter);
7164}
7165
7166
7167int JSObject::NumberOfEnumElements() {
Steve Blockd0582a62009-12-15 09:54:21 +00007168 // Fast case for objects with no elements.
7169 if (!IsJSValue() && HasFastElements()) {
7170 uint32_t length = IsJSArray() ?
7171 static_cast<uint32_t>(
7172 Smi::cast(JSArray::cast(this)->length())->value()) :
7173 static_cast<uint32_t>(FixedArray::cast(elements())->length());
7174 if (length == 0) return 0;
7175 }
7176 // Compute the number of enumerable elements.
Steve Blocka7e24c12009-10-30 11:49:00 +00007177 return NumberOfLocalElements(static_cast<PropertyAttributes>(DONT_ENUM));
7178}
7179
7180
7181int JSObject::GetLocalElementKeys(FixedArray* storage,
7182 PropertyAttributes filter) {
7183 int counter = 0;
7184 switch (GetElementsKind()) {
7185 case FAST_ELEMENTS: {
7186 int length = IsJSArray() ?
7187 Smi::cast(JSArray::cast(this)->length())->value() :
7188 FixedArray::cast(elements())->length();
7189 for (int i = 0; i < length; i++) {
7190 if (!FixedArray::cast(elements())->get(i)->IsTheHole()) {
7191 if (storage != NULL) {
Leon Clarke4515c472010-02-03 11:58:03 +00007192 storage->set(counter, Smi::FromInt(i));
Steve Blocka7e24c12009-10-30 11:49:00 +00007193 }
7194 counter++;
7195 }
7196 }
7197 ASSERT(!storage || storage->length() >= counter);
7198 break;
7199 }
7200 case PIXEL_ELEMENTS: {
7201 int length = PixelArray::cast(elements())->length();
7202 while (counter < length) {
7203 if (storage != NULL) {
Leon Clarke4515c472010-02-03 11:58:03 +00007204 storage->set(counter, Smi::FromInt(counter));
Steve Blocka7e24c12009-10-30 11:49:00 +00007205 }
7206 counter++;
7207 }
7208 ASSERT(!storage || storage->length() >= counter);
7209 break;
7210 }
Steve Block3ce2e202009-11-05 08:53:23 +00007211 case EXTERNAL_BYTE_ELEMENTS:
7212 case EXTERNAL_UNSIGNED_BYTE_ELEMENTS:
7213 case EXTERNAL_SHORT_ELEMENTS:
7214 case EXTERNAL_UNSIGNED_SHORT_ELEMENTS:
7215 case EXTERNAL_INT_ELEMENTS:
7216 case EXTERNAL_UNSIGNED_INT_ELEMENTS:
7217 case EXTERNAL_FLOAT_ELEMENTS: {
7218 int length = ExternalArray::cast(elements())->length();
7219 while (counter < length) {
7220 if (storage != NULL) {
Leon Clarke4515c472010-02-03 11:58:03 +00007221 storage->set(counter, Smi::FromInt(counter));
Steve Block3ce2e202009-11-05 08:53:23 +00007222 }
7223 counter++;
7224 }
7225 ASSERT(!storage || storage->length() >= counter);
7226 break;
7227 }
Steve Blocka7e24c12009-10-30 11:49:00 +00007228 case DICTIONARY_ELEMENTS: {
7229 if (storage != NULL) {
7230 element_dictionary()->CopyKeysTo(storage, filter);
7231 }
7232 counter = element_dictionary()->NumberOfElementsFilterAttributes(filter);
7233 break;
7234 }
7235 default:
7236 UNREACHABLE();
7237 break;
7238 }
7239
7240 if (this->IsJSValue()) {
7241 Object* val = JSValue::cast(this)->value();
7242 if (val->IsString()) {
7243 String* str = String::cast(val);
7244 if (storage) {
7245 for (int i = 0; i < str->length(); i++) {
Leon Clarke4515c472010-02-03 11:58:03 +00007246 storage->set(counter + i, Smi::FromInt(i));
Steve Blocka7e24c12009-10-30 11:49:00 +00007247 }
7248 }
7249 counter += str->length();
7250 }
7251 }
7252 ASSERT(!storage || storage->length() == counter);
7253 return counter;
7254}
7255
7256
7257int JSObject::GetEnumElementKeys(FixedArray* storage) {
7258 return GetLocalElementKeys(storage,
7259 static_cast<PropertyAttributes>(DONT_ENUM));
7260}
7261
7262
7263bool NumberDictionaryShape::IsMatch(uint32_t key, Object* other) {
7264 ASSERT(other->IsNumber());
7265 return key == static_cast<uint32_t>(other->Number());
7266}
7267
7268
7269uint32_t NumberDictionaryShape::Hash(uint32_t key) {
7270 return ComputeIntegerHash(key);
7271}
7272
7273
7274uint32_t NumberDictionaryShape::HashForObject(uint32_t key, Object* other) {
7275 ASSERT(other->IsNumber());
7276 return ComputeIntegerHash(static_cast<uint32_t>(other->Number()));
7277}
7278
7279
7280Object* NumberDictionaryShape::AsObject(uint32_t key) {
7281 return Heap::NumberFromUint32(key);
7282}
7283
7284
7285bool StringDictionaryShape::IsMatch(String* key, Object* other) {
7286 // We know that all entries in a hash table had their hash keys created.
7287 // Use that knowledge to have fast failure.
7288 if (key->Hash() != String::cast(other)->Hash()) return false;
7289 return key->Equals(String::cast(other));
7290}
7291
7292
7293uint32_t StringDictionaryShape::Hash(String* key) {
7294 return key->Hash();
7295}
7296
7297
7298uint32_t StringDictionaryShape::HashForObject(String* key, Object* other) {
7299 return String::cast(other)->Hash();
7300}
7301
7302
7303Object* StringDictionaryShape::AsObject(String* key) {
7304 return key;
7305}
7306
7307
7308// StringKey simply carries a string object as key.
7309class StringKey : public HashTableKey {
7310 public:
7311 explicit StringKey(String* string) :
7312 string_(string),
7313 hash_(HashForObject(string)) { }
7314
7315 bool IsMatch(Object* string) {
7316 // We know that all entries in a hash table had their hash keys created.
7317 // Use that knowledge to have fast failure.
7318 if (hash_ != HashForObject(string)) {
7319 return false;
7320 }
7321 return string_->Equals(String::cast(string));
7322 }
7323
7324 uint32_t Hash() { return hash_; }
7325
7326 uint32_t HashForObject(Object* other) { return String::cast(other)->Hash(); }
7327
7328 Object* AsObject() { return string_; }
7329
7330 String* string_;
7331 uint32_t hash_;
7332};
7333
7334
7335// StringSharedKeys are used as keys in the eval cache.
7336class StringSharedKey : public HashTableKey {
7337 public:
7338 StringSharedKey(String* source, SharedFunctionInfo* shared)
7339 : source_(source), shared_(shared) { }
7340
7341 bool IsMatch(Object* other) {
7342 if (!other->IsFixedArray()) return false;
7343 FixedArray* pair = FixedArray::cast(other);
7344 SharedFunctionInfo* shared = SharedFunctionInfo::cast(pair->get(0));
7345 if (shared != shared_) return false;
7346 String* source = String::cast(pair->get(1));
7347 return source->Equals(source_);
7348 }
7349
7350 static uint32_t StringSharedHashHelper(String* source,
7351 SharedFunctionInfo* shared) {
7352 uint32_t hash = source->Hash();
7353 if (shared->HasSourceCode()) {
7354 // Instead of using the SharedFunctionInfo pointer in the hash
7355 // code computation, we use a combination of the hash of the
7356 // script source code and the start and end positions. We do
7357 // this to ensure that the cache entries can survive garbage
7358 // collection.
7359 Script* script = Script::cast(shared->script());
7360 hash ^= String::cast(script->source())->Hash();
7361 hash += shared->start_position();
7362 }
7363 return hash;
7364 }
7365
7366 uint32_t Hash() {
7367 return StringSharedHashHelper(source_, shared_);
7368 }
7369
7370 uint32_t HashForObject(Object* obj) {
7371 FixedArray* pair = FixedArray::cast(obj);
7372 SharedFunctionInfo* shared = SharedFunctionInfo::cast(pair->get(0));
7373 String* source = String::cast(pair->get(1));
7374 return StringSharedHashHelper(source, shared);
7375 }
7376
7377 Object* AsObject() {
7378 Object* obj = Heap::AllocateFixedArray(2);
7379 if (obj->IsFailure()) return obj;
7380 FixedArray* pair = FixedArray::cast(obj);
7381 pair->set(0, shared_);
7382 pair->set(1, source_);
7383 return pair;
7384 }
7385
7386 private:
7387 String* source_;
7388 SharedFunctionInfo* shared_;
7389};
7390
7391
7392// RegExpKey carries the source and flags of a regular expression as key.
7393class RegExpKey : public HashTableKey {
7394 public:
7395 RegExpKey(String* string, JSRegExp::Flags flags)
7396 : string_(string),
7397 flags_(Smi::FromInt(flags.value())) { }
7398
Steve Block3ce2e202009-11-05 08:53:23 +00007399 // Rather than storing the key in the hash table, a pointer to the
7400 // stored value is stored where the key should be. IsMatch then
7401 // compares the search key to the found object, rather than comparing
7402 // a key to a key.
Steve Blocka7e24c12009-10-30 11:49:00 +00007403 bool IsMatch(Object* obj) {
7404 FixedArray* val = FixedArray::cast(obj);
7405 return string_->Equals(String::cast(val->get(JSRegExp::kSourceIndex)))
7406 && (flags_ == val->get(JSRegExp::kFlagsIndex));
7407 }
7408
7409 uint32_t Hash() { return RegExpHash(string_, flags_); }
7410
7411 Object* AsObject() {
7412 // Plain hash maps, which is where regexp keys are used, don't
7413 // use this function.
7414 UNREACHABLE();
7415 return NULL;
7416 }
7417
7418 uint32_t HashForObject(Object* obj) {
7419 FixedArray* val = FixedArray::cast(obj);
7420 return RegExpHash(String::cast(val->get(JSRegExp::kSourceIndex)),
7421 Smi::cast(val->get(JSRegExp::kFlagsIndex)));
7422 }
7423
7424 static uint32_t RegExpHash(String* string, Smi* flags) {
7425 return string->Hash() + flags->value();
7426 }
7427
7428 String* string_;
7429 Smi* flags_;
7430};
7431
7432// Utf8SymbolKey carries a vector of chars as key.
7433class Utf8SymbolKey : public HashTableKey {
7434 public:
7435 explicit Utf8SymbolKey(Vector<const char> string)
Steve Blockd0582a62009-12-15 09:54:21 +00007436 : string_(string), hash_field_(0) { }
Steve Blocka7e24c12009-10-30 11:49:00 +00007437
7438 bool IsMatch(Object* string) {
7439 return String::cast(string)->IsEqualTo(string_);
7440 }
7441
7442 uint32_t Hash() {
Steve Blockd0582a62009-12-15 09:54:21 +00007443 if (hash_field_ != 0) return hash_field_ >> String::kHashShift;
Steve Blocka7e24c12009-10-30 11:49:00 +00007444 unibrow::Utf8InputBuffer<> buffer(string_.start(),
7445 static_cast<unsigned>(string_.length()));
7446 chars_ = buffer.Length();
Steve Blockd0582a62009-12-15 09:54:21 +00007447 hash_field_ = String::ComputeHashField(&buffer, chars_);
7448 uint32_t result = hash_field_ >> String::kHashShift;
Steve Blocka7e24c12009-10-30 11:49:00 +00007449 ASSERT(result != 0); // Ensure that the hash value of 0 is never computed.
7450 return result;
7451 }
7452
7453 uint32_t HashForObject(Object* other) {
7454 return String::cast(other)->Hash();
7455 }
7456
7457 Object* AsObject() {
Steve Blockd0582a62009-12-15 09:54:21 +00007458 if (hash_field_ == 0) Hash();
7459 return Heap::AllocateSymbol(string_, chars_, hash_field_);
Steve Blocka7e24c12009-10-30 11:49:00 +00007460 }
7461
7462 Vector<const char> string_;
Steve Blockd0582a62009-12-15 09:54:21 +00007463 uint32_t hash_field_;
Steve Blocka7e24c12009-10-30 11:49:00 +00007464 int chars_; // Caches the number of characters when computing the hash code.
7465};
7466
7467
7468// SymbolKey carries a string/symbol object as key.
7469class SymbolKey : public HashTableKey {
7470 public:
7471 explicit SymbolKey(String* string) : string_(string) { }
7472
7473 bool IsMatch(Object* string) {
7474 return String::cast(string)->Equals(string_);
7475 }
7476
7477 uint32_t Hash() { return string_->Hash(); }
7478
7479 uint32_t HashForObject(Object* other) {
7480 return String::cast(other)->Hash();
7481 }
7482
7483 Object* AsObject() {
Leon Clarkef7060e22010-06-03 12:02:55 +01007484 // Attempt to flatten the string, so that symbols will most often
7485 // be flat strings.
7486 string_ = string_->TryFlattenGetString();
Steve Blocka7e24c12009-10-30 11:49:00 +00007487 // Transform string to symbol if possible.
7488 Map* map = Heap::SymbolMapForString(string_);
7489 if (map != NULL) {
7490 string_->set_map(map);
7491 ASSERT(string_->IsSymbol());
7492 return string_;
7493 }
7494 // Otherwise allocate a new symbol.
7495 StringInputBuffer buffer(string_);
7496 return Heap::AllocateInternalSymbol(&buffer,
7497 string_->length(),
Steve Blockd0582a62009-12-15 09:54:21 +00007498 string_->hash_field());
Steve Blocka7e24c12009-10-30 11:49:00 +00007499 }
7500
7501 static uint32_t StringHash(Object* obj) {
7502 return String::cast(obj)->Hash();
7503 }
7504
7505 String* string_;
7506};
7507
7508
7509template<typename Shape, typename Key>
7510void HashTable<Shape, Key>::IteratePrefix(ObjectVisitor* v) {
7511 IteratePointers(v, 0, kElementsStartOffset);
7512}
7513
7514
7515template<typename Shape, typename Key>
7516void HashTable<Shape, Key>::IterateElements(ObjectVisitor* v) {
7517 IteratePointers(v,
7518 kElementsStartOffset,
7519 kHeaderSize + length() * kPointerSize);
7520}
7521
7522
7523template<typename Shape, typename Key>
Steve Block6ded16b2010-05-10 14:33:55 +01007524Object* HashTable<Shape, Key>::Allocate(int at_least_space_for,
7525 PretenureFlag pretenure) {
7526 const int kMinCapacity = 32;
7527 int capacity = RoundUpToPowerOf2(at_least_space_for * 2);
7528 if (capacity < kMinCapacity) {
7529 capacity = kMinCapacity; // Guarantee min capacity.
Leon Clarkee46be812010-01-19 14:06:41 +00007530 } else if (capacity > HashTable::kMaxCapacity) {
7531 return Failure::OutOfMemoryException();
7532 }
7533
Steve Block6ded16b2010-05-10 14:33:55 +01007534 Object* obj = Heap::AllocateHashTable(EntryToIndex(capacity), pretenure);
Steve Blocka7e24c12009-10-30 11:49:00 +00007535 if (!obj->IsFailure()) {
7536 HashTable::cast(obj)->SetNumberOfElements(0);
Leon Clarkee46be812010-01-19 14:06:41 +00007537 HashTable::cast(obj)->SetNumberOfDeletedElements(0);
Steve Blocka7e24c12009-10-30 11:49:00 +00007538 HashTable::cast(obj)->SetCapacity(capacity);
7539 }
7540 return obj;
7541}
7542
7543
Leon Clarkee46be812010-01-19 14:06:41 +00007544// Find entry for key otherwise return kNotFound.
Steve Blocka7e24c12009-10-30 11:49:00 +00007545template<typename Shape, typename Key>
7546int HashTable<Shape, Key>::FindEntry(Key key) {
Steve Blocka7e24c12009-10-30 11:49:00 +00007547 uint32_t capacity = Capacity();
Leon Clarkee46be812010-01-19 14:06:41 +00007548 uint32_t entry = FirstProbe(Shape::Hash(key), capacity);
7549 uint32_t count = 1;
7550 // EnsureCapacity will guarantee the hash table is never full.
7551 while (true) {
7552 Object* element = KeyAt(entry);
7553 if (element->IsUndefined()) break; // Empty entry.
7554 if (!element->IsNull() && Shape::IsMatch(key, element)) return entry;
7555 entry = NextProbe(entry, count++, capacity);
Steve Blocka7e24c12009-10-30 11:49:00 +00007556 }
7557 return kNotFound;
7558}
7559
7560
Ben Murdoch3bec4d22010-07-22 14:51:16 +01007561// Find entry for key otherwise return kNotFound.
7562int StringDictionary::FindEntry(String* key) {
7563 if (!key->IsSymbol()) {
7564 return HashTable<StringDictionaryShape, String*>::FindEntry(key);
7565 }
7566
7567 // Optimized for symbol key. Knowledge of the key type allows:
7568 // 1. Move the check if the key is a symbol out of the loop.
7569 // 2. Avoid comparing hash codes in symbol to symbol comparision.
7570 // 3. Detect a case when a dictionary key is not a symbol but the key is.
7571 // In case of positive result the dictionary key may be replaced by
7572 // the symbol with minimal performance penalty. It gives a chance to
7573 // perform further lookups in code stubs (and significant performance boost
7574 // a certain style of code).
7575
7576 // EnsureCapacity will guarantee the hash table is never full.
7577 uint32_t capacity = Capacity();
7578 uint32_t entry = FirstProbe(key->Hash(), capacity);
7579 uint32_t count = 1;
7580
7581 while (true) {
7582 int index = EntryToIndex(entry);
7583 Object* element = get(index);
7584 if (element->IsUndefined()) break; // Empty entry.
7585 if (key == element) return entry;
7586 if (!element->IsSymbol() &&
7587 !element->IsNull() &&
7588 String::cast(element)->Equals(key)) {
7589 // Replace a non-symbol key by the equivalent symbol for faster further
7590 // lookups.
7591 set(index, key);
7592 return entry;
7593 }
7594 ASSERT(element->IsNull() || !String::cast(element)->Equals(key));
7595 entry = NextProbe(entry, count++, capacity);
7596 }
7597 return kNotFound;
7598}
7599
7600
Steve Blocka7e24c12009-10-30 11:49:00 +00007601template<typename Shape, typename Key>
7602Object* HashTable<Shape, Key>::EnsureCapacity(int n, Key key) {
7603 int capacity = Capacity();
7604 int nof = NumberOfElements() + n;
Leon Clarkee46be812010-01-19 14:06:41 +00007605 int nod = NumberOfDeletedElements();
7606 // Return if:
7607 // 50% is still free after adding n elements and
7608 // at most 50% of the free elements are deleted elements.
Steve Block6ded16b2010-05-10 14:33:55 +01007609 if (nod <= (capacity - nof) >> 1) {
7610 int needed_free = nof >> 1;
7611 if (nof + needed_free <= capacity) return this;
7612 }
Steve Blocka7e24c12009-10-30 11:49:00 +00007613
Steve Block6ded16b2010-05-10 14:33:55 +01007614 const int kMinCapacityForPretenure = 256;
7615 bool pretenure =
7616 (capacity > kMinCapacityForPretenure) && !Heap::InNewSpace(this);
7617 Object* obj = Allocate(nof * 2, pretenure ? TENURED : NOT_TENURED);
Steve Blocka7e24c12009-10-30 11:49:00 +00007618 if (obj->IsFailure()) return obj;
Leon Clarke4515c472010-02-03 11:58:03 +00007619
7620 AssertNoAllocation no_gc;
Steve Blocka7e24c12009-10-30 11:49:00 +00007621 HashTable* table = HashTable::cast(obj);
Leon Clarke4515c472010-02-03 11:58:03 +00007622 WriteBarrierMode mode = table->GetWriteBarrierMode(no_gc);
Steve Blocka7e24c12009-10-30 11:49:00 +00007623
7624 // Copy prefix to new array.
7625 for (int i = kPrefixStartIndex;
7626 i < kPrefixStartIndex + Shape::kPrefixSize;
7627 i++) {
7628 table->set(i, get(i), mode);
7629 }
7630 // Rehash the elements.
7631 for (int i = 0; i < capacity; i++) {
7632 uint32_t from_index = EntryToIndex(i);
7633 Object* k = get(from_index);
7634 if (IsKey(k)) {
7635 uint32_t hash = Shape::HashForObject(key, k);
7636 uint32_t insertion_index =
7637 EntryToIndex(table->FindInsertionEntry(hash));
7638 for (int j = 0; j < Shape::kEntrySize; j++) {
7639 table->set(insertion_index + j, get(from_index + j), mode);
7640 }
7641 }
7642 }
7643 table->SetNumberOfElements(NumberOfElements());
Leon Clarkee46be812010-01-19 14:06:41 +00007644 table->SetNumberOfDeletedElements(0);
Steve Blocka7e24c12009-10-30 11:49:00 +00007645 return table;
7646}
7647
7648
7649template<typename Shape, typename Key>
7650uint32_t HashTable<Shape, Key>::FindInsertionEntry(uint32_t hash) {
7651 uint32_t capacity = Capacity();
Leon Clarkee46be812010-01-19 14:06:41 +00007652 uint32_t entry = FirstProbe(hash, capacity);
7653 uint32_t count = 1;
7654 // EnsureCapacity will guarantee the hash table is never full.
7655 while (true) {
7656 Object* element = KeyAt(entry);
7657 if (element->IsUndefined() || element->IsNull()) break;
7658 entry = NextProbe(entry, count++, capacity);
Steve Blocka7e24c12009-10-30 11:49:00 +00007659 }
Steve Blocka7e24c12009-10-30 11:49:00 +00007660 return entry;
7661}
7662
7663// Force instantiation of template instances class.
7664// Please note this list is compiler dependent.
7665
7666template class HashTable<SymbolTableShape, HashTableKey*>;
7667
7668template class HashTable<CompilationCacheShape, HashTableKey*>;
7669
7670template class HashTable<MapCacheShape, HashTableKey*>;
7671
7672template class Dictionary<StringDictionaryShape, String*>;
7673
7674template class Dictionary<NumberDictionaryShape, uint32_t>;
7675
7676template Object* Dictionary<NumberDictionaryShape, uint32_t>::Allocate(
7677 int);
7678
7679template Object* Dictionary<StringDictionaryShape, String*>::Allocate(
7680 int);
7681
7682template Object* Dictionary<NumberDictionaryShape, uint32_t>::AtPut(
7683 uint32_t, Object*);
7684
7685template Object* Dictionary<NumberDictionaryShape, uint32_t>::SlowReverseLookup(
7686 Object*);
7687
7688template Object* Dictionary<StringDictionaryShape, String*>::SlowReverseLookup(
7689 Object*);
7690
7691template void Dictionary<NumberDictionaryShape, uint32_t>::CopyKeysTo(
7692 FixedArray*, PropertyAttributes);
7693
7694template Object* Dictionary<StringDictionaryShape, String*>::DeleteProperty(
7695 int, JSObject::DeleteMode);
7696
7697template Object* Dictionary<NumberDictionaryShape, uint32_t>::DeleteProperty(
7698 int, JSObject::DeleteMode);
7699
7700template void Dictionary<StringDictionaryShape, String*>::CopyKeysTo(
7701 FixedArray*);
7702
7703template int
7704Dictionary<StringDictionaryShape, String*>::NumberOfElementsFilterAttributes(
7705 PropertyAttributes);
7706
7707template Object* Dictionary<StringDictionaryShape, String*>::Add(
7708 String*, Object*, PropertyDetails);
7709
7710template Object*
7711Dictionary<StringDictionaryShape, String*>::GenerateNewEnumerationIndices();
7712
7713template int
7714Dictionary<NumberDictionaryShape, uint32_t>::NumberOfElementsFilterAttributes(
7715 PropertyAttributes);
7716
7717template Object* Dictionary<NumberDictionaryShape, uint32_t>::Add(
7718 uint32_t, Object*, PropertyDetails);
7719
7720template Object* Dictionary<NumberDictionaryShape, uint32_t>::EnsureCapacity(
7721 int, uint32_t);
7722
7723template Object* Dictionary<StringDictionaryShape, String*>::EnsureCapacity(
7724 int, String*);
7725
7726template Object* Dictionary<NumberDictionaryShape, uint32_t>::AddEntry(
7727 uint32_t, Object*, PropertyDetails, uint32_t);
7728
7729template Object* Dictionary<StringDictionaryShape, String*>::AddEntry(
7730 String*, Object*, PropertyDetails, uint32_t);
7731
7732template
7733int Dictionary<NumberDictionaryShape, uint32_t>::NumberOfEnumElements();
7734
7735template
7736int Dictionary<StringDictionaryShape, String*>::NumberOfEnumElements();
7737
Leon Clarkee46be812010-01-19 14:06:41 +00007738template
7739int HashTable<NumberDictionaryShape, uint32_t>::FindEntry(uint32_t);
7740
7741
Steve Blocka7e24c12009-10-30 11:49:00 +00007742// Collates undefined and unexisting elements below limit from position
7743// zero of the elements. The object stays in Dictionary mode.
7744Object* JSObject::PrepareSlowElementsForSort(uint32_t limit) {
7745 ASSERT(HasDictionaryElements());
7746 // Must stay in dictionary mode, either because of requires_slow_elements,
7747 // or because we are not going to sort (and therefore compact) all of the
7748 // elements.
7749 NumberDictionary* dict = element_dictionary();
7750 HeapNumber* result_double = NULL;
7751 if (limit > static_cast<uint32_t>(Smi::kMaxValue)) {
7752 // Allocate space for result before we start mutating the object.
7753 Object* new_double = Heap::AllocateHeapNumber(0.0);
7754 if (new_double->IsFailure()) return new_double;
7755 result_double = HeapNumber::cast(new_double);
7756 }
7757
Steve Block6ded16b2010-05-10 14:33:55 +01007758 Object* obj = NumberDictionary::Allocate(dict->NumberOfElements());
Steve Blocka7e24c12009-10-30 11:49:00 +00007759 if (obj->IsFailure()) return obj;
7760 NumberDictionary* new_dict = NumberDictionary::cast(obj);
7761
7762 AssertNoAllocation no_alloc;
7763
7764 uint32_t pos = 0;
7765 uint32_t undefs = 0;
Steve Block6ded16b2010-05-10 14:33:55 +01007766 int capacity = dict->Capacity();
Steve Blocka7e24c12009-10-30 11:49:00 +00007767 for (int i = 0; i < capacity; i++) {
7768 Object* k = dict->KeyAt(i);
7769 if (dict->IsKey(k)) {
7770 ASSERT(k->IsNumber());
7771 ASSERT(!k->IsSmi() || Smi::cast(k)->value() >= 0);
7772 ASSERT(!k->IsHeapNumber() || HeapNumber::cast(k)->value() >= 0);
7773 ASSERT(!k->IsHeapNumber() || HeapNumber::cast(k)->value() <= kMaxUInt32);
7774 Object* value = dict->ValueAt(i);
7775 PropertyDetails details = dict->DetailsAt(i);
7776 if (details.type() == CALLBACKS) {
7777 // Bail out and do the sorting of undefineds and array holes in JS.
7778 return Smi::FromInt(-1);
7779 }
7780 uint32_t key = NumberToUint32(k);
7781 if (key < limit) {
7782 if (value->IsUndefined()) {
7783 undefs++;
7784 } else {
7785 new_dict->AddNumberEntry(pos, value, details);
7786 pos++;
7787 }
7788 } else {
7789 new_dict->AddNumberEntry(key, value, details);
7790 }
7791 }
7792 }
7793
7794 uint32_t result = pos;
7795 PropertyDetails no_details = PropertyDetails(NONE, NORMAL);
7796 while (undefs > 0) {
7797 new_dict->AddNumberEntry(pos, Heap::undefined_value(), no_details);
7798 pos++;
7799 undefs--;
7800 }
7801
7802 set_elements(new_dict);
7803
7804 if (result <= static_cast<uint32_t>(Smi::kMaxValue)) {
7805 return Smi::FromInt(static_cast<int>(result));
7806 }
7807
7808 ASSERT_NE(NULL, result_double);
7809 result_double->set_value(static_cast<double>(result));
7810 return result_double;
7811}
7812
7813
7814// Collects all defined (non-hole) and non-undefined (array) elements at
7815// the start of the elements array.
7816// If the object is in dictionary mode, it is converted to fast elements
7817// mode.
7818Object* JSObject::PrepareElementsForSort(uint32_t limit) {
Steve Block3ce2e202009-11-05 08:53:23 +00007819 ASSERT(!HasPixelElements() && !HasExternalArrayElements());
Steve Blocka7e24c12009-10-30 11:49:00 +00007820
7821 if (HasDictionaryElements()) {
7822 // Convert to fast elements containing only the existing properties.
7823 // Ordering is irrelevant, since we are going to sort anyway.
7824 NumberDictionary* dict = element_dictionary();
7825 if (IsJSArray() || dict->requires_slow_elements() ||
7826 dict->max_number_key() >= limit) {
7827 return PrepareSlowElementsForSort(limit);
7828 }
7829 // Convert to fast elements.
7830
Steve Block8defd9f2010-07-08 12:39:36 +01007831 Object* obj = map()->GetFastElementsMap();
7832 if (obj->IsFailure()) return obj;
7833 Map* new_map = Map::cast(obj);
7834
Steve Blocka7e24c12009-10-30 11:49:00 +00007835 PretenureFlag tenure = Heap::InNewSpace(this) ? NOT_TENURED: TENURED;
7836 Object* new_array =
7837 Heap::AllocateFixedArray(dict->NumberOfElements(), tenure);
Steve Block8defd9f2010-07-08 12:39:36 +01007838 if (new_array->IsFailure()) return new_array;
Steve Blocka7e24c12009-10-30 11:49:00 +00007839 FixedArray* fast_elements = FixedArray::cast(new_array);
7840 dict->CopyValuesTo(fast_elements);
Steve Block8defd9f2010-07-08 12:39:36 +01007841
7842 set_map(new_map);
Steve Blocka7e24c12009-10-30 11:49:00 +00007843 set_elements(fast_elements);
Iain Merrick75681382010-08-19 15:07:18 +01007844 } else {
7845 Object* obj = EnsureWritableFastElements();
7846 if (obj->IsFailure()) return obj;
Steve Blocka7e24c12009-10-30 11:49:00 +00007847 }
7848 ASSERT(HasFastElements());
7849
7850 // Collect holes at the end, undefined before that and the rest at the
7851 // start, and return the number of non-hole, non-undefined values.
7852
7853 FixedArray* elements = FixedArray::cast(this->elements());
7854 uint32_t elements_length = static_cast<uint32_t>(elements->length());
7855 if (limit > elements_length) {
7856 limit = elements_length ;
7857 }
7858 if (limit == 0) {
7859 return Smi::FromInt(0);
7860 }
7861
7862 HeapNumber* result_double = NULL;
7863 if (limit > static_cast<uint32_t>(Smi::kMaxValue)) {
7864 // Pessimistically allocate space for return value before
7865 // we start mutating the array.
7866 Object* new_double = Heap::AllocateHeapNumber(0.0);
7867 if (new_double->IsFailure()) return new_double;
7868 result_double = HeapNumber::cast(new_double);
7869 }
7870
7871 AssertNoAllocation no_alloc;
7872
7873 // Split elements into defined, undefined and the_hole, in that order.
7874 // Only count locations for undefined and the hole, and fill them afterwards.
Leon Clarke4515c472010-02-03 11:58:03 +00007875 WriteBarrierMode write_barrier = elements->GetWriteBarrierMode(no_alloc);
Steve Blocka7e24c12009-10-30 11:49:00 +00007876 unsigned int undefs = limit;
7877 unsigned int holes = limit;
7878 // Assume most arrays contain no holes and undefined values, so minimize the
7879 // number of stores of non-undefined, non-the-hole values.
7880 for (unsigned int i = 0; i < undefs; i++) {
7881 Object* current = elements->get(i);
7882 if (current->IsTheHole()) {
7883 holes--;
7884 undefs--;
7885 } else if (current->IsUndefined()) {
7886 undefs--;
7887 } else {
7888 continue;
7889 }
7890 // Position i needs to be filled.
7891 while (undefs > i) {
7892 current = elements->get(undefs);
7893 if (current->IsTheHole()) {
7894 holes--;
7895 undefs--;
7896 } else if (current->IsUndefined()) {
7897 undefs--;
7898 } else {
7899 elements->set(i, current, write_barrier);
7900 break;
7901 }
7902 }
7903 }
7904 uint32_t result = undefs;
7905 while (undefs < holes) {
7906 elements->set_undefined(undefs);
7907 undefs++;
7908 }
7909 while (holes < limit) {
7910 elements->set_the_hole(holes);
7911 holes++;
7912 }
7913
7914 if (result <= static_cast<uint32_t>(Smi::kMaxValue)) {
7915 return Smi::FromInt(static_cast<int>(result));
7916 }
7917 ASSERT_NE(NULL, result_double);
7918 result_double->set_value(static_cast<double>(result));
7919 return result_double;
7920}
7921
7922
7923Object* PixelArray::SetValue(uint32_t index, Object* value) {
7924 uint8_t clamped_value = 0;
7925 if (index < static_cast<uint32_t>(length())) {
7926 if (value->IsSmi()) {
7927 int int_value = Smi::cast(value)->value();
7928 if (int_value < 0) {
7929 clamped_value = 0;
7930 } else if (int_value > 255) {
7931 clamped_value = 255;
7932 } else {
7933 clamped_value = static_cast<uint8_t>(int_value);
7934 }
7935 } else if (value->IsHeapNumber()) {
7936 double double_value = HeapNumber::cast(value)->value();
7937 if (!(double_value > 0)) {
7938 // NaN and less than zero clamp to zero.
7939 clamped_value = 0;
7940 } else if (double_value > 255) {
7941 // Greater than 255 clamp to 255.
7942 clamped_value = 255;
7943 } else {
7944 // Other doubles are rounded to the nearest integer.
7945 clamped_value = static_cast<uint8_t>(double_value + 0.5);
7946 }
7947 } else {
7948 // Clamp undefined to zero (default). All other types have been
7949 // converted to a number type further up in the call chain.
7950 ASSERT(value->IsUndefined());
7951 }
7952 set(index, clamped_value);
7953 }
7954 return Smi::FromInt(clamped_value);
7955}
7956
7957
Steve Block3ce2e202009-11-05 08:53:23 +00007958template<typename ExternalArrayClass, typename ValueType>
7959static Object* ExternalArrayIntSetter(ExternalArrayClass* receiver,
7960 uint32_t index,
7961 Object* value) {
7962 ValueType cast_value = 0;
7963 if (index < static_cast<uint32_t>(receiver->length())) {
7964 if (value->IsSmi()) {
7965 int int_value = Smi::cast(value)->value();
7966 cast_value = static_cast<ValueType>(int_value);
7967 } else if (value->IsHeapNumber()) {
7968 double double_value = HeapNumber::cast(value)->value();
7969 cast_value = static_cast<ValueType>(DoubleToInt32(double_value));
7970 } else {
7971 // Clamp undefined to zero (default). All other types have been
7972 // converted to a number type further up in the call chain.
7973 ASSERT(value->IsUndefined());
7974 }
7975 receiver->set(index, cast_value);
7976 }
7977 return Heap::NumberFromInt32(cast_value);
7978}
7979
7980
7981Object* ExternalByteArray::SetValue(uint32_t index, Object* value) {
7982 return ExternalArrayIntSetter<ExternalByteArray, int8_t>
7983 (this, index, value);
7984}
7985
7986
7987Object* ExternalUnsignedByteArray::SetValue(uint32_t index, Object* value) {
7988 return ExternalArrayIntSetter<ExternalUnsignedByteArray, uint8_t>
7989 (this, index, value);
7990}
7991
7992
7993Object* ExternalShortArray::SetValue(uint32_t index, Object* value) {
7994 return ExternalArrayIntSetter<ExternalShortArray, int16_t>
7995 (this, index, value);
7996}
7997
7998
7999Object* ExternalUnsignedShortArray::SetValue(uint32_t index, Object* value) {
8000 return ExternalArrayIntSetter<ExternalUnsignedShortArray, uint16_t>
8001 (this, index, value);
8002}
8003
8004
8005Object* ExternalIntArray::SetValue(uint32_t index, Object* value) {
8006 return ExternalArrayIntSetter<ExternalIntArray, int32_t>
8007 (this, index, value);
8008}
8009
8010
8011Object* ExternalUnsignedIntArray::SetValue(uint32_t index, Object* value) {
8012 uint32_t cast_value = 0;
8013 if (index < static_cast<uint32_t>(length())) {
8014 if (value->IsSmi()) {
8015 int int_value = Smi::cast(value)->value();
8016 cast_value = static_cast<uint32_t>(int_value);
8017 } else if (value->IsHeapNumber()) {
8018 double double_value = HeapNumber::cast(value)->value();
8019 cast_value = static_cast<uint32_t>(DoubleToUint32(double_value));
8020 } else {
8021 // Clamp undefined to zero (default). All other types have been
8022 // converted to a number type further up in the call chain.
8023 ASSERT(value->IsUndefined());
8024 }
8025 set(index, cast_value);
8026 }
8027 return Heap::NumberFromUint32(cast_value);
8028}
8029
8030
8031Object* ExternalFloatArray::SetValue(uint32_t index, Object* value) {
8032 float cast_value = 0;
8033 if (index < static_cast<uint32_t>(length())) {
8034 if (value->IsSmi()) {
8035 int int_value = Smi::cast(value)->value();
8036 cast_value = static_cast<float>(int_value);
8037 } else if (value->IsHeapNumber()) {
8038 double double_value = HeapNumber::cast(value)->value();
8039 cast_value = static_cast<float>(double_value);
8040 } else {
8041 // Clamp undefined to zero (default). All other types have been
8042 // converted to a number type further up in the call chain.
8043 ASSERT(value->IsUndefined());
8044 }
8045 set(index, cast_value);
8046 }
8047 return Heap::AllocateHeapNumber(cast_value);
8048}
8049
8050
Steve Blocka7e24c12009-10-30 11:49:00 +00008051Object* GlobalObject::GetPropertyCell(LookupResult* result) {
8052 ASSERT(!HasFastProperties());
8053 Object* value = property_dictionary()->ValueAt(result->GetDictionaryEntry());
8054 ASSERT(value->IsJSGlobalPropertyCell());
8055 return value;
8056}
8057
8058
8059Object* GlobalObject::EnsurePropertyCell(String* name) {
8060 ASSERT(!HasFastProperties());
8061 int entry = property_dictionary()->FindEntry(name);
8062 if (entry == StringDictionary::kNotFound) {
8063 Object* cell = Heap::AllocateJSGlobalPropertyCell(Heap::the_hole_value());
8064 if (cell->IsFailure()) return cell;
8065 PropertyDetails details(NONE, NORMAL);
8066 details = details.AsDeleted();
8067 Object* dictionary = property_dictionary()->Add(name, cell, details);
8068 if (dictionary->IsFailure()) return dictionary;
8069 set_properties(StringDictionary::cast(dictionary));
8070 return cell;
8071 } else {
8072 Object* value = property_dictionary()->ValueAt(entry);
8073 ASSERT(value->IsJSGlobalPropertyCell());
8074 return value;
8075 }
8076}
8077
8078
8079Object* SymbolTable::LookupString(String* string, Object** s) {
8080 SymbolKey key(string);
8081 return LookupKey(&key, s);
8082}
8083
8084
Steve Blockd0582a62009-12-15 09:54:21 +00008085// This class is used for looking up two character strings in the symbol table.
8086// If we don't have a hit we don't want to waste much time so we unroll the
8087// string hash calculation loop here for speed. Doesn't work if the two
8088// characters form a decimal integer, since such strings have a different hash
8089// algorithm.
8090class TwoCharHashTableKey : public HashTableKey {
8091 public:
8092 TwoCharHashTableKey(uint32_t c1, uint32_t c2)
8093 : c1_(c1), c2_(c2) {
8094 // Char 1.
8095 uint32_t hash = c1 + (c1 << 10);
8096 hash ^= hash >> 6;
8097 // Char 2.
8098 hash += c2;
8099 hash += hash << 10;
8100 hash ^= hash >> 6;
8101 // GetHash.
8102 hash += hash << 3;
8103 hash ^= hash >> 11;
8104 hash += hash << 15;
8105 if (hash == 0) hash = 27;
8106#ifdef DEBUG
8107 StringHasher hasher(2);
8108 hasher.AddCharacter(c1);
8109 hasher.AddCharacter(c2);
8110 // If this assert fails then we failed to reproduce the two-character
8111 // version of the string hashing algorithm above. One reason could be
8112 // that we were passed two digits as characters, since the hash
8113 // algorithm is different in that case.
8114 ASSERT_EQ(static_cast<int>(hasher.GetHash()), static_cast<int>(hash));
8115#endif
8116 hash_ = hash;
8117 }
8118
8119 bool IsMatch(Object* o) {
8120 if (!o->IsString()) return false;
8121 String* other = String::cast(o);
8122 if (other->length() != 2) return false;
8123 if (other->Get(0) != c1_) return false;
8124 return other->Get(1) == c2_;
8125 }
8126
8127 uint32_t Hash() { return hash_; }
8128 uint32_t HashForObject(Object* key) {
8129 if (!key->IsString()) return 0;
8130 return String::cast(key)->Hash();
8131 }
8132
8133 Object* AsObject() {
8134 // The TwoCharHashTableKey is only used for looking in the symbol
8135 // table, not for adding to it.
8136 UNREACHABLE();
8137 return NULL;
8138 }
8139 private:
8140 uint32_t c1_;
8141 uint32_t c2_;
8142 uint32_t hash_;
8143};
8144
8145
Steve Blocka7e24c12009-10-30 11:49:00 +00008146bool SymbolTable::LookupSymbolIfExists(String* string, String** symbol) {
8147 SymbolKey key(string);
8148 int entry = FindEntry(&key);
8149 if (entry == kNotFound) {
8150 return false;
8151 } else {
8152 String* result = String::cast(KeyAt(entry));
8153 ASSERT(StringShape(result).IsSymbol());
8154 *symbol = result;
8155 return true;
8156 }
8157}
8158
8159
Steve Blockd0582a62009-12-15 09:54:21 +00008160bool SymbolTable::LookupTwoCharsSymbolIfExists(uint32_t c1,
8161 uint32_t c2,
8162 String** symbol) {
8163 TwoCharHashTableKey key(c1, c2);
8164 int entry = FindEntry(&key);
8165 if (entry == kNotFound) {
8166 return false;
8167 } else {
8168 String* result = String::cast(KeyAt(entry));
8169 ASSERT(StringShape(result).IsSymbol());
8170 *symbol = result;
8171 return true;
8172 }
8173}
8174
8175
Steve Blocka7e24c12009-10-30 11:49:00 +00008176Object* SymbolTable::LookupSymbol(Vector<const char> str, Object** s) {
8177 Utf8SymbolKey key(str);
8178 return LookupKey(&key, s);
8179}
8180
8181
8182Object* SymbolTable::LookupKey(HashTableKey* key, Object** s) {
8183 int entry = FindEntry(key);
8184
8185 // Symbol already in table.
8186 if (entry != kNotFound) {
8187 *s = KeyAt(entry);
8188 return this;
8189 }
8190
8191 // Adding new symbol. Grow table if needed.
8192 Object* obj = EnsureCapacity(1, key);
8193 if (obj->IsFailure()) return obj;
8194
8195 // Create symbol object.
8196 Object* symbol = key->AsObject();
8197 if (symbol->IsFailure()) return symbol;
8198
8199 // If the symbol table grew as part of EnsureCapacity, obj is not
8200 // the current symbol table and therefore we cannot use
8201 // SymbolTable::cast here.
8202 SymbolTable* table = reinterpret_cast<SymbolTable*>(obj);
8203
8204 // Add the new symbol and return it along with the symbol table.
8205 entry = table->FindInsertionEntry(key->Hash());
8206 table->set(EntryToIndex(entry), symbol);
8207 table->ElementAdded();
8208 *s = symbol;
8209 return table;
8210}
8211
8212
8213Object* CompilationCacheTable::Lookup(String* src) {
8214 StringKey key(src);
8215 int entry = FindEntry(&key);
8216 if (entry == kNotFound) return Heap::undefined_value();
8217 return get(EntryToIndex(entry) + 1);
8218}
8219
8220
8221Object* CompilationCacheTable::LookupEval(String* src, Context* context) {
8222 StringSharedKey key(src, context->closure()->shared());
8223 int entry = FindEntry(&key);
8224 if (entry == kNotFound) return Heap::undefined_value();
8225 return get(EntryToIndex(entry) + 1);
8226}
8227
8228
8229Object* CompilationCacheTable::LookupRegExp(String* src,
8230 JSRegExp::Flags flags) {
8231 RegExpKey key(src, flags);
8232 int entry = FindEntry(&key);
8233 if (entry == kNotFound) return Heap::undefined_value();
8234 return get(EntryToIndex(entry) + 1);
8235}
8236
8237
8238Object* CompilationCacheTable::Put(String* src, Object* value) {
8239 StringKey key(src);
8240 Object* obj = EnsureCapacity(1, &key);
8241 if (obj->IsFailure()) return obj;
8242
8243 CompilationCacheTable* cache =
8244 reinterpret_cast<CompilationCacheTable*>(obj);
8245 int entry = cache->FindInsertionEntry(key.Hash());
8246 cache->set(EntryToIndex(entry), src);
8247 cache->set(EntryToIndex(entry) + 1, value);
8248 cache->ElementAdded();
8249 return cache;
8250}
8251
8252
8253Object* CompilationCacheTable::PutEval(String* src,
8254 Context* context,
8255 Object* value) {
8256 StringSharedKey key(src, context->closure()->shared());
8257 Object* obj = EnsureCapacity(1, &key);
8258 if (obj->IsFailure()) return obj;
8259
8260 CompilationCacheTable* cache =
8261 reinterpret_cast<CompilationCacheTable*>(obj);
8262 int entry = cache->FindInsertionEntry(key.Hash());
8263
8264 Object* k = key.AsObject();
8265 if (k->IsFailure()) return k;
8266
8267 cache->set(EntryToIndex(entry), k);
8268 cache->set(EntryToIndex(entry) + 1, value);
8269 cache->ElementAdded();
8270 return cache;
8271}
8272
8273
8274Object* CompilationCacheTable::PutRegExp(String* src,
8275 JSRegExp::Flags flags,
8276 FixedArray* value) {
8277 RegExpKey key(src, flags);
8278 Object* obj = EnsureCapacity(1, &key);
8279 if (obj->IsFailure()) return obj;
8280
8281 CompilationCacheTable* cache =
8282 reinterpret_cast<CompilationCacheTable*>(obj);
8283 int entry = cache->FindInsertionEntry(key.Hash());
Steve Block3ce2e202009-11-05 08:53:23 +00008284 // We store the value in the key slot, and compare the search key
8285 // to the stored value with a custon IsMatch function during lookups.
Steve Blocka7e24c12009-10-30 11:49:00 +00008286 cache->set(EntryToIndex(entry), value);
8287 cache->set(EntryToIndex(entry) + 1, value);
8288 cache->ElementAdded();
8289 return cache;
8290}
8291
8292
8293// SymbolsKey used for HashTable where key is array of symbols.
8294class SymbolsKey : public HashTableKey {
8295 public:
8296 explicit SymbolsKey(FixedArray* symbols) : symbols_(symbols) { }
8297
8298 bool IsMatch(Object* symbols) {
8299 FixedArray* o = FixedArray::cast(symbols);
8300 int len = symbols_->length();
8301 if (o->length() != len) return false;
8302 for (int i = 0; i < len; i++) {
8303 if (o->get(i) != symbols_->get(i)) return false;
8304 }
8305 return true;
8306 }
8307
8308 uint32_t Hash() { return HashForObject(symbols_); }
8309
8310 uint32_t HashForObject(Object* obj) {
8311 FixedArray* symbols = FixedArray::cast(obj);
8312 int len = symbols->length();
8313 uint32_t hash = 0;
8314 for (int i = 0; i < len; i++) {
8315 hash ^= String::cast(symbols->get(i))->Hash();
8316 }
8317 return hash;
8318 }
8319
8320 Object* AsObject() { return symbols_; }
8321
8322 private:
8323 FixedArray* symbols_;
8324};
8325
8326
8327Object* MapCache::Lookup(FixedArray* array) {
8328 SymbolsKey key(array);
8329 int entry = FindEntry(&key);
8330 if (entry == kNotFound) return Heap::undefined_value();
8331 return get(EntryToIndex(entry) + 1);
8332}
8333
8334
8335Object* MapCache::Put(FixedArray* array, Map* value) {
8336 SymbolsKey key(array);
8337 Object* obj = EnsureCapacity(1, &key);
8338 if (obj->IsFailure()) return obj;
8339
8340 MapCache* cache = reinterpret_cast<MapCache*>(obj);
8341 int entry = cache->FindInsertionEntry(key.Hash());
8342 cache->set(EntryToIndex(entry), array);
8343 cache->set(EntryToIndex(entry) + 1, value);
8344 cache->ElementAdded();
8345 return cache;
8346}
8347
8348
8349template<typename Shape, typename Key>
8350Object* Dictionary<Shape, Key>::Allocate(int at_least_space_for) {
8351 Object* obj = HashTable<Shape, Key>::Allocate(at_least_space_for);
8352 // Initialize the next enumeration index.
8353 if (!obj->IsFailure()) {
8354 Dictionary<Shape, Key>::cast(obj)->
8355 SetNextEnumerationIndex(PropertyDetails::kInitialIndex);
8356 }
8357 return obj;
8358}
8359
8360
8361template<typename Shape, typename Key>
8362Object* Dictionary<Shape, Key>::GenerateNewEnumerationIndices() {
8363 int length = HashTable<Shape, Key>::NumberOfElements();
8364
8365 // Allocate and initialize iteration order array.
8366 Object* obj = Heap::AllocateFixedArray(length);
8367 if (obj->IsFailure()) return obj;
8368 FixedArray* iteration_order = FixedArray::cast(obj);
8369 for (int i = 0; i < length; i++) {
Leon Clarke4515c472010-02-03 11:58:03 +00008370 iteration_order->set(i, Smi::FromInt(i));
Steve Blocka7e24c12009-10-30 11:49:00 +00008371 }
8372
8373 // Allocate array with enumeration order.
8374 obj = Heap::AllocateFixedArray(length);
8375 if (obj->IsFailure()) return obj;
8376 FixedArray* enumeration_order = FixedArray::cast(obj);
8377
8378 // Fill the enumeration order array with property details.
8379 int capacity = HashTable<Shape, Key>::Capacity();
8380 int pos = 0;
8381 for (int i = 0; i < capacity; i++) {
8382 if (Dictionary<Shape, Key>::IsKey(Dictionary<Shape, Key>::KeyAt(i))) {
Leon Clarke4515c472010-02-03 11:58:03 +00008383 enumeration_order->set(pos++, Smi::FromInt(DetailsAt(i).index()));
Steve Blocka7e24c12009-10-30 11:49:00 +00008384 }
8385 }
8386
8387 // Sort the arrays wrt. enumeration order.
8388 iteration_order->SortPairs(enumeration_order, enumeration_order->length());
8389
8390 // Overwrite the enumeration_order with the enumeration indices.
8391 for (int i = 0; i < length; i++) {
8392 int index = Smi::cast(iteration_order->get(i))->value();
8393 int enum_index = PropertyDetails::kInitialIndex + i;
Leon Clarke4515c472010-02-03 11:58:03 +00008394 enumeration_order->set(index, Smi::FromInt(enum_index));
Steve Blocka7e24c12009-10-30 11:49:00 +00008395 }
8396
8397 // Update the dictionary with new indices.
8398 capacity = HashTable<Shape, Key>::Capacity();
8399 pos = 0;
8400 for (int i = 0; i < capacity; i++) {
8401 if (Dictionary<Shape, Key>::IsKey(Dictionary<Shape, Key>::KeyAt(i))) {
8402 int enum_index = Smi::cast(enumeration_order->get(pos++))->value();
8403 PropertyDetails details = DetailsAt(i);
8404 PropertyDetails new_details =
8405 PropertyDetails(details.attributes(), details.type(), enum_index);
8406 DetailsAtPut(i, new_details);
8407 }
8408 }
8409
8410 // Set the next enumeration index.
8411 SetNextEnumerationIndex(PropertyDetails::kInitialIndex+length);
8412 return this;
8413}
8414
8415template<typename Shape, typename Key>
8416Object* Dictionary<Shape, Key>::EnsureCapacity(int n, Key key) {
8417 // Check whether there are enough enumeration indices to add n elements.
8418 if (Shape::kIsEnumerable &&
8419 !PropertyDetails::IsValidIndex(NextEnumerationIndex() + n)) {
8420 // If not, we generate new indices for the properties.
8421 Object* result = GenerateNewEnumerationIndices();
8422 if (result->IsFailure()) return result;
8423 }
8424 return HashTable<Shape, Key>::EnsureCapacity(n, key);
8425}
8426
8427
8428void NumberDictionary::RemoveNumberEntries(uint32_t from, uint32_t to) {
8429 // Do nothing if the interval [from, to) is empty.
8430 if (from >= to) return;
8431
8432 int removed_entries = 0;
8433 Object* sentinel = Heap::null_value();
8434 int capacity = Capacity();
8435 for (int i = 0; i < capacity; i++) {
8436 Object* key = KeyAt(i);
8437 if (key->IsNumber()) {
8438 uint32_t number = static_cast<uint32_t>(key->Number());
8439 if (from <= number && number < to) {
8440 SetEntry(i, sentinel, sentinel, Smi::FromInt(0));
8441 removed_entries++;
8442 }
8443 }
8444 }
8445
8446 // Update the number of elements.
Leon Clarkee46be812010-01-19 14:06:41 +00008447 ElementsRemoved(removed_entries);
Steve Blocka7e24c12009-10-30 11:49:00 +00008448}
8449
8450
8451template<typename Shape, typename Key>
8452Object* Dictionary<Shape, Key>::DeleteProperty(int entry,
8453 JSObject::DeleteMode mode) {
8454 PropertyDetails details = DetailsAt(entry);
8455 // Ignore attributes if forcing a deletion.
8456 if (details.IsDontDelete() && mode == JSObject::NORMAL_DELETION) {
8457 return Heap::false_value();
8458 }
8459 SetEntry(entry, Heap::null_value(), Heap::null_value(), Smi::FromInt(0));
8460 HashTable<Shape, Key>::ElementRemoved();
8461 return Heap::true_value();
8462}
8463
8464
8465template<typename Shape, typename Key>
8466Object* Dictionary<Shape, Key>::AtPut(Key key, Object* value) {
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01008467 int entry = this->FindEntry(key);
Steve Blocka7e24c12009-10-30 11:49:00 +00008468
8469 // If the entry is present set the value;
8470 if (entry != Dictionary<Shape, Key>::kNotFound) {
8471 ValueAtPut(entry, value);
8472 return this;
8473 }
8474
8475 // Check whether the dictionary should be extended.
8476 Object* obj = EnsureCapacity(1, key);
8477 if (obj->IsFailure()) return obj;
8478
8479 Object* k = Shape::AsObject(key);
8480 if (k->IsFailure()) return k;
8481 PropertyDetails details = PropertyDetails(NONE, NORMAL);
8482 return Dictionary<Shape, Key>::cast(obj)->
8483 AddEntry(key, value, details, Shape::Hash(key));
8484}
8485
8486
8487template<typename Shape, typename Key>
8488Object* Dictionary<Shape, Key>::Add(Key key,
8489 Object* value,
8490 PropertyDetails details) {
8491 // Valdate key is absent.
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01008492 SLOW_ASSERT((this->FindEntry(key) == Dictionary<Shape, Key>::kNotFound));
Steve Blocka7e24c12009-10-30 11:49:00 +00008493 // Check whether the dictionary should be extended.
8494 Object* obj = EnsureCapacity(1, key);
8495 if (obj->IsFailure()) return obj;
8496 return Dictionary<Shape, Key>::cast(obj)->
8497 AddEntry(key, value, details, Shape::Hash(key));
8498}
8499
8500
8501// Add a key, value pair to the dictionary.
8502template<typename Shape, typename Key>
8503Object* Dictionary<Shape, Key>::AddEntry(Key key,
8504 Object* value,
8505 PropertyDetails details,
8506 uint32_t hash) {
8507 // Compute the key object.
8508 Object* k = Shape::AsObject(key);
8509 if (k->IsFailure()) return k;
8510
8511 uint32_t entry = Dictionary<Shape, Key>::FindInsertionEntry(hash);
8512 // Insert element at empty or deleted entry
8513 if (!details.IsDeleted() && details.index() == 0 && Shape::kIsEnumerable) {
8514 // Assign an enumeration index to the property and update
8515 // SetNextEnumerationIndex.
8516 int index = NextEnumerationIndex();
8517 details = PropertyDetails(details.attributes(), details.type(), index);
8518 SetNextEnumerationIndex(index + 1);
8519 }
8520 SetEntry(entry, k, value, details);
8521 ASSERT((Dictionary<Shape, Key>::KeyAt(entry)->IsNumber()
8522 || Dictionary<Shape, Key>::KeyAt(entry)->IsString()));
8523 HashTable<Shape, Key>::ElementAdded();
8524 return this;
8525}
8526
8527
8528void NumberDictionary::UpdateMaxNumberKey(uint32_t key) {
8529 // If the dictionary requires slow elements an element has already
8530 // been added at a high index.
8531 if (requires_slow_elements()) return;
8532 // Check if this index is high enough that we should require slow
8533 // elements.
8534 if (key > kRequiresSlowElementsLimit) {
8535 set_requires_slow_elements();
8536 return;
8537 }
8538 // Update max key value.
8539 Object* max_index_object = get(kMaxNumberKeyIndex);
8540 if (!max_index_object->IsSmi() || max_number_key() < key) {
8541 FixedArray::set(kMaxNumberKeyIndex,
Leon Clarke4515c472010-02-03 11:58:03 +00008542 Smi::FromInt(key << kRequiresSlowElementsTagSize));
Steve Blocka7e24c12009-10-30 11:49:00 +00008543 }
8544}
8545
8546
8547Object* NumberDictionary::AddNumberEntry(uint32_t key,
8548 Object* value,
8549 PropertyDetails details) {
8550 UpdateMaxNumberKey(key);
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01008551 SLOW_ASSERT(this->FindEntry(key) == kNotFound);
Steve Blocka7e24c12009-10-30 11:49:00 +00008552 return Add(key, value, details);
8553}
8554
8555
8556Object* NumberDictionary::AtNumberPut(uint32_t key, Object* value) {
8557 UpdateMaxNumberKey(key);
8558 return AtPut(key, value);
8559}
8560
8561
8562Object* NumberDictionary::Set(uint32_t key,
8563 Object* value,
8564 PropertyDetails details) {
8565 int entry = FindEntry(key);
8566 if (entry == kNotFound) return AddNumberEntry(key, value, details);
8567 // Preserve enumeration index.
8568 details = PropertyDetails(details.attributes(),
8569 details.type(),
8570 DetailsAt(entry).index());
8571 SetEntry(entry, NumberDictionaryShape::AsObject(key), value, details);
8572 return this;
8573}
8574
8575
8576
8577template<typename Shape, typename Key>
8578int Dictionary<Shape, Key>::NumberOfElementsFilterAttributes(
8579 PropertyAttributes filter) {
8580 int capacity = HashTable<Shape, Key>::Capacity();
8581 int result = 0;
8582 for (int i = 0; i < capacity; i++) {
8583 Object* k = HashTable<Shape, Key>::KeyAt(i);
8584 if (HashTable<Shape, Key>::IsKey(k)) {
8585 PropertyDetails details = DetailsAt(i);
8586 if (details.IsDeleted()) continue;
8587 PropertyAttributes attr = details.attributes();
8588 if ((attr & filter) == 0) result++;
8589 }
8590 }
8591 return result;
8592}
8593
8594
8595template<typename Shape, typename Key>
8596int Dictionary<Shape, Key>::NumberOfEnumElements() {
8597 return NumberOfElementsFilterAttributes(
8598 static_cast<PropertyAttributes>(DONT_ENUM));
8599}
8600
8601
8602template<typename Shape, typename Key>
8603void Dictionary<Shape, Key>::CopyKeysTo(FixedArray* storage,
8604 PropertyAttributes filter) {
8605 ASSERT(storage->length() >= NumberOfEnumElements());
8606 int capacity = HashTable<Shape, Key>::Capacity();
8607 int index = 0;
8608 for (int i = 0; i < capacity; i++) {
8609 Object* k = HashTable<Shape, Key>::KeyAt(i);
8610 if (HashTable<Shape, Key>::IsKey(k)) {
8611 PropertyDetails details = DetailsAt(i);
8612 if (details.IsDeleted()) continue;
8613 PropertyAttributes attr = details.attributes();
8614 if ((attr & filter) == 0) storage->set(index++, k);
8615 }
8616 }
8617 storage->SortPairs(storage, index);
8618 ASSERT(storage->length() >= index);
8619}
8620
8621
8622void StringDictionary::CopyEnumKeysTo(FixedArray* storage,
8623 FixedArray* sort_array) {
8624 ASSERT(storage->length() >= NumberOfEnumElements());
8625 int capacity = Capacity();
8626 int index = 0;
8627 for (int i = 0; i < capacity; i++) {
8628 Object* k = KeyAt(i);
8629 if (IsKey(k)) {
8630 PropertyDetails details = DetailsAt(i);
8631 if (details.IsDeleted() || details.IsDontEnum()) continue;
8632 storage->set(index, k);
Leon Clarke4515c472010-02-03 11:58:03 +00008633 sort_array->set(index, Smi::FromInt(details.index()));
Steve Blocka7e24c12009-10-30 11:49:00 +00008634 index++;
8635 }
8636 }
8637 storage->SortPairs(sort_array, sort_array->length());
8638 ASSERT(storage->length() >= index);
8639}
8640
8641
8642template<typename Shape, typename Key>
8643void Dictionary<Shape, Key>::CopyKeysTo(FixedArray* storage) {
8644 ASSERT(storage->length() >= NumberOfElementsFilterAttributes(
8645 static_cast<PropertyAttributes>(NONE)));
8646 int capacity = HashTable<Shape, Key>::Capacity();
8647 int index = 0;
8648 for (int i = 0; i < capacity; i++) {
8649 Object* k = HashTable<Shape, Key>::KeyAt(i);
8650 if (HashTable<Shape, Key>::IsKey(k)) {
8651 PropertyDetails details = DetailsAt(i);
8652 if (details.IsDeleted()) continue;
8653 storage->set(index++, k);
8654 }
8655 }
8656 ASSERT(storage->length() >= index);
8657}
8658
8659
8660// Backwards lookup (slow).
8661template<typename Shape, typename Key>
8662Object* Dictionary<Shape, Key>::SlowReverseLookup(Object* value) {
8663 int capacity = HashTable<Shape, Key>::Capacity();
8664 for (int i = 0; i < capacity; i++) {
8665 Object* k = HashTable<Shape, Key>::KeyAt(i);
8666 if (Dictionary<Shape, Key>::IsKey(k)) {
8667 Object* e = ValueAt(i);
8668 if (e->IsJSGlobalPropertyCell()) {
8669 e = JSGlobalPropertyCell::cast(e)->value();
8670 }
8671 if (e == value) return k;
8672 }
8673 }
8674 return Heap::undefined_value();
8675}
8676
8677
8678Object* StringDictionary::TransformPropertiesToFastFor(
8679 JSObject* obj, int unused_property_fields) {
8680 // Make sure we preserve dictionary representation if there are too many
8681 // descriptors.
8682 if (NumberOfElements() > DescriptorArray::kMaxNumberOfDescriptors) return obj;
8683
8684 // Figure out if it is necessary to generate new enumeration indices.
8685 int max_enumeration_index =
8686 NextEnumerationIndex() +
8687 (DescriptorArray::kMaxNumberOfDescriptors -
8688 NumberOfElements());
8689 if (!PropertyDetails::IsValidIndex(max_enumeration_index)) {
8690 Object* result = GenerateNewEnumerationIndices();
8691 if (result->IsFailure()) return result;
8692 }
8693
8694 int instance_descriptor_length = 0;
8695 int number_of_fields = 0;
8696
8697 // Compute the length of the instance descriptor.
8698 int capacity = Capacity();
8699 for (int i = 0; i < capacity; i++) {
8700 Object* k = KeyAt(i);
8701 if (IsKey(k)) {
8702 Object* value = ValueAt(i);
8703 PropertyType type = DetailsAt(i).type();
8704 ASSERT(type != FIELD);
8705 instance_descriptor_length++;
Leon Clarkee46be812010-01-19 14:06:41 +00008706 if (type == NORMAL &&
8707 (!value->IsJSFunction() || Heap::InNewSpace(value))) {
8708 number_of_fields += 1;
8709 }
Steve Blocka7e24c12009-10-30 11:49:00 +00008710 }
8711 }
8712
8713 // Allocate the instance descriptor.
8714 Object* descriptors_unchecked =
8715 DescriptorArray::Allocate(instance_descriptor_length);
8716 if (descriptors_unchecked->IsFailure()) return descriptors_unchecked;
8717 DescriptorArray* descriptors = DescriptorArray::cast(descriptors_unchecked);
8718
8719 int inobject_props = obj->map()->inobject_properties();
8720 int number_of_allocated_fields =
8721 number_of_fields + unused_property_fields - inobject_props;
8722
8723 // Allocate the fixed array for the fields.
8724 Object* fields = Heap::AllocateFixedArray(number_of_allocated_fields);
8725 if (fields->IsFailure()) return fields;
8726
8727 // Fill in the instance descriptor and the fields.
8728 int next_descriptor = 0;
8729 int current_offset = 0;
8730 for (int i = 0; i < capacity; i++) {
8731 Object* k = KeyAt(i);
8732 if (IsKey(k)) {
8733 Object* value = ValueAt(i);
8734 // Ensure the key is a symbol before writing into the instance descriptor.
8735 Object* key = Heap::LookupSymbol(String::cast(k));
8736 if (key->IsFailure()) return key;
8737 PropertyDetails details = DetailsAt(i);
8738 PropertyType type = details.type();
8739
Leon Clarkee46be812010-01-19 14:06:41 +00008740 if (value->IsJSFunction() && !Heap::InNewSpace(value)) {
Steve Blocka7e24c12009-10-30 11:49:00 +00008741 ConstantFunctionDescriptor d(String::cast(key),
8742 JSFunction::cast(value),
8743 details.attributes(),
8744 details.index());
8745 descriptors->Set(next_descriptor++, &d);
8746 } else if (type == NORMAL) {
8747 if (current_offset < inobject_props) {
8748 obj->InObjectPropertyAtPut(current_offset,
8749 value,
8750 UPDATE_WRITE_BARRIER);
8751 } else {
8752 int offset = current_offset - inobject_props;
8753 FixedArray::cast(fields)->set(offset, value);
8754 }
8755 FieldDescriptor d(String::cast(key),
8756 current_offset++,
8757 details.attributes(),
8758 details.index());
8759 descriptors->Set(next_descriptor++, &d);
8760 } else if (type == CALLBACKS) {
8761 CallbacksDescriptor d(String::cast(key),
8762 value,
8763 details.attributes(),
8764 details.index());
8765 descriptors->Set(next_descriptor++, &d);
8766 } else {
8767 UNREACHABLE();
8768 }
8769 }
8770 }
8771 ASSERT(current_offset == number_of_fields);
8772
8773 descriptors->Sort();
8774 // Allocate new map.
8775 Object* new_map = obj->map()->CopyDropDescriptors();
8776 if (new_map->IsFailure()) return new_map;
8777
8778 // Transform the object.
8779 obj->set_map(Map::cast(new_map));
8780 obj->map()->set_instance_descriptors(descriptors);
8781 obj->map()->set_unused_property_fields(unused_property_fields);
8782
8783 obj->set_properties(FixedArray::cast(fields));
8784 ASSERT(obj->IsJSObject());
8785
8786 descriptors->SetNextEnumerationIndex(NextEnumerationIndex());
8787 // Check that it really works.
8788 ASSERT(obj->HasFastProperties());
8789
8790 return obj;
8791}
8792
8793
8794#ifdef ENABLE_DEBUGGER_SUPPORT
8795// Check if there is a break point at this code position.
8796bool DebugInfo::HasBreakPoint(int code_position) {
8797 // Get the break point info object for this code position.
8798 Object* break_point_info = GetBreakPointInfo(code_position);
8799
8800 // If there is no break point info object or no break points in the break
8801 // point info object there is no break point at this code position.
8802 if (break_point_info->IsUndefined()) return false;
8803 return BreakPointInfo::cast(break_point_info)->GetBreakPointCount() > 0;
8804}
8805
8806
8807// Get the break point info object for this code position.
8808Object* DebugInfo::GetBreakPointInfo(int code_position) {
8809 // Find the index of the break point info object for this code position.
8810 int index = GetBreakPointInfoIndex(code_position);
8811
8812 // Return the break point info object if any.
8813 if (index == kNoBreakPointInfo) return Heap::undefined_value();
8814 return BreakPointInfo::cast(break_points()->get(index));
8815}
8816
8817
8818// Clear a break point at the specified code position.
8819void DebugInfo::ClearBreakPoint(Handle<DebugInfo> debug_info,
8820 int code_position,
8821 Handle<Object> break_point_object) {
8822 Handle<Object> break_point_info(debug_info->GetBreakPointInfo(code_position));
8823 if (break_point_info->IsUndefined()) return;
8824 BreakPointInfo::ClearBreakPoint(
8825 Handle<BreakPointInfo>::cast(break_point_info),
8826 break_point_object);
8827}
8828
8829
8830void DebugInfo::SetBreakPoint(Handle<DebugInfo> debug_info,
8831 int code_position,
8832 int source_position,
8833 int statement_position,
8834 Handle<Object> break_point_object) {
8835 Handle<Object> break_point_info(debug_info->GetBreakPointInfo(code_position));
8836 if (!break_point_info->IsUndefined()) {
8837 BreakPointInfo::SetBreakPoint(
8838 Handle<BreakPointInfo>::cast(break_point_info),
8839 break_point_object);
8840 return;
8841 }
8842
8843 // Adding a new break point for a code position which did not have any
8844 // break points before. Try to find a free slot.
8845 int index = kNoBreakPointInfo;
8846 for (int i = 0; i < debug_info->break_points()->length(); i++) {
8847 if (debug_info->break_points()->get(i)->IsUndefined()) {
8848 index = i;
8849 break;
8850 }
8851 }
8852 if (index == kNoBreakPointInfo) {
8853 // No free slot - extend break point info array.
8854 Handle<FixedArray> old_break_points =
8855 Handle<FixedArray>(FixedArray::cast(debug_info->break_points()));
Steve Blocka7e24c12009-10-30 11:49:00 +00008856 Handle<FixedArray> new_break_points =
Kristian Monsen0d5e1162010-09-30 15:31:59 +01008857 Factory::NewFixedArray(old_break_points->length() +
8858 Debug::kEstimatedNofBreakPointsInFunction);
8859
8860 debug_info->set_break_points(*new_break_points);
Steve Blocka7e24c12009-10-30 11:49:00 +00008861 for (int i = 0; i < old_break_points->length(); i++) {
8862 new_break_points->set(i, old_break_points->get(i));
8863 }
8864 index = old_break_points->length();
8865 }
8866 ASSERT(index != kNoBreakPointInfo);
8867
8868 // Allocate new BreakPointInfo object and set the break point.
8869 Handle<BreakPointInfo> new_break_point_info =
8870 Handle<BreakPointInfo>::cast(Factory::NewStruct(BREAK_POINT_INFO_TYPE));
8871 new_break_point_info->set_code_position(Smi::FromInt(code_position));
8872 new_break_point_info->set_source_position(Smi::FromInt(source_position));
8873 new_break_point_info->
8874 set_statement_position(Smi::FromInt(statement_position));
8875 new_break_point_info->set_break_point_objects(Heap::undefined_value());
8876 BreakPointInfo::SetBreakPoint(new_break_point_info, break_point_object);
8877 debug_info->break_points()->set(index, *new_break_point_info);
8878}
8879
8880
8881// Get the break point objects for a code position.
8882Object* DebugInfo::GetBreakPointObjects(int code_position) {
8883 Object* break_point_info = GetBreakPointInfo(code_position);
8884 if (break_point_info->IsUndefined()) {
8885 return Heap::undefined_value();
8886 }
8887 return BreakPointInfo::cast(break_point_info)->break_point_objects();
8888}
8889
8890
8891// Get the total number of break points.
8892int DebugInfo::GetBreakPointCount() {
8893 if (break_points()->IsUndefined()) return 0;
8894 int count = 0;
8895 for (int i = 0; i < break_points()->length(); i++) {
8896 if (!break_points()->get(i)->IsUndefined()) {
8897 BreakPointInfo* break_point_info =
8898 BreakPointInfo::cast(break_points()->get(i));
8899 count += break_point_info->GetBreakPointCount();
8900 }
8901 }
8902 return count;
8903}
8904
8905
8906Object* DebugInfo::FindBreakPointInfo(Handle<DebugInfo> debug_info,
8907 Handle<Object> break_point_object) {
8908 if (debug_info->break_points()->IsUndefined()) return Heap::undefined_value();
8909 for (int i = 0; i < debug_info->break_points()->length(); i++) {
8910 if (!debug_info->break_points()->get(i)->IsUndefined()) {
8911 Handle<BreakPointInfo> break_point_info =
8912 Handle<BreakPointInfo>(BreakPointInfo::cast(
8913 debug_info->break_points()->get(i)));
8914 if (BreakPointInfo::HasBreakPointObject(break_point_info,
8915 break_point_object)) {
8916 return *break_point_info;
8917 }
8918 }
8919 }
8920 return Heap::undefined_value();
8921}
8922
8923
8924// Find the index of the break point info object for the specified code
8925// position.
8926int DebugInfo::GetBreakPointInfoIndex(int code_position) {
8927 if (break_points()->IsUndefined()) return kNoBreakPointInfo;
8928 for (int i = 0; i < break_points()->length(); i++) {
8929 if (!break_points()->get(i)->IsUndefined()) {
8930 BreakPointInfo* break_point_info =
8931 BreakPointInfo::cast(break_points()->get(i));
8932 if (break_point_info->code_position()->value() == code_position) {
8933 return i;
8934 }
8935 }
8936 }
8937 return kNoBreakPointInfo;
8938}
8939
8940
8941// Remove the specified break point object.
8942void BreakPointInfo::ClearBreakPoint(Handle<BreakPointInfo> break_point_info,
8943 Handle<Object> break_point_object) {
8944 // If there are no break points just ignore.
8945 if (break_point_info->break_point_objects()->IsUndefined()) return;
8946 // If there is a single break point clear it if it is the same.
8947 if (!break_point_info->break_point_objects()->IsFixedArray()) {
8948 if (break_point_info->break_point_objects() == *break_point_object) {
8949 break_point_info->set_break_point_objects(Heap::undefined_value());
8950 }
8951 return;
8952 }
8953 // If there are multiple break points shrink the array
8954 ASSERT(break_point_info->break_point_objects()->IsFixedArray());
8955 Handle<FixedArray> old_array =
8956 Handle<FixedArray>(
8957 FixedArray::cast(break_point_info->break_point_objects()));
8958 Handle<FixedArray> new_array =
8959 Factory::NewFixedArray(old_array->length() - 1);
8960 int found_count = 0;
8961 for (int i = 0; i < old_array->length(); i++) {
8962 if (old_array->get(i) == *break_point_object) {
8963 ASSERT(found_count == 0);
8964 found_count++;
8965 } else {
8966 new_array->set(i - found_count, old_array->get(i));
8967 }
8968 }
8969 // If the break point was found in the list change it.
8970 if (found_count > 0) break_point_info->set_break_point_objects(*new_array);
8971}
8972
8973
8974// Add the specified break point object.
8975void BreakPointInfo::SetBreakPoint(Handle<BreakPointInfo> break_point_info,
8976 Handle<Object> break_point_object) {
8977 // If there was no break point objects before just set it.
8978 if (break_point_info->break_point_objects()->IsUndefined()) {
8979 break_point_info->set_break_point_objects(*break_point_object);
8980 return;
8981 }
8982 // If the break point object is the same as before just ignore.
8983 if (break_point_info->break_point_objects() == *break_point_object) return;
8984 // If there was one break point object before replace with array.
8985 if (!break_point_info->break_point_objects()->IsFixedArray()) {
8986 Handle<FixedArray> array = Factory::NewFixedArray(2);
8987 array->set(0, break_point_info->break_point_objects());
8988 array->set(1, *break_point_object);
8989 break_point_info->set_break_point_objects(*array);
8990 return;
8991 }
8992 // If there was more than one break point before extend array.
8993 Handle<FixedArray> old_array =
8994 Handle<FixedArray>(
8995 FixedArray::cast(break_point_info->break_point_objects()));
8996 Handle<FixedArray> new_array =
8997 Factory::NewFixedArray(old_array->length() + 1);
8998 for (int i = 0; i < old_array->length(); i++) {
8999 // If the break point was there before just ignore.
9000 if (old_array->get(i) == *break_point_object) return;
9001 new_array->set(i, old_array->get(i));
9002 }
9003 // Add the new break point.
9004 new_array->set(old_array->length(), *break_point_object);
9005 break_point_info->set_break_point_objects(*new_array);
9006}
9007
9008
9009bool BreakPointInfo::HasBreakPointObject(
9010 Handle<BreakPointInfo> break_point_info,
9011 Handle<Object> break_point_object) {
9012 // No break point.
9013 if (break_point_info->break_point_objects()->IsUndefined()) return false;
9014 // Single beak point.
9015 if (!break_point_info->break_point_objects()->IsFixedArray()) {
9016 return break_point_info->break_point_objects() == *break_point_object;
9017 }
9018 // Multiple break points.
9019 FixedArray* array = FixedArray::cast(break_point_info->break_point_objects());
9020 for (int i = 0; i < array->length(); i++) {
9021 if (array->get(i) == *break_point_object) {
9022 return true;
9023 }
9024 }
9025 return false;
9026}
9027
9028
9029// Get the number of break points.
9030int BreakPointInfo::GetBreakPointCount() {
9031 // No break point.
9032 if (break_point_objects()->IsUndefined()) return 0;
9033 // Single beak point.
9034 if (!break_point_objects()->IsFixedArray()) return 1;
9035 // Multiple break points.
9036 return FixedArray::cast(break_point_objects())->length();
9037}
9038#endif
9039
9040
9041} } // namespace v8::internal