blob: ac20b2e6f7842cc458243bca6e48dc09db8e2442 [file] [log] [blame]
Ben Murdochf87a2032010-10-22 12:50:53 +01001// Copyright 2010 the V8 project authors. All rights reserved.
Steve Blocka7e24c12009-10-30 11:49:00 +00002// 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
Steve Blocka7e24c12009-10-30 11:49:00 +0000577// Should a word be prefixed by 'a' or 'an' in order to read naturally in
578// English? Returns false for non-ASCII or words that don't start with
579// a capital letter. The a/an rule follows pronunciation in English.
580// We don't use the BBC's overcorrect "an historic occasion" though if
581// you speak a dialect you may well say "an 'istoric occasion".
582static bool AnWord(String* str) {
583 if (str->length() == 0) return false; // A nothing.
584 int c0 = str->Get(0);
585 int c1 = str->length() > 1 ? str->Get(1) : 0;
586 if (c0 == 'U') {
587 if (c1 > 'Z') {
588 return true; // An Umpire, but a UTF8String, a U.
589 }
590 } else if (c0 == 'A' || c0 == 'E' || c0 == 'I' || c0 == 'O') {
591 return true; // An Ape, an ABCBook.
592 } else if ((c1 == 0 || (c1 >= 'A' && c1 <= 'Z')) &&
593 (c0 == 'F' || c0 == 'H' || c0 == 'M' || c0 == 'N' || c0 == 'R' ||
594 c0 == 'S' || c0 == 'X')) {
595 return true; // An MP3File, an M.
596 }
597 return false;
598}
599
600
Steve Block6ded16b2010-05-10 14:33:55 +0100601Object* String::SlowTryFlatten(PretenureFlag pretenure) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000602#ifdef DEBUG
603 // Do not attempt to flatten in debug mode when allocation is not
604 // allowed. This is to avoid an assertion failure when allocating.
605 // Flattening strings is the only case where we always allow
606 // allocation because no GC is performed if the allocation fails.
607 if (!Heap::IsAllocationAllowed()) return this;
608#endif
609
610 switch (StringShape(this).representation_tag()) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000611 case kConsStringTag: {
612 ConsString* cs = ConsString::cast(this);
613 if (cs->second()->length() == 0) {
Leon Clarkef7060e22010-06-03 12:02:55 +0100614 return cs->first();
Steve Blocka7e24c12009-10-30 11:49:00 +0000615 }
616 // There's little point in putting the flat string in new space if the
617 // cons string is in old space. It can never get GCed until there is
618 // an old space GC.
Steve Block6ded16b2010-05-10 14:33:55 +0100619 PretenureFlag tenure = Heap::InNewSpace(this) ? pretenure : TENURED;
Steve Blocka7e24c12009-10-30 11:49:00 +0000620 int len = length();
621 Object* object;
622 String* result;
623 if (IsAsciiRepresentation()) {
624 object = Heap::AllocateRawAsciiString(len, tenure);
625 if (object->IsFailure()) return object;
626 result = String::cast(object);
627 String* first = cs->first();
628 int first_length = first->length();
629 char* dest = SeqAsciiString::cast(result)->GetChars();
630 WriteToFlat(first, dest, 0, first_length);
631 String* second = cs->second();
632 WriteToFlat(second,
633 dest + first_length,
634 0,
635 len - first_length);
636 } else {
637 object = Heap::AllocateRawTwoByteString(len, tenure);
638 if (object->IsFailure()) return object;
639 result = String::cast(object);
640 uc16* dest = SeqTwoByteString::cast(result)->GetChars();
641 String* first = cs->first();
642 int first_length = first->length();
643 WriteToFlat(first, dest, 0, first_length);
644 String* second = cs->second();
645 WriteToFlat(second,
646 dest + first_length,
647 0,
648 len - first_length);
649 }
650 cs->set_first(result);
651 cs->set_second(Heap::empty_string());
Leon Clarkef7060e22010-06-03 12:02:55 +0100652 return result;
Steve Blocka7e24c12009-10-30 11:49:00 +0000653 }
654 default:
655 return this;
656 }
657}
658
659
660bool String::MakeExternal(v8::String::ExternalStringResource* resource) {
Steve Block8defd9f2010-07-08 12:39:36 +0100661 // Externalizing twice leaks the external resource, so it's
Kristian Monsen9dcf7e22010-06-28 14:14:28 +0100662 // prohibited by the API.
663 ASSERT(!this->IsExternalString());
Steve Blocka7e24c12009-10-30 11:49:00 +0000664#ifdef DEBUG
Steve Block3ce2e202009-11-05 08:53:23 +0000665 if (FLAG_enable_slow_asserts) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000666 // Assert that the resource and the string are equivalent.
667 ASSERT(static_cast<size_t>(this->length()) == resource->length());
Kristian Monsen25f61362010-05-21 11:50:48 +0100668 ScopedVector<uc16> smart_chars(this->length());
669 String::WriteToFlat(this, smart_chars.start(), 0, this->length());
670 ASSERT(memcmp(smart_chars.start(),
Steve Blocka7e24c12009-10-30 11:49:00 +0000671 resource->data(),
Kristian Monsen25f61362010-05-21 11:50:48 +0100672 resource->length() * sizeof(smart_chars[0])) == 0);
Steve Blocka7e24c12009-10-30 11:49:00 +0000673 }
674#endif // DEBUG
675
676 int size = this->Size(); // Byte size of the original string.
677 if (size < ExternalString::kSize) {
678 // The string is too small to fit an external String in its place. This can
679 // only happen for zero length strings.
680 return false;
681 }
682 ASSERT(size >= ExternalString::kSize);
Kristian Monsen9dcf7e22010-06-28 14:14:28 +0100683 bool is_ascii = this->IsAsciiRepresentation();
Steve Blocka7e24c12009-10-30 11:49:00 +0000684 bool is_symbol = this->IsSymbol();
685 int length = this->length();
Steve Blockd0582a62009-12-15 09:54:21 +0000686 int hash_field = this->hash_field();
Steve Blocka7e24c12009-10-30 11:49:00 +0000687
688 // Morph the object to an external string by adjusting the map and
689 // reinitializing the fields.
Kristian Monsen9dcf7e22010-06-28 14:14:28 +0100690 this->set_map(is_ascii ?
691 Heap::external_string_with_ascii_data_map() :
692 Heap::external_string_map());
Steve Blocka7e24c12009-10-30 11:49:00 +0000693 ExternalTwoByteString* self = ExternalTwoByteString::cast(this);
694 self->set_length(length);
Steve Blockd0582a62009-12-15 09:54:21 +0000695 self->set_hash_field(hash_field);
Steve Blocka7e24c12009-10-30 11:49:00 +0000696 self->set_resource(resource);
697 // Additionally make the object into an external symbol if the original string
698 // was a symbol to start with.
699 if (is_symbol) {
700 self->Hash(); // Force regeneration of the hash value.
701 // Now morph this external string into a external symbol.
Kristian Monsen9dcf7e22010-06-28 14:14:28 +0100702 this->set_map(is_ascii ?
703 Heap::external_symbol_with_ascii_data_map() :
704 Heap::external_symbol_map());
Steve Blocka7e24c12009-10-30 11:49:00 +0000705 }
706
707 // Fill the remainder of the string with dead wood.
708 int new_size = this->Size(); // Byte size of the external String object.
709 Heap::CreateFillerObjectAt(this->address() + new_size, size - new_size);
710 return true;
711}
712
713
714bool String::MakeExternal(v8::String::ExternalAsciiStringResource* resource) {
715#ifdef DEBUG
Steve Block3ce2e202009-11-05 08:53:23 +0000716 if (FLAG_enable_slow_asserts) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000717 // Assert that the resource and the string are equivalent.
718 ASSERT(static_cast<size_t>(this->length()) == resource->length());
Kristian Monsen25f61362010-05-21 11:50:48 +0100719 ScopedVector<char> smart_chars(this->length());
720 String::WriteToFlat(this, smart_chars.start(), 0, this->length());
721 ASSERT(memcmp(smart_chars.start(),
Steve Blocka7e24c12009-10-30 11:49:00 +0000722 resource->data(),
Kristian Monsen25f61362010-05-21 11:50:48 +0100723 resource->length() * sizeof(smart_chars[0])) == 0);
Steve Blocka7e24c12009-10-30 11:49:00 +0000724 }
725#endif // DEBUG
726
727 int size = this->Size(); // Byte size of the original string.
728 if (size < ExternalString::kSize) {
729 // The string is too small to fit an external String in its place. This can
730 // only happen for zero length strings.
731 return false;
732 }
733 ASSERT(size >= ExternalString::kSize);
734 bool is_symbol = this->IsSymbol();
735 int length = this->length();
Steve Blockd0582a62009-12-15 09:54:21 +0000736 int hash_field = this->hash_field();
Steve Blocka7e24c12009-10-30 11:49:00 +0000737
738 // Morph the object to an external string by adjusting the map and
739 // reinitializing the fields.
Steve Blockd0582a62009-12-15 09:54:21 +0000740 this->set_map(Heap::external_ascii_string_map());
Steve Blocka7e24c12009-10-30 11:49:00 +0000741 ExternalAsciiString* self = ExternalAsciiString::cast(this);
742 self->set_length(length);
Steve Blockd0582a62009-12-15 09:54:21 +0000743 self->set_hash_field(hash_field);
Steve Blocka7e24c12009-10-30 11:49:00 +0000744 self->set_resource(resource);
745 // Additionally make the object into an external symbol if the original string
746 // was a symbol to start with.
747 if (is_symbol) {
748 self->Hash(); // Force regeneration of the hash value.
749 // Now morph this external string into a external symbol.
Steve Blockd0582a62009-12-15 09:54:21 +0000750 this->set_map(Heap::external_ascii_symbol_map());
Steve Blocka7e24c12009-10-30 11:49:00 +0000751 }
752
753 // Fill the remainder of the string with dead wood.
754 int new_size = this->Size(); // Byte size of the external String object.
755 Heap::CreateFillerObjectAt(this->address() + new_size, size - new_size);
756 return true;
757}
758
759
760void String::StringShortPrint(StringStream* accumulator) {
761 int len = length();
Steve Blockd0582a62009-12-15 09:54:21 +0000762 if (len > kMaxShortPrintLength) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000763 accumulator->Add("<Very long string[%u]>", len);
764 return;
765 }
766
767 if (!LooksValid()) {
768 accumulator->Add("<Invalid String>");
769 return;
770 }
771
772 StringInputBuffer buf(this);
773
774 bool truncated = false;
775 if (len > kMaxShortPrintLength) {
776 len = kMaxShortPrintLength;
777 truncated = true;
778 }
779 bool ascii = true;
780 for (int i = 0; i < len; i++) {
781 int c = buf.GetNext();
782
783 if (c < 32 || c >= 127) {
784 ascii = false;
785 }
786 }
787 buf.Reset(this);
788 if (ascii) {
789 accumulator->Add("<String[%u]: ", length());
790 for (int i = 0; i < len; i++) {
791 accumulator->Put(buf.GetNext());
792 }
793 accumulator->Put('>');
794 } else {
795 // Backslash indicates that the string contains control
796 // characters and that backslashes are therefore escaped.
797 accumulator->Add("<String[%u]\\: ", length());
798 for (int i = 0; i < len; i++) {
799 int c = buf.GetNext();
800 if (c == '\n') {
801 accumulator->Add("\\n");
802 } else if (c == '\r') {
803 accumulator->Add("\\r");
804 } else if (c == '\\') {
805 accumulator->Add("\\\\");
806 } else if (c < 32 || c > 126) {
807 accumulator->Add("\\x%02x", c);
808 } else {
809 accumulator->Put(c);
810 }
811 }
812 if (truncated) {
813 accumulator->Put('.');
814 accumulator->Put('.');
815 accumulator->Put('.');
816 }
817 accumulator->Put('>');
818 }
819 return;
820}
821
822
823void JSObject::JSObjectShortPrint(StringStream* accumulator) {
824 switch (map()->instance_type()) {
825 case JS_ARRAY_TYPE: {
826 double length = JSArray::cast(this)->length()->Number();
827 accumulator->Add("<JS array[%u]>", static_cast<uint32_t>(length));
828 break;
829 }
830 case JS_REGEXP_TYPE: {
831 accumulator->Add("<JS RegExp>");
832 break;
833 }
834 case JS_FUNCTION_TYPE: {
835 Object* fun_name = JSFunction::cast(this)->shared()->name();
836 bool printed = false;
837 if (fun_name->IsString()) {
838 String* str = String::cast(fun_name);
839 if (str->length() > 0) {
840 accumulator->Add("<JS Function ");
841 accumulator->Put(str);
842 accumulator->Put('>');
843 printed = true;
844 }
845 }
846 if (!printed) {
847 accumulator->Add("<JS Function>");
848 }
849 break;
850 }
851 // All other JSObjects are rather similar to each other (JSObject,
852 // JSGlobalProxy, JSGlobalObject, JSUndetectableObject, JSValue).
853 default: {
854 Object* constructor = map()->constructor();
855 bool printed = false;
856 if (constructor->IsHeapObject() &&
857 !Heap::Contains(HeapObject::cast(constructor))) {
858 accumulator->Add("!!!INVALID CONSTRUCTOR!!!");
859 } else {
860 bool global_object = IsJSGlobalProxy();
861 if (constructor->IsJSFunction()) {
862 if (!Heap::Contains(JSFunction::cast(constructor)->shared())) {
863 accumulator->Add("!!!INVALID SHARED ON CONSTRUCTOR!!!");
864 } else {
865 Object* constructor_name =
866 JSFunction::cast(constructor)->shared()->name();
867 if (constructor_name->IsString()) {
868 String* str = String::cast(constructor_name);
869 if (str->length() > 0) {
870 bool vowel = AnWord(str);
871 accumulator->Add("<%sa%s ",
872 global_object ? "Global Object: " : "",
873 vowel ? "n" : "");
874 accumulator->Put(str);
875 accumulator->Put('>');
876 printed = true;
877 }
878 }
879 }
880 }
881 if (!printed) {
882 accumulator->Add("<JS %sObject", global_object ? "Global " : "");
883 }
884 }
885 if (IsJSValue()) {
886 accumulator->Add(" value = ");
887 JSValue::cast(this)->value()->ShortPrint(accumulator);
888 }
889 accumulator->Put('>');
890 break;
891 }
892 }
893}
894
895
896void HeapObject::HeapObjectShortPrint(StringStream* accumulator) {
897 // if (!Heap::InNewSpace(this)) PrintF("*", this);
898 if (!Heap::Contains(this)) {
899 accumulator->Add("!!!INVALID POINTER!!!");
900 return;
901 }
902 if (!Heap::Contains(map())) {
903 accumulator->Add("!!!INVALID MAP!!!");
904 return;
905 }
906
907 accumulator->Add("%p ", this);
908
909 if (IsString()) {
910 String::cast(this)->StringShortPrint(accumulator);
911 return;
912 }
913 if (IsJSObject()) {
914 JSObject::cast(this)->JSObjectShortPrint(accumulator);
915 return;
916 }
917 switch (map()->instance_type()) {
918 case MAP_TYPE:
919 accumulator->Add("<Map>");
920 break;
921 case FIXED_ARRAY_TYPE:
922 accumulator->Add("<FixedArray[%u]>", FixedArray::cast(this)->length());
923 break;
924 case BYTE_ARRAY_TYPE:
925 accumulator->Add("<ByteArray[%u]>", ByteArray::cast(this)->length());
926 break;
927 case PIXEL_ARRAY_TYPE:
928 accumulator->Add("<PixelArray[%u]>", PixelArray::cast(this)->length());
929 break;
Steve Block3ce2e202009-11-05 08:53:23 +0000930 case EXTERNAL_BYTE_ARRAY_TYPE:
931 accumulator->Add("<ExternalByteArray[%u]>",
932 ExternalByteArray::cast(this)->length());
933 break;
934 case EXTERNAL_UNSIGNED_BYTE_ARRAY_TYPE:
935 accumulator->Add("<ExternalUnsignedByteArray[%u]>",
936 ExternalUnsignedByteArray::cast(this)->length());
937 break;
938 case EXTERNAL_SHORT_ARRAY_TYPE:
939 accumulator->Add("<ExternalShortArray[%u]>",
940 ExternalShortArray::cast(this)->length());
941 break;
942 case EXTERNAL_UNSIGNED_SHORT_ARRAY_TYPE:
943 accumulator->Add("<ExternalUnsignedShortArray[%u]>",
944 ExternalUnsignedShortArray::cast(this)->length());
945 break;
946 case EXTERNAL_INT_ARRAY_TYPE:
947 accumulator->Add("<ExternalIntArray[%u]>",
948 ExternalIntArray::cast(this)->length());
949 break;
950 case EXTERNAL_UNSIGNED_INT_ARRAY_TYPE:
951 accumulator->Add("<ExternalUnsignedIntArray[%u]>",
952 ExternalUnsignedIntArray::cast(this)->length());
953 break;
954 case EXTERNAL_FLOAT_ARRAY_TYPE:
955 accumulator->Add("<ExternalFloatArray[%u]>",
956 ExternalFloatArray::cast(this)->length());
957 break;
Steve Blocka7e24c12009-10-30 11:49:00 +0000958 case SHARED_FUNCTION_INFO_TYPE:
959 accumulator->Add("<SharedFunctionInfo>");
960 break;
961#define MAKE_STRUCT_CASE(NAME, Name, name) \
962 case NAME##_TYPE: \
963 accumulator->Put('<'); \
964 accumulator->Add(#Name); \
965 accumulator->Put('>'); \
966 break;
967 STRUCT_LIST(MAKE_STRUCT_CASE)
968#undef MAKE_STRUCT_CASE
969 case CODE_TYPE:
970 accumulator->Add("<Code>");
971 break;
972 case ODDBALL_TYPE: {
973 if (IsUndefined())
974 accumulator->Add("<undefined>");
975 else if (IsTheHole())
976 accumulator->Add("<the hole>");
977 else if (IsNull())
978 accumulator->Add("<null>");
979 else if (IsTrue())
980 accumulator->Add("<true>");
981 else if (IsFalse())
982 accumulator->Add("<false>");
983 else
984 accumulator->Add("<Odd Oddball>");
985 break;
986 }
987 case HEAP_NUMBER_TYPE:
988 accumulator->Add("<Number: ");
989 HeapNumber::cast(this)->HeapNumberPrint(accumulator);
990 accumulator->Put('>');
991 break;
992 case PROXY_TYPE:
993 accumulator->Add("<Proxy>");
994 break;
995 case JS_GLOBAL_PROPERTY_CELL_TYPE:
996 accumulator->Add("Cell for ");
997 JSGlobalPropertyCell::cast(this)->value()->ShortPrint(accumulator);
998 break;
999 default:
1000 accumulator->Add("<Other heap object (%d)>", map()->instance_type());
1001 break;
1002 }
1003}
1004
1005
Steve Blocka7e24c12009-10-30 11:49:00 +00001006void HeapObject::Iterate(ObjectVisitor* v) {
1007 // Handle header
1008 IteratePointer(v, kMapOffset);
1009 // Handle object body
1010 Map* m = map();
1011 IterateBody(m->instance_type(), SizeFromMap(m), v);
1012}
1013
1014
1015void HeapObject::IterateBody(InstanceType type, int object_size,
1016 ObjectVisitor* v) {
1017 // Avoiding <Type>::cast(this) because it accesses the map pointer field.
1018 // During GC, the map pointer field is encoded.
1019 if (type < FIRST_NONSTRING_TYPE) {
1020 switch (type & kStringRepresentationMask) {
1021 case kSeqStringTag:
1022 break;
1023 case kConsStringTag:
Iain Merrick75681382010-08-19 15:07:18 +01001024 ConsString::BodyDescriptor::IterateBody(this, v);
Steve Blocka7e24c12009-10-30 11:49:00 +00001025 break;
Steve Blockd0582a62009-12-15 09:54:21 +00001026 case kExternalStringTag:
1027 if ((type & kStringEncodingMask) == kAsciiStringTag) {
1028 reinterpret_cast<ExternalAsciiString*>(this)->
1029 ExternalAsciiStringIterateBody(v);
1030 } else {
1031 reinterpret_cast<ExternalTwoByteString*>(this)->
1032 ExternalTwoByteStringIterateBody(v);
1033 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001034 break;
1035 }
1036 return;
1037 }
1038
1039 switch (type) {
1040 case FIXED_ARRAY_TYPE:
Iain Merrick75681382010-08-19 15:07:18 +01001041 FixedArray::BodyDescriptor::IterateBody(this, object_size, v);
Steve Blocka7e24c12009-10-30 11:49:00 +00001042 break;
1043 case JS_OBJECT_TYPE:
1044 case JS_CONTEXT_EXTENSION_OBJECT_TYPE:
1045 case JS_VALUE_TYPE:
1046 case JS_ARRAY_TYPE:
1047 case JS_REGEXP_TYPE:
Steve Blocka7e24c12009-10-30 11:49:00 +00001048 case JS_GLOBAL_PROXY_TYPE:
1049 case JS_GLOBAL_OBJECT_TYPE:
1050 case JS_BUILTINS_OBJECT_TYPE:
Iain Merrick75681382010-08-19 15:07:18 +01001051 JSObject::BodyDescriptor::IterateBody(this, object_size, v);
Steve Blocka7e24c12009-10-30 11:49:00 +00001052 break;
Steve Block791712a2010-08-27 10:21:07 +01001053 case JS_FUNCTION_TYPE:
1054 reinterpret_cast<JSFunction*>(this)
1055 ->JSFunctionIterateBody(object_size, v);
1056 break;
Steve Blocka7e24c12009-10-30 11:49:00 +00001057 case ODDBALL_TYPE:
Iain Merrick75681382010-08-19 15:07:18 +01001058 Oddball::BodyDescriptor::IterateBody(this, v);
Steve Blocka7e24c12009-10-30 11:49:00 +00001059 break;
1060 case PROXY_TYPE:
1061 reinterpret_cast<Proxy*>(this)->ProxyIterateBody(v);
1062 break;
1063 case MAP_TYPE:
Iain Merrick75681382010-08-19 15:07:18 +01001064 Map::BodyDescriptor::IterateBody(this, v);
Steve Blocka7e24c12009-10-30 11:49:00 +00001065 break;
1066 case CODE_TYPE:
1067 reinterpret_cast<Code*>(this)->CodeIterateBody(v);
1068 break;
1069 case JS_GLOBAL_PROPERTY_CELL_TYPE:
Iain Merrick75681382010-08-19 15:07:18 +01001070 JSGlobalPropertyCell::BodyDescriptor::IterateBody(this, v);
Steve Blocka7e24c12009-10-30 11:49:00 +00001071 break;
1072 case HEAP_NUMBER_TYPE:
1073 case FILLER_TYPE:
1074 case BYTE_ARRAY_TYPE:
1075 case PIXEL_ARRAY_TYPE:
Steve Block3ce2e202009-11-05 08:53:23 +00001076 case EXTERNAL_BYTE_ARRAY_TYPE:
1077 case EXTERNAL_UNSIGNED_BYTE_ARRAY_TYPE:
1078 case EXTERNAL_SHORT_ARRAY_TYPE:
1079 case EXTERNAL_UNSIGNED_SHORT_ARRAY_TYPE:
1080 case EXTERNAL_INT_ARRAY_TYPE:
1081 case EXTERNAL_UNSIGNED_INT_ARRAY_TYPE:
1082 case EXTERNAL_FLOAT_ARRAY_TYPE:
Steve Blocka7e24c12009-10-30 11:49:00 +00001083 break;
Iain Merrick75681382010-08-19 15:07:18 +01001084 case SHARED_FUNCTION_INFO_TYPE:
1085 SharedFunctionInfo::BodyDescriptor::IterateBody(this, v);
Steve Blocka7e24c12009-10-30 11:49:00 +00001086 break;
Iain Merrick75681382010-08-19 15:07:18 +01001087
Steve Blocka7e24c12009-10-30 11:49:00 +00001088#define MAKE_STRUCT_CASE(NAME, Name, name) \
1089 case NAME##_TYPE:
1090 STRUCT_LIST(MAKE_STRUCT_CASE)
1091#undef MAKE_STRUCT_CASE
Iain Merrick75681382010-08-19 15:07:18 +01001092 StructBodyDescriptor::IterateBody(this, object_size, v);
Steve Blocka7e24c12009-10-30 11:49:00 +00001093 break;
1094 default:
1095 PrintF("Unknown type: %d\n", type);
1096 UNREACHABLE();
1097 }
1098}
1099
1100
Steve Blocka7e24c12009-10-30 11:49:00 +00001101Object* HeapNumber::HeapNumberToBoolean() {
1102 // NaN, +0, and -0 should return the false object
Iain Merrick75681382010-08-19 15:07:18 +01001103#if __BYTE_ORDER == __LITTLE_ENDIAN
1104 union IeeeDoubleLittleEndianArchType u;
1105#elif __BYTE_ORDER == __BIG_ENDIAN
1106 union IeeeDoubleBigEndianArchType u;
1107#endif
1108 u.d = value();
1109 if (u.bits.exp == 2047) {
1110 // Detect NaN for IEEE double precision floating point.
1111 if ((u.bits.man_low | u.bits.man_high) != 0)
1112 return Heap::false_value();
Steve Blocka7e24c12009-10-30 11:49:00 +00001113 }
Iain Merrick75681382010-08-19 15:07:18 +01001114 if (u.bits.exp == 0) {
1115 // Detect +0, and -0 for IEEE double precision floating point.
1116 if ((u.bits.man_low | u.bits.man_high) == 0)
1117 return Heap::false_value();
1118 }
1119 return Heap::true_value();
Steve Blocka7e24c12009-10-30 11:49:00 +00001120}
1121
1122
1123void HeapNumber::HeapNumberPrint() {
1124 PrintF("%.16g", Number());
1125}
1126
1127
1128void HeapNumber::HeapNumberPrint(StringStream* accumulator) {
1129 // The Windows version of vsnprintf can allocate when printing a %g string
1130 // into a buffer that may not be big enough. We don't want random memory
1131 // allocation when producing post-crash stack traces, so we print into a
1132 // buffer that is plenty big enough for any floating point number, then
1133 // print that using vsnprintf (which may truncate but never allocate if
1134 // there is no more space in the buffer).
1135 EmbeddedVector<char, 100> buffer;
1136 OS::SNPrintF(buffer, "%.16g", Number());
1137 accumulator->Add("%s", buffer.start());
1138}
1139
1140
1141String* JSObject::class_name() {
1142 if (IsJSFunction()) {
1143 return Heap::function_class_symbol();
1144 }
1145 if (map()->constructor()->IsJSFunction()) {
1146 JSFunction* constructor = JSFunction::cast(map()->constructor());
1147 return String::cast(constructor->shared()->instance_class_name());
1148 }
1149 // If the constructor is not present, return "Object".
1150 return Heap::Object_symbol();
1151}
1152
1153
1154String* JSObject::constructor_name() {
1155 if (IsJSFunction()) {
Steve Block6ded16b2010-05-10 14:33:55 +01001156 return Heap::closure_symbol();
Steve Blocka7e24c12009-10-30 11:49:00 +00001157 }
1158 if (map()->constructor()->IsJSFunction()) {
1159 JSFunction* constructor = JSFunction::cast(map()->constructor());
1160 String* name = String::cast(constructor->shared()->name());
Ben Murdochf87a2032010-10-22 12:50:53 +01001161 if (name->length() > 0) return name;
1162 String* inferred_name = constructor->shared()->inferred_name();
1163 if (inferred_name->length() > 0) return inferred_name;
1164 Object* proto = GetPrototype();
1165 if (proto->IsJSObject()) return JSObject::cast(proto)->constructor_name();
Steve Blocka7e24c12009-10-30 11:49:00 +00001166 }
1167 // If the constructor is not present, return "Object".
1168 return Heap::Object_symbol();
1169}
1170
1171
Steve Blocka7e24c12009-10-30 11:49:00 +00001172Object* JSObject::AddFastPropertyUsingMap(Map* new_map,
1173 String* name,
1174 Object* value) {
1175 int index = new_map->PropertyIndexFor(name);
1176 if (map()->unused_property_fields() == 0) {
1177 ASSERT(map()->unused_property_fields() == 0);
1178 int new_unused = new_map->unused_property_fields();
1179 Object* values =
1180 properties()->CopySize(properties()->length() + new_unused + 1);
1181 if (values->IsFailure()) return values;
1182 set_properties(FixedArray::cast(values));
1183 }
1184 set_map(new_map);
1185 return FastPropertyAtPut(index, value);
1186}
1187
1188
1189Object* JSObject::AddFastProperty(String* name,
1190 Object* value,
1191 PropertyAttributes attributes) {
1192 // Normalize the object if the name is an actual string (not the
1193 // hidden symbols) and is not a real identifier.
1194 StringInputBuffer buffer(name);
1195 if (!Scanner::IsIdentifier(&buffer) && name != Heap::hidden_symbol()) {
1196 Object* obj = NormalizeProperties(CLEAR_INOBJECT_PROPERTIES, 0);
1197 if (obj->IsFailure()) return obj;
1198 return AddSlowProperty(name, value, attributes);
1199 }
1200
1201 DescriptorArray* old_descriptors = map()->instance_descriptors();
1202 // Compute the new index for new field.
1203 int index = map()->NextFreePropertyIndex();
1204
1205 // Allocate new instance descriptors with (name, index) added
1206 FieldDescriptor new_field(name, index, attributes);
1207 Object* new_descriptors =
1208 old_descriptors->CopyInsert(&new_field, REMOVE_TRANSITIONS);
1209 if (new_descriptors->IsFailure()) return new_descriptors;
1210
1211 // Only allow map transition if the object's map is NOT equal to the
1212 // global object_function's map and there is not a transition for name.
1213 bool allow_map_transition =
1214 !old_descriptors->Contains(name) &&
1215 (Top::context()->global_context()->object_function()->map() != map());
1216
1217 ASSERT(index < map()->inobject_properties() ||
1218 (index - map()->inobject_properties()) < properties()->length() ||
1219 map()->unused_property_fields() == 0);
1220 // Allocate a new map for the object.
1221 Object* r = map()->CopyDropDescriptors();
1222 if (r->IsFailure()) return r;
1223 Map* new_map = Map::cast(r);
1224 if (allow_map_transition) {
1225 // Allocate new instance descriptors for the old map with map transition.
1226 MapTransitionDescriptor d(name, Map::cast(new_map), attributes);
1227 Object* r = old_descriptors->CopyInsert(&d, KEEP_TRANSITIONS);
1228 if (r->IsFailure()) return r;
1229 old_descriptors = DescriptorArray::cast(r);
1230 }
1231
1232 if (map()->unused_property_fields() == 0) {
Steve Block8defd9f2010-07-08 12:39:36 +01001233 if (properties()->length() > MaxFastProperties()) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001234 Object* obj = NormalizeProperties(CLEAR_INOBJECT_PROPERTIES, 0);
1235 if (obj->IsFailure()) return obj;
1236 return AddSlowProperty(name, value, attributes);
1237 }
1238 // Make room for the new value
1239 Object* values =
1240 properties()->CopySize(properties()->length() + kFieldsAdded);
1241 if (values->IsFailure()) return values;
1242 set_properties(FixedArray::cast(values));
1243 new_map->set_unused_property_fields(kFieldsAdded - 1);
1244 } else {
1245 new_map->set_unused_property_fields(map()->unused_property_fields() - 1);
1246 }
1247 // We have now allocated all the necessary objects.
1248 // All the changes can be applied at once, so they are atomic.
1249 map()->set_instance_descriptors(old_descriptors);
1250 new_map->set_instance_descriptors(DescriptorArray::cast(new_descriptors));
1251 set_map(new_map);
1252 return FastPropertyAtPut(index, value);
1253}
1254
1255
1256Object* JSObject::AddConstantFunctionProperty(String* name,
1257 JSFunction* function,
1258 PropertyAttributes attributes) {
Leon Clarkee46be812010-01-19 14:06:41 +00001259 ASSERT(!Heap::InNewSpace(function));
1260
Steve Blocka7e24c12009-10-30 11:49:00 +00001261 // Allocate new instance descriptors with (name, function) added
1262 ConstantFunctionDescriptor d(name, function, attributes);
1263 Object* new_descriptors =
1264 map()->instance_descriptors()->CopyInsert(&d, REMOVE_TRANSITIONS);
1265 if (new_descriptors->IsFailure()) return new_descriptors;
1266
1267 // Allocate a new map for the object.
1268 Object* new_map = map()->CopyDropDescriptors();
1269 if (new_map->IsFailure()) return new_map;
1270
1271 DescriptorArray* descriptors = DescriptorArray::cast(new_descriptors);
1272 Map::cast(new_map)->set_instance_descriptors(descriptors);
1273 Map* old_map = map();
1274 set_map(Map::cast(new_map));
1275
1276 // If the old map is the global object map (from new Object()),
1277 // then transitions are not added to it, so we are done.
1278 if (old_map == Top::context()->global_context()->object_function()->map()) {
1279 return function;
1280 }
1281
1282 // Do not add CONSTANT_TRANSITIONS to global objects
1283 if (IsGlobalObject()) {
1284 return function;
1285 }
1286
1287 // Add a CONSTANT_TRANSITION descriptor to the old map,
1288 // so future assignments to this property on other objects
1289 // of the same type will create a normal field, not a constant function.
1290 // Don't do this for special properties, with non-trival attributes.
1291 if (attributes != NONE) {
1292 return function;
1293 }
Iain Merrick75681382010-08-19 15:07:18 +01001294 ConstTransitionDescriptor mark(name, Map::cast(new_map));
Steve Blocka7e24c12009-10-30 11:49:00 +00001295 new_descriptors =
1296 old_map->instance_descriptors()->CopyInsert(&mark, KEEP_TRANSITIONS);
1297 if (new_descriptors->IsFailure()) {
1298 return function; // We have accomplished the main goal, so return success.
1299 }
1300 old_map->set_instance_descriptors(DescriptorArray::cast(new_descriptors));
1301
1302 return function;
1303}
1304
1305
1306// Add property in slow mode
1307Object* JSObject::AddSlowProperty(String* name,
1308 Object* value,
1309 PropertyAttributes attributes) {
1310 ASSERT(!HasFastProperties());
1311 StringDictionary* dict = property_dictionary();
1312 Object* store_value = value;
1313 if (IsGlobalObject()) {
1314 // In case name is an orphaned property reuse the cell.
1315 int entry = dict->FindEntry(name);
1316 if (entry != StringDictionary::kNotFound) {
1317 store_value = dict->ValueAt(entry);
1318 JSGlobalPropertyCell::cast(store_value)->set_value(value);
1319 // Assign an enumeration index to the property and update
1320 // SetNextEnumerationIndex.
1321 int index = dict->NextEnumerationIndex();
1322 PropertyDetails details = PropertyDetails(attributes, NORMAL, index);
1323 dict->SetNextEnumerationIndex(index + 1);
1324 dict->SetEntry(entry, name, store_value, details);
1325 return value;
1326 }
1327 store_value = Heap::AllocateJSGlobalPropertyCell(value);
1328 if (store_value->IsFailure()) return store_value;
1329 JSGlobalPropertyCell::cast(store_value)->set_value(value);
1330 }
1331 PropertyDetails details = PropertyDetails(attributes, NORMAL);
1332 Object* result = dict->Add(name, store_value, details);
1333 if (result->IsFailure()) return result;
1334 if (dict != result) set_properties(StringDictionary::cast(result));
1335 return value;
1336}
1337
1338
1339Object* JSObject::AddProperty(String* name,
1340 Object* value,
1341 PropertyAttributes attributes) {
1342 ASSERT(!IsJSGlobalProxy());
Steve Block8defd9f2010-07-08 12:39:36 +01001343 if (!map()->is_extensible()) {
1344 Handle<Object> args[1] = {Handle<String>(name)};
1345 return Top::Throw(*Factory::NewTypeError("object_not_extensible",
1346 HandleVector(args, 1)));
1347 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001348 if (HasFastProperties()) {
1349 // Ensure the descriptor array does not get too big.
1350 if (map()->instance_descriptors()->number_of_descriptors() <
1351 DescriptorArray::kMaxNumberOfDescriptors) {
Leon Clarkee46be812010-01-19 14:06:41 +00001352 if (value->IsJSFunction() && !Heap::InNewSpace(value)) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001353 return AddConstantFunctionProperty(name,
1354 JSFunction::cast(value),
1355 attributes);
1356 } else {
1357 return AddFastProperty(name, value, attributes);
1358 }
1359 } else {
1360 // Normalize the object to prevent very large instance descriptors.
1361 // This eliminates unwanted N^2 allocation and lookup behavior.
1362 Object* obj = NormalizeProperties(CLEAR_INOBJECT_PROPERTIES, 0);
1363 if (obj->IsFailure()) return obj;
1364 }
1365 }
1366 return AddSlowProperty(name, value, attributes);
1367}
1368
1369
1370Object* JSObject::SetPropertyPostInterceptor(String* name,
1371 Object* value,
1372 PropertyAttributes attributes) {
1373 // Check local property, ignore interceptor.
1374 LookupResult result;
1375 LocalLookupRealNamedProperty(name, &result);
Andrei Popescu402d9372010-02-26 13:31:12 +00001376 if (result.IsFound()) {
1377 // An existing property, a map transition or a null descriptor was
1378 // found. Use set property to handle all these cases.
1379 return SetProperty(&result, name, value, attributes);
1380 }
1381 // Add a new real property.
Steve Blocka7e24c12009-10-30 11:49:00 +00001382 return AddProperty(name, value, attributes);
1383}
1384
1385
1386Object* JSObject::ReplaceSlowProperty(String* name,
Steve Blockd0582a62009-12-15 09:54:21 +00001387 Object* value,
1388 PropertyAttributes attributes) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001389 StringDictionary* dictionary = property_dictionary();
1390 int old_index = dictionary->FindEntry(name);
1391 int new_enumeration_index = 0; // 0 means "Use the next available index."
1392 if (old_index != -1) {
1393 // All calls to ReplaceSlowProperty have had all transitions removed.
1394 ASSERT(!dictionary->DetailsAt(old_index).IsTransition());
1395 new_enumeration_index = dictionary->DetailsAt(old_index).index();
1396 }
1397
1398 PropertyDetails new_details(attributes, NORMAL, new_enumeration_index);
1399 return SetNormalizedProperty(name, value, new_details);
1400}
1401
Steve Blockd0582a62009-12-15 09:54:21 +00001402
Steve Blocka7e24c12009-10-30 11:49:00 +00001403Object* JSObject::ConvertDescriptorToFieldAndMapTransition(
1404 String* name,
1405 Object* new_value,
1406 PropertyAttributes attributes) {
1407 Map* old_map = map();
1408 Object* result = ConvertDescriptorToField(name, new_value, attributes);
1409 if (result->IsFailure()) return result;
1410 // If we get to this point we have succeeded - do not return failure
1411 // after this point. Later stuff is optional.
1412 if (!HasFastProperties()) {
1413 return result;
1414 }
1415 // Do not add transitions to the map of "new Object()".
1416 if (map() == Top::context()->global_context()->object_function()->map()) {
1417 return result;
1418 }
1419
1420 MapTransitionDescriptor transition(name,
1421 map(),
1422 attributes);
1423 Object* new_descriptors =
1424 old_map->instance_descriptors()->
1425 CopyInsert(&transition, KEEP_TRANSITIONS);
1426 if (new_descriptors->IsFailure()) return result; // Yes, return _result_.
1427 old_map->set_instance_descriptors(DescriptorArray::cast(new_descriptors));
1428 return result;
1429}
1430
1431
1432Object* JSObject::ConvertDescriptorToField(String* name,
1433 Object* new_value,
1434 PropertyAttributes attributes) {
1435 if (map()->unused_property_fields() == 0 &&
Steve Block8defd9f2010-07-08 12:39:36 +01001436 properties()->length() > MaxFastProperties()) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001437 Object* obj = NormalizeProperties(CLEAR_INOBJECT_PROPERTIES, 0);
1438 if (obj->IsFailure()) return obj;
1439 return ReplaceSlowProperty(name, new_value, attributes);
1440 }
1441
1442 int index = map()->NextFreePropertyIndex();
1443 FieldDescriptor new_field(name, index, attributes);
1444 // Make a new DescriptorArray replacing an entry with FieldDescriptor.
1445 Object* descriptors_unchecked = map()->instance_descriptors()->
1446 CopyInsert(&new_field, REMOVE_TRANSITIONS);
1447 if (descriptors_unchecked->IsFailure()) return descriptors_unchecked;
1448 DescriptorArray* new_descriptors =
1449 DescriptorArray::cast(descriptors_unchecked);
1450
1451 // Make a new map for the object.
1452 Object* new_map_unchecked = map()->CopyDropDescriptors();
1453 if (new_map_unchecked->IsFailure()) return new_map_unchecked;
1454 Map* new_map = Map::cast(new_map_unchecked);
1455 new_map->set_instance_descriptors(new_descriptors);
1456
1457 // Make new properties array if necessary.
1458 FixedArray* new_properties = 0; // Will always be NULL or a valid pointer.
1459 int new_unused_property_fields = map()->unused_property_fields() - 1;
1460 if (map()->unused_property_fields() == 0) {
Kristian Monsen0d5e1162010-09-30 15:31:59 +01001461 new_unused_property_fields = kFieldsAdded - 1;
1462 Object* new_properties_unchecked =
Steve Blocka7e24c12009-10-30 11:49:00 +00001463 properties()->CopySize(properties()->length() + kFieldsAdded);
1464 if (new_properties_unchecked->IsFailure()) return new_properties_unchecked;
1465 new_properties = FixedArray::cast(new_properties_unchecked);
1466 }
1467
1468 // Update pointers to commit changes.
1469 // Object points to the new map.
1470 new_map->set_unused_property_fields(new_unused_property_fields);
1471 set_map(new_map);
1472 if (new_properties) {
1473 set_properties(FixedArray::cast(new_properties));
1474 }
1475 return FastPropertyAtPut(index, new_value);
1476}
1477
1478
1479
1480Object* JSObject::SetPropertyWithInterceptor(String* name,
1481 Object* value,
1482 PropertyAttributes attributes) {
1483 HandleScope scope;
1484 Handle<JSObject> this_handle(this);
1485 Handle<String> name_handle(name);
1486 Handle<Object> value_handle(value);
1487 Handle<InterceptorInfo> interceptor(GetNamedInterceptor());
1488 if (!interceptor->setter()->IsUndefined()) {
1489 LOG(ApiNamedPropertyAccess("interceptor-named-set", this, name));
1490 CustomArguments args(interceptor->data(), this, this);
1491 v8::AccessorInfo info(args.end());
1492 v8::NamedPropertySetter setter =
1493 v8::ToCData<v8::NamedPropertySetter>(interceptor->setter());
1494 v8::Handle<v8::Value> result;
1495 {
1496 // Leaving JavaScript.
1497 VMState state(EXTERNAL);
1498 Handle<Object> value_unhole(value->IsTheHole() ?
1499 Heap::undefined_value() :
1500 value);
1501 result = setter(v8::Utils::ToLocal(name_handle),
1502 v8::Utils::ToLocal(value_unhole),
1503 info);
1504 }
1505 RETURN_IF_SCHEDULED_EXCEPTION();
1506 if (!result.IsEmpty()) return *value_handle;
1507 }
1508 Object* raw_result = this_handle->SetPropertyPostInterceptor(*name_handle,
1509 *value_handle,
1510 attributes);
1511 RETURN_IF_SCHEDULED_EXCEPTION();
1512 return raw_result;
1513}
1514
1515
1516Object* JSObject::SetProperty(String* name,
1517 Object* value,
1518 PropertyAttributes attributes) {
1519 LookupResult result;
1520 LocalLookup(name, &result);
1521 return SetProperty(&result, name, value, attributes);
1522}
1523
1524
1525Object* JSObject::SetPropertyWithCallback(Object* structure,
1526 String* name,
1527 Object* value,
1528 JSObject* holder) {
1529 HandleScope scope;
1530
1531 // We should never get here to initialize a const with the hole
1532 // value since a const declaration would conflict with the setter.
1533 ASSERT(!value->IsTheHole());
1534 Handle<Object> value_handle(value);
1535
1536 // To accommodate both the old and the new api we switch on the
1537 // data structure used to store the callbacks. Eventually proxy
1538 // callbacks should be phased out.
1539 if (structure->IsProxy()) {
1540 AccessorDescriptor* callback =
1541 reinterpret_cast<AccessorDescriptor*>(Proxy::cast(structure)->proxy());
1542 Object* obj = (callback->setter)(this, value, callback->data);
1543 RETURN_IF_SCHEDULED_EXCEPTION();
1544 if (obj->IsFailure()) return obj;
1545 return *value_handle;
1546 }
1547
1548 if (structure->IsAccessorInfo()) {
1549 // api style callbacks
1550 AccessorInfo* data = AccessorInfo::cast(structure);
1551 Object* call_obj = data->setter();
1552 v8::AccessorSetter call_fun = v8::ToCData<v8::AccessorSetter>(call_obj);
1553 if (call_fun == NULL) return value;
1554 Handle<String> key(name);
1555 LOG(ApiNamedPropertyAccess("store", this, name));
1556 CustomArguments args(data->data(), this, JSObject::cast(holder));
1557 v8::AccessorInfo info(args.end());
1558 {
1559 // Leaving JavaScript.
1560 VMState state(EXTERNAL);
1561 call_fun(v8::Utils::ToLocal(key),
1562 v8::Utils::ToLocal(value_handle),
1563 info);
1564 }
1565 RETURN_IF_SCHEDULED_EXCEPTION();
1566 return *value_handle;
1567 }
1568
1569 if (structure->IsFixedArray()) {
1570 Object* setter = FixedArray::cast(structure)->get(kSetterIndex);
1571 if (setter->IsJSFunction()) {
1572 return SetPropertyWithDefinedSetter(JSFunction::cast(setter), value);
1573 } else {
1574 Handle<String> key(name);
1575 Handle<Object> holder_handle(holder);
1576 Handle<Object> args[2] = { key, holder_handle };
1577 return Top::Throw(*Factory::NewTypeError("no_setter_in_callback",
1578 HandleVector(args, 2)));
1579 }
1580 }
1581
1582 UNREACHABLE();
Leon Clarkef7060e22010-06-03 12:02:55 +01001583 return NULL;
Steve Blocka7e24c12009-10-30 11:49:00 +00001584}
1585
1586
1587Object* JSObject::SetPropertyWithDefinedSetter(JSFunction* setter,
1588 Object* value) {
1589 Handle<Object> value_handle(value);
1590 Handle<JSFunction> fun(JSFunction::cast(setter));
1591 Handle<JSObject> self(this);
1592#ifdef ENABLE_DEBUGGER_SUPPORT
1593 // Handle stepping into a setter if step into is active.
1594 if (Debug::StepInActive()) {
1595 Debug::HandleStepIn(fun, Handle<Object>::null(), 0, false);
1596 }
1597#endif
1598 bool has_pending_exception;
1599 Object** argv[] = { value_handle.location() };
1600 Execution::Call(fun, self, 1, argv, &has_pending_exception);
1601 // Check for pending exception and return the result.
1602 if (has_pending_exception) return Failure::Exception();
1603 return *value_handle;
1604}
1605
1606
1607void JSObject::LookupCallbackSetterInPrototypes(String* name,
1608 LookupResult* result) {
1609 for (Object* pt = GetPrototype();
1610 pt != Heap::null_value();
1611 pt = pt->GetPrototype()) {
1612 JSObject::cast(pt)->LocalLookupRealNamedProperty(name, result);
Andrei Popescu402d9372010-02-26 13:31:12 +00001613 if (result->IsProperty()) {
1614 if (result->IsReadOnly()) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001615 result->NotFound();
1616 return;
1617 }
1618 if (result->type() == CALLBACKS) {
1619 return;
1620 }
1621 }
1622 }
1623 result->NotFound();
1624}
1625
1626
Leon Clarkef7060e22010-06-03 12:02:55 +01001627bool JSObject::SetElementWithCallbackSetterInPrototypes(uint32_t index,
1628 Object* value) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001629 for (Object* pt = GetPrototype();
1630 pt != Heap::null_value();
1631 pt = pt->GetPrototype()) {
1632 if (!JSObject::cast(pt)->HasDictionaryElements()) {
1633 continue;
1634 }
1635 NumberDictionary* dictionary = JSObject::cast(pt)->element_dictionary();
1636 int entry = dictionary->FindEntry(index);
1637 if (entry != NumberDictionary::kNotFound) {
1638 Object* element = dictionary->ValueAt(entry);
1639 PropertyDetails details = dictionary->DetailsAt(entry);
1640 if (details.type() == CALLBACKS) {
Leon Clarkef7060e22010-06-03 12:02:55 +01001641 SetElementWithCallback(element, index, value, JSObject::cast(pt));
1642 return true;
Steve Blocka7e24c12009-10-30 11:49:00 +00001643 }
1644 }
1645 }
Leon Clarkef7060e22010-06-03 12:02:55 +01001646 return false;
Steve Blocka7e24c12009-10-30 11:49:00 +00001647}
1648
1649
1650void JSObject::LookupInDescriptor(String* name, LookupResult* result) {
1651 DescriptorArray* descriptors = map()->instance_descriptors();
Iain Merrick75681382010-08-19 15:07:18 +01001652 int number = descriptors->SearchWithCache(name);
Steve Blocka7e24c12009-10-30 11:49:00 +00001653 if (number != DescriptorArray::kNotFound) {
1654 result->DescriptorResult(this, descriptors->GetDetails(number), number);
1655 } else {
1656 result->NotFound();
1657 }
1658}
1659
1660
1661void JSObject::LocalLookupRealNamedProperty(String* name,
1662 LookupResult* result) {
1663 if (IsJSGlobalProxy()) {
1664 Object* proto = GetPrototype();
1665 if (proto->IsNull()) return result->NotFound();
1666 ASSERT(proto->IsJSGlobalObject());
1667 return JSObject::cast(proto)->LocalLookupRealNamedProperty(name, result);
1668 }
1669
1670 if (HasFastProperties()) {
1671 LookupInDescriptor(name, result);
Andrei Popescu402d9372010-02-26 13:31:12 +00001672 if (result->IsFound()) {
1673 // A property, a map transition or a null descriptor was found.
1674 // We return all of these result types because
1675 // LocalLookupRealNamedProperty is used when setting properties
1676 // where map transitions and null descriptors are handled.
Steve Blocka7e24c12009-10-30 11:49:00 +00001677 ASSERT(result->holder() == this && result->type() != NORMAL);
1678 // Disallow caching for uninitialized constants. These can only
1679 // occur as fields.
1680 if (result->IsReadOnly() && result->type() == FIELD &&
1681 FastPropertyAt(result->GetFieldIndex())->IsTheHole()) {
1682 result->DisallowCaching();
1683 }
1684 return;
1685 }
1686 } else {
1687 int entry = property_dictionary()->FindEntry(name);
1688 if (entry != StringDictionary::kNotFound) {
1689 Object* value = property_dictionary()->ValueAt(entry);
1690 if (IsGlobalObject()) {
1691 PropertyDetails d = property_dictionary()->DetailsAt(entry);
1692 if (d.IsDeleted()) {
1693 result->NotFound();
1694 return;
1695 }
1696 value = JSGlobalPropertyCell::cast(value)->value();
Steve Blocka7e24c12009-10-30 11:49:00 +00001697 }
1698 // Make sure to disallow caching for uninitialized constants
1699 // found in the dictionary-mode objects.
1700 if (value->IsTheHole()) result->DisallowCaching();
1701 result->DictionaryResult(this, entry);
1702 return;
1703 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001704 }
1705 result->NotFound();
1706}
1707
1708
1709void JSObject::LookupRealNamedProperty(String* name, LookupResult* result) {
1710 LocalLookupRealNamedProperty(name, result);
1711 if (result->IsProperty()) return;
1712
1713 LookupRealNamedPropertyInPrototypes(name, result);
1714}
1715
1716
1717void JSObject::LookupRealNamedPropertyInPrototypes(String* name,
1718 LookupResult* result) {
1719 for (Object* pt = GetPrototype();
1720 pt != Heap::null_value();
1721 pt = JSObject::cast(pt)->GetPrototype()) {
1722 JSObject::cast(pt)->LocalLookupRealNamedProperty(name, result);
Andrei Popescu402d9372010-02-26 13:31:12 +00001723 if (result->IsProperty() && (result->type() != INTERCEPTOR)) return;
Steve Blocka7e24c12009-10-30 11:49:00 +00001724 }
1725 result->NotFound();
1726}
1727
1728
1729// We only need to deal with CALLBACKS and INTERCEPTORS
1730Object* JSObject::SetPropertyWithFailedAccessCheck(LookupResult* result,
1731 String* name,
1732 Object* value) {
1733 if (!result->IsProperty()) {
1734 LookupCallbackSetterInPrototypes(name, result);
1735 }
1736
1737 if (result->IsProperty()) {
1738 if (!result->IsReadOnly()) {
1739 switch (result->type()) {
1740 case CALLBACKS: {
1741 Object* obj = result->GetCallbackObject();
1742 if (obj->IsAccessorInfo()) {
1743 AccessorInfo* info = AccessorInfo::cast(obj);
1744 if (info->all_can_write()) {
1745 return SetPropertyWithCallback(result->GetCallbackObject(),
1746 name,
1747 value,
1748 result->holder());
1749 }
1750 }
1751 break;
1752 }
1753 case INTERCEPTOR: {
1754 // Try lookup real named properties. Note that only property can be
1755 // set is callbacks marked as ALL_CAN_WRITE on the prototype chain.
1756 LookupResult r;
1757 LookupRealNamedProperty(name, &r);
1758 if (r.IsProperty()) {
1759 return SetPropertyWithFailedAccessCheck(&r, name, value);
1760 }
1761 break;
1762 }
1763 default: {
1764 break;
1765 }
1766 }
1767 }
1768 }
1769
Iain Merrick75681382010-08-19 15:07:18 +01001770 HandleScope scope;
1771 Handle<Object> value_handle(value);
Steve Blocka7e24c12009-10-30 11:49:00 +00001772 Top::ReportFailedAccessCheck(this, v8::ACCESS_SET);
Iain Merrick75681382010-08-19 15:07:18 +01001773 return *value_handle;
Steve Blocka7e24c12009-10-30 11:49:00 +00001774}
1775
1776
1777Object* JSObject::SetProperty(LookupResult* result,
1778 String* name,
1779 Object* value,
1780 PropertyAttributes attributes) {
1781 // Make sure that the top context does not change when doing callbacks or
1782 // interceptor calls.
1783 AssertNoContextChange ncc;
1784
Steve Blockd0582a62009-12-15 09:54:21 +00001785 // Optimization for 2-byte strings often used as keys in a decompression
1786 // dictionary. We make these short keys into symbols to avoid constantly
1787 // reallocating them.
1788 if (!name->IsSymbol() && name->length() <= 2) {
1789 Object* symbol_version = Heap::LookupSymbol(name);
1790 if (!symbol_version->IsFailure()) name = String::cast(symbol_version);
1791 }
1792
Steve Blocka7e24c12009-10-30 11:49:00 +00001793 // Check access rights if needed.
1794 if (IsAccessCheckNeeded()
1795 && !Top::MayNamedAccess(this, name, v8::ACCESS_SET)) {
1796 return SetPropertyWithFailedAccessCheck(result, name, value);
1797 }
1798
1799 if (IsJSGlobalProxy()) {
1800 Object* proto = GetPrototype();
1801 if (proto->IsNull()) return value;
1802 ASSERT(proto->IsJSGlobalObject());
1803 return JSObject::cast(proto)->SetProperty(result, name, value, attributes);
1804 }
1805
1806 if (!result->IsProperty() && !IsJSContextExtensionObject()) {
1807 // We could not find a local property so let's check whether there is an
1808 // accessor that wants to handle the property.
1809 LookupResult accessor_result;
1810 LookupCallbackSetterInPrototypes(name, &accessor_result);
Andrei Popescu402d9372010-02-26 13:31:12 +00001811 if (accessor_result.IsProperty()) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001812 return SetPropertyWithCallback(accessor_result.GetCallbackObject(),
1813 name,
1814 value,
1815 accessor_result.holder());
1816 }
1817 }
Andrei Popescu402d9372010-02-26 13:31:12 +00001818 if (!result->IsFound()) {
1819 // Neither properties nor transitions found.
Steve Blocka7e24c12009-10-30 11:49:00 +00001820 return AddProperty(name, value, attributes);
1821 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001822 if (result->IsReadOnly() && result->IsProperty()) return value;
1823 // This is a real property that is not read-only, or it is a
1824 // transition or null descriptor and there are no setters in the prototypes.
1825 switch (result->type()) {
1826 case NORMAL:
1827 return SetNormalizedProperty(result, value);
1828 case FIELD:
1829 return FastPropertyAtPut(result->GetFieldIndex(), value);
1830 case MAP_TRANSITION:
1831 if (attributes == result->GetAttributes()) {
1832 // Only use map transition if the attributes match.
1833 return AddFastPropertyUsingMap(result->GetTransitionMap(),
1834 name,
1835 value);
1836 }
1837 return ConvertDescriptorToField(name, value, attributes);
1838 case CONSTANT_FUNCTION:
1839 // Only replace the function if necessary.
1840 if (value == result->GetConstantFunction()) return value;
1841 // Preserve the attributes of this existing property.
1842 attributes = result->GetAttributes();
1843 return ConvertDescriptorToField(name, value, attributes);
1844 case CALLBACKS:
1845 return SetPropertyWithCallback(result->GetCallbackObject(),
1846 name,
1847 value,
1848 result->holder());
1849 case INTERCEPTOR:
1850 return SetPropertyWithInterceptor(name, value, attributes);
Iain Merrick75681382010-08-19 15:07:18 +01001851 case CONSTANT_TRANSITION: {
1852 // If the same constant function is being added we can simply
1853 // transition to the target map.
1854 Map* target_map = result->GetTransitionMap();
1855 DescriptorArray* target_descriptors = target_map->instance_descriptors();
1856 int number = target_descriptors->SearchWithCache(name);
1857 ASSERT(number != DescriptorArray::kNotFound);
1858 ASSERT(target_descriptors->GetType(number) == CONSTANT_FUNCTION);
1859 JSFunction* function =
1860 JSFunction::cast(target_descriptors->GetValue(number));
1861 ASSERT(!Heap::InNewSpace(function));
1862 if (value == function) {
1863 set_map(target_map);
1864 return value;
1865 }
1866 // Otherwise, replace with a MAP_TRANSITION to a new map with a
1867 // FIELD, even if the value is a constant function.
Steve Blocka7e24c12009-10-30 11:49:00 +00001868 return ConvertDescriptorToFieldAndMapTransition(name, value, attributes);
Iain Merrick75681382010-08-19 15:07:18 +01001869 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001870 case NULL_DESCRIPTOR:
1871 return ConvertDescriptorToFieldAndMapTransition(name, value, attributes);
1872 default:
1873 UNREACHABLE();
1874 }
1875 UNREACHABLE();
1876 return value;
1877}
1878
1879
1880// Set a real local property, even if it is READ_ONLY. If the property is not
1881// present, add it with attributes NONE. This code is an exact clone of
1882// SetProperty, with the check for IsReadOnly and the check for a
1883// callback setter removed. The two lines looking up the LookupResult
1884// result are also added. If one of the functions is changed, the other
1885// should be.
1886Object* JSObject::IgnoreAttributesAndSetLocalProperty(
1887 String* name,
1888 Object* value,
1889 PropertyAttributes attributes) {
1890 // Make sure that the top context does not change when doing callbacks or
1891 // interceptor calls.
1892 AssertNoContextChange ncc;
Andrei Popescu402d9372010-02-26 13:31:12 +00001893 LookupResult result;
1894 LocalLookup(name, &result);
Steve Blocka7e24c12009-10-30 11:49:00 +00001895 // Check access rights if needed.
1896 if (IsAccessCheckNeeded()
Andrei Popescu402d9372010-02-26 13:31:12 +00001897 && !Top::MayNamedAccess(this, name, v8::ACCESS_SET)) {
1898 return SetPropertyWithFailedAccessCheck(&result, name, value);
Steve Blocka7e24c12009-10-30 11:49:00 +00001899 }
1900
1901 if (IsJSGlobalProxy()) {
1902 Object* proto = GetPrototype();
1903 if (proto->IsNull()) return value;
1904 ASSERT(proto->IsJSGlobalObject());
1905 return JSObject::cast(proto)->IgnoreAttributesAndSetLocalProperty(
1906 name,
1907 value,
1908 attributes);
1909 }
1910
1911 // Check for accessor in prototype chain removed here in clone.
Andrei Popescu402d9372010-02-26 13:31:12 +00001912 if (!result.IsFound()) {
1913 // Neither properties nor transitions found.
Steve Blocka7e24c12009-10-30 11:49:00 +00001914 return AddProperty(name, value, attributes);
1915 }
Steve Block6ded16b2010-05-10 14:33:55 +01001916
Andrei Popescu402d9372010-02-26 13:31:12 +00001917 PropertyDetails details = PropertyDetails(attributes, NORMAL);
1918
Steve Blocka7e24c12009-10-30 11:49:00 +00001919 // Check of IsReadOnly removed from here in clone.
Andrei Popescu402d9372010-02-26 13:31:12 +00001920 switch (result.type()) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001921 case NORMAL:
Andrei Popescu402d9372010-02-26 13:31:12 +00001922 return SetNormalizedProperty(name, value, details);
Steve Blocka7e24c12009-10-30 11:49:00 +00001923 case FIELD:
Andrei Popescu402d9372010-02-26 13:31:12 +00001924 return FastPropertyAtPut(result.GetFieldIndex(), value);
Steve Blocka7e24c12009-10-30 11:49:00 +00001925 case MAP_TRANSITION:
Andrei Popescu402d9372010-02-26 13:31:12 +00001926 if (attributes == result.GetAttributes()) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001927 // Only use map transition if the attributes match.
Andrei Popescu402d9372010-02-26 13:31:12 +00001928 return AddFastPropertyUsingMap(result.GetTransitionMap(),
Steve Blocka7e24c12009-10-30 11:49:00 +00001929 name,
1930 value);
1931 }
1932 return ConvertDescriptorToField(name, value, attributes);
1933 case CONSTANT_FUNCTION:
1934 // Only replace the function if necessary.
Andrei Popescu402d9372010-02-26 13:31:12 +00001935 if (value == result.GetConstantFunction()) return value;
Steve Blocka7e24c12009-10-30 11:49:00 +00001936 // Preserve the attributes of this existing property.
Andrei Popescu402d9372010-02-26 13:31:12 +00001937 attributes = result.GetAttributes();
Steve Blocka7e24c12009-10-30 11:49:00 +00001938 return ConvertDescriptorToField(name, value, attributes);
1939 case CALLBACKS:
1940 case INTERCEPTOR:
1941 // Override callback in clone
1942 return ConvertDescriptorToField(name, value, attributes);
1943 case CONSTANT_TRANSITION:
1944 // Replace with a MAP_TRANSITION to a new map with a FIELD, even
1945 // if the value is a function.
1946 return ConvertDescriptorToFieldAndMapTransition(name, value, attributes);
1947 case NULL_DESCRIPTOR:
1948 return ConvertDescriptorToFieldAndMapTransition(name, value, attributes);
1949 default:
1950 UNREACHABLE();
1951 }
1952 UNREACHABLE();
1953 return value;
1954}
1955
1956
1957PropertyAttributes JSObject::GetPropertyAttributePostInterceptor(
1958 JSObject* receiver,
1959 String* name,
1960 bool continue_search) {
1961 // Check local property, ignore interceptor.
1962 LookupResult result;
1963 LocalLookupRealNamedProperty(name, &result);
1964 if (result.IsProperty()) return result.GetAttributes();
1965
1966 if (continue_search) {
1967 // Continue searching via the prototype chain.
1968 Object* pt = GetPrototype();
1969 if (pt != Heap::null_value()) {
1970 return JSObject::cast(pt)->
1971 GetPropertyAttributeWithReceiver(receiver, name);
1972 }
1973 }
1974 return ABSENT;
1975}
1976
1977
1978PropertyAttributes JSObject::GetPropertyAttributeWithInterceptor(
1979 JSObject* receiver,
1980 String* name,
1981 bool continue_search) {
1982 // Make sure that the top context does not change when doing
1983 // callbacks or interceptor calls.
1984 AssertNoContextChange ncc;
1985
1986 HandleScope scope;
1987 Handle<InterceptorInfo> interceptor(GetNamedInterceptor());
1988 Handle<JSObject> receiver_handle(receiver);
1989 Handle<JSObject> holder_handle(this);
1990 Handle<String> name_handle(name);
1991 CustomArguments args(interceptor->data(), receiver, this);
1992 v8::AccessorInfo info(args.end());
1993 if (!interceptor->query()->IsUndefined()) {
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01001994 v8::NamedPropertyQuery query =
1995 v8::ToCData<v8::NamedPropertyQuery>(interceptor->query());
Steve Blocka7e24c12009-10-30 11:49:00 +00001996 LOG(ApiNamedPropertyAccess("interceptor-named-has", *holder_handle, name));
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01001997 v8::Handle<v8::Integer> result;
Steve Blocka7e24c12009-10-30 11:49:00 +00001998 {
1999 // Leaving JavaScript.
2000 VMState state(EXTERNAL);
2001 result = query(v8::Utils::ToLocal(name_handle), info);
2002 }
2003 if (!result.IsEmpty()) {
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01002004 ASSERT(result->IsInt32());
2005 return static_cast<PropertyAttributes>(result->Int32Value());
Steve Blocka7e24c12009-10-30 11:49:00 +00002006 }
2007 } else if (!interceptor->getter()->IsUndefined()) {
2008 v8::NamedPropertyGetter getter =
2009 v8::ToCData<v8::NamedPropertyGetter>(interceptor->getter());
2010 LOG(ApiNamedPropertyAccess("interceptor-named-get-has", this, name));
2011 v8::Handle<v8::Value> result;
2012 {
2013 // Leaving JavaScript.
2014 VMState state(EXTERNAL);
2015 result = getter(v8::Utils::ToLocal(name_handle), info);
2016 }
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01002017 if (!result.IsEmpty()) return DONT_ENUM;
Steve Blocka7e24c12009-10-30 11:49:00 +00002018 }
2019 return holder_handle->GetPropertyAttributePostInterceptor(*receiver_handle,
2020 *name_handle,
2021 continue_search);
2022}
2023
2024
2025PropertyAttributes JSObject::GetPropertyAttributeWithReceiver(
2026 JSObject* receiver,
2027 String* key) {
2028 uint32_t index = 0;
2029 if (key->AsArrayIndex(&index)) {
2030 if (HasElementWithReceiver(receiver, index)) return NONE;
2031 return ABSENT;
2032 }
2033 // Named property.
2034 LookupResult result;
2035 Lookup(key, &result);
2036 return GetPropertyAttribute(receiver, &result, key, true);
2037}
2038
2039
2040PropertyAttributes JSObject::GetPropertyAttribute(JSObject* receiver,
2041 LookupResult* result,
2042 String* name,
2043 bool continue_search) {
2044 // Check access rights if needed.
2045 if (IsAccessCheckNeeded() &&
2046 !Top::MayNamedAccess(this, name, v8::ACCESS_HAS)) {
2047 return GetPropertyAttributeWithFailedAccessCheck(receiver,
2048 result,
2049 name,
2050 continue_search);
2051 }
Andrei Popescu402d9372010-02-26 13:31:12 +00002052 if (result->IsProperty()) {
Steve Blocka7e24c12009-10-30 11:49:00 +00002053 switch (result->type()) {
2054 case NORMAL: // fall through
2055 case FIELD:
2056 case CONSTANT_FUNCTION:
2057 case CALLBACKS:
2058 return result->GetAttributes();
2059 case INTERCEPTOR:
2060 return result->holder()->
2061 GetPropertyAttributeWithInterceptor(receiver, name, continue_search);
Steve Blocka7e24c12009-10-30 11:49:00 +00002062 default:
2063 UNREACHABLE();
Steve Blocka7e24c12009-10-30 11:49:00 +00002064 }
2065 }
2066 return ABSENT;
2067}
2068
2069
2070PropertyAttributes JSObject::GetLocalPropertyAttribute(String* name) {
2071 // Check whether the name is an array index.
2072 uint32_t index = 0;
2073 if (name->AsArrayIndex(&index)) {
2074 if (HasLocalElement(index)) return NONE;
2075 return ABSENT;
2076 }
2077 // Named property.
2078 LookupResult result;
2079 LocalLookup(name, &result);
2080 return GetPropertyAttribute(this, &result, name, false);
2081}
2082
2083
Kristian Monsen80d68ea2010-09-08 11:05:35 +01002084Object* NormalizedMapCache::Get(JSObject* obj, PropertyNormalizationMode mode) {
Kristian Monsen80d68ea2010-09-08 11:05:35 +01002085 Map* fast = obj->map();
Kristian Monsen0d5e1162010-09-30 15:31:59 +01002086 int index = Hash(fast) % kEntries;
2087 Object* result = get(index);
2088 if (result->IsMap() && CheckHit(Map::cast(result), fast, mode)) {
Kristian Monsen80d68ea2010-09-08 11:05:35 +01002089#ifdef DEBUG
Kristian Monsen0d5e1162010-09-30 15:31:59 +01002090 if (FLAG_enable_slow_asserts) {
2091 // The cached map should match newly created normalized map bit-by-bit.
2092 Object* fresh = fast->CopyNormalized(mode, SHARED_NORMALIZED_MAP);
2093 if (!fresh->IsFailure()) {
2094 ASSERT(memcmp(Map::cast(fresh)->address(),
2095 Map::cast(result)->address(),
2096 Map::kSize) == 0);
Kristian Monsen80d68ea2010-09-08 11:05:35 +01002097 }
Kristian Monsen80d68ea2010-09-08 11:05:35 +01002098 }
Kristian Monsen0d5e1162010-09-30 15:31:59 +01002099#endif
2100 return result;
Kristian Monsen80d68ea2010-09-08 11:05:35 +01002101 }
Kristian Monsen0d5e1162010-09-30 15:31:59 +01002102
2103 result = fast->CopyNormalized(mode, SHARED_NORMALIZED_MAP);
2104 if (result->IsFailure()) return result;
2105 set(index, result);
Kristian Monsen80d68ea2010-09-08 11:05:35 +01002106 Counters::normalized_maps.Increment();
2107
2108 return result;
2109}
2110
2111
Kristian Monsen80d68ea2010-09-08 11:05:35 +01002112void NormalizedMapCache::Clear() {
2113 int entries = length();
2114 for (int i = 0; i != entries; i++) {
2115 set_undefined(i);
2116 }
2117}
2118
2119
2120int NormalizedMapCache::Hash(Map* fast) {
2121 // For performance reasons we only hash the 3 most variable fields of a map:
2122 // constructor, prototype and bit_field2.
2123
2124 // Shift away the tag.
2125 int hash = (static_cast<uint32_t>(
2126 reinterpret_cast<uintptr_t>(fast->constructor())) >> 2);
2127
2128 // XOR-ing the prototype and constructor directly yields too many zero bits
2129 // when the two pointers are close (which is fairly common).
2130 // To avoid this we shift the prototype 4 bits relatively to the constructor.
2131 hash ^= (static_cast<uint32_t>(
2132 reinterpret_cast<uintptr_t>(fast->prototype())) << 2);
2133
2134 return hash ^ (hash >> 16) ^ fast->bit_field2();
2135}
2136
2137
2138bool NormalizedMapCache::CheckHit(Map* slow,
2139 Map* fast,
2140 PropertyNormalizationMode mode) {
2141#ifdef DEBUG
Kristian Monsen0d5e1162010-09-30 15:31:59 +01002142 slow->SharedMapVerify();
Kristian Monsen80d68ea2010-09-08 11:05:35 +01002143#endif
2144 return
2145 slow->constructor() == fast->constructor() &&
2146 slow->prototype() == fast->prototype() &&
2147 slow->inobject_properties() == ((mode == CLEAR_INOBJECT_PROPERTIES) ?
2148 0 :
2149 fast->inobject_properties()) &&
2150 slow->instance_type() == fast->instance_type() &&
2151 slow->bit_field() == fast->bit_field() &&
Kristian Monsen0d5e1162010-09-30 15:31:59 +01002152 (slow->bit_field2() & ~(1<<Map::kIsShared)) == fast->bit_field2();
Kristian Monsen80d68ea2010-09-08 11:05:35 +01002153}
2154
2155
2156Object* JSObject::UpdateMapCodeCache(String* name, Code* code) {
Kristian Monsen0d5e1162010-09-30 15:31:59 +01002157 if (map()->is_shared()) {
2158 // Fast case maps are never marked as shared.
2159 ASSERT(!HasFastProperties());
2160 // Replace the map with an identical copy that can be safely modified.
2161 Object* obj = map()->CopyNormalized(KEEP_INOBJECT_PROPERTIES,
2162 UNIQUE_NORMALIZED_MAP);
Kristian Monsen80d68ea2010-09-08 11:05:35 +01002163 if (obj->IsFailure()) return obj;
2164 Counters::normalized_maps.Increment();
2165
2166 set_map(Map::cast(obj));
2167 }
2168 return map()->UpdateCodeCache(name, code);
2169}
2170
2171
Steve Blocka7e24c12009-10-30 11:49:00 +00002172Object* JSObject::NormalizeProperties(PropertyNormalizationMode mode,
2173 int expected_additional_properties) {
2174 if (!HasFastProperties()) return this;
2175
2176 // The global object is always normalized.
2177 ASSERT(!IsGlobalObject());
2178
2179 // Allocate new content.
2180 int property_count = map()->NumberOfDescribedProperties();
2181 if (expected_additional_properties > 0) {
2182 property_count += expected_additional_properties;
2183 } else {
2184 property_count += 2; // Make space for two more properties.
2185 }
2186 Object* obj =
Steve Block6ded16b2010-05-10 14:33:55 +01002187 StringDictionary::Allocate(property_count);
Steve Blocka7e24c12009-10-30 11:49:00 +00002188 if (obj->IsFailure()) return obj;
2189 StringDictionary* dictionary = StringDictionary::cast(obj);
2190
2191 DescriptorArray* descs = map()->instance_descriptors();
2192 for (int i = 0; i < descs->number_of_descriptors(); i++) {
2193 PropertyDetails details = descs->GetDetails(i);
2194 switch (details.type()) {
2195 case CONSTANT_FUNCTION: {
2196 PropertyDetails d =
2197 PropertyDetails(details.attributes(), NORMAL, details.index());
2198 Object* value = descs->GetConstantFunction(i);
2199 Object* result = dictionary->Add(descs->GetKey(i), value, d);
2200 if (result->IsFailure()) return result;
2201 dictionary = StringDictionary::cast(result);
2202 break;
2203 }
2204 case FIELD: {
2205 PropertyDetails d =
2206 PropertyDetails(details.attributes(), NORMAL, details.index());
2207 Object* value = FastPropertyAt(descs->GetFieldIndex(i));
2208 Object* result = dictionary->Add(descs->GetKey(i), value, d);
2209 if (result->IsFailure()) return result;
2210 dictionary = StringDictionary::cast(result);
2211 break;
2212 }
2213 case CALLBACKS: {
2214 PropertyDetails d =
2215 PropertyDetails(details.attributes(), CALLBACKS, details.index());
2216 Object* value = descs->GetCallbacksObject(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 MAP_TRANSITION:
2223 case CONSTANT_TRANSITION:
2224 case NULL_DESCRIPTOR:
2225 case INTERCEPTOR:
2226 break;
2227 default:
2228 UNREACHABLE();
2229 }
2230 }
2231
2232 // Copy the next enumeration index from instance descriptor.
2233 int index = map()->instance_descriptors()->NextEnumerationIndex();
2234 dictionary->SetNextEnumerationIndex(index);
2235
Kristian Monsen80d68ea2010-09-08 11:05:35 +01002236 obj = Top::context()->global_context()->
2237 normalized_map_cache()->Get(this, mode);
Steve Blocka7e24c12009-10-30 11:49:00 +00002238 if (obj->IsFailure()) return obj;
2239 Map* new_map = Map::cast(obj);
2240
Steve Blocka7e24c12009-10-30 11:49:00 +00002241 // We have now successfully allocated all the necessary objects.
2242 // Changes can now be made with the guarantee that all of them take effect.
Kristian Monsen80d68ea2010-09-08 11:05:35 +01002243
2244 // Resize the object in the heap if necessary.
2245 int new_instance_size = new_map->instance_size();
2246 int instance_size_delta = map()->instance_size() - new_instance_size;
2247 ASSERT(instance_size_delta >= 0);
2248 Heap::CreateFillerObjectAt(this->address() + new_instance_size,
2249 instance_size_delta);
2250
Steve Blocka7e24c12009-10-30 11:49:00 +00002251 set_map(new_map);
Steve Blocka7e24c12009-10-30 11:49:00 +00002252
2253 set_properties(dictionary);
2254
2255 Counters::props_to_dictionary.Increment();
2256
2257#ifdef DEBUG
2258 if (FLAG_trace_normalization) {
2259 PrintF("Object properties have been normalized:\n");
2260 Print();
2261 }
2262#endif
2263 return this;
2264}
2265
2266
2267Object* JSObject::TransformToFastProperties(int unused_property_fields) {
2268 if (HasFastProperties()) return this;
2269 ASSERT(!IsGlobalObject());
2270 return property_dictionary()->
2271 TransformPropertiesToFastFor(this, unused_property_fields);
2272}
2273
2274
2275Object* JSObject::NormalizeElements() {
Steve Block3ce2e202009-11-05 08:53:23 +00002276 ASSERT(!HasPixelElements() && !HasExternalArrayElements());
Steve Blocka7e24c12009-10-30 11:49:00 +00002277 if (HasDictionaryElements()) return this;
Steve Block8defd9f2010-07-08 12:39:36 +01002278 ASSERT(map()->has_fast_elements());
2279
2280 Object* obj = map()->GetSlowElementsMap();
2281 if (obj->IsFailure()) return obj;
2282 Map* new_map = Map::cast(obj);
Steve Blocka7e24c12009-10-30 11:49:00 +00002283
2284 // Get number of entries.
2285 FixedArray* array = FixedArray::cast(elements());
2286
2287 // Compute the effective length.
2288 int length = IsJSArray() ?
2289 Smi::cast(JSArray::cast(this)->length())->value() :
2290 array->length();
Steve Block8defd9f2010-07-08 12:39:36 +01002291 obj = NumberDictionary::Allocate(length);
Steve Blocka7e24c12009-10-30 11:49:00 +00002292 if (obj->IsFailure()) return obj;
2293 NumberDictionary* dictionary = NumberDictionary::cast(obj);
2294 // Copy entries.
2295 for (int i = 0; i < length; i++) {
2296 Object* value = array->get(i);
2297 if (!value->IsTheHole()) {
2298 PropertyDetails details = PropertyDetails(NONE, NORMAL);
2299 Object* result = dictionary->AddNumberEntry(i, array->get(i), details);
2300 if (result->IsFailure()) return result;
2301 dictionary = NumberDictionary::cast(result);
2302 }
2303 }
Steve Block8defd9f2010-07-08 12:39:36 +01002304 // Switch to using the dictionary as the backing storage for
2305 // elements. Set the new map first to satify the elements type
2306 // assert in set_elements().
2307 set_map(new_map);
Steve Blocka7e24c12009-10-30 11:49:00 +00002308 set_elements(dictionary);
2309
2310 Counters::elements_to_dictionary.Increment();
2311
2312#ifdef DEBUG
2313 if (FLAG_trace_normalization) {
2314 PrintF("Object elements have been normalized:\n");
2315 Print();
2316 }
2317#endif
2318
2319 return this;
2320}
2321
2322
2323Object* JSObject::DeletePropertyPostInterceptor(String* name, DeleteMode mode) {
2324 // Check local property, ignore interceptor.
2325 LookupResult result;
2326 LocalLookupRealNamedProperty(name, &result);
Andrei Popescu402d9372010-02-26 13:31:12 +00002327 if (!result.IsProperty()) return Heap::true_value();
Steve Blocka7e24c12009-10-30 11:49:00 +00002328
2329 // Normalize object if needed.
2330 Object* obj = NormalizeProperties(CLEAR_INOBJECT_PROPERTIES, 0);
2331 if (obj->IsFailure()) return obj;
2332
2333 return DeleteNormalizedProperty(name, mode);
2334}
2335
2336
2337Object* JSObject::DeletePropertyWithInterceptor(String* name) {
2338 HandleScope scope;
2339 Handle<InterceptorInfo> interceptor(GetNamedInterceptor());
2340 Handle<String> name_handle(name);
2341 Handle<JSObject> this_handle(this);
2342 if (!interceptor->deleter()->IsUndefined()) {
2343 v8::NamedPropertyDeleter deleter =
2344 v8::ToCData<v8::NamedPropertyDeleter>(interceptor->deleter());
2345 LOG(ApiNamedPropertyAccess("interceptor-named-delete", *this_handle, name));
2346 CustomArguments args(interceptor->data(), this, this);
2347 v8::AccessorInfo info(args.end());
2348 v8::Handle<v8::Boolean> result;
2349 {
2350 // Leaving JavaScript.
2351 VMState state(EXTERNAL);
2352 result = deleter(v8::Utils::ToLocal(name_handle), info);
2353 }
2354 RETURN_IF_SCHEDULED_EXCEPTION();
2355 if (!result.IsEmpty()) {
2356 ASSERT(result->IsBoolean());
2357 return *v8::Utils::OpenHandle(*result);
2358 }
2359 }
2360 Object* raw_result =
2361 this_handle->DeletePropertyPostInterceptor(*name_handle, NORMAL_DELETION);
2362 RETURN_IF_SCHEDULED_EXCEPTION();
2363 return raw_result;
2364}
2365
2366
2367Object* JSObject::DeleteElementPostInterceptor(uint32_t index,
2368 DeleteMode mode) {
Steve Block3ce2e202009-11-05 08:53:23 +00002369 ASSERT(!HasPixelElements() && !HasExternalArrayElements());
Steve Blocka7e24c12009-10-30 11:49:00 +00002370 switch (GetElementsKind()) {
2371 case FAST_ELEMENTS: {
Iain Merrick75681382010-08-19 15:07:18 +01002372 Object* obj = EnsureWritableFastElements();
2373 if (obj->IsFailure()) return obj;
Steve Blocka7e24c12009-10-30 11:49:00 +00002374 uint32_t length = IsJSArray() ?
2375 static_cast<uint32_t>(Smi::cast(JSArray::cast(this)->length())->value()) :
2376 static_cast<uint32_t>(FixedArray::cast(elements())->length());
2377 if (index < length) {
2378 FixedArray::cast(elements())->set_the_hole(index);
2379 }
2380 break;
2381 }
2382 case DICTIONARY_ELEMENTS: {
2383 NumberDictionary* dictionary = element_dictionary();
2384 int entry = dictionary->FindEntry(index);
2385 if (entry != NumberDictionary::kNotFound) {
2386 return dictionary->DeleteProperty(entry, mode);
2387 }
2388 break;
2389 }
2390 default:
2391 UNREACHABLE();
2392 break;
2393 }
2394 return Heap::true_value();
2395}
2396
2397
2398Object* JSObject::DeleteElementWithInterceptor(uint32_t index) {
2399 // Make sure that the top context does not change when doing
2400 // callbacks or interceptor calls.
2401 AssertNoContextChange ncc;
2402 HandleScope scope;
2403 Handle<InterceptorInfo> interceptor(GetIndexedInterceptor());
2404 if (interceptor->deleter()->IsUndefined()) return Heap::false_value();
2405 v8::IndexedPropertyDeleter deleter =
2406 v8::ToCData<v8::IndexedPropertyDeleter>(interceptor->deleter());
2407 Handle<JSObject> this_handle(this);
2408 LOG(ApiIndexedPropertyAccess("interceptor-indexed-delete", this, index));
2409 CustomArguments args(interceptor->data(), this, this);
2410 v8::AccessorInfo info(args.end());
2411 v8::Handle<v8::Boolean> result;
2412 {
2413 // Leaving JavaScript.
2414 VMState state(EXTERNAL);
2415 result = deleter(index, info);
2416 }
2417 RETURN_IF_SCHEDULED_EXCEPTION();
2418 if (!result.IsEmpty()) {
2419 ASSERT(result->IsBoolean());
2420 return *v8::Utils::OpenHandle(*result);
2421 }
2422 Object* raw_result =
2423 this_handle->DeleteElementPostInterceptor(index, NORMAL_DELETION);
2424 RETURN_IF_SCHEDULED_EXCEPTION();
2425 return raw_result;
2426}
2427
2428
2429Object* JSObject::DeleteElement(uint32_t index, DeleteMode mode) {
2430 // Check access rights if needed.
2431 if (IsAccessCheckNeeded() &&
2432 !Top::MayIndexedAccess(this, index, v8::ACCESS_DELETE)) {
2433 Top::ReportFailedAccessCheck(this, v8::ACCESS_DELETE);
2434 return Heap::false_value();
2435 }
2436
2437 if (IsJSGlobalProxy()) {
2438 Object* proto = GetPrototype();
2439 if (proto->IsNull()) return Heap::false_value();
2440 ASSERT(proto->IsJSGlobalObject());
2441 return JSGlobalObject::cast(proto)->DeleteElement(index, mode);
2442 }
2443
2444 if (HasIndexedInterceptor()) {
2445 // Skip interceptor if forcing deletion.
2446 if (mode == FORCE_DELETION) {
2447 return DeleteElementPostInterceptor(index, mode);
2448 }
2449 return DeleteElementWithInterceptor(index);
2450 }
2451
2452 switch (GetElementsKind()) {
2453 case FAST_ELEMENTS: {
Iain Merrick75681382010-08-19 15:07:18 +01002454 Object* obj = EnsureWritableFastElements();
2455 if (obj->IsFailure()) return obj;
Steve Blocka7e24c12009-10-30 11:49:00 +00002456 uint32_t length = IsJSArray() ?
2457 static_cast<uint32_t>(Smi::cast(JSArray::cast(this)->length())->value()) :
2458 static_cast<uint32_t>(FixedArray::cast(elements())->length());
2459 if (index < length) {
2460 FixedArray::cast(elements())->set_the_hole(index);
2461 }
2462 break;
2463 }
Steve Block3ce2e202009-11-05 08:53:23 +00002464 case PIXEL_ELEMENTS:
2465 case EXTERNAL_BYTE_ELEMENTS:
2466 case EXTERNAL_UNSIGNED_BYTE_ELEMENTS:
2467 case EXTERNAL_SHORT_ELEMENTS:
2468 case EXTERNAL_UNSIGNED_SHORT_ELEMENTS:
2469 case EXTERNAL_INT_ELEMENTS:
2470 case EXTERNAL_UNSIGNED_INT_ELEMENTS:
2471 case EXTERNAL_FLOAT_ELEMENTS:
2472 // Pixel and external array elements cannot be deleted. Just
2473 // silently ignore here.
Steve Blocka7e24c12009-10-30 11:49:00 +00002474 break;
Steve Blocka7e24c12009-10-30 11:49:00 +00002475 case DICTIONARY_ELEMENTS: {
2476 NumberDictionary* dictionary = element_dictionary();
2477 int entry = dictionary->FindEntry(index);
2478 if (entry != NumberDictionary::kNotFound) {
2479 return dictionary->DeleteProperty(entry, mode);
2480 }
2481 break;
2482 }
2483 default:
2484 UNREACHABLE();
2485 break;
2486 }
2487 return Heap::true_value();
2488}
2489
2490
2491Object* JSObject::DeleteProperty(String* name, DeleteMode mode) {
2492 // ECMA-262, 3rd, 8.6.2.5
2493 ASSERT(name->IsString());
2494
2495 // Check access rights if needed.
2496 if (IsAccessCheckNeeded() &&
2497 !Top::MayNamedAccess(this, name, v8::ACCESS_DELETE)) {
2498 Top::ReportFailedAccessCheck(this, v8::ACCESS_DELETE);
2499 return Heap::false_value();
2500 }
2501
2502 if (IsJSGlobalProxy()) {
2503 Object* proto = GetPrototype();
2504 if (proto->IsNull()) return Heap::false_value();
2505 ASSERT(proto->IsJSGlobalObject());
2506 return JSGlobalObject::cast(proto)->DeleteProperty(name, mode);
2507 }
2508
2509 uint32_t index = 0;
2510 if (name->AsArrayIndex(&index)) {
2511 return DeleteElement(index, mode);
2512 } else {
2513 LookupResult result;
2514 LocalLookup(name, &result);
Andrei Popescu402d9372010-02-26 13:31:12 +00002515 if (!result.IsProperty()) return Heap::true_value();
Steve Blocka7e24c12009-10-30 11:49:00 +00002516 // Ignore attributes if forcing a deletion.
2517 if (result.IsDontDelete() && mode != FORCE_DELETION) {
2518 return Heap::false_value();
2519 }
2520 // Check for interceptor.
2521 if (result.type() == INTERCEPTOR) {
2522 // Skip interceptor if forcing a deletion.
2523 if (mode == FORCE_DELETION) {
2524 return DeletePropertyPostInterceptor(name, mode);
2525 }
2526 return DeletePropertyWithInterceptor(name);
2527 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002528 // Normalize object if needed.
2529 Object* obj = NormalizeProperties(CLEAR_INOBJECT_PROPERTIES, 0);
2530 if (obj->IsFailure()) return obj;
2531 // Make sure the properties are normalized before removing the entry.
2532 return DeleteNormalizedProperty(name, mode);
2533 }
2534}
2535
2536
2537// Check whether this object references another object.
2538bool JSObject::ReferencesObject(Object* obj) {
2539 AssertNoAllocation no_alloc;
2540
2541 // Is the object the constructor for this object?
2542 if (map()->constructor() == obj) {
2543 return true;
2544 }
2545
2546 // Is the object the prototype for this object?
2547 if (map()->prototype() == obj) {
2548 return true;
2549 }
2550
2551 // Check if the object is among the named properties.
2552 Object* key = SlowReverseLookup(obj);
2553 if (key != Heap::undefined_value()) {
2554 return true;
2555 }
2556
2557 // Check if the object is among the indexed properties.
2558 switch (GetElementsKind()) {
2559 case PIXEL_ELEMENTS:
Steve Block3ce2e202009-11-05 08:53:23 +00002560 case EXTERNAL_BYTE_ELEMENTS:
2561 case EXTERNAL_UNSIGNED_BYTE_ELEMENTS:
2562 case EXTERNAL_SHORT_ELEMENTS:
2563 case EXTERNAL_UNSIGNED_SHORT_ELEMENTS:
2564 case EXTERNAL_INT_ELEMENTS:
2565 case EXTERNAL_UNSIGNED_INT_ELEMENTS:
2566 case EXTERNAL_FLOAT_ELEMENTS:
2567 // Raw pixels and external arrays do not reference other
2568 // objects.
Steve Blocka7e24c12009-10-30 11:49:00 +00002569 break;
2570 case FAST_ELEMENTS: {
2571 int length = IsJSArray() ?
2572 Smi::cast(JSArray::cast(this)->length())->value() :
2573 FixedArray::cast(elements())->length();
2574 for (int i = 0; i < length; i++) {
2575 Object* element = FixedArray::cast(elements())->get(i);
2576 if (!element->IsTheHole() && element == obj) {
2577 return true;
2578 }
2579 }
2580 break;
2581 }
2582 case DICTIONARY_ELEMENTS: {
2583 key = element_dictionary()->SlowReverseLookup(obj);
2584 if (key != Heap::undefined_value()) {
2585 return true;
2586 }
2587 break;
2588 }
2589 default:
2590 UNREACHABLE();
2591 break;
2592 }
2593
Steve Block6ded16b2010-05-10 14:33:55 +01002594 // For functions check the context.
2595 if (IsJSFunction()) {
Steve Blocka7e24c12009-10-30 11:49:00 +00002596 // Get the constructor function for arguments array.
2597 JSObject* arguments_boilerplate =
2598 Top::context()->global_context()->arguments_boilerplate();
2599 JSFunction* arguments_function =
2600 JSFunction::cast(arguments_boilerplate->map()->constructor());
2601
2602 // Get the context and don't check if it is the global context.
2603 JSFunction* f = JSFunction::cast(this);
2604 Context* context = f->context();
2605 if (context->IsGlobalContext()) {
2606 return false;
2607 }
2608
2609 // Check the non-special context slots.
2610 for (int i = Context::MIN_CONTEXT_SLOTS; i < context->length(); i++) {
2611 // Only check JS objects.
2612 if (context->get(i)->IsJSObject()) {
2613 JSObject* ctxobj = JSObject::cast(context->get(i));
2614 // If it is an arguments array check the content.
2615 if (ctxobj->map()->constructor() == arguments_function) {
2616 if (ctxobj->ReferencesObject(obj)) {
2617 return true;
2618 }
2619 } else if (ctxobj == obj) {
2620 return true;
2621 }
2622 }
2623 }
2624
2625 // Check the context extension if any.
2626 if (context->has_extension()) {
2627 return context->extension()->ReferencesObject(obj);
2628 }
2629 }
2630
2631 // No references to object.
2632 return false;
2633}
2634
2635
Steve Block8defd9f2010-07-08 12:39:36 +01002636Object* JSObject::PreventExtensions() {
2637 // If there are fast elements we normalize.
2638 if (HasFastElements()) {
Kristian Monsen80d68ea2010-09-08 11:05:35 +01002639 Object* ok = NormalizeElements();
2640 if (ok->IsFailure()) return ok;
Steve Block8defd9f2010-07-08 12:39:36 +01002641 }
2642 // Make sure that we never go back to fast case.
2643 element_dictionary()->set_requires_slow_elements();
2644
2645 // Do a map transition, other objects with this map may still
2646 // be extensible.
2647 Object* new_map = map()->CopyDropTransitions();
2648 if (new_map->IsFailure()) return new_map;
2649 Map::cast(new_map)->set_is_extensible(false);
2650 set_map(Map::cast(new_map));
2651 ASSERT(!map()->is_extensible());
2652 return new_map;
2653}
2654
2655
Steve Blocka7e24c12009-10-30 11:49:00 +00002656// Tests for the fast common case for property enumeration:
Steve Blockd0582a62009-12-15 09:54:21 +00002657// - This object and all prototypes has an enum cache (which means that it has
2658// no interceptors and needs no access checks).
2659// - This object has no elements.
2660// - No prototype has enumerable properties/elements.
Steve Blocka7e24c12009-10-30 11:49:00 +00002661bool JSObject::IsSimpleEnum() {
Steve Blocka7e24c12009-10-30 11:49:00 +00002662 for (Object* o = this;
2663 o != Heap::null_value();
2664 o = JSObject::cast(o)->GetPrototype()) {
2665 JSObject* curr = JSObject::cast(o);
Steve Blocka7e24c12009-10-30 11:49:00 +00002666 if (!curr->map()->instance_descriptors()->HasEnumCache()) return false;
Steve Blockd0582a62009-12-15 09:54:21 +00002667 ASSERT(!curr->HasNamedInterceptor());
2668 ASSERT(!curr->HasIndexedInterceptor());
2669 ASSERT(!curr->IsAccessCheckNeeded());
Steve Blocka7e24c12009-10-30 11:49:00 +00002670 if (curr->NumberOfEnumElements() > 0) return false;
Steve Blocka7e24c12009-10-30 11:49:00 +00002671 if (curr != this) {
2672 FixedArray* curr_fixed_array =
2673 FixedArray::cast(curr->map()->instance_descriptors()->GetEnumCache());
Steve Blockd0582a62009-12-15 09:54:21 +00002674 if (curr_fixed_array->length() > 0) return false;
Steve Blocka7e24c12009-10-30 11:49:00 +00002675 }
2676 }
2677 return true;
2678}
2679
2680
2681int Map::NumberOfDescribedProperties() {
2682 int result = 0;
2683 DescriptorArray* descs = instance_descriptors();
2684 for (int i = 0; i < descs->number_of_descriptors(); i++) {
2685 if (descs->IsProperty(i)) result++;
2686 }
2687 return result;
2688}
2689
2690
2691int Map::PropertyIndexFor(String* name) {
2692 DescriptorArray* descs = instance_descriptors();
2693 for (int i = 0; i < descs->number_of_descriptors(); i++) {
2694 if (name->Equals(descs->GetKey(i)) && !descs->IsNullDescriptor(i)) {
2695 return descs->GetFieldIndex(i);
2696 }
2697 }
2698 return -1;
2699}
2700
2701
2702int Map::NextFreePropertyIndex() {
2703 int max_index = -1;
2704 DescriptorArray* descs = instance_descriptors();
2705 for (int i = 0; i < descs->number_of_descriptors(); i++) {
2706 if (descs->GetType(i) == FIELD) {
2707 int current_index = descs->GetFieldIndex(i);
2708 if (current_index > max_index) max_index = current_index;
2709 }
2710 }
2711 return max_index + 1;
2712}
2713
2714
2715AccessorDescriptor* Map::FindAccessor(String* name) {
2716 DescriptorArray* descs = instance_descriptors();
2717 for (int i = 0; i < descs->number_of_descriptors(); i++) {
2718 if (name->Equals(descs->GetKey(i)) && descs->GetType(i) == CALLBACKS) {
2719 return descs->GetCallbacks(i);
2720 }
2721 }
2722 return NULL;
2723}
2724
2725
2726void JSObject::LocalLookup(String* name, LookupResult* result) {
2727 ASSERT(name->IsString());
2728
2729 if (IsJSGlobalProxy()) {
2730 Object* proto = GetPrototype();
2731 if (proto->IsNull()) return result->NotFound();
2732 ASSERT(proto->IsJSGlobalObject());
2733 return JSObject::cast(proto)->LocalLookup(name, result);
2734 }
2735
2736 // Do not use inline caching if the object is a non-global object
2737 // that requires access checks.
2738 if (!IsJSGlobalProxy() && IsAccessCheckNeeded()) {
2739 result->DisallowCaching();
2740 }
2741
2742 // Check __proto__ before interceptor.
2743 if (name->Equals(Heap::Proto_symbol()) && !IsJSContextExtensionObject()) {
2744 result->ConstantResult(this);
2745 return;
2746 }
2747
2748 // Check for lookup interceptor except when bootstrapping.
2749 if (HasNamedInterceptor() && !Bootstrapper::IsActive()) {
2750 result->InterceptorResult(this);
2751 return;
2752 }
2753
2754 LocalLookupRealNamedProperty(name, result);
2755}
2756
2757
2758void JSObject::Lookup(String* name, LookupResult* result) {
2759 // Ecma-262 3rd 8.6.2.4
2760 for (Object* current = this;
2761 current != Heap::null_value();
2762 current = JSObject::cast(current)->GetPrototype()) {
2763 JSObject::cast(current)->LocalLookup(name, result);
Andrei Popescu402d9372010-02-26 13:31:12 +00002764 if (result->IsProperty()) return;
Steve Blocka7e24c12009-10-30 11:49:00 +00002765 }
2766 result->NotFound();
2767}
2768
2769
2770// Search object and it's prototype chain for callback properties.
2771void JSObject::LookupCallback(String* name, LookupResult* result) {
2772 for (Object* current = this;
2773 current != Heap::null_value();
2774 current = JSObject::cast(current)->GetPrototype()) {
2775 JSObject::cast(current)->LocalLookupRealNamedProperty(name, result);
Andrei Popescu402d9372010-02-26 13:31:12 +00002776 if (result->IsProperty() && result->type() == CALLBACKS) return;
Steve Blocka7e24c12009-10-30 11:49:00 +00002777 }
2778 result->NotFound();
2779}
2780
2781
2782Object* JSObject::DefineGetterSetter(String* name,
2783 PropertyAttributes attributes) {
2784 // Make sure that the top context does not change when doing callbacks or
2785 // interceptor calls.
2786 AssertNoContextChange ncc;
2787
Steve Blocka7e24c12009-10-30 11:49:00 +00002788 // Try to flatten before operating on the string.
Steve Block6ded16b2010-05-10 14:33:55 +01002789 name->TryFlatten();
Steve Blocka7e24c12009-10-30 11:49:00 +00002790
Leon Clarkef7060e22010-06-03 12:02:55 +01002791 if (!CanSetCallback(name)) {
2792 return Heap::undefined_value();
Steve Blocka7e24c12009-10-30 11:49:00 +00002793 }
2794
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01002795 uint32_t index = 0;
Steve Blocka7e24c12009-10-30 11:49:00 +00002796 bool is_element = name->AsArrayIndex(&index);
2797 if (is_element && IsJSArray()) return Heap::undefined_value();
2798
2799 if (is_element) {
2800 switch (GetElementsKind()) {
2801 case FAST_ELEMENTS:
2802 break;
2803 case PIXEL_ELEMENTS:
Steve Block3ce2e202009-11-05 08:53:23 +00002804 case EXTERNAL_BYTE_ELEMENTS:
2805 case EXTERNAL_UNSIGNED_BYTE_ELEMENTS:
2806 case EXTERNAL_SHORT_ELEMENTS:
2807 case EXTERNAL_UNSIGNED_SHORT_ELEMENTS:
2808 case EXTERNAL_INT_ELEMENTS:
2809 case EXTERNAL_UNSIGNED_INT_ELEMENTS:
2810 case EXTERNAL_FLOAT_ELEMENTS:
2811 // Ignore getters and setters on pixel and external array
2812 // elements.
Steve Blocka7e24c12009-10-30 11:49:00 +00002813 return Heap::undefined_value();
2814 case DICTIONARY_ELEMENTS: {
2815 // Lookup the index.
2816 NumberDictionary* dictionary = element_dictionary();
2817 int entry = dictionary->FindEntry(index);
2818 if (entry != NumberDictionary::kNotFound) {
2819 Object* result = dictionary->ValueAt(entry);
2820 PropertyDetails details = dictionary->DetailsAt(entry);
2821 if (details.IsReadOnly()) return Heap::undefined_value();
2822 if (details.type() == CALLBACKS) {
Leon Clarkef7060e22010-06-03 12:02:55 +01002823 if (result->IsFixedArray()) {
2824 return result;
2825 }
2826 // Otherwise allow to override it.
Steve Blocka7e24c12009-10-30 11:49:00 +00002827 }
2828 }
2829 break;
2830 }
2831 default:
2832 UNREACHABLE();
2833 break;
2834 }
2835 } else {
2836 // Lookup the name.
2837 LookupResult result;
2838 LocalLookup(name, &result);
Andrei Popescu402d9372010-02-26 13:31:12 +00002839 if (result.IsProperty()) {
Steve Blocka7e24c12009-10-30 11:49:00 +00002840 if (result.IsReadOnly()) return Heap::undefined_value();
2841 if (result.type() == CALLBACKS) {
2842 Object* obj = result.GetCallbackObject();
Leon Clarkef7060e22010-06-03 12:02:55 +01002843 // Need to preserve old getters/setters.
Leon Clarked91b9f72010-01-27 17:25:45 +00002844 if (obj->IsFixedArray()) {
Leon Clarkef7060e22010-06-03 12:02:55 +01002845 // Use set to update attributes.
2846 return SetPropertyCallback(name, obj, attributes);
Leon Clarked91b9f72010-01-27 17:25:45 +00002847 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002848 }
2849 }
2850 }
2851
2852 // Allocate the fixed array to hold getter and setter.
2853 Object* structure = Heap::AllocateFixedArray(2, TENURED);
2854 if (structure->IsFailure()) return structure;
Steve Blocka7e24c12009-10-30 11:49:00 +00002855
2856 if (is_element) {
Leon Clarkef7060e22010-06-03 12:02:55 +01002857 return SetElementCallback(index, structure, attributes);
Steve Blocka7e24c12009-10-30 11:49:00 +00002858 } else {
Leon Clarkef7060e22010-06-03 12:02:55 +01002859 return SetPropertyCallback(name, structure, attributes);
Steve Blocka7e24c12009-10-30 11:49:00 +00002860 }
Leon Clarkef7060e22010-06-03 12:02:55 +01002861}
2862
2863
2864bool JSObject::CanSetCallback(String* name) {
2865 ASSERT(!IsAccessCheckNeeded()
2866 || Top::MayNamedAccess(this, name, v8::ACCESS_SET));
2867
2868 // Check if there is an API defined callback object which prohibits
2869 // callback overwriting in this object or it's prototype chain.
2870 // This mechanism is needed for instance in a browser setting, where
2871 // certain accessors such as window.location should not be allowed
2872 // to be overwritten because allowing overwriting could potentially
2873 // cause security problems.
2874 LookupResult callback_result;
2875 LookupCallback(name, &callback_result);
2876 if (callback_result.IsProperty()) {
2877 Object* obj = callback_result.GetCallbackObject();
2878 if (obj->IsAccessorInfo() &&
2879 AccessorInfo::cast(obj)->prohibits_overwriting()) {
2880 return false;
2881 }
2882 }
2883
2884 return true;
2885}
2886
2887
2888Object* JSObject::SetElementCallback(uint32_t index,
2889 Object* structure,
2890 PropertyAttributes attributes) {
2891 PropertyDetails details = PropertyDetails(attributes, CALLBACKS);
2892
2893 // Normalize elements to make this operation simple.
2894 Object* ok = NormalizeElements();
2895 if (ok->IsFailure()) return ok;
2896
2897 // Update the dictionary with the new CALLBACKS property.
2898 Object* dict =
2899 element_dictionary()->Set(index, structure, details);
2900 if (dict->IsFailure()) return dict;
2901
2902 NumberDictionary* elements = NumberDictionary::cast(dict);
2903 elements->set_requires_slow_elements();
2904 // Set the potential new dictionary on the object.
2905 set_elements(elements);
Steve Blocka7e24c12009-10-30 11:49:00 +00002906
2907 return structure;
2908}
2909
2910
Leon Clarkef7060e22010-06-03 12:02:55 +01002911Object* JSObject::SetPropertyCallback(String* name,
2912 Object* structure,
2913 PropertyAttributes attributes) {
2914 PropertyDetails details = PropertyDetails(attributes, CALLBACKS);
2915
2916 bool convert_back_to_fast = HasFastProperties() &&
2917 (map()->instance_descriptors()->number_of_descriptors()
2918 < DescriptorArray::kMaxNumberOfDescriptors);
2919
2920 // Normalize object to make this operation simple.
2921 Object* ok = NormalizeProperties(CLEAR_INOBJECT_PROPERTIES, 0);
2922 if (ok->IsFailure()) return ok;
2923
2924 // For the global object allocate a new map to invalidate the global inline
2925 // caches which have a global property cell reference directly in the code.
2926 if (IsGlobalObject()) {
2927 Object* new_map = map()->CopyDropDescriptors();
2928 if (new_map->IsFailure()) return new_map;
2929 set_map(Map::cast(new_map));
2930 }
2931
2932 // Update the dictionary with the new CALLBACKS property.
2933 Object* result = SetNormalizedProperty(name, structure, details);
2934 if (result->IsFailure()) return result;
2935
2936 if (convert_back_to_fast) {
2937 ok = TransformToFastProperties(0);
2938 if (ok->IsFailure()) return ok;
2939 }
2940 return result;
2941}
2942
Steve Blocka7e24c12009-10-30 11:49:00 +00002943Object* JSObject::DefineAccessor(String* name, bool is_getter, JSFunction* fun,
2944 PropertyAttributes attributes) {
2945 // Check access rights if needed.
2946 if (IsAccessCheckNeeded() &&
Leon Clarkef7060e22010-06-03 12:02:55 +01002947 !Top::MayNamedAccess(this, name, v8::ACCESS_SET)) {
2948 Top::ReportFailedAccessCheck(this, v8::ACCESS_SET);
Steve Blocka7e24c12009-10-30 11:49:00 +00002949 return Heap::undefined_value();
2950 }
2951
2952 if (IsJSGlobalProxy()) {
2953 Object* proto = GetPrototype();
2954 if (proto->IsNull()) return this;
2955 ASSERT(proto->IsJSGlobalObject());
2956 return JSObject::cast(proto)->DefineAccessor(name, is_getter,
2957 fun, attributes);
2958 }
2959
2960 Object* array = DefineGetterSetter(name, attributes);
2961 if (array->IsFailure() || array->IsUndefined()) return array;
2962 FixedArray::cast(array)->set(is_getter ? 0 : 1, fun);
2963 return this;
2964}
2965
2966
Leon Clarkef7060e22010-06-03 12:02:55 +01002967Object* JSObject::DefineAccessor(AccessorInfo* info) {
2968 String* name = String::cast(info->name());
2969 // Check access rights if needed.
2970 if (IsAccessCheckNeeded() &&
2971 !Top::MayNamedAccess(this, name, v8::ACCESS_SET)) {
2972 Top::ReportFailedAccessCheck(this, v8::ACCESS_SET);
2973 return Heap::undefined_value();
2974 }
2975
2976 if (IsJSGlobalProxy()) {
2977 Object* proto = GetPrototype();
2978 if (proto->IsNull()) return this;
2979 ASSERT(proto->IsJSGlobalObject());
2980 return JSObject::cast(proto)->DefineAccessor(info);
2981 }
2982
2983 // Make sure that the top context does not change when doing callbacks or
2984 // interceptor calls.
2985 AssertNoContextChange ncc;
2986
2987 // Try to flatten before operating on the string.
2988 name->TryFlatten();
2989
2990 if (!CanSetCallback(name)) {
2991 return Heap::undefined_value();
2992 }
2993
2994 uint32_t index = 0;
2995 bool is_element = name->AsArrayIndex(&index);
2996
2997 if (is_element) {
2998 if (IsJSArray()) return Heap::undefined_value();
2999
3000 // Accessors overwrite previous callbacks (cf. with getters/setters).
3001 switch (GetElementsKind()) {
3002 case FAST_ELEMENTS:
3003 break;
3004 case PIXEL_ELEMENTS:
3005 case EXTERNAL_BYTE_ELEMENTS:
3006 case EXTERNAL_UNSIGNED_BYTE_ELEMENTS:
3007 case EXTERNAL_SHORT_ELEMENTS:
3008 case EXTERNAL_UNSIGNED_SHORT_ELEMENTS:
3009 case EXTERNAL_INT_ELEMENTS:
3010 case EXTERNAL_UNSIGNED_INT_ELEMENTS:
3011 case EXTERNAL_FLOAT_ELEMENTS:
3012 // Ignore getters and setters on pixel and external array
3013 // elements.
3014 return Heap::undefined_value();
3015 case DICTIONARY_ELEMENTS:
3016 break;
3017 default:
3018 UNREACHABLE();
3019 break;
3020 }
3021
Kristian Monsen50ef84f2010-07-29 15:18:00 +01003022 Object* ok = SetElementCallback(index, info, info->property_attributes());
3023 if (ok->IsFailure()) return ok;
Leon Clarkef7060e22010-06-03 12:02:55 +01003024 } else {
3025 // Lookup the name.
3026 LookupResult result;
3027 LocalLookup(name, &result);
3028 // ES5 forbids turning a property into an accessor if it's not
3029 // configurable (that is IsDontDelete in ES3 and v8), see 8.6.1 (Table 5).
3030 if (result.IsProperty() && (result.IsReadOnly() || result.IsDontDelete())) {
3031 return Heap::undefined_value();
3032 }
Kristian Monsen50ef84f2010-07-29 15:18:00 +01003033 Object* ok = SetPropertyCallback(name, info, info->property_attributes());
3034 if (ok->IsFailure()) return ok;
Leon Clarkef7060e22010-06-03 12:02:55 +01003035 }
3036
3037 return this;
3038}
3039
3040
Steve Blocka7e24c12009-10-30 11:49:00 +00003041Object* JSObject::LookupAccessor(String* name, bool is_getter) {
3042 // Make sure that the top context does not change when doing callbacks or
3043 // interceptor calls.
3044 AssertNoContextChange ncc;
3045
3046 // Check access rights if needed.
3047 if (IsAccessCheckNeeded() &&
3048 !Top::MayNamedAccess(this, name, v8::ACCESS_HAS)) {
3049 Top::ReportFailedAccessCheck(this, v8::ACCESS_HAS);
3050 return Heap::undefined_value();
3051 }
3052
3053 // Make the lookup and include prototypes.
3054 int accessor_index = is_getter ? kGetterIndex : kSetterIndex;
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01003055 uint32_t index = 0;
Steve Blocka7e24c12009-10-30 11:49:00 +00003056 if (name->AsArrayIndex(&index)) {
3057 for (Object* obj = this;
3058 obj != Heap::null_value();
3059 obj = JSObject::cast(obj)->GetPrototype()) {
3060 JSObject* js_object = JSObject::cast(obj);
3061 if (js_object->HasDictionaryElements()) {
3062 NumberDictionary* dictionary = js_object->element_dictionary();
3063 int entry = dictionary->FindEntry(index);
3064 if (entry != NumberDictionary::kNotFound) {
3065 Object* element = dictionary->ValueAt(entry);
3066 PropertyDetails details = dictionary->DetailsAt(entry);
3067 if (details.type() == CALLBACKS) {
Leon Clarkef7060e22010-06-03 12:02:55 +01003068 if (element->IsFixedArray()) {
3069 return FixedArray::cast(element)->get(accessor_index);
3070 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003071 }
3072 }
3073 }
3074 }
3075 } else {
3076 for (Object* obj = this;
3077 obj != Heap::null_value();
3078 obj = JSObject::cast(obj)->GetPrototype()) {
3079 LookupResult result;
3080 JSObject::cast(obj)->LocalLookup(name, &result);
Andrei Popescu402d9372010-02-26 13:31:12 +00003081 if (result.IsProperty()) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003082 if (result.IsReadOnly()) return Heap::undefined_value();
3083 if (result.type() == CALLBACKS) {
3084 Object* obj = result.GetCallbackObject();
3085 if (obj->IsFixedArray()) {
3086 return FixedArray::cast(obj)->get(accessor_index);
3087 }
3088 }
3089 }
3090 }
3091 }
3092 return Heap::undefined_value();
3093}
3094
3095
3096Object* JSObject::SlowReverseLookup(Object* value) {
3097 if (HasFastProperties()) {
3098 DescriptorArray* descs = map()->instance_descriptors();
3099 for (int i = 0; i < descs->number_of_descriptors(); i++) {
3100 if (descs->GetType(i) == FIELD) {
3101 if (FastPropertyAt(descs->GetFieldIndex(i)) == value) {
3102 return descs->GetKey(i);
3103 }
3104 } else if (descs->GetType(i) == CONSTANT_FUNCTION) {
3105 if (descs->GetConstantFunction(i) == value) {
3106 return descs->GetKey(i);
3107 }
3108 }
3109 }
3110 return Heap::undefined_value();
3111 } else {
3112 return property_dictionary()->SlowReverseLookup(value);
3113 }
3114}
3115
3116
3117Object* Map::CopyDropDescriptors() {
3118 Object* result = Heap::AllocateMap(instance_type(), instance_size());
3119 if (result->IsFailure()) return result;
3120 Map::cast(result)->set_prototype(prototype());
3121 Map::cast(result)->set_constructor(constructor());
3122 // Don't copy descriptors, so map transitions always remain a forest.
3123 // If we retained the same descriptors we would have two maps
3124 // pointing to the same transition which is bad because the garbage
3125 // collector relies on being able to reverse pointers from transitions
3126 // to maps. If properties need to be retained use CopyDropTransitions.
3127 Map::cast(result)->set_instance_descriptors(Heap::empty_descriptor_array());
3128 // Please note instance_type and instance_size are set when allocated.
3129 Map::cast(result)->set_inobject_properties(inobject_properties());
3130 Map::cast(result)->set_unused_property_fields(unused_property_fields());
3131
3132 // If the map has pre-allocated properties always start out with a descriptor
3133 // array describing these properties.
3134 if (pre_allocated_property_fields() > 0) {
3135 ASSERT(constructor()->IsJSFunction());
3136 JSFunction* ctor = JSFunction::cast(constructor());
3137 Object* descriptors =
3138 ctor->initial_map()->instance_descriptors()->RemoveTransitions();
3139 if (descriptors->IsFailure()) return descriptors;
3140 Map::cast(result)->set_instance_descriptors(
3141 DescriptorArray::cast(descriptors));
3142 Map::cast(result)->set_pre_allocated_property_fields(
3143 pre_allocated_property_fields());
3144 }
3145 Map::cast(result)->set_bit_field(bit_field());
3146 Map::cast(result)->set_bit_field2(bit_field2());
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003147 Map::cast(result)->set_is_shared(false);
Steve Blocka7e24c12009-10-30 11:49:00 +00003148 Map::cast(result)->ClearCodeCache();
3149 return result;
3150}
3151
3152
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003153Object* Map::CopyNormalized(PropertyNormalizationMode mode,
3154 NormalizedMapSharingMode sharing) {
Kristian Monsen80d68ea2010-09-08 11:05:35 +01003155 int new_instance_size = instance_size();
3156 if (mode == CLEAR_INOBJECT_PROPERTIES) {
3157 new_instance_size -= inobject_properties() * kPointerSize;
3158 }
3159
3160 Object* result = Heap::AllocateMap(instance_type(), new_instance_size);
3161 if (result->IsFailure()) return result;
3162
3163 if (mode != CLEAR_INOBJECT_PROPERTIES) {
3164 Map::cast(result)->set_inobject_properties(inobject_properties());
3165 }
3166
3167 Map::cast(result)->set_prototype(prototype());
3168 Map::cast(result)->set_constructor(constructor());
3169
3170 Map::cast(result)->set_bit_field(bit_field());
3171 Map::cast(result)->set_bit_field2(bit_field2());
3172
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003173 Map::cast(result)->set_is_shared(sharing == SHARED_NORMALIZED_MAP);
3174
Kristian Monsen80d68ea2010-09-08 11:05:35 +01003175#ifdef DEBUG
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003176 if (Map::cast(result)->is_shared()) {
3177 Map::cast(result)->SharedMapVerify();
3178 }
Kristian Monsen80d68ea2010-09-08 11:05:35 +01003179#endif
3180
3181 return result;
3182}
3183
3184
Steve Blocka7e24c12009-10-30 11:49:00 +00003185Object* Map::CopyDropTransitions() {
3186 Object* new_map = CopyDropDescriptors();
3187 if (new_map->IsFailure()) return new_map;
3188 Object* descriptors = instance_descriptors()->RemoveTransitions();
3189 if (descriptors->IsFailure()) return descriptors;
3190 cast(new_map)->set_instance_descriptors(DescriptorArray::cast(descriptors));
Steve Block8defd9f2010-07-08 12:39:36 +01003191 return new_map;
Steve Blocka7e24c12009-10-30 11:49:00 +00003192}
3193
3194
3195Object* Map::UpdateCodeCache(String* name, Code* code) {
Steve Block6ded16b2010-05-10 14:33:55 +01003196 // Allocate the code cache if not present.
3197 if (code_cache()->IsFixedArray()) {
3198 Object* result = Heap::AllocateCodeCache();
3199 if (result->IsFailure()) return result;
3200 set_code_cache(result);
3201 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003202
Steve Block6ded16b2010-05-10 14:33:55 +01003203 // Update the code cache.
3204 return CodeCache::cast(code_cache())->Update(name, code);
3205}
3206
3207
3208Object* Map::FindInCodeCache(String* name, Code::Flags flags) {
3209 // Do a lookup if a code cache exists.
3210 if (!code_cache()->IsFixedArray()) {
3211 return CodeCache::cast(code_cache())->Lookup(name, flags);
3212 } else {
3213 return Heap::undefined_value();
3214 }
3215}
3216
3217
3218int Map::IndexInCodeCache(Object* name, Code* code) {
3219 // Get the internal index if a code cache exists.
3220 if (!code_cache()->IsFixedArray()) {
3221 return CodeCache::cast(code_cache())->GetIndex(name, code);
3222 }
3223 return -1;
3224}
3225
3226
3227void Map::RemoveFromCodeCache(String* name, Code* code, int index) {
3228 // No GC is supposed to happen between a call to IndexInCodeCache and
3229 // RemoveFromCodeCache so the code cache must be there.
3230 ASSERT(!code_cache()->IsFixedArray());
3231 CodeCache::cast(code_cache())->RemoveByIndex(name, code, index);
3232}
3233
3234
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003235void Map::TraverseTransitionTree(TraverseCallback callback, void* data) {
3236 Map* current = this;
3237 while (current != Heap::meta_map()) {
3238 DescriptorArray* d = reinterpret_cast<DescriptorArray*>(
3239 *RawField(current, Map::kInstanceDescriptorsOffset));
3240 if (d == Heap::empty_descriptor_array()) {
3241 Map* prev = current->map();
3242 current->set_map(Heap::meta_map());
3243 callback(current, data);
3244 current = prev;
3245 continue;
3246 }
3247
3248 FixedArray* contents = reinterpret_cast<FixedArray*>(
3249 d->get(DescriptorArray::kContentArrayIndex));
3250 Object** map_or_index_field = RawField(contents, HeapObject::kMapOffset);
3251 Object* map_or_index = *map_or_index_field;
3252 bool map_done = true;
3253 for (int i = map_or_index->IsSmi() ? Smi::cast(map_or_index)->value() : 0;
3254 i < contents->length();
3255 i += 2) {
3256 PropertyDetails details(Smi::cast(contents->get(i + 1)));
3257 if (details.IsTransition()) {
3258 Map* next = reinterpret_cast<Map*>(contents->get(i));
3259 next->set_map(current);
3260 *map_or_index_field = Smi::FromInt(i + 2);
3261 current = next;
3262 map_done = false;
3263 break;
3264 }
3265 }
3266 if (!map_done) continue;
3267 *map_or_index_field = Heap::fixed_array_map();
3268 Map* prev = current->map();
3269 current->set_map(Heap::meta_map());
3270 callback(current, data);
3271 current = prev;
3272 }
3273}
3274
3275
Steve Block6ded16b2010-05-10 14:33:55 +01003276Object* CodeCache::Update(String* name, Code* code) {
3277 ASSERT(code->ic_state() == MONOMORPHIC);
3278
3279 // The number of monomorphic stubs for normal load/store/call IC's can grow to
3280 // a large number and therefore they need to go into a hash table. They are
3281 // used to load global properties from cells.
3282 if (code->type() == NORMAL) {
3283 // Make sure that a hash table is allocated for the normal load code cache.
3284 if (normal_type_cache()->IsUndefined()) {
3285 Object* result =
3286 CodeCacheHashTable::Allocate(CodeCacheHashTable::kInitialSize);
3287 if (result->IsFailure()) return result;
3288 set_normal_type_cache(result);
3289 }
3290 return UpdateNormalTypeCache(name, code);
3291 } else {
3292 ASSERT(default_cache()->IsFixedArray());
3293 return UpdateDefaultCache(name, code);
3294 }
3295}
3296
3297
3298Object* CodeCache::UpdateDefaultCache(String* name, Code* code) {
3299 // When updating the default code cache we disregard the type encoded in the
Steve Blocka7e24c12009-10-30 11:49:00 +00003300 // flags. This allows call constant stubs to overwrite call field
3301 // stubs, etc.
3302 Code::Flags flags = Code::RemoveTypeFromFlags(code->flags());
3303
3304 // First check whether we can update existing code cache without
3305 // extending it.
Steve Block6ded16b2010-05-10 14:33:55 +01003306 FixedArray* cache = default_cache();
Steve Blocka7e24c12009-10-30 11:49:00 +00003307 int length = cache->length();
3308 int deleted_index = -1;
Steve Block6ded16b2010-05-10 14:33:55 +01003309 for (int i = 0; i < length; i += kCodeCacheEntrySize) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003310 Object* key = cache->get(i);
3311 if (key->IsNull()) {
3312 if (deleted_index < 0) deleted_index = i;
3313 continue;
3314 }
3315 if (key->IsUndefined()) {
3316 if (deleted_index >= 0) i = deleted_index;
Steve Block6ded16b2010-05-10 14:33:55 +01003317 cache->set(i + kCodeCacheEntryNameOffset, name);
3318 cache->set(i + kCodeCacheEntryCodeOffset, code);
Steve Blocka7e24c12009-10-30 11:49:00 +00003319 return this;
3320 }
3321 if (name->Equals(String::cast(key))) {
Steve Block6ded16b2010-05-10 14:33:55 +01003322 Code::Flags found =
3323 Code::cast(cache->get(i + kCodeCacheEntryCodeOffset))->flags();
Steve Blocka7e24c12009-10-30 11:49:00 +00003324 if (Code::RemoveTypeFromFlags(found) == flags) {
Steve Block6ded16b2010-05-10 14:33:55 +01003325 cache->set(i + kCodeCacheEntryCodeOffset, code);
Steve Blocka7e24c12009-10-30 11:49:00 +00003326 return this;
3327 }
3328 }
3329 }
3330
3331 // Reached the end of the code cache. If there were deleted
3332 // elements, reuse the space for the first of them.
3333 if (deleted_index >= 0) {
Steve Block6ded16b2010-05-10 14:33:55 +01003334 cache->set(deleted_index + kCodeCacheEntryNameOffset, name);
3335 cache->set(deleted_index + kCodeCacheEntryCodeOffset, code);
Steve Blocka7e24c12009-10-30 11:49:00 +00003336 return this;
3337 }
3338
Steve Block6ded16b2010-05-10 14:33:55 +01003339 // Extend the code cache with some new entries (at least one). Must be a
3340 // multiple of the entry size.
3341 int new_length = length + ((length >> 1)) + kCodeCacheEntrySize;
3342 new_length = new_length - new_length % kCodeCacheEntrySize;
3343 ASSERT((new_length % kCodeCacheEntrySize) == 0);
Steve Blocka7e24c12009-10-30 11:49:00 +00003344 Object* result = cache->CopySize(new_length);
3345 if (result->IsFailure()) return result;
3346
3347 // Add the (name, code) pair to the new cache.
3348 cache = FixedArray::cast(result);
Steve Block6ded16b2010-05-10 14:33:55 +01003349 cache->set(length + kCodeCacheEntryNameOffset, name);
3350 cache->set(length + kCodeCacheEntryCodeOffset, code);
3351 set_default_cache(cache);
Steve Blocka7e24c12009-10-30 11:49:00 +00003352 return this;
3353}
3354
3355
Steve Block6ded16b2010-05-10 14:33:55 +01003356Object* CodeCache::UpdateNormalTypeCache(String* name, Code* code) {
3357 // Adding a new entry can cause a new cache to be allocated.
3358 CodeCacheHashTable* cache = CodeCacheHashTable::cast(normal_type_cache());
3359 Object* new_cache = cache->Put(name, code);
3360 if (new_cache->IsFailure()) return new_cache;
3361 set_normal_type_cache(new_cache);
3362 return this;
3363}
3364
3365
3366Object* CodeCache::Lookup(String* name, Code::Flags flags) {
3367 if (Code::ExtractTypeFromFlags(flags) == NORMAL) {
3368 return LookupNormalTypeCache(name, flags);
3369 } else {
3370 return LookupDefaultCache(name, flags);
3371 }
3372}
3373
3374
3375Object* CodeCache::LookupDefaultCache(String* name, Code::Flags flags) {
3376 FixedArray* cache = default_cache();
Steve Blocka7e24c12009-10-30 11:49:00 +00003377 int length = cache->length();
Steve Block6ded16b2010-05-10 14:33:55 +01003378 for (int i = 0; i < length; i += kCodeCacheEntrySize) {
3379 Object* key = cache->get(i + kCodeCacheEntryNameOffset);
Steve Blocka7e24c12009-10-30 11:49:00 +00003380 // Skip deleted elements.
3381 if (key->IsNull()) continue;
3382 if (key->IsUndefined()) return key;
3383 if (name->Equals(String::cast(key))) {
Steve Block6ded16b2010-05-10 14:33:55 +01003384 Code* code = Code::cast(cache->get(i + kCodeCacheEntryCodeOffset));
3385 if (code->flags() == flags) {
3386 return code;
3387 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003388 }
3389 }
3390 return Heap::undefined_value();
3391}
3392
3393
Steve Block6ded16b2010-05-10 14:33:55 +01003394Object* CodeCache::LookupNormalTypeCache(String* name, Code::Flags flags) {
3395 if (!normal_type_cache()->IsUndefined()) {
3396 CodeCacheHashTable* cache = CodeCacheHashTable::cast(normal_type_cache());
3397 return cache->Lookup(name, flags);
3398 } else {
3399 return Heap::undefined_value();
3400 }
3401}
3402
3403
3404int CodeCache::GetIndex(Object* name, Code* code) {
3405 if (code->type() == NORMAL) {
3406 if (normal_type_cache()->IsUndefined()) return -1;
3407 CodeCacheHashTable* cache = CodeCacheHashTable::cast(normal_type_cache());
3408 return cache->GetIndex(String::cast(name), code->flags());
3409 }
3410
3411 FixedArray* array = default_cache();
Steve Blocka7e24c12009-10-30 11:49:00 +00003412 int len = array->length();
Steve Block6ded16b2010-05-10 14:33:55 +01003413 for (int i = 0; i < len; i += kCodeCacheEntrySize) {
3414 if (array->get(i + kCodeCacheEntryCodeOffset) == code) return i + 1;
Steve Blocka7e24c12009-10-30 11:49:00 +00003415 }
3416 return -1;
3417}
3418
3419
Steve Block6ded16b2010-05-10 14:33:55 +01003420void CodeCache::RemoveByIndex(Object* name, Code* code, int index) {
3421 if (code->type() == NORMAL) {
3422 ASSERT(!normal_type_cache()->IsUndefined());
3423 CodeCacheHashTable* cache = CodeCacheHashTable::cast(normal_type_cache());
3424 ASSERT(cache->GetIndex(String::cast(name), code->flags()) == index);
3425 cache->RemoveByIndex(index);
3426 } else {
3427 FixedArray* array = default_cache();
3428 ASSERT(array->length() >= index && array->get(index)->IsCode());
3429 // Use null instead of undefined for deleted elements to distinguish
3430 // deleted elements from unused elements. This distinction is used
3431 // when looking up in the cache and when updating the cache.
3432 ASSERT_EQ(1, kCodeCacheEntryCodeOffset - kCodeCacheEntryNameOffset);
3433 array->set_null(index - 1); // Name.
3434 array->set_null(index); // Code.
3435 }
3436}
3437
3438
3439// The key in the code cache hash table consists of the property name and the
3440// code object. The actual match is on the name and the code flags. If a key
3441// is created using the flags and not a code object it can only be used for
3442// lookup not to create a new entry.
3443class CodeCacheHashTableKey : public HashTableKey {
3444 public:
3445 CodeCacheHashTableKey(String* name, Code::Flags flags)
3446 : name_(name), flags_(flags), code_(NULL) { }
3447
3448 CodeCacheHashTableKey(String* name, Code* code)
3449 : name_(name),
3450 flags_(code->flags()),
3451 code_(code) { }
3452
3453
3454 bool IsMatch(Object* other) {
3455 if (!other->IsFixedArray()) return false;
3456 FixedArray* pair = FixedArray::cast(other);
3457 String* name = String::cast(pair->get(0));
3458 Code::Flags flags = Code::cast(pair->get(1))->flags();
3459 if (flags != flags_) {
3460 return false;
3461 }
3462 return name_->Equals(name);
3463 }
3464
3465 static uint32_t NameFlagsHashHelper(String* name, Code::Flags flags) {
3466 return name->Hash() ^ flags;
3467 }
3468
3469 uint32_t Hash() { return NameFlagsHashHelper(name_, flags_); }
3470
3471 uint32_t HashForObject(Object* obj) {
3472 FixedArray* pair = FixedArray::cast(obj);
3473 String* name = String::cast(pair->get(0));
3474 Code* code = Code::cast(pair->get(1));
3475 return NameFlagsHashHelper(name, code->flags());
3476 }
3477
3478 Object* AsObject() {
3479 ASSERT(code_ != NULL);
3480 Object* obj = Heap::AllocateFixedArray(2);
3481 if (obj->IsFailure()) return obj;
3482 FixedArray* pair = FixedArray::cast(obj);
3483 pair->set(0, name_);
3484 pair->set(1, code_);
3485 return pair;
3486 }
3487
3488 private:
3489 String* name_;
3490 Code::Flags flags_;
3491 Code* code_;
3492};
3493
3494
3495Object* CodeCacheHashTable::Lookup(String* name, Code::Flags flags) {
3496 CodeCacheHashTableKey key(name, flags);
3497 int entry = FindEntry(&key);
3498 if (entry == kNotFound) return Heap::undefined_value();
3499 return get(EntryToIndex(entry) + 1);
3500}
3501
3502
3503Object* CodeCacheHashTable::Put(String* name, Code* code) {
3504 CodeCacheHashTableKey key(name, code);
3505 Object* obj = EnsureCapacity(1, &key);
3506 if (obj->IsFailure()) return obj;
3507
3508 // Don't use this, as the table might have grown.
3509 CodeCacheHashTable* cache = reinterpret_cast<CodeCacheHashTable*>(obj);
3510
3511 int entry = cache->FindInsertionEntry(key.Hash());
3512 Object* k = key.AsObject();
3513 if (k->IsFailure()) return k;
3514
3515 cache->set(EntryToIndex(entry), k);
3516 cache->set(EntryToIndex(entry) + 1, code);
3517 cache->ElementAdded();
3518 return cache;
3519}
3520
3521
3522int CodeCacheHashTable::GetIndex(String* name, Code::Flags flags) {
3523 CodeCacheHashTableKey key(name, flags);
3524 int entry = FindEntry(&key);
3525 return (entry == kNotFound) ? -1 : entry;
3526}
3527
3528
3529void CodeCacheHashTable::RemoveByIndex(int index) {
3530 ASSERT(index >= 0);
3531 set(EntryToIndex(index), Heap::null_value());
3532 set(EntryToIndex(index) + 1, Heap::null_value());
3533 ElementRemoved();
Steve Blocka7e24c12009-10-30 11:49:00 +00003534}
3535
3536
Steve Blocka7e24c12009-10-30 11:49:00 +00003537static bool HasKey(FixedArray* array, Object* key) {
3538 int len0 = array->length();
3539 for (int i = 0; i < len0; i++) {
3540 Object* element = array->get(i);
3541 if (element->IsSmi() && key->IsSmi() && (element == key)) return true;
3542 if (element->IsString() &&
3543 key->IsString() && String::cast(element)->Equals(String::cast(key))) {
3544 return true;
3545 }
3546 }
3547 return false;
3548}
3549
3550
3551Object* FixedArray::AddKeysFromJSArray(JSArray* array) {
Steve Block3ce2e202009-11-05 08:53:23 +00003552 ASSERT(!array->HasPixelElements() && !array->HasExternalArrayElements());
Steve Blocka7e24c12009-10-30 11:49:00 +00003553 switch (array->GetElementsKind()) {
3554 case JSObject::FAST_ELEMENTS:
3555 return UnionOfKeys(FixedArray::cast(array->elements()));
3556 case JSObject::DICTIONARY_ELEMENTS: {
3557 NumberDictionary* dict = array->element_dictionary();
3558 int size = dict->NumberOfElements();
3559
3560 // Allocate a temporary fixed array.
3561 Object* object = Heap::AllocateFixedArray(size);
3562 if (object->IsFailure()) return object;
3563 FixedArray* key_array = FixedArray::cast(object);
3564
3565 int capacity = dict->Capacity();
3566 int pos = 0;
3567 // Copy the elements from the JSArray to the temporary fixed array.
3568 for (int i = 0; i < capacity; i++) {
3569 if (dict->IsKey(dict->KeyAt(i))) {
3570 key_array->set(pos++, dict->ValueAt(i));
3571 }
3572 }
3573 // Compute the union of this and the temporary fixed array.
3574 return UnionOfKeys(key_array);
3575 }
3576 default:
3577 UNREACHABLE();
3578 }
3579 UNREACHABLE();
3580 return Heap::null_value(); // Failure case needs to "return" a value.
3581}
3582
3583
3584Object* FixedArray::UnionOfKeys(FixedArray* other) {
3585 int len0 = length();
Ben Murdochf87a2032010-10-22 12:50:53 +01003586#ifdef DEBUG
3587 if (FLAG_enable_slow_asserts) {
3588 for (int i = 0; i < len0; i++) {
3589 ASSERT(get(i)->IsString() || get(i)->IsNumber());
3590 }
3591 }
3592#endif
Steve Blocka7e24c12009-10-30 11:49:00 +00003593 int len1 = other->length();
Ben Murdochf87a2032010-10-22 12:50:53 +01003594 // Optimize if 'other' is empty.
3595 // We cannot optimize if 'this' is empty, as other may have holes
3596 // or non keys.
Steve Blocka7e24c12009-10-30 11:49:00 +00003597 if (len1 == 0) return this;
3598
3599 // Compute how many elements are not in this.
3600 int extra = 0;
3601 for (int y = 0; y < len1; y++) {
3602 Object* value = other->get(y);
3603 if (!value->IsTheHole() && !HasKey(this, value)) extra++;
3604 }
3605
3606 if (extra == 0) return this;
3607
3608 // Allocate the result
3609 Object* obj = Heap::AllocateFixedArray(len0 + extra);
3610 if (obj->IsFailure()) return obj;
3611 // Fill in the content
Leon Clarke4515c472010-02-03 11:58:03 +00003612 AssertNoAllocation no_gc;
Steve Blocka7e24c12009-10-30 11:49:00 +00003613 FixedArray* result = FixedArray::cast(obj);
Leon Clarke4515c472010-02-03 11:58:03 +00003614 WriteBarrierMode mode = result->GetWriteBarrierMode(no_gc);
Steve Blocka7e24c12009-10-30 11:49:00 +00003615 for (int i = 0; i < len0; i++) {
Ben Murdochf87a2032010-10-22 12:50:53 +01003616 Object* e = get(i);
3617 ASSERT(e->IsString() || e->IsNumber());
3618 result->set(i, e, mode);
Steve Blocka7e24c12009-10-30 11:49:00 +00003619 }
3620 // Fill in the extra keys.
3621 int index = 0;
3622 for (int y = 0; y < len1; y++) {
3623 Object* value = other->get(y);
3624 if (!value->IsTheHole() && !HasKey(this, value)) {
Ben Murdochf87a2032010-10-22 12:50:53 +01003625 Object* e = other->get(y);
3626 ASSERT(e->IsString() || e->IsNumber());
3627 result->set(len0 + index, e, mode);
Steve Blocka7e24c12009-10-30 11:49:00 +00003628 index++;
3629 }
3630 }
3631 ASSERT(extra == index);
3632 return result;
3633}
3634
3635
3636Object* FixedArray::CopySize(int new_length) {
3637 if (new_length == 0) return Heap::empty_fixed_array();
3638 Object* obj = Heap::AllocateFixedArray(new_length);
3639 if (obj->IsFailure()) return obj;
3640 FixedArray* result = FixedArray::cast(obj);
3641 // Copy the content
Leon Clarke4515c472010-02-03 11:58:03 +00003642 AssertNoAllocation no_gc;
Steve Blocka7e24c12009-10-30 11:49:00 +00003643 int len = length();
3644 if (new_length < len) len = new_length;
3645 result->set_map(map());
Leon Clarke4515c472010-02-03 11:58:03 +00003646 WriteBarrierMode mode = result->GetWriteBarrierMode(no_gc);
Steve Blocka7e24c12009-10-30 11:49:00 +00003647 for (int i = 0; i < len; i++) {
3648 result->set(i, get(i), mode);
3649 }
3650 return result;
3651}
3652
3653
3654void FixedArray::CopyTo(int pos, FixedArray* dest, int dest_pos, int len) {
Leon Clarke4515c472010-02-03 11:58:03 +00003655 AssertNoAllocation no_gc;
3656 WriteBarrierMode mode = dest->GetWriteBarrierMode(no_gc);
Steve Blocka7e24c12009-10-30 11:49:00 +00003657 for (int index = 0; index < len; index++) {
3658 dest->set(dest_pos+index, get(pos+index), mode);
3659 }
3660}
3661
3662
3663#ifdef DEBUG
3664bool FixedArray::IsEqualTo(FixedArray* other) {
3665 if (length() != other->length()) return false;
3666 for (int i = 0 ; i < length(); ++i) {
3667 if (get(i) != other->get(i)) return false;
3668 }
3669 return true;
3670}
3671#endif
3672
3673
3674Object* DescriptorArray::Allocate(int number_of_descriptors) {
3675 if (number_of_descriptors == 0) {
3676 return Heap::empty_descriptor_array();
3677 }
3678 // Allocate the array of keys.
Leon Clarkee46be812010-01-19 14:06:41 +00003679 Object* array =
3680 Heap::AllocateFixedArray(ToKeyIndex(number_of_descriptors));
Steve Blocka7e24c12009-10-30 11:49:00 +00003681 if (array->IsFailure()) return array;
3682 // Do not use DescriptorArray::cast on incomplete object.
3683 FixedArray* result = FixedArray::cast(array);
3684
3685 // Allocate the content array and set it in the descriptor array.
3686 array = Heap::AllocateFixedArray(number_of_descriptors << 1);
3687 if (array->IsFailure()) return array;
3688 result->set(kContentArrayIndex, array);
3689 result->set(kEnumerationIndexIndex,
Leon Clarke4515c472010-02-03 11:58:03 +00003690 Smi::FromInt(PropertyDetails::kInitialIndex));
Steve Blocka7e24c12009-10-30 11:49:00 +00003691 return result;
3692}
3693
3694
3695void DescriptorArray::SetEnumCache(FixedArray* bridge_storage,
3696 FixedArray* new_cache) {
3697 ASSERT(bridge_storage->length() >= kEnumCacheBridgeLength);
3698 if (HasEnumCache()) {
3699 FixedArray::cast(get(kEnumerationIndexIndex))->
3700 set(kEnumCacheBridgeCacheIndex, new_cache);
3701 } else {
3702 if (IsEmpty()) return; // Do nothing for empty descriptor array.
3703 FixedArray::cast(bridge_storage)->
3704 set(kEnumCacheBridgeCacheIndex, new_cache);
3705 fast_set(FixedArray::cast(bridge_storage),
3706 kEnumCacheBridgeEnumIndex,
3707 get(kEnumerationIndexIndex));
3708 set(kEnumerationIndexIndex, bridge_storage);
3709 }
3710}
3711
3712
3713Object* DescriptorArray::CopyInsert(Descriptor* descriptor,
3714 TransitionFlag transition_flag) {
3715 // Transitions are only kept when inserting another transition.
3716 // This precondition is not required by this function's implementation, but
3717 // is currently required by the semantics of maps, so we check it.
3718 // Conversely, we filter after replacing, so replacing a transition and
3719 // removing all other transitions is not supported.
3720 bool remove_transitions = transition_flag == REMOVE_TRANSITIONS;
3721 ASSERT(remove_transitions == !descriptor->GetDetails().IsTransition());
3722 ASSERT(descriptor->GetDetails().type() != NULL_DESCRIPTOR);
3723
3724 // Ensure the key is a symbol.
3725 Object* result = descriptor->KeyToSymbol();
3726 if (result->IsFailure()) return result;
3727
3728 int transitions = 0;
3729 int null_descriptors = 0;
3730 if (remove_transitions) {
3731 for (int i = 0; i < number_of_descriptors(); i++) {
3732 if (IsTransition(i)) transitions++;
3733 if (IsNullDescriptor(i)) null_descriptors++;
3734 }
3735 } else {
3736 for (int i = 0; i < number_of_descriptors(); i++) {
3737 if (IsNullDescriptor(i)) null_descriptors++;
3738 }
3739 }
3740 int new_size = number_of_descriptors() - transitions - null_descriptors;
3741
3742 // If key is in descriptor, we replace it in-place when filtering.
3743 // Count a null descriptor for key as inserted, not replaced.
3744 int index = Search(descriptor->GetKey());
3745 const bool inserting = (index == kNotFound);
3746 const bool replacing = !inserting;
3747 bool keep_enumeration_index = false;
3748 if (inserting) {
3749 ++new_size;
3750 }
3751 if (replacing) {
3752 // We are replacing an existing descriptor. We keep the enumeration
3753 // index of a visible property.
3754 PropertyType t = PropertyDetails(GetDetails(index)).type();
3755 if (t == CONSTANT_FUNCTION ||
3756 t == FIELD ||
3757 t == CALLBACKS ||
3758 t == INTERCEPTOR) {
3759 keep_enumeration_index = true;
3760 } else if (remove_transitions) {
3761 // Replaced descriptor has been counted as removed if it is
3762 // a transition that will be replaced. Adjust count in this case.
3763 ++new_size;
3764 }
3765 }
3766 result = Allocate(new_size);
3767 if (result->IsFailure()) return result;
3768 DescriptorArray* new_descriptors = DescriptorArray::cast(result);
3769 // Set the enumeration index in the descriptors and set the enumeration index
3770 // in the result.
3771 int enumeration_index = NextEnumerationIndex();
3772 if (!descriptor->GetDetails().IsTransition()) {
3773 if (keep_enumeration_index) {
3774 descriptor->SetEnumerationIndex(
3775 PropertyDetails(GetDetails(index)).index());
3776 } else {
3777 descriptor->SetEnumerationIndex(enumeration_index);
3778 ++enumeration_index;
3779 }
3780 }
3781 new_descriptors->SetNextEnumerationIndex(enumeration_index);
3782
3783 // Copy the descriptors, filtering out transitions and null descriptors,
3784 // and inserting or replacing a descriptor.
3785 uint32_t descriptor_hash = descriptor->GetKey()->Hash();
3786 int from_index = 0;
3787 int to_index = 0;
3788
3789 for (; from_index < number_of_descriptors(); from_index++) {
3790 String* key = GetKey(from_index);
3791 if (key->Hash() > descriptor_hash || key == descriptor->GetKey()) {
3792 break;
3793 }
3794 if (IsNullDescriptor(from_index)) continue;
3795 if (remove_transitions && IsTransition(from_index)) continue;
3796 new_descriptors->CopyFrom(to_index++, this, from_index);
3797 }
3798
3799 new_descriptors->Set(to_index++, descriptor);
3800 if (replacing) from_index++;
3801
3802 for (; from_index < number_of_descriptors(); from_index++) {
3803 if (IsNullDescriptor(from_index)) continue;
3804 if (remove_transitions && IsTransition(from_index)) continue;
3805 new_descriptors->CopyFrom(to_index++, this, from_index);
3806 }
3807
3808 ASSERT(to_index == new_descriptors->number_of_descriptors());
3809 SLOW_ASSERT(new_descriptors->IsSortedNoDuplicates());
3810
3811 return new_descriptors;
3812}
3813
3814
3815Object* DescriptorArray::RemoveTransitions() {
3816 // Remove all transitions and null descriptors. Return a copy of the array
3817 // with all transitions removed, or a Failure object if the new array could
3818 // not be allocated.
3819
3820 // Compute the size of the map transition entries to be removed.
3821 int num_removed = 0;
3822 for (int i = 0; i < number_of_descriptors(); i++) {
3823 if (!IsProperty(i)) num_removed++;
3824 }
3825
3826 // Allocate the new descriptor array.
3827 Object* result = Allocate(number_of_descriptors() - num_removed);
3828 if (result->IsFailure()) return result;
3829 DescriptorArray* new_descriptors = DescriptorArray::cast(result);
3830
3831 // Copy the content.
3832 int next_descriptor = 0;
3833 for (int i = 0; i < number_of_descriptors(); i++) {
3834 if (IsProperty(i)) new_descriptors->CopyFrom(next_descriptor++, this, i);
3835 }
3836 ASSERT(next_descriptor == new_descriptors->number_of_descriptors());
3837
3838 return new_descriptors;
3839}
3840
3841
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003842void DescriptorArray::SortUnchecked() {
Steve Blocka7e24c12009-10-30 11:49:00 +00003843 // In-place heap sort.
3844 int len = number_of_descriptors();
3845
3846 // Bottom-up max-heap construction.
Steve Block6ded16b2010-05-10 14:33:55 +01003847 // Index of the last node with children
3848 const int max_parent_index = (len / 2) - 1;
3849 for (int i = max_parent_index; i >= 0; --i) {
3850 int parent_index = i;
3851 const uint32_t parent_hash = GetKey(i)->Hash();
3852 while (parent_index <= max_parent_index) {
3853 int child_index = 2 * parent_index + 1;
Steve Blocka7e24c12009-10-30 11:49:00 +00003854 uint32_t child_hash = GetKey(child_index)->Hash();
Steve Block6ded16b2010-05-10 14:33:55 +01003855 if (child_index + 1 < len) {
3856 uint32_t right_child_hash = GetKey(child_index + 1)->Hash();
3857 if (right_child_hash > child_hash) {
3858 child_index++;
3859 child_hash = right_child_hash;
3860 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003861 }
Steve Block6ded16b2010-05-10 14:33:55 +01003862 if (child_hash <= parent_hash) break;
3863 Swap(parent_index, child_index);
3864 // Now element at child_index could be < its children.
3865 parent_index = child_index; // parent_hash remains correct.
Steve Blocka7e24c12009-10-30 11:49:00 +00003866 }
3867 }
3868
3869 // Extract elements and create sorted array.
3870 for (int i = len - 1; i > 0; --i) {
3871 // Put max element at the back of the array.
3872 Swap(0, i);
3873 // Sift down the new top element.
3874 int parent_index = 0;
Steve Block6ded16b2010-05-10 14:33:55 +01003875 const uint32_t parent_hash = GetKey(parent_index)->Hash();
3876 const int max_parent_index = (i / 2) - 1;
3877 while (parent_index <= max_parent_index) {
3878 int child_index = parent_index * 2 + 1;
3879 uint32_t child_hash = GetKey(child_index)->Hash();
3880 if (child_index + 1 < i) {
3881 uint32_t right_child_hash = GetKey(child_index + 1)->Hash();
3882 if (right_child_hash > child_hash) {
3883 child_index++;
3884 child_hash = right_child_hash;
3885 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003886 }
Steve Block6ded16b2010-05-10 14:33:55 +01003887 if (child_hash <= parent_hash) break;
3888 Swap(parent_index, child_index);
3889 parent_index = child_index;
Steve Blocka7e24c12009-10-30 11:49:00 +00003890 }
3891 }
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003892}
Steve Blocka7e24c12009-10-30 11:49:00 +00003893
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003894
3895void DescriptorArray::Sort() {
3896 SortUnchecked();
Steve Blocka7e24c12009-10-30 11:49:00 +00003897 SLOW_ASSERT(IsSortedNoDuplicates());
3898}
3899
3900
3901int DescriptorArray::BinarySearch(String* name, int low, int high) {
3902 uint32_t hash = name->Hash();
3903
3904 while (low <= high) {
3905 int mid = (low + high) / 2;
3906 String* mid_name = GetKey(mid);
3907 uint32_t mid_hash = mid_name->Hash();
3908
3909 if (mid_hash > hash) {
3910 high = mid - 1;
3911 continue;
3912 }
3913 if (mid_hash < hash) {
3914 low = mid + 1;
3915 continue;
3916 }
3917 // Found an element with the same hash-code.
3918 ASSERT(hash == mid_hash);
3919 // There might be more, so we find the first one and
3920 // check them all to see if we have a match.
3921 if (name == mid_name && !is_null_descriptor(mid)) return mid;
3922 while ((mid > low) && (GetKey(mid - 1)->Hash() == hash)) mid--;
3923 for (; (mid <= high) && (GetKey(mid)->Hash() == hash); mid++) {
3924 if (GetKey(mid)->Equals(name) && !is_null_descriptor(mid)) return mid;
3925 }
3926 break;
3927 }
3928 return kNotFound;
3929}
3930
3931
3932int DescriptorArray::LinearSearch(String* name, int len) {
3933 uint32_t hash = name->Hash();
3934 for (int number = 0; number < len; number++) {
3935 String* entry = GetKey(number);
3936 if ((entry->Hash() == hash) &&
3937 name->Equals(entry) &&
3938 !is_null_descriptor(number)) {
3939 return number;
3940 }
3941 }
3942 return kNotFound;
3943}
3944
3945
3946#ifdef DEBUG
3947bool DescriptorArray::IsEqualTo(DescriptorArray* other) {
3948 if (IsEmpty()) return other->IsEmpty();
3949 if (other->IsEmpty()) return false;
3950 if (length() != other->length()) return false;
3951 for (int i = 0; i < length(); ++i) {
3952 if (get(i) != other->get(i) && i != kContentArrayIndex) return false;
3953 }
3954 return GetContentArray()->IsEqualTo(other->GetContentArray());
3955}
3956#endif
3957
3958
3959static StaticResource<StringInputBuffer> string_input_buffer;
3960
3961
3962bool String::LooksValid() {
3963 if (!Heap::Contains(this)) return false;
3964 return true;
3965}
3966
3967
3968int String::Utf8Length() {
3969 if (IsAsciiRepresentation()) return length();
3970 // Attempt to flatten before accessing the string. It probably
3971 // doesn't make Utf8Length faster, but it is very likely that
3972 // the string will be accessed later (for example by WriteUtf8)
3973 // so it's still a good idea.
Steve Block6ded16b2010-05-10 14:33:55 +01003974 TryFlatten();
Steve Blocka7e24c12009-10-30 11:49:00 +00003975 Access<StringInputBuffer> buffer(&string_input_buffer);
3976 buffer->Reset(0, this);
3977 int result = 0;
3978 while (buffer->has_more())
3979 result += unibrow::Utf8::Length(buffer->GetNext());
3980 return result;
3981}
3982
3983
3984Vector<const char> String::ToAsciiVector() {
3985 ASSERT(IsAsciiRepresentation());
3986 ASSERT(IsFlat());
3987
3988 int offset = 0;
3989 int length = this->length();
3990 StringRepresentationTag string_tag = StringShape(this).representation_tag();
3991 String* string = this;
Steve Blockd0582a62009-12-15 09:54:21 +00003992 if (string_tag == kConsStringTag) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003993 ConsString* cons = ConsString::cast(string);
3994 ASSERT(cons->second()->length() == 0);
3995 string = cons->first();
3996 string_tag = StringShape(string).representation_tag();
3997 }
3998 if (string_tag == kSeqStringTag) {
3999 SeqAsciiString* seq = SeqAsciiString::cast(string);
4000 char* start = seq->GetChars();
4001 return Vector<const char>(start + offset, length);
4002 }
4003 ASSERT(string_tag == kExternalStringTag);
4004 ExternalAsciiString* ext = ExternalAsciiString::cast(string);
4005 const char* start = ext->resource()->data();
4006 return Vector<const char>(start + offset, length);
4007}
4008
4009
4010Vector<const uc16> String::ToUC16Vector() {
4011 ASSERT(IsTwoByteRepresentation());
4012 ASSERT(IsFlat());
4013
4014 int offset = 0;
4015 int length = this->length();
4016 StringRepresentationTag string_tag = StringShape(this).representation_tag();
4017 String* string = this;
Steve Blockd0582a62009-12-15 09:54:21 +00004018 if (string_tag == kConsStringTag) {
Steve Blocka7e24c12009-10-30 11:49:00 +00004019 ConsString* cons = ConsString::cast(string);
4020 ASSERT(cons->second()->length() == 0);
4021 string = cons->first();
4022 string_tag = StringShape(string).representation_tag();
4023 }
4024 if (string_tag == kSeqStringTag) {
4025 SeqTwoByteString* seq = SeqTwoByteString::cast(string);
4026 return Vector<const uc16>(seq->GetChars() + offset, length);
4027 }
4028 ASSERT(string_tag == kExternalStringTag);
4029 ExternalTwoByteString* ext = ExternalTwoByteString::cast(string);
4030 const uc16* start =
4031 reinterpret_cast<const uc16*>(ext->resource()->data());
4032 return Vector<const uc16>(start + offset, length);
4033}
4034
4035
4036SmartPointer<char> String::ToCString(AllowNullsFlag allow_nulls,
4037 RobustnessFlag robust_flag,
4038 int offset,
4039 int length,
4040 int* length_return) {
4041 ASSERT(NativeAllocationChecker::allocation_allowed());
4042 if (robust_flag == ROBUST_STRING_TRAVERSAL && !LooksValid()) {
4043 return SmartPointer<char>(NULL);
4044 }
4045
4046 // Negative length means the to the end of the string.
4047 if (length < 0) length = kMaxInt - offset;
4048
4049 // Compute the size of the UTF-8 string. Start at the specified offset.
4050 Access<StringInputBuffer> buffer(&string_input_buffer);
4051 buffer->Reset(offset, this);
4052 int character_position = offset;
4053 int utf8_bytes = 0;
4054 while (buffer->has_more()) {
4055 uint16_t character = buffer->GetNext();
4056 if (character_position < offset + length) {
4057 utf8_bytes += unibrow::Utf8::Length(character);
4058 }
4059 character_position++;
4060 }
4061
4062 if (length_return) {
4063 *length_return = utf8_bytes;
4064 }
4065
4066 char* result = NewArray<char>(utf8_bytes + 1);
4067
4068 // Convert the UTF-16 string to a UTF-8 buffer. Start at the specified offset.
4069 buffer->Rewind();
4070 buffer->Seek(offset);
4071 character_position = offset;
4072 int utf8_byte_position = 0;
4073 while (buffer->has_more()) {
4074 uint16_t character = buffer->GetNext();
4075 if (character_position < offset + length) {
4076 if (allow_nulls == DISALLOW_NULLS && character == 0) {
4077 character = ' ';
4078 }
4079 utf8_byte_position +=
4080 unibrow::Utf8::Encode(result + utf8_byte_position, character);
4081 }
4082 character_position++;
4083 }
4084 result[utf8_byte_position] = 0;
4085 return SmartPointer<char>(result);
4086}
4087
4088
4089SmartPointer<char> String::ToCString(AllowNullsFlag allow_nulls,
4090 RobustnessFlag robust_flag,
4091 int* length_return) {
4092 return ToCString(allow_nulls, robust_flag, 0, -1, length_return);
4093}
4094
4095
4096const uc16* String::GetTwoByteData() {
4097 return GetTwoByteData(0);
4098}
4099
4100
4101const uc16* String::GetTwoByteData(unsigned start) {
4102 ASSERT(!IsAsciiRepresentation());
4103 switch (StringShape(this).representation_tag()) {
4104 case kSeqStringTag:
4105 return SeqTwoByteString::cast(this)->SeqTwoByteStringGetData(start);
4106 case kExternalStringTag:
4107 return ExternalTwoByteString::cast(this)->
4108 ExternalTwoByteStringGetData(start);
Steve Blocka7e24c12009-10-30 11:49:00 +00004109 case kConsStringTag:
4110 UNREACHABLE();
4111 return NULL;
4112 }
4113 UNREACHABLE();
4114 return NULL;
4115}
4116
4117
4118SmartPointer<uc16> String::ToWideCString(RobustnessFlag robust_flag) {
4119 ASSERT(NativeAllocationChecker::allocation_allowed());
4120
4121 if (robust_flag == ROBUST_STRING_TRAVERSAL && !LooksValid()) {
4122 return SmartPointer<uc16>();
4123 }
4124
4125 Access<StringInputBuffer> buffer(&string_input_buffer);
4126 buffer->Reset(this);
4127
4128 uc16* result = NewArray<uc16>(length() + 1);
4129
4130 int i = 0;
4131 while (buffer->has_more()) {
4132 uint16_t character = buffer->GetNext();
4133 result[i++] = character;
4134 }
4135 result[i] = 0;
4136 return SmartPointer<uc16>(result);
4137}
4138
4139
4140const uc16* SeqTwoByteString::SeqTwoByteStringGetData(unsigned start) {
4141 return reinterpret_cast<uc16*>(
4142 reinterpret_cast<char*>(this) - kHeapObjectTag + kHeaderSize) + start;
4143}
4144
4145
4146void SeqTwoByteString::SeqTwoByteStringReadBlockIntoBuffer(ReadBlockBuffer* rbb,
4147 unsigned* offset_ptr,
4148 unsigned max_chars) {
4149 unsigned chars_read = 0;
4150 unsigned offset = *offset_ptr;
4151 while (chars_read < max_chars) {
4152 uint16_t c = *reinterpret_cast<uint16_t*>(
4153 reinterpret_cast<char*>(this) -
4154 kHeapObjectTag + kHeaderSize + offset * kShortSize);
4155 if (c <= kMaxAsciiCharCode) {
4156 // Fast case for ASCII characters. Cursor is an input output argument.
4157 if (!unibrow::CharacterStream::EncodeAsciiCharacter(c,
4158 rbb->util_buffer,
4159 rbb->capacity,
4160 rbb->cursor)) {
4161 break;
4162 }
4163 } else {
4164 if (!unibrow::CharacterStream::EncodeNonAsciiCharacter(c,
4165 rbb->util_buffer,
4166 rbb->capacity,
4167 rbb->cursor)) {
4168 break;
4169 }
4170 }
4171 offset++;
4172 chars_read++;
4173 }
4174 *offset_ptr = offset;
4175 rbb->remaining += chars_read;
4176}
4177
4178
4179const unibrow::byte* SeqAsciiString::SeqAsciiStringReadBlock(
4180 unsigned* remaining,
4181 unsigned* offset_ptr,
4182 unsigned max_chars) {
4183 const unibrow::byte* b = reinterpret_cast<unibrow::byte*>(this) -
4184 kHeapObjectTag + kHeaderSize + *offset_ptr * kCharSize;
4185 *remaining = max_chars;
4186 *offset_ptr += max_chars;
4187 return b;
4188}
4189
4190
4191// This will iterate unless the block of string data spans two 'halves' of
4192// a ConsString, in which case it will recurse. Since the block of string
4193// data to be read has a maximum size this limits the maximum recursion
4194// depth to something sane. Since C++ does not have tail call recursion
4195// elimination, the iteration must be explicit. Since this is not an
4196// -IntoBuffer method it can delegate to one of the efficient
4197// *AsciiStringReadBlock routines.
4198const unibrow::byte* ConsString::ConsStringReadBlock(ReadBlockBuffer* rbb,
4199 unsigned* offset_ptr,
4200 unsigned max_chars) {
4201 ConsString* current = this;
4202 unsigned offset = *offset_ptr;
4203 int offset_correction = 0;
4204
4205 while (true) {
4206 String* left = current->first();
4207 unsigned left_length = (unsigned)left->length();
4208 if (left_length > offset &&
4209 (max_chars <= left_length - offset ||
4210 (rbb->capacity <= left_length - offset &&
4211 (max_chars = left_length - offset, true)))) { // comma operator!
4212 // Left hand side only - iterate unless we have reached the bottom of
4213 // the cons tree. The assignment on the left of the comma operator is
4214 // in order to make use of the fact that the -IntoBuffer routines can
4215 // produce at most 'capacity' characters. This enables us to postpone
4216 // the point where we switch to the -IntoBuffer routines (below) in order
4217 // to maximize the chances of delegating a big chunk of work to the
4218 // efficient *AsciiStringReadBlock routines.
4219 if (StringShape(left).IsCons()) {
4220 current = ConsString::cast(left);
4221 continue;
4222 } else {
4223 const unibrow::byte* answer =
4224 String::ReadBlock(left, rbb, &offset, max_chars);
4225 *offset_ptr = offset + offset_correction;
4226 return answer;
4227 }
4228 } else if (left_length <= offset) {
4229 // Right hand side only - iterate unless we have reached the bottom of
4230 // the cons tree.
4231 String* right = current->second();
4232 offset -= left_length;
4233 offset_correction += left_length;
4234 if (StringShape(right).IsCons()) {
4235 current = ConsString::cast(right);
4236 continue;
4237 } else {
4238 const unibrow::byte* answer =
4239 String::ReadBlock(right, rbb, &offset, max_chars);
4240 *offset_ptr = offset + offset_correction;
4241 return answer;
4242 }
4243 } else {
4244 // The block to be read spans two sides of the ConsString, so we call the
4245 // -IntoBuffer version, which will recurse. The -IntoBuffer methods
4246 // are able to assemble data from several part strings because they use
4247 // the util_buffer to store their data and never return direct pointers
4248 // to their storage. We don't try to read more than the buffer capacity
4249 // here or we can get too much recursion.
4250 ASSERT(rbb->remaining == 0);
4251 ASSERT(rbb->cursor == 0);
4252 current->ConsStringReadBlockIntoBuffer(
4253 rbb,
4254 &offset,
4255 max_chars > rbb->capacity ? rbb->capacity : max_chars);
4256 *offset_ptr = offset + offset_correction;
4257 return rbb->util_buffer;
4258 }
4259 }
4260}
4261
4262
Steve Blocka7e24c12009-10-30 11:49:00 +00004263uint16_t ExternalAsciiString::ExternalAsciiStringGet(int index) {
4264 ASSERT(index >= 0 && index < length());
4265 return resource()->data()[index];
4266}
4267
4268
4269const unibrow::byte* ExternalAsciiString::ExternalAsciiStringReadBlock(
4270 unsigned* remaining,
4271 unsigned* offset_ptr,
4272 unsigned max_chars) {
4273 // Cast const char* to unibrow::byte* (signedness difference).
4274 const unibrow::byte* b =
4275 reinterpret_cast<const unibrow::byte*>(resource()->data()) + *offset_ptr;
4276 *remaining = max_chars;
4277 *offset_ptr += max_chars;
4278 return b;
4279}
4280
4281
4282const uc16* ExternalTwoByteString::ExternalTwoByteStringGetData(
4283 unsigned start) {
4284 return resource()->data() + start;
4285}
4286
4287
4288uint16_t ExternalTwoByteString::ExternalTwoByteStringGet(int index) {
4289 ASSERT(index >= 0 && index < length());
4290 return resource()->data()[index];
4291}
4292
4293
4294void ExternalTwoByteString::ExternalTwoByteStringReadBlockIntoBuffer(
4295 ReadBlockBuffer* rbb,
4296 unsigned* offset_ptr,
4297 unsigned max_chars) {
4298 unsigned chars_read = 0;
4299 unsigned offset = *offset_ptr;
4300 const uint16_t* data = resource()->data();
4301 while (chars_read < max_chars) {
4302 uint16_t c = data[offset];
4303 if (c <= kMaxAsciiCharCode) {
4304 // Fast case for ASCII characters. Cursor is an input output argument.
4305 if (!unibrow::CharacterStream::EncodeAsciiCharacter(c,
4306 rbb->util_buffer,
4307 rbb->capacity,
4308 rbb->cursor))
4309 break;
4310 } else {
4311 if (!unibrow::CharacterStream::EncodeNonAsciiCharacter(c,
4312 rbb->util_buffer,
4313 rbb->capacity,
4314 rbb->cursor))
4315 break;
4316 }
4317 offset++;
4318 chars_read++;
4319 }
4320 *offset_ptr = offset;
4321 rbb->remaining += chars_read;
4322}
4323
4324
4325void SeqAsciiString::SeqAsciiStringReadBlockIntoBuffer(ReadBlockBuffer* rbb,
4326 unsigned* offset_ptr,
4327 unsigned max_chars) {
4328 unsigned capacity = rbb->capacity - rbb->cursor;
4329 if (max_chars > capacity) max_chars = capacity;
4330 memcpy(rbb->util_buffer + rbb->cursor,
4331 reinterpret_cast<char*>(this) - kHeapObjectTag + kHeaderSize +
4332 *offset_ptr * kCharSize,
4333 max_chars);
4334 rbb->remaining += max_chars;
4335 *offset_ptr += max_chars;
4336 rbb->cursor += max_chars;
4337}
4338
4339
4340void ExternalAsciiString::ExternalAsciiStringReadBlockIntoBuffer(
4341 ReadBlockBuffer* rbb,
4342 unsigned* offset_ptr,
4343 unsigned max_chars) {
4344 unsigned capacity = rbb->capacity - rbb->cursor;
4345 if (max_chars > capacity) max_chars = capacity;
4346 memcpy(rbb->util_buffer + rbb->cursor,
4347 resource()->data() + *offset_ptr,
4348 max_chars);
4349 rbb->remaining += max_chars;
4350 *offset_ptr += max_chars;
4351 rbb->cursor += max_chars;
4352}
4353
4354
4355// This method determines the type of string involved and then copies
4356// a whole chunk of characters into a buffer, or returns a pointer to a buffer
4357// where they can be found. The pointer is not necessarily valid across a GC
4358// (see AsciiStringReadBlock).
4359const unibrow::byte* String::ReadBlock(String* input,
4360 ReadBlockBuffer* rbb,
4361 unsigned* offset_ptr,
4362 unsigned max_chars) {
4363 ASSERT(*offset_ptr <= static_cast<unsigned>(input->length()));
4364 if (max_chars == 0) {
4365 rbb->remaining = 0;
4366 return NULL;
4367 }
4368 switch (StringShape(input).representation_tag()) {
4369 case kSeqStringTag:
4370 if (input->IsAsciiRepresentation()) {
4371 SeqAsciiString* str = SeqAsciiString::cast(input);
4372 return str->SeqAsciiStringReadBlock(&rbb->remaining,
4373 offset_ptr,
4374 max_chars);
4375 } else {
4376 SeqTwoByteString* str = SeqTwoByteString::cast(input);
4377 str->SeqTwoByteStringReadBlockIntoBuffer(rbb,
4378 offset_ptr,
4379 max_chars);
4380 return rbb->util_buffer;
4381 }
4382 case kConsStringTag:
4383 return ConsString::cast(input)->ConsStringReadBlock(rbb,
4384 offset_ptr,
4385 max_chars);
Steve Blocka7e24c12009-10-30 11:49:00 +00004386 case kExternalStringTag:
4387 if (input->IsAsciiRepresentation()) {
4388 return ExternalAsciiString::cast(input)->ExternalAsciiStringReadBlock(
4389 &rbb->remaining,
4390 offset_ptr,
4391 max_chars);
4392 } else {
4393 ExternalTwoByteString::cast(input)->
4394 ExternalTwoByteStringReadBlockIntoBuffer(rbb,
4395 offset_ptr,
4396 max_chars);
4397 return rbb->util_buffer;
4398 }
4399 default:
4400 break;
4401 }
4402
4403 UNREACHABLE();
4404 return 0;
4405}
4406
4407
4408Relocatable* Relocatable::top_ = NULL;
4409
4410
4411void Relocatable::PostGarbageCollectionProcessing() {
4412 Relocatable* current = top_;
4413 while (current != NULL) {
4414 current->PostGarbageCollection();
4415 current = current->prev_;
4416 }
4417}
4418
4419
4420// Reserve space for statics needing saving and restoring.
4421int Relocatable::ArchiveSpacePerThread() {
4422 return sizeof(top_);
4423}
4424
4425
4426// Archive statics that are thread local.
4427char* Relocatable::ArchiveState(char* to) {
4428 *reinterpret_cast<Relocatable**>(to) = top_;
4429 top_ = NULL;
4430 return to + ArchiveSpacePerThread();
4431}
4432
4433
4434// Restore statics that are thread local.
4435char* Relocatable::RestoreState(char* from) {
4436 top_ = *reinterpret_cast<Relocatable**>(from);
4437 return from + ArchiveSpacePerThread();
4438}
4439
4440
4441char* Relocatable::Iterate(ObjectVisitor* v, char* thread_storage) {
4442 Relocatable* top = *reinterpret_cast<Relocatable**>(thread_storage);
4443 Iterate(v, top);
4444 return thread_storage + ArchiveSpacePerThread();
4445}
4446
4447
4448void Relocatable::Iterate(ObjectVisitor* v) {
4449 Iterate(v, top_);
4450}
4451
4452
4453void Relocatable::Iterate(ObjectVisitor* v, Relocatable* top) {
4454 Relocatable* current = top;
4455 while (current != NULL) {
4456 current->IterateInstance(v);
4457 current = current->prev_;
4458 }
4459}
4460
4461
4462FlatStringReader::FlatStringReader(Handle<String> str)
4463 : str_(str.location()),
4464 length_(str->length()) {
4465 PostGarbageCollection();
4466}
4467
4468
4469FlatStringReader::FlatStringReader(Vector<const char> input)
4470 : str_(0),
4471 is_ascii_(true),
4472 length_(input.length()),
4473 start_(input.start()) { }
4474
4475
4476void FlatStringReader::PostGarbageCollection() {
4477 if (str_ == NULL) return;
4478 Handle<String> str(str_);
4479 ASSERT(str->IsFlat());
4480 is_ascii_ = str->IsAsciiRepresentation();
4481 if (is_ascii_) {
4482 start_ = str->ToAsciiVector().start();
4483 } else {
4484 start_ = str->ToUC16Vector().start();
4485 }
4486}
4487
4488
4489void StringInputBuffer::Seek(unsigned pos) {
4490 Reset(pos, input_);
4491}
4492
4493
4494void SafeStringInputBuffer::Seek(unsigned pos) {
4495 Reset(pos, input_);
4496}
4497
4498
4499// This method determines the type of string involved and then copies
4500// a whole chunk of characters into a buffer. It can be used with strings
4501// that have been glued together to form a ConsString and which must cooperate
4502// to fill up a buffer.
4503void String::ReadBlockIntoBuffer(String* input,
4504 ReadBlockBuffer* rbb,
4505 unsigned* offset_ptr,
4506 unsigned max_chars) {
4507 ASSERT(*offset_ptr <= (unsigned)input->length());
4508 if (max_chars == 0) return;
4509
4510 switch (StringShape(input).representation_tag()) {
4511 case kSeqStringTag:
4512 if (input->IsAsciiRepresentation()) {
4513 SeqAsciiString::cast(input)->SeqAsciiStringReadBlockIntoBuffer(rbb,
4514 offset_ptr,
4515 max_chars);
4516 return;
4517 } else {
4518 SeqTwoByteString::cast(input)->SeqTwoByteStringReadBlockIntoBuffer(rbb,
4519 offset_ptr,
4520 max_chars);
4521 return;
4522 }
4523 case kConsStringTag:
4524 ConsString::cast(input)->ConsStringReadBlockIntoBuffer(rbb,
4525 offset_ptr,
4526 max_chars);
4527 return;
Steve Blocka7e24c12009-10-30 11:49:00 +00004528 case kExternalStringTag:
4529 if (input->IsAsciiRepresentation()) {
Steve Blockd0582a62009-12-15 09:54:21 +00004530 ExternalAsciiString::cast(input)->
4531 ExternalAsciiStringReadBlockIntoBuffer(rbb, offset_ptr, max_chars);
4532 } else {
4533 ExternalTwoByteString::cast(input)->
4534 ExternalTwoByteStringReadBlockIntoBuffer(rbb,
4535 offset_ptr,
4536 max_chars);
Steve Blocka7e24c12009-10-30 11:49:00 +00004537 }
4538 return;
4539 default:
4540 break;
4541 }
4542
4543 UNREACHABLE();
4544 return;
4545}
4546
4547
4548const unibrow::byte* String::ReadBlock(String* input,
4549 unibrow::byte* util_buffer,
4550 unsigned capacity,
4551 unsigned* remaining,
4552 unsigned* offset_ptr) {
4553 ASSERT(*offset_ptr <= (unsigned)input->length());
4554 unsigned chars = input->length() - *offset_ptr;
4555 ReadBlockBuffer rbb(util_buffer, 0, capacity, 0);
4556 const unibrow::byte* answer = ReadBlock(input, &rbb, offset_ptr, chars);
4557 ASSERT(rbb.remaining <= static_cast<unsigned>(input->length()));
4558 *remaining = rbb.remaining;
4559 return answer;
4560}
4561
4562
4563const unibrow::byte* String::ReadBlock(String** raw_input,
4564 unibrow::byte* util_buffer,
4565 unsigned capacity,
4566 unsigned* remaining,
4567 unsigned* offset_ptr) {
4568 Handle<String> input(raw_input);
4569 ASSERT(*offset_ptr <= (unsigned)input->length());
4570 unsigned chars = input->length() - *offset_ptr;
4571 if (chars > capacity) chars = capacity;
4572 ReadBlockBuffer rbb(util_buffer, 0, capacity, 0);
4573 ReadBlockIntoBuffer(*input, &rbb, offset_ptr, chars);
4574 ASSERT(rbb.remaining <= static_cast<unsigned>(input->length()));
4575 *remaining = rbb.remaining;
4576 return rbb.util_buffer;
4577}
4578
4579
4580// This will iterate unless the block of string data spans two 'halves' of
4581// a ConsString, in which case it will recurse. Since the block of string
4582// data to be read has a maximum size this limits the maximum recursion
4583// depth to something sane. Since C++ does not have tail call recursion
4584// elimination, the iteration must be explicit.
4585void ConsString::ConsStringReadBlockIntoBuffer(ReadBlockBuffer* rbb,
4586 unsigned* offset_ptr,
4587 unsigned max_chars) {
4588 ConsString* current = this;
4589 unsigned offset = *offset_ptr;
4590 int offset_correction = 0;
4591
4592 while (true) {
4593 String* left = current->first();
4594 unsigned left_length = (unsigned)left->length();
4595 if (left_length > offset &&
4596 max_chars <= left_length - offset) {
4597 // Left hand side only - iterate unless we have reached the bottom of
4598 // the cons tree.
4599 if (StringShape(left).IsCons()) {
4600 current = ConsString::cast(left);
4601 continue;
4602 } else {
4603 String::ReadBlockIntoBuffer(left, rbb, &offset, max_chars);
4604 *offset_ptr = offset + offset_correction;
4605 return;
4606 }
4607 } else if (left_length <= offset) {
4608 // Right hand side only - iterate unless we have reached the bottom of
4609 // the cons tree.
4610 offset -= left_length;
4611 offset_correction += left_length;
4612 String* right = current->second();
4613 if (StringShape(right).IsCons()) {
4614 current = ConsString::cast(right);
4615 continue;
4616 } else {
4617 String::ReadBlockIntoBuffer(right, rbb, &offset, max_chars);
4618 *offset_ptr = offset + offset_correction;
4619 return;
4620 }
4621 } else {
4622 // The block to be read spans two sides of the ConsString, so we recurse.
4623 // First recurse on the left.
4624 max_chars -= left_length - offset;
4625 String::ReadBlockIntoBuffer(left, rbb, &offset, left_length - offset);
4626 // We may have reached the max or there may not have been enough space
4627 // in the buffer for the characters in the left hand side.
4628 if (offset == left_length) {
4629 // Recurse on the right.
4630 String* right = String::cast(current->second());
4631 offset -= left_length;
4632 offset_correction += left_length;
4633 String::ReadBlockIntoBuffer(right, rbb, &offset, max_chars);
4634 }
4635 *offset_ptr = offset + offset_correction;
4636 return;
4637 }
4638 }
4639}
4640
4641
Steve Blocka7e24c12009-10-30 11:49:00 +00004642uint16_t ConsString::ConsStringGet(int index) {
4643 ASSERT(index >= 0 && index < this->length());
4644
4645 // Check for a flattened cons string
4646 if (second()->length() == 0) {
4647 String* left = first();
4648 return left->Get(index);
4649 }
4650
4651 String* string = String::cast(this);
4652
4653 while (true) {
4654 if (StringShape(string).IsCons()) {
4655 ConsString* cons_string = ConsString::cast(string);
4656 String* left = cons_string->first();
4657 if (left->length() > index) {
4658 string = left;
4659 } else {
4660 index -= left->length();
4661 string = cons_string->second();
4662 }
4663 } else {
4664 return string->Get(index);
4665 }
4666 }
4667
4668 UNREACHABLE();
4669 return 0;
4670}
4671
4672
4673template <typename sinkchar>
4674void String::WriteToFlat(String* src,
4675 sinkchar* sink,
4676 int f,
4677 int t) {
4678 String* source = src;
4679 int from = f;
4680 int to = t;
4681 while (true) {
4682 ASSERT(0 <= from && from <= to && to <= source->length());
4683 switch (StringShape(source).full_representation_tag()) {
4684 case kAsciiStringTag | kExternalStringTag: {
4685 CopyChars(sink,
4686 ExternalAsciiString::cast(source)->resource()->data() + from,
4687 to - from);
4688 return;
4689 }
4690 case kTwoByteStringTag | kExternalStringTag: {
4691 const uc16* data =
4692 ExternalTwoByteString::cast(source)->resource()->data();
4693 CopyChars(sink,
4694 data + from,
4695 to - from);
4696 return;
4697 }
4698 case kAsciiStringTag | kSeqStringTag: {
4699 CopyChars(sink,
4700 SeqAsciiString::cast(source)->GetChars() + from,
4701 to - from);
4702 return;
4703 }
4704 case kTwoByteStringTag | kSeqStringTag: {
4705 CopyChars(sink,
4706 SeqTwoByteString::cast(source)->GetChars() + from,
4707 to - from);
4708 return;
4709 }
Steve Blocka7e24c12009-10-30 11:49:00 +00004710 case kAsciiStringTag | kConsStringTag:
4711 case kTwoByteStringTag | kConsStringTag: {
4712 ConsString* cons_string = ConsString::cast(source);
4713 String* first = cons_string->first();
4714 int boundary = first->length();
4715 if (to - boundary >= boundary - from) {
4716 // Right hand side is longer. Recurse over left.
4717 if (from < boundary) {
4718 WriteToFlat(first, sink, from, boundary);
4719 sink += boundary - from;
4720 from = 0;
4721 } else {
4722 from -= boundary;
4723 }
4724 to -= boundary;
4725 source = cons_string->second();
4726 } else {
4727 // Left hand side is longer. Recurse over right.
4728 if (to > boundary) {
4729 String* second = cons_string->second();
4730 WriteToFlat(second,
4731 sink + boundary - from,
4732 0,
4733 to - boundary);
4734 to = boundary;
4735 }
4736 source = first;
4737 }
4738 break;
4739 }
4740 }
4741 }
4742}
4743
4744
Steve Blocka7e24c12009-10-30 11:49:00 +00004745template <typename IteratorA, typename IteratorB>
4746static inline bool CompareStringContents(IteratorA* ia, IteratorB* ib) {
4747 // General slow case check. We know that the ia and ib iterators
4748 // have the same length.
4749 while (ia->has_more()) {
4750 uc32 ca = ia->GetNext();
4751 uc32 cb = ib->GetNext();
4752 if (ca != cb)
4753 return false;
4754 }
4755 return true;
4756}
4757
4758
4759// Compares the contents of two strings by reading and comparing
4760// int-sized blocks of characters.
4761template <typename Char>
4762static inline bool CompareRawStringContents(Vector<Char> a, Vector<Char> b) {
4763 int length = a.length();
4764 ASSERT_EQ(length, b.length());
4765 const Char* pa = a.start();
4766 const Char* pb = b.start();
4767 int i = 0;
4768#ifndef V8_HOST_CAN_READ_UNALIGNED
4769 // If this architecture isn't comfortable reading unaligned ints
4770 // then we have to check that the strings are aligned before
4771 // comparing them blockwise.
4772 const int kAlignmentMask = sizeof(uint32_t) - 1; // NOLINT
4773 uint32_t pa_addr = reinterpret_cast<uint32_t>(pa);
4774 uint32_t pb_addr = reinterpret_cast<uint32_t>(pb);
4775 if (((pa_addr & kAlignmentMask) | (pb_addr & kAlignmentMask)) == 0) {
4776#endif
4777 const int kStepSize = sizeof(int) / sizeof(Char); // NOLINT
4778 int endpoint = length - kStepSize;
4779 // Compare blocks until we reach near the end of the string.
4780 for (; i <= endpoint; i += kStepSize) {
4781 uint32_t wa = *reinterpret_cast<const uint32_t*>(pa + i);
4782 uint32_t wb = *reinterpret_cast<const uint32_t*>(pb + i);
4783 if (wa != wb) {
4784 return false;
4785 }
4786 }
4787#ifndef V8_HOST_CAN_READ_UNALIGNED
4788 }
4789#endif
4790 // Compare the remaining characters that didn't fit into a block.
4791 for (; i < length; i++) {
4792 if (a[i] != b[i]) {
4793 return false;
4794 }
4795 }
4796 return true;
4797}
4798
4799
4800static StringInputBuffer string_compare_buffer_b;
4801
4802
4803template <typename IteratorA>
4804static inline bool CompareStringContentsPartial(IteratorA* ia, String* b) {
4805 if (b->IsFlat()) {
4806 if (b->IsAsciiRepresentation()) {
4807 VectorIterator<char> ib(b->ToAsciiVector());
4808 return CompareStringContents(ia, &ib);
4809 } else {
4810 VectorIterator<uc16> ib(b->ToUC16Vector());
4811 return CompareStringContents(ia, &ib);
4812 }
4813 } else {
4814 string_compare_buffer_b.Reset(0, b);
4815 return CompareStringContents(ia, &string_compare_buffer_b);
4816 }
4817}
4818
4819
4820static StringInputBuffer string_compare_buffer_a;
4821
4822
4823bool String::SlowEquals(String* other) {
4824 // Fast check: negative check with lengths.
4825 int len = length();
4826 if (len != other->length()) return false;
4827 if (len == 0) return true;
4828
4829 // Fast check: if hash code is computed for both strings
4830 // a fast negative check can be performed.
4831 if (HasHashCode() && other->HasHashCode()) {
4832 if (Hash() != other->Hash()) return false;
4833 }
4834
Leon Clarkef7060e22010-06-03 12:02:55 +01004835 // We know the strings are both non-empty. Compare the first chars
4836 // before we try to flatten the strings.
4837 if (this->Get(0) != other->Get(0)) return false;
4838
4839 String* lhs = this->TryFlattenGetString();
4840 String* rhs = other->TryFlattenGetString();
4841
4842 if (StringShape(lhs).IsSequentialAscii() &&
4843 StringShape(rhs).IsSequentialAscii()) {
4844 const char* str1 = SeqAsciiString::cast(lhs)->GetChars();
4845 const char* str2 = SeqAsciiString::cast(rhs)->GetChars();
Steve Blocka7e24c12009-10-30 11:49:00 +00004846 return CompareRawStringContents(Vector<const char>(str1, len),
4847 Vector<const char>(str2, len));
4848 }
4849
Leon Clarkef7060e22010-06-03 12:02:55 +01004850 if (lhs->IsFlat()) {
Ben Murdochbb769b22010-08-11 14:56:33 +01004851 if (lhs->IsAsciiRepresentation()) {
Leon Clarkef7060e22010-06-03 12:02:55 +01004852 Vector<const char> vec1 = lhs->ToAsciiVector();
4853 if (rhs->IsFlat()) {
4854 if (rhs->IsAsciiRepresentation()) {
4855 Vector<const char> vec2 = rhs->ToAsciiVector();
Steve Blocka7e24c12009-10-30 11:49:00 +00004856 return CompareRawStringContents(vec1, vec2);
4857 } else {
4858 VectorIterator<char> buf1(vec1);
Leon Clarkef7060e22010-06-03 12:02:55 +01004859 VectorIterator<uc16> ib(rhs->ToUC16Vector());
Steve Blocka7e24c12009-10-30 11:49:00 +00004860 return CompareStringContents(&buf1, &ib);
4861 }
4862 } else {
4863 VectorIterator<char> buf1(vec1);
Leon Clarkef7060e22010-06-03 12:02:55 +01004864 string_compare_buffer_b.Reset(0, rhs);
Steve Blocka7e24c12009-10-30 11:49:00 +00004865 return CompareStringContents(&buf1, &string_compare_buffer_b);
4866 }
4867 } else {
Leon Clarkef7060e22010-06-03 12:02:55 +01004868 Vector<const uc16> vec1 = lhs->ToUC16Vector();
4869 if (rhs->IsFlat()) {
4870 if (rhs->IsAsciiRepresentation()) {
Steve Blocka7e24c12009-10-30 11:49:00 +00004871 VectorIterator<uc16> buf1(vec1);
Leon Clarkef7060e22010-06-03 12:02:55 +01004872 VectorIterator<char> ib(rhs->ToAsciiVector());
Steve Blocka7e24c12009-10-30 11:49:00 +00004873 return CompareStringContents(&buf1, &ib);
4874 } else {
Leon Clarkef7060e22010-06-03 12:02:55 +01004875 Vector<const uc16> vec2(rhs->ToUC16Vector());
Steve Blocka7e24c12009-10-30 11:49:00 +00004876 return CompareRawStringContents(vec1, vec2);
4877 }
4878 } else {
4879 VectorIterator<uc16> buf1(vec1);
Leon Clarkef7060e22010-06-03 12:02:55 +01004880 string_compare_buffer_b.Reset(0, rhs);
Steve Blocka7e24c12009-10-30 11:49:00 +00004881 return CompareStringContents(&buf1, &string_compare_buffer_b);
4882 }
4883 }
4884 } else {
Leon Clarkef7060e22010-06-03 12:02:55 +01004885 string_compare_buffer_a.Reset(0, lhs);
4886 return CompareStringContentsPartial(&string_compare_buffer_a, rhs);
Steve Blocka7e24c12009-10-30 11:49:00 +00004887 }
4888}
4889
4890
4891bool String::MarkAsUndetectable() {
4892 if (StringShape(this).IsSymbol()) return false;
4893
4894 Map* map = this->map();
Steve Blockd0582a62009-12-15 09:54:21 +00004895 if (map == Heap::string_map()) {
4896 this->set_map(Heap::undetectable_string_map());
Steve Blocka7e24c12009-10-30 11:49:00 +00004897 return true;
Steve Blockd0582a62009-12-15 09:54:21 +00004898 } else if (map == Heap::ascii_string_map()) {
4899 this->set_map(Heap::undetectable_ascii_string_map());
Steve Blocka7e24c12009-10-30 11:49:00 +00004900 return true;
4901 }
4902 // Rest cannot be marked as undetectable
4903 return false;
4904}
4905
4906
4907bool String::IsEqualTo(Vector<const char> str) {
4908 int slen = length();
4909 Access<Scanner::Utf8Decoder> decoder(Scanner::utf8_decoder());
4910 decoder->Reset(str.start(), str.length());
4911 int i;
4912 for (i = 0; i < slen && decoder->has_more(); i++) {
4913 uc32 r = decoder->GetNext();
4914 if (Get(i) != r) return false;
4915 }
4916 return i == slen && !decoder->has_more();
4917}
4918
4919
Steve Block6ded16b2010-05-10 14:33:55 +01004920template <typename schar>
4921static inline uint32_t HashSequentialString(const schar* chars, int length) {
4922 StringHasher hasher(length);
4923 if (!hasher.has_trivial_hash()) {
4924 int i;
4925 for (i = 0; hasher.is_array_index() && (i < length); i++) {
4926 hasher.AddCharacter(chars[i]);
4927 }
4928 for (; i < length; i++) {
4929 hasher.AddCharacterNoIndex(chars[i]);
4930 }
4931 }
4932 return hasher.GetHashField();
4933}
4934
4935
Steve Blocka7e24c12009-10-30 11:49:00 +00004936uint32_t String::ComputeAndSetHash() {
4937 // Should only be called if hash code has not yet been computed.
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01004938 ASSERT(!HasHashCode());
Steve Blocka7e24c12009-10-30 11:49:00 +00004939
Steve Block6ded16b2010-05-10 14:33:55 +01004940 const int len = length();
4941
Steve Blocka7e24c12009-10-30 11:49:00 +00004942 // Compute the hash code.
Steve Block6ded16b2010-05-10 14:33:55 +01004943 uint32_t field = 0;
4944 if (StringShape(this).IsSequentialAscii()) {
4945 field = HashSequentialString(SeqAsciiString::cast(this)->GetChars(), len);
4946 } else if (StringShape(this).IsSequentialTwoByte()) {
4947 field = HashSequentialString(SeqTwoByteString::cast(this)->GetChars(), len);
4948 } else {
4949 StringInputBuffer buffer(this);
4950 field = ComputeHashField(&buffer, len);
4951 }
Steve Blocka7e24c12009-10-30 11:49:00 +00004952
4953 // Store the hash code in the object.
Steve Blockd0582a62009-12-15 09:54:21 +00004954 set_hash_field(field);
Steve Blocka7e24c12009-10-30 11:49:00 +00004955
4956 // Check the hash code is there.
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01004957 ASSERT(HasHashCode());
Steve Blocka7e24c12009-10-30 11:49:00 +00004958 uint32_t result = field >> kHashShift;
4959 ASSERT(result != 0); // Ensure that the hash value of 0 is never computed.
4960 return result;
4961}
4962
4963
4964bool String::ComputeArrayIndex(unibrow::CharacterStream* buffer,
4965 uint32_t* index,
4966 int length) {
4967 if (length == 0 || length > kMaxArrayIndexSize) return false;
4968 uc32 ch = buffer->GetNext();
4969
4970 // If the string begins with a '0' character, it must only consist
4971 // of it to be a legal array index.
4972 if (ch == '0') {
4973 *index = 0;
4974 return length == 1;
4975 }
4976
4977 // Convert string to uint32 array index; character by character.
4978 int d = ch - '0';
4979 if (d < 0 || d > 9) return false;
4980 uint32_t result = d;
4981 while (buffer->has_more()) {
4982 d = buffer->GetNext() - '0';
4983 if (d < 0 || d > 9) return false;
4984 // Check that the new result is below the 32 bit limit.
4985 if (result > 429496729U - ((d > 5) ? 1 : 0)) return false;
4986 result = (result * 10) + d;
4987 }
4988
4989 *index = result;
4990 return true;
4991}
4992
4993
4994bool String::SlowAsArrayIndex(uint32_t* index) {
4995 if (length() <= kMaxCachedArrayIndexLength) {
4996 Hash(); // force computation of hash code
Steve Blockd0582a62009-12-15 09:54:21 +00004997 uint32_t field = hash_field();
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01004998 if ((field & kIsNotArrayIndexMask) != 0) return false;
Steve Blockd0582a62009-12-15 09:54:21 +00004999 // Isolate the array index form the full hash field.
5000 *index = (kArrayIndexHashMask & field) >> kHashShift;
Steve Blocka7e24c12009-10-30 11:49:00 +00005001 return true;
5002 } else {
5003 StringInputBuffer buffer(this);
5004 return ComputeArrayIndex(&buffer, index, length());
5005 }
5006}
5007
5008
Iain Merrick9ac36c92010-09-13 15:29:50 +01005009uint32_t StringHasher::MakeArrayIndexHash(uint32_t value, int length) {
Kristian Monsen80d68ea2010-09-08 11:05:35 +01005010 // For array indexes mix the length into the hash as an array index could
5011 // be zero.
5012 ASSERT(length > 0);
5013 ASSERT(length <= String::kMaxArrayIndexSize);
5014 ASSERT(TenToThe(String::kMaxCachedArrayIndexLength) <
5015 (1 << String::kArrayIndexValueBits));
Iain Merrick9ac36c92010-09-13 15:29:50 +01005016
5017 value <<= String::kHashShift;
Kristian Monsen80d68ea2010-09-08 11:05:35 +01005018 value |= length << String::kArrayIndexHashLengthShift;
Iain Merrick9ac36c92010-09-13 15:29:50 +01005019
5020 ASSERT((value & String::kIsNotArrayIndexMask) == 0);
5021 ASSERT((length > String::kMaxCachedArrayIndexLength) ||
5022 (value & String::kContainsCachedArrayIndexMask) == 0);
Kristian Monsen80d68ea2010-09-08 11:05:35 +01005023 return value;
Steve Blocka7e24c12009-10-30 11:49:00 +00005024}
5025
5026
5027uint32_t StringHasher::GetHashField() {
5028 ASSERT(is_valid());
Steve Blockd0582a62009-12-15 09:54:21 +00005029 if (length_ <= String::kMaxHashCalcLength) {
Steve Blocka7e24c12009-10-30 11:49:00 +00005030 if (is_array_index()) {
Iain Merrick9ac36c92010-09-13 15:29:50 +01005031 return MakeArrayIndexHash(array_index(), length_);
Steve Blocka7e24c12009-10-30 11:49:00 +00005032 }
Kristian Monsen80d68ea2010-09-08 11:05:35 +01005033 return (GetHash() << String::kHashShift) | String::kIsNotArrayIndexMask;
Steve Blocka7e24c12009-10-30 11:49:00 +00005034 } else {
Kristian Monsen80d68ea2010-09-08 11:05:35 +01005035 return (length_ << String::kHashShift) | String::kIsNotArrayIndexMask;
Steve Blocka7e24c12009-10-30 11:49:00 +00005036 }
5037}
5038
5039
Steve Blockd0582a62009-12-15 09:54:21 +00005040uint32_t String::ComputeHashField(unibrow::CharacterStream* buffer,
5041 int length) {
Steve Blocka7e24c12009-10-30 11:49:00 +00005042 StringHasher hasher(length);
5043
5044 // Very long strings have a trivial hash that doesn't inspect the
5045 // string contents.
5046 if (hasher.has_trivial_hash()) {
5047 return hasher.GetHashField();
5048 }
5049
5050 // Do the iterative array index computation as long as there is a
5051 // chance this is an array index.
5052 while (buffer->has_more() && hasher.is_array_index()) {
5053 hasher.AddCharacter(buffer->GetNext());
5054 }
5055
5056 // Process the remaining characters without updating the array
5057 // index.
5058 while (buffer->has_more()) {
5059 hasher.AddCharacterNoIndex(buffer->GetNext());
5060 }
5061
5062 return hasher.GetHashField();
5063}
5064
5065
Steve Block6ded16b2010-05-10 14:33:55 +01005066Object* String::SubString(int start, int end, PretenureFlag pretenure) {
Steve Blocka7e24c12009-10-30 11:49:00 +00005067 if (start == 0 && end == length()) return this;
Steve Block6ded16b2010-05-10 14:33:55 +01005068 Object* result = Heap::AllocateSubString(this, start, end, pretenure);
Steve Blockd0582a62009-12-15 09:54:21 +00005069 return result;
Steve Blocka7e24c12009-10-30 11:49:00 +00005070}
5071
5072
5073void String::PrintOn(FILE* file) {
5074 int length = this->length();
5075 for (int i = 0; i < length; i++) {
5076 fprintf(file, "%c", Get(i));
5077 }
5078}
5079
5080
5081void Map::CreateBackPointers() {
5082 DescriptorArray* descriptors = instance_descriptors();
5083 for (int i = 0; i < descriptors->number_of_descriptors(); i++) {
Iain Merrick75681382010-08-19 15:07:18 +01005084 if (descriptors->GetType(i) == MAP_TRANSITION ||
5085 descriptors->GetType(i) == CONSTANT_TRANSITION) {
Steve Blocka7e24c12009-10-30 11:49:00 +00005086 // Get target.
5087 Map* target = Map::cast(descriptors->GetValue(i));
5088#ifdef DEBUG
5089 // Verify target.
5090 Object* source_prototype = prototype();
5091 Object* target_prototype = target->prototype();
5092 ASSERT(source_prototype->IsJSObject() ||
5093 source_prototype->IsMap() ||
5094 source_prototype->IsNull());
5095 ASSERT(target_prototype->IsJSObject() ||
5096 target_prototype->IsNull());
5097 ASSERT(source_prototype->IsMap() ||
5098 source_prototype == target_prototype);
5099#endif
5100 // Point target back to source. set_prototype() will not let us set
5101 // the prototype to a map, as we do here.
5102 *RawField(target, kPrototypeOffset) = this;
5103 }
5104 }
5105}
5106
5107
5108void Map::ClearNonLiveTransitions(Object* real_prototype) {
5109 // Live DescriptorArray objects will be marked, so we must use
5110 // low-level accessors to get and modify their data.
5111 DescriptorArray* d = reinterpret_cast<DescriptorArray*>(
5112 *RawField(this, Map::kInstanceDescriptorsOffset));
5113 if (d == Heap::raw_unchecked_empty_descriptor_array()) return;
5114 Smi* NullDescriptorDetails =
5115 PropertyDetails(NONE, NULL_DESCRIPTOR).AsSmi();
5116 FixedArray* contents = reinterpret_cast<FixedArray*>(
5117 d->get(DescriptorArray::kContentArrayIndex));
5118 ASSERT(contents->length() >= 2);
5119 for (int i = 0; i < contents->length(); i += 2) {
5120 // If the pair (value, details) is a map transition,
5121 // check if the target is live. If not, null the descriptor.
5122 // Also drop the back pointer for that map transition, so that this
5123 // map is not reached again by following a back pointer from a
5124 // non-live object.
5125 PropertyDetails details(Smi::cast(contents->get(i + 1)));
Iain Merrick75681382010-08-19 15:07:18 +01005126 if (details.type() == MAP_TRANSITION ||
5127 details.type() == CONSTANT_TRANSITION) {
Steve Blocka7e24c12009-10-30 11:49:00 +00005128 Map* target = reinterpret_cast<Map*>(contents->get(i));
5129 ASSERT(target->IsHeapObject());
5130 if (!target->IsMarked()) {
5131 ASSERT(target->IsMap());
Iain Merrick75681382010-08-19 15:07:18 +01005132 contents->set_unchecked(i + 1, NullDescriptorDetails);
5133 contents->set_null_unchecked(i);
Steve Blocka7e24c12009-10-30 11:49:00 +00005134 ASSERT(target->prototype() == this ||
5135 target->prototype() == real_prototype);
5136 // Getter prototype() is read-only, set_prototype() has side effects.
5137 *RawField(target, Map::kPrototypeOffset) = real_prototype;
5138 }
5139 }
5140 }
5141}
5142
5143
Steve Block791712a2010-08-27 10:21:07 +01005144void JSFunction::JSFunctionIterateBody(int object_size, ObjectVisitor* v) {
5145 // Iterate over all fields in the body but take care in dealing with
5146 // the code entry.
5147 IteratePointers(v, kPropertiesOffset, kCodeEntryOffset);
5148 v->VisitCodeEntry(this->address() + kCodeEntryOffset);
5149 IteratePointers(v, kCodeEntryOffset + kPointerSize, object_size);
5150}
5151
5152
Steve Blocka7e24c12009-10-30 11:49:00 +00005153Object* JSFunction::SetInstancePrototype(Object* value) {
5154 ASSERT(value->IsJSObject());
5155
5156 if (has_initial_map()) {
5157 initial_map()->set_prototype(value);
5158 } else {
5159 // Put the value in the initial map field until an initial map is
5160 // needed. At that point, a new initial map is created and the
5161 // prototype is put into the initial map where it belongs.
5162 set_prototype_or_initial_map(value);
5163 }
Kristian Monsen25f61362010-05-21 11:50:48 +01005164 Heap::ClearInstanceofCache();
Steve Blocka7e24c12009-10-30 11:49:00 +00005165 return value;
5166}
5167
5168
Steve Blocka7e24c12009-10-30 11:49:00 +00005169Object* JSFunction::SetPrototype(Object* value) {
Steve Block6ded16b2010-05-10 14:33:55 +01005170 ASSERT(should_have_prototype());
Steve Blocka7e24c12009-10-30 11:49:00 +00005171 Object* construct_prototype = value;
5172
5173 // If the value is not a JSObject, store the value in the map's
5174 // constructor field so it can be accessed. Also, set the prototype
5175 // used for constructing objects to the original object prototype.
5176 // See ECMA-262 13.2.2.
5177 if (!value->IsJSObject()) {
5178 // Copy the map so this does not affect unrelated functions.
5179 // Remove map transitions because they point to maps with a
5180 // different prototype.
5181 Object* new_map = map()->CopyDropTransitions();
5182 if (new_map->IsFailure()) return new_map;
5183 set_map(Map::cast(new_map));
5184 map()->set_constructor(value);
5185 map()->set_non_instance_prototype(true);
5186 construct_prototype =
5187 Top::context()->global_context()->initial_object_prototype();
5188 } else {
5189 map()->set_non_instance_prototype(false);
5190 }
5191
5192 return SetInstancePrototype(construct_prototype);
5193}
5194
5195
Steve Block6ded16b2010-05-10 14:33:55 +01005196Object* JSFunction::RemovePrototype() {
5197 ASSERT(map() == context()->global_context()->function_map());
5198 set_map(context()->global_context()->function_without_prototype_map());
5199 set_prototype_or_initial_map(Heap::the_hole_value());
5200 return this;
5201}
5202
5203
Steve Blocka7e24c12009-10-30 11:49:00 +00005204Object* JSFunction::SetInstanceClassName(String* name) {
5205 shared()->set_instance_class_name(name);
5206 return this;
5207}
5208
5209
5210Context* JSFunction::GlobalContextFromLiterals(FixedArray* literals) {
5211 return Context::cast(literals->get(JSFunction::kLiteralGlobalContextIndex));
5212}
5213
5214
Steve Blocka7e24c12009-10-30 11:49:00 +00005215Object* Oddball::Initialize(const char* to_string, Object* to_number) {
5216 Object* symbol = Heap::LookupAsciiSymbol(to_string);
5217 if (symbol->IsFailure()) return symbol;
5218 set_to_string(String::cast(symbol));
5219 set_to_number(to_number);
5220 return this;
5221}
5222
5223
Ben Murdochf87a2032010-10-22 12:50:53 +01005224String* SharedFunctionInfo::DebugName() {
5225 Object* n = name();
5226 if (!n->IsString() || String::cast(n)->length() == 0) return inferred_name();
5227 return String::cast(n);
5228}
5229
5230
Steve Blocka7e24c12009-10-30 11:49:00 +00005231bool SharedFunctionInfo::HasSourceCode() {
5232 return !script()->IsUndefined() &&
Iain Merrick75681382010-08-19 15:07:18 +01005233 !reinterpret_cast<Script*>(script())->source()->IsUndefined();
Steve Blocka7e24c12009-10-30 11:49:00 +00005234}
5235
5236
5237Object* SharedFunctionInfo::GetSourceCode() {
5238 HandleScope scope;
5239 if (script()->IsUndefined()) return Heap::undefined_value();
5240 Object* source = Script::cast(script())->source();
5241 if (source->IsUndefined()) return Heap::undefined_value();
5242 return *SubString(Handle<String>(String::cast(source)),
5243 start_position(), end_position());
5244}
5245
5246
5247int SharedFunctionInfo::CalculateInstanceSize() {
5248 int instance_size =
5249 JSObject::kHeaderSize +
5250 expected_nof_properties() * kPointerSize;
5251 if (instance_size > JSObject::kMaxInstanceSize) {
5252 instance_size = JSObject::kMaxInstanceSize;
5253 }
5254 return instance_size;
5255}
5256
5257
5258int SharedFunctionInfo::CalculateInObjectProperties() {
5259 return (CalculateInstanceSize() - JSObject::kHeaderSize) / kPointerSize;
5260}
5261
5262
Andrei Popescu402d9372010-02-26 13:31:12 +00005263bool SharedFunctionInfo::CanGenerateInlineConstructor(Object* prototype) {
5264 // Check the basic conditions for generating inline constructor code.
5265 if (!FLAG_inline_new
5266 || !has_only_simple_this_property_assignments()
5267 || this_property_assignments_count() == 0) {
5268 return false;
5269 }
5270
5271 // If the prototype is null inline constructors cause no problems.
5272 if (!prototype->IsJSObject()) {
5273 ASSERT(prototype->IsNull());
5274 return true;
5275 }
5276
5277 // Traverse the proposed prototype chain looking for setters for properties of
5278 // the same names as are set by the inline constructor.
5279 for (Object* obj = prototype;
5280 obj != Heap::null_value();
5281 obj = obj->GetPrototype()) {
5282 JSObject* js_object = JSObject::cast(obj);
5283 for (int i = 0; i < this_property_assignments_count(); i++) {
5284 LookupResult result;
5285 String* name = GetThisPropertyAssignmentName(i);
5286 js_object->LocalLookupRealNamedProperty(name, &result);
5287 if (result.IsProperty() && result.type() == CALLBACKS) {
5288 return false;
5289 }
5290 }
5291 }
5292
5293 return true;
5294}
5295
5296
Kristian Monsen0d5e1162010-09-30 15:31:59 +01005297void SharedFunctionInfo::ForbidInlineConstructor() {
5298 set_compiler_hints(BooleanBit::set(compiler_hints(),
5299 kHasOnlySimpleThisPropertyAssignments,
5300 false));
5301}
5302
5303
Steve Blocka7e24c12009-10-30 11:49:00 +00005304void SharedFunctionInfo::SetThisPropertyAssignmentsInfo(
Steve Blocka7e24c12009-10-30 11:49:00 +00005305 bool only_simple_this_property_assignments,
5306 FixedArray* assignments) {
5307 set_compiler_hints(BooleanBit::set(compiler_hints(),
Steve Blocka7e24c12009-10-30 11:49:00 +00005308 kHasOnlySimpleThisPropertyAssignments,
5309 only_simple_this_property_assignments));
5310 set_this_property_assignments(assignments);
5311 set_this_property_assignments_count(assignments->length() / 3);
5312}
5313
5314
5315void SharedFunctionInfo::ClearThisPropertyAssignmentsInfo() {
5316 set_compiler_hints(BooleanBit::set(compiler_hints(),
Steve Blocka7e24c12009-10-30 11:49:00 +00005317 kHasOnlySimpleThisPropertyAssignments,
5318 false));
5319 set_this_property_assignments(Heap::undefined_value());
5320 set_this_property_assignments_count(0);
5321}
5322
5323
5324String* SharedFunctionInfo::GetThisPropertyAssignmentName(int index) {
5325 Object* obj = this_property_assignments();
5326 ASSERT(obj->IsFixedArray());
5327 ASSERT(index < this_property_assignments_count());
5328 obj = FixedArray::cast(obj)->get(index * 3);
5329 ASSERT(obj->IsString());
5330 return String::cast(obj);
5331}
5332
5333
5334bool SharedFunctionInfo::IsThisPropertyAssignmentArgument(int index) {
5335 Object* obj = this_property_assignments();
5336 ASSERT(obj->IsFixedArray());
5337 ASSERT(index < this_property_assignments_count());
5338 obj = FixedArray::cast(obj)->get(index * 3 + 1);
5339 return Smi::cast(obj)->value() != -1;
5340}
5341
5342
5343int SharedFunctionInfo::GetThisPropertyAssignmentArgument(int index) {
5344 ASSERT(IsThisPropertyAssignmentArgument(index));
5345 Object* obj =
5346 FixedArray::cast(this_property_assignments())->get(index * 3 + 1);
5347 return Smi::cast(obj)->value();
5348}
5349
5350
5351Object* SharedFunctionInfo::GetThisPropertyAssignmentConstant(int index) {
5352 ASSERT(!IsThisPropertyAssignmentArgument(index));
5353 Object* obj =
5354 FixedArray::cast(this_property_assignments())->get(index * 3 + 2);
5355 return obj;
5356}
5357
5358
Steve Blocka7e24c12009-10-30 11:49:00 +00005359// Support function for printing the source code to a StringStream
5360// without any allocation in the heap.
5361void SharedFunctionInfo::SourceCodePrint(StringStream* accumulator,
5362 int max_length) {
5363 // For some native functions there is no source.
5364 if (script()->IsUndefined() ||
5365 Script::cast(script())->source()->IsUndefined()) {
5366 accumulator->Add("<No Source>");
5367 return;
5368 }
5369
Steve Blockd0582a62009-12-15 09:54:21 +00005370 // Get the source for the script which this function came from.
Steve Blocka7e24c12009-10-30 11:49:00 +00005371 // Don't use String::cast because we don't want more assertion errors while
5372 // we are already creating a stack dump.
5373 String* script_source =
5374 reinterpret_cast<String*>(Script::cast(script())->source());
5375
5376 if (!script_source->LooksValid()) {
5377 accumulator->Add("<Invalid Source>");
5378 return;
5379 }
5380
5381 if (!is_toplevel()) {
5382 accumulator->Add("function ");
5383 Object* name = this->name();
5384 if (name->IsString() && String::cast(name)->length() > 0) {
5385 accumulator->PrintName(name);
5386 }
5387 }
5388
5389 int len = end_position() - start_position();
5390 if (len > max_length) {
5391 accumulator->Put(script_source,
5392 start_position(),
5393 start_position() + max_length);
5394 accumulator->Add("...\n");
5395 } else {
5396 accumulator->Put(script_source, start_position(), end_position());
5397 }
5398}
5399
5400
Kristian Monsen0d5e1162010-09-30 15:31:59 +01005401void SharedFunctionInfo::StartInobjectSlackTracking(Map* map) {
5402 ASSERT(!IsInobjectSlackTrackingInProgress());
5403
5404 // Only initiate the tracking the first time.
5405 if (live_objects_may_exist()) return;
5406 set_live_objects_may_exist(true);
5407
5408 // No tracking during the snapshot construction phase.
5409 if (Serializer::enabled()) return;
5410
5411 if (map->unused_property_fields() == 0) return;
5412
5413 // Nonzero counter is a leftover from the previous attempt interrupted
5414 // by GC, keep it.
5415 if (construction_count() == 0) {
5416 set_construction_count(kGenerousAllocationCount);
5417 }
5418 set_initial_map(map);
5419 ASSERT_EQ(Builtins::builtin(Builtins::JSConstructStubGeneric),
5420 construct_stub());
5421 set_construct_stub(Builtins::builtin(Builtins::JSConstructStubCountdown));
5422}
5423
5424
5425// Called from GC, hence reinterpret_cast and unchecked accessors.
5426void SharedFunctionInfo::DetachInitialMap() {
5427 Map* map = reinterpret_cast<Map*>(initial_map());
5428
5429 // Make the map remember to restore the link if it survives the GC.
5430 map->set_bit_field2(
5431 map->bit_field2() | (1 << Map::kAttachedToSharedFunctionInfo));
5432
5433 // Undo state changes made by StartInobjectTracking (except the
5434 // construction_count). This way if the initial map does not survive the GC
5435 // then StartInobjectTracking will be called again the next time the
5436 // constructor is called. The countdown will continue and (possibly after
5437 // several more GCs) CompleteInobjectSlackTracking will eventually be called.
5438 set_initial_map(Heap::raw_unchecked_undefined_value());
5439 ASSERT_EQ(Builtins::builtin(Builtins::JSConstructStubCountdown),
5440 *RawField(this, kConstructStubOffset));
5441 set_construct_stub(Builtins::builtin(Builtins::JSConstructStubGeneric));
5442 // It is safe to clear the flag: it will be set again if the map is live.
5443 set_live_objects_may_exist(false);
5444}
5445
5446
5447// Called from GC, hence reinterpret_cast and unchecked accessors.
5448void SharedFunctionInfo::AttachInitialMap(Map* map) {
5449 map->set_bit_field2(
5450 map->bit_field2() & ~(1 << Map::kAttachedToSharedFunctionInfo));
5451
5452 // Resume inobject slack tracking.
5453 set_initial_map(map);
5454 ASSERT_EQ(Builtins::builtin(Builtins::JSConstructStubGeneric),
5455 *RawField(this, kConstructStubOffset));
5456 set_construct_stub(Builtins::builtin(Builtins::JSConstructStubCountdown));
5457 // The map survived the gc, so there may be objects referencing it.
5458 set_live_objects_may_exist(true);
5459}
5460
5461
5462static void GetMinInobjectSlack(Map* map, void* data) {
5463 int slack = map->unused_property_fields();
5464 if (*reinterpret_cast<int*>(data) > slack) {
5465 *reinterpret_cast<int*>(data) = slack;
5466 }
5467}
5468
5469
5470static void ShrinkInstanceSize(Map* map, void* data) {
5471 int slack = *reinterpret_cast<int*>(data);
5472 map->set_inobject_properties(map->inobject_properties() - slack);
5473 map->set_unused_property_fields(map->unused_property_fields() - slack);
5474 map->set_instance_size(map->instance_size() - slack * kPointerSize);
5475
5476 // Visitor id might depend on the instance size, recalculate it.
5477 map->set_visitor_id(StaticVisitorBase::GetVisitorId(map));
5478}
5479
5480
5481void SharedFunctionInfo::CompleteInobjectSlackTracking() {
5482 ASSERT(live_objects_may_exist() && IsInobjectSlackTrackingInProgress());
5483 Map* map = Map::cast(initial_map());
5484
5485 set_initial_map(Heap::undefined_value());
5486 ASSERT_EQ(Builtins::builtin(Builtins::JSConstructStubCountdown),
5487 construct_stub());
5488 set_construct_stub(Builtins::builtin(Builtins::JSConstructStubGeneric));
5489
5490 int slack = map->unused_property_fields();
5491 map->TraverseTransitionTree(&GetMinInobjectSlack, &slack);
5492 if (slack != 0) {
5493 // Resize the initial map and all maps in its transition tree.
5494 map->TraverseTransitionTree(&ShrinkInstanceSize, &slack);
5495 // Give the correct expected_nof_properties to initial maps created later.
5496 ASSERT(expected_nof_properties() >= slack);
5497 set_expected_nof_properties(expected_nof_properties() - slack);
5498 }
5499}
5500
5501
Steve Blocka7e24c12009-10-30 11:49:00 +00005502void ObjectVisitor::VisitCodeTarget(RelocInfo* rinfo) {
5503 ASSERT(RelocInfo::IsCodeTarget(rinfo->rmode()));
5504 Object* target = Code::GetCodeFromTargetAddress(rinfo->target_address());
5505 Object* old_target = target;
5506 VisitPointer(&target);
5507 CHECK_EQ(target, old_target); // VisitPointer doesn't change Code* *target.
5508}
5509
5510
Steve Block791712a2010-08-27 10:21:07 +01005511void ObjectVisitor::VisitCodeEntry(Address entry_address) {
5512 Object* code = Code::GetObjectFromEntryAddress(entry_address);
5513 Object* old_code = code;
5514 VisitPointer(&code);
5515 if (code != old_code) {
5516 Memory::Address_at(entry_address) = reinterpret_cast<Code*>(code)->entry();
5517 }
5518}
5519
5520
Steve Blocka7e24c12009-10-30 11:49:00 +00005521void ObjectVisitor::VisitDebugTarget(RelocInfo* rinfo) {
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01005522 ASSERT((RelocInfo::IsJSReturn(rinfo->rmode()) &&
5523 rinfo->IsPatchedReturnSequence()) ||
5524 (RelocInfo::IsDebugBreakSlot(rinfo->rmode()) &&
5525 rinfo->IsPatchedDebugBreakSlotSequence()));
Steve Blocka7e24c12009-10-30 11:49:00 +00005526 Object* target = Code::GetCodeFromTargetAddress(rinfo->call_address());
5527 Object* old_target = target;
5528 VisitPointer(&target);
5529 CHECK_EQ(target, old_target); // VisitPointer doesn't change Code* *target.
5530}
5531
5532
Steve Blockd0582a62009-12-15 09:54:21 +00005533void Code::Relocate(intptr_t delta) {
Steve Blocka7e24c12009-10-30 11:49:00 +00005534 for (RelocIterator it(this, RelocInfo::kApplyMask); !it.done(); it.next()) {
5535 it.rinfo()->apply(delta);
5536 }
5537 CPU::FlushICache(instruction_start(), instruction_size());
5538}
5539
5540
5541void Code::CopyFrom(const CodeDesc& desc) {
5542 // copy code
5543 memmove(instruction_start(), desc.buffer, desc.instr_size);
5544
Steve Blocka7e24c12009-10-30 11:49:00 +00005545 // copy reloc info
5546 memmove(relocation_start(),
5547 desc.buffer + desc.buffer_size - desc.reloc_size,
5548 desc.reloc_size);
5549
5550 // unbox handles and relocate
Steve Block3ce2e202009-11-05 08:53:23 +00005551 intptr_t delta = instruction_start() - desc.buffer;
Steve Blocka7e24c12009-10-30 11:49:00 +00005552 int mode_mask = RelocInfo::kCodeTargetMask |
5553 RelocInfo::ModeMask(RelocInfo::EMBEDDED_OBJECT) |
5554 RelocInfo::kApplyMask;
Steve Block3ce2e202009-11-05 08:53:23 +00005555 Assembler* origin = desc.origin; // Needed to find target_object on X64.
Steve Blocka7e24c12009-10-30 11:49:00 +00005556 for (RelocIterator it(this, mode_mask); !it.done(); it.next()) {
5557 RelocInfo::Mode mode = it.rinfo()->rmode();
5558 if (mode == RelocInfo::EMBEDDED_OBJECT) {
Steve Block3ce2e202009-11-05 08:53:23 +00005559 Handle<Object> p = it.rinfo()->target_object_handle(origin);
Steve Blocka7e24c12009-10-30 11:49:00 +00005560 it.rinfo()->set_target_object(*p);
5561 } else if (RelocInfo::IsCodeTarget(mode)) {
5562 // rewrite code handles in inline cache targets to direct
5563 // pointers to the first instruction in the code object
Steve Block3ce2e202009-11-05 08:53:23 +00005564 Handle<Object> p = it.rinfo()->target_object_handle(origin);
Steve Blocka7e24c12009-10-30 11:49:00 +00005565 Code* code = Code::cast(*p);
5566 it.rinfo()->set_target_address(code->instruction_start());
5567 } else {
5568 it.rinfo()->apply(delta);
5569 }
5570 }
5571 CPU::FlushICache(instruction_start(), instruction_size());
5572}
5573
5574
5575// Locate the source position which is closest to the address in the code. This
5576// is using the source position information embedded in the relocation info.
5577// The position returned is relative to the beginning of the script where the
5578// source for this function is found.
5579int Code::SourcePosition(Address pc) {
5580 int distance = kMaxInt;
5581 int position = RelocInfo::kNoPosition; // Initially no position found.
5582 // Run through all the relocation info to find the best matching source
5583 // position. All the code needs to be considered as the sequence of the
5584 // instructions in the code does not necessarily follow the same order as the
5585 // source.
5586 RelocIterator it(this, RelocInfo::kPositionMask);
5587 while (!it.done()) {
5588 // Only look at positions after the current pc.
5589 if (it.rinfo()->pc() < pc) {
5590 // Get position and distance.
Steve Blockd0582a62009-12-15 09:54:21 +00005591
5592 int dist = static_cast<int>(pc - it.rinfo()->pc());
5593 int pos = static_cast<int>(it.rinfo()->data());
Steve Blocka7e24c12009-10-30 11:49:00 +00005594 // If this position is closer than the current candidate or if it has the
5595 // same distance as the current candidate and the position is higher then
5596 // this position is the new candidate.
5597 if ((dist < distance) ||
5598 (dist == distance && pos > position)) {
5599 position = pos;
5600 distance = dist;
5601 }
5602 }
5603 it.next();
5604 }
5605 return position;
5606}
5607
5608
5609// Same as Code::SourcePosition above except it only looks for statement
5610// positions.
5611int Code::SourceStatementPosition(Address pc) {
5612 // First find the position as close as possible using all position
5613 // information.
5614 int position = SourcePosition(pc);
5615 // Now find the closest statement position before the position.
5616 int statement_position = 0;
5617 RelocIterator it(this, RelocInfo::kPositionMask);
5618 while (!it.done()) {
5619 if (RelocInfo::IsStatementPosition(it.rinfo()->rmode())) {
Steve Blockd0582a62009-12-15 09:54:21 +00005620 int p = static_cast<int>(it.rinfo()->data());
Steve Blocka7e24c12009-10-30 11:49:00 +00005621 if (statement_position < p && p <= position) {
5622 statement_position = p;
5623 }
5624 }
5625 it.next();
5626 }
5627 return statement_position;
5628}
5629
5630
5631#ifdef ENABLE_DISASSEMBLER
5632// Identify kind of code.
5633const char* Code::Kind2String(Kind kind) {
5634 switch (kind) {
5635 case FUNCTION: return "FUNCTION";
5636 case STUB: return "STUB";
5637 case BUILTIN: return "BUILTIN";
5638 case LOAD_IC: return "LOAD_IC";
5639 case KEYED_LOAD_IC: return "KEYED_LOAD_IC";
5640 case STORE_IC: return "STORE_IC";
5641 case KEYED_STORE_IC: return "KEYED_STORE_IC";
5642 case CALL_IC: return "CALL_IC";
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01005643 case KEYED_CALL_IC: return "KEYED_CALL_IC";
Steve Block6ded16b2010-05-10 14:33:55 +01005644 case BINARY_OP_IC: return "BINARY_OP_IC";
Steve Blocka7e24c12009-10-30 11:49:00 +00005645 }
5646 UNREACHABLE();
5647 return NULL;
5648}
5649
5650
5651const char* Code::ICState2String(InlineCacheState state) {
5652 switch (state) {
5653 case UNINITIALIZED: return "UNINITIALIZED";
5654 case PREMONOMORPHIC: return "PREMONOMORPHIC";
5655 case MONOMORPHIC: return "MONOMORPHIC";
5656 case MONOMORPHIC_PROTOTYPE_FAILURE: return "MONOMORPHIC_PROTOTYPE_FAILURE";
5657 case MEGAMORPHIC: return "MEGAMORPHIC";
5658 case DEBUG_BREAK: return "DEBUG_BREAK";
5659 case DEBUG_PREPARE_STEP_IN: return "DEBUG_PREPARE_STEP_IN";
5660 }
5661 UNREACHABLE();
5662 return NULL;
5663}
5664
5665
5666const char* Code::PropertyType2String(PropertyType type) {
5667 switch (type) {
5668 case NORMAL: return "NORMAL";
5669 case FIELD: return "FIELD";
5670 case CONSTANT_FUNCTION: return "CONSTANT_FUNCTION";
5671 case CALLBACKS: return "CALLBACKS";
5672 case INTERCEPTOR: return "INTERCEPTOR";
5673 case MAP_TRANSITION: return "MAP_TRANSITION";
5674 case CONSTANT_TRANSITION: return "CONSTANT_TRANSITION";
5675 case NULL_DESCRIPTOR: return "NULL_DESCRIPTOR";
5676 }
5677 UNREACHABLE();
5678 return NULL;
5679}
5680
5681void Code::Disassemble(const char* name) {
5682 PrintF("kind = %s\n", Kind2String(kind()));
5683 if (is_inline_cache_stub()) {
5684 PrintF("ic_state = %s\n", ICState2String(ic_state()));
5685 PrintF("ic_in_loop = %d\n", ic_in_loop() == IN_LOOP);
5686 if (ic_state() == MONOMORPHIC) {
5687 PrintF("type = %s\n", PropertyType2String(type()));
5688 }
5689 }
5690 if ((name != NULL) && (name[0] != '\0')) {
5691 PrintF("name = %s\n", name);
5692 }
5693
5694 PrintF("Instructions (size = %d)\n", instruction_size());
5695 Disassembler::Decode(NULL, this);
5696 PrintF("\n");
5697
5698 PrintF("RelocInfo (size = %d)\n", relocation_size());
5699 for (RelocIterator it(this); !it.done(); it.next())
5700 it.rinfo()->Print();
5701 PrintF("\n");
5702}
5703#endif // ENABLE_DISASSEMBLER
5704
5705
Steve Block8defd9f2010-07-08 12:39:36 +01005706Object* JSObject::SetFastElementsCapacityAndLength(int capacity, int length) {
Steve Block3ce2e202009-11-05 08:53:23 +00005707 // We should never end in here with a pixel or external array.
5708 ASSERT(!HasPixelElements() && !HasExternalArrayElements());
Steve Block8defd9f2010-07-08 12:39:36 +01005709
5710 Object* obj = Heap::AllocateFixedArrayWithHoles(capacity);
5711 if (obj->IsFailure()) return obj;
5712 FixedArray* elems = FixedArray::cast(obj);
5713
5714 obj = map()->GetFastElementsMap();
5715 if (obj->IsFailure()) return obj;
5716 Map* new_map = Map::cast(obj);
5717
Leon Clarke4515c472010-02-03 11:58:03 +00005718 AssertNoAllocation no_gc;
5719 WriteBarrierMode mode = elems->GetWriteBarrierMode(no_gc);
Steve Blocka7e24c12009-10-30 11:49:00 +00005720 switch (GetElementsKind()) {
5721 case FAST_ELEMENTS: {
5722 FixedArray* old_elements = FixedArray::cast(elements());
5723 uint32_t old_length = static_cast<uint32_t>(old_elements->length());
5724 // Fill out the new array with this content and array holes.
5725 for (uint32_t i = 0; i < old_length; i++) {
5726 elems->set(i, old_elements->get(i), mode);
5727 }
5728 break;
5729 }
5730 case DICTIONARY_ELEMENTS: {
5731 NumberDictionary* dictionary = NumberDictionary::cast(elements());
5732 for (int i = 0; i < dictionary->Capacity(); i++) {
5733 Object* key = dictionary->KeyAt(i);
5734 if (key->IsNumber()) {
5735 uint32_t entry = static_cast<uint32_t>(key->Number());
5736 elems->set(entry, dictionary->ValueAt(i), mode);
5737 }
5738 }
5739 break;
5740 }
5741 default:
5742 UNREACHABLE();
5743 break;
5744 }
Steve Block8defd9f2010-07-08 12:39:36 +01005745
5746 set_map(new_map);
Steve Blocka7e24c12009-10-30 11:49:00 +00005747 set_elements(elems);
Steve Block8defd9f2010-07-08 12:39:36 +01005748
5749 if (IsJSArray()) {
5750 JSArray::cast(this)->set_length(Smi::FromInt(length));
5751 }
5752
5753 return this;
Steve Blocka7e24c12009-10-30 11:49:00 +00005754}
5755
5756
5757Object* JSObject::SetSlowElements(Object* len) {
Steve Block3ce2e202009-11-05 08:53:23 +00005758 // We should never end in here with a pixel or external array.
5759 ASSERT(!HasPixelElements() && !HasExternalArrayElements());
Steve Blocka7e24c12009-10-30 11:49:00 +00005760
5761 uint32_t new_length = static_cast<uint32_t>(len->Number());
5762
5763 switch (GetElementsKind()) {
5764 case FAST_ELEMENTS: {
5765 // Make sure we never try to shrink dense arrays into sparse arrays.
5766 ASSERT(static_cast<uint32_t>(FixedArray::cast(elements())->length()) <=
5767 new_length);
5768 Object* obj = NormalizeElements();
5769 if (obj->IsFailure()) return obj;
5770
5771 // Update length for JSArrays.
5772 if (IsJSArray()) JSArray::cast(this)->set_length(len);
5773 break;
5774 }
5775 case DICTIONARY_ELEMENTS: {
5776 if (IsJSArray()) {
5777 uint32_t old_length =
Steve Block6ded16b2010-05-10 14:33:55 +01005778 static_cast<uint32_t>(JSArray::cast(this)->length()->Number());
Steve Blocka7e24c12009-10-30 11:49:00 +00005779 element_dictionary()->RemoveNumberEntries(new_length, old_length),
5780 JSArray::cast(this)->set_length(len);
5781 }
5782 break;
5783 }
5784 default:
5785 UNREACHABLE();
5786 break;
5787 }
5788 return this;
5789}
5790
5791
5792Object* JSArray::Initialize(int capacity) {
5793 ASSERT(capacity >= 0);
Leon Clarke4515c472010-02-03 11:58:03 +00005794 set_length(Smi::FromInt(0));
Steve Blocka7e24c12009-10-30 11:49:00 +00005795 FixedArray* new_elements;
5796 if (capacity == 0) {
5797 new_elements = Heap::empty_fixed_array();
5798 } else {
5799 Object* obj = Heap::AllocateFixedArrayWithHoles(capacity);
5800 if (obj->IsFailure()) return obj;
5801 new_elements = FixedArray::cast(obj);
5802 }
5803 set_elements(new_elements);
5804 return this;
5805}
5806
5807
5808void JSArray::Expand(int required_size) {
5809 Handle<JSArray> self(this);
5810 Handle<FixedArray> old_backing(FixedArray::cast(elements()));
5811 int old_size = old_backing->length();
Steve Blockd0582a62009-12-15 09:54:21 +00005812 int new_size = required_size > old_size ? required_size : old_size;
Steve Blocka7e24c12009-10-30 11:49:00 +00005813 Handle<FixedArray> new_backing = Factory::NewFixedArray(new_size);
5814 // Can't use this any more now because we may have had a GC!
5815 for (int i = 0; i < old_size; i++) new_backing->set(i, old_backing->get(i));
5816 self->SetContent(*new_backing);
5817}
5818
5819
5820// Computes the new capacity when expanding the elements of a JSObject.
5821static int NewElementsCapacity(int old_capacity) {
5822 // (old_capacity + 50%) + 16
5823 return old_capacity + (old_capacity >> 1) + 16;
5824}
5825
5826
5827static Object* ArrayLengthRangeError() {
5828 HandleScope scope;
5829 return Top::Throw(*Factory::NewRangeError("invalid_array_length",
5830 HandleVector<Object>(NULL, 0)));
5831}
5832
5833
5834Object* JSObject::SetElementsLength(Object* len) {
Steve Block3ce2e202009-11-05 08:53:23 +00005835 // We should never end in here with a pixel or external array.
Steve Block6ded16b2010-05-10 14:33:55 +01005836 ASSERT(AllowsSetElementsLength());
Steve Blocka7e24c12009-10-30 11:49:00 +00005837
5838 Object* smi_length = len->ToSmi();
5839 if (smi_length->IsSmi()) {
Steve Block8defd9f2010-07-08 12:39:36 +01005840 const int value = Smi::cast(smi_length)->value();
Steve Blocka7e24c12009-10-30 11:49:00 +00005841 if (value < 0) return ArrayLengthRangeError();
5842 switch (GetElementsKind()) {
5843 case FAST_ELEMENTS: {
5844 int old_capacity = FixedArray::cast(elements())->length();
5845 if (value <= old_capacity) {
5846 if (IsJSArray()) {
Iain Merrick75681382010-08-19 15:07:18 +01005847 Object* obj = EnsureWritableFastElements();
5848 if (obj->IsFailure()) return obj;
Steve Blocka7e24c12009-10-30 11:49:00 +00005849 int old_length = FastD2I(JSArray::cast(this)->length()->Number());
5850 // NOTE: We may be able to optimize this by removing the
5851 // last part of the elements backing storage array and
5852 // setting the capacity to the new size.
5853 for (int i = value; i < old_length; i++) {
5854 FixedArray::cast(elements())->set_the_hole(i);
5855 }
Leon Clarke4515c472010-02-03 11:58:03 +00005856 JSArray::cast(this)->set_length(Smi::cast(smi_length));
Steve Blocka7e24c12009-10-30 11:49:00 +00005857 }
5858 return this;
5859 }
5860 int min = NewElementsCapacity(old_capacity);
5861 int new_capacity = value > min ? value : min;
5862 if (new_capacity <= kMaxFastElementsLength ||
5863 !ShouldConvertToSlowElements(new_capacity)) {
Steve Block8defd9f2010-07-08 12:39:36 +01005864 Object* obj = SetFastElementsCapacityAndLength(new_capacity, value);
Steve Blocka7e24c12009-10-30 11:49:00 +00005865 if (obj->IsFailure()) return obj;
Steve Blocka7e24c12009-10-30 11:49:00 +00005866 return this;
5867 }
5868 break;
5869 }
5870 case DICTIONARY_ELEMENTS: {
5871 if (IsJSArray()) {
5872 if (value == 0) {
5873 // If the length of a slow array is reset to zero, we clear
5874 // the array and flush backing storage. This has the added
5875 // benefit that the array returns to fast mode.
Steve Block8defd9f2010-07-08 12:39:36 +01005876 Object* obj = ResetElements();
5877 if (obj->IsFailure()) return obj;
Steve Blocka7e24c12009-10-30 11:49:00 +00005878 } else {
5879 // Remove deleted elements.
5880 uint32_t old_length =
5881 static_cast<uint32_t>(JSArray::cast(this)->length()->Number());
5882 element_dictionary()->RemoveNumberEntries(value, old_length);
5883 }
Leon Clarke4515c472010-02-03 11:58:03 +00005884 JSArray::cast(this)->set_length(Smi::cast(smi_length));
Steve Blocka7e24c12009-10-30 11:49:00 +00005885 }
5886 return this;
5887 }
5888 default:
5889 UNREACHABLE();
5890 break;
5891 }
5892 }
5893
5894 // General slow case.
5895 if (len->IsNumber()) {
5896 uint32_t length;
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01005897 if (len->ToArrayIndex(&length)) {
Steve Blocka7e24c12009-10-30 11:49:00 +00005898 return SetSlowElements(len);
5899 } else {
5900 return ArrayLengthRangeError();
5901 }
5902 }
5903
5904 // len is not a number so make the array size one and
5905 // set only element to len.
5906 Object* obj = Heap::AllocateFixedArray(1);
5907 if (obj->IsFailure()) return obj;
5908 FixedArray::cast(obj)->set(0, len);
Leon Clarke4515c472010-02-03 11:58:03 +00005909 if (IsJSArray()) JSArray::cast(this)->set_length(Smi::FromInt(1));
Steve Blocka7e24c12009-10-30 11:49:00 +00005910 set_elements(FixedArray::cast(obj));
5911 return this;
5912}
5913
5914
Andrei Popescu402d9372010-02-26 13:31:12 +00005915Object* JSObject::SetPrototype(Object* value,
5916 bool skip_hidden_prototypes) {
5917 // Silently ignore the change if value is not a JSObject or null.
5918 // SpiderMonkey behaves this way.
5919 if (!value->IsJSObject() && !value->IsNull()) return value;
5920
5921 // Before we can set the prototype we need to be sure
5922 // prototype cycles are prevented.
5923 // It is sufficient to validate that the receiver is not in the new prototype
5924 // chain.
5925 for (Object* pt = value; pt != Heap::null_value(); pt = pt->GetPrototype()) {
5926 if (JSObject::cast(pt) == this) {
5927 // Cycle detected.
5928 HandleScope scope;
5929 return Top::Throw(*Factory::NewError("cyclic_proto",
5930 HandleVector<Object>(NULL, 0)));
5931 }
5932 }
5933
5934 JSObject* real_receiver = this;
5935
5936 if (skip_hidden_prototypes) {
5937 // Find the first object in the chain whose prototype object is not
5938 // hidden and set the new prototype on that object.
5939 Object* current_proto = real_receiver->GetPrototype();
5940 while (current_proto->IsJSObject() &&
5941 JSObject::cast(current_proto)->map()->is_hidden_prototype()) {
5942 real_receiver = JSObject::cast(current_proto);
5943 current_proto = current_proto->GetPrototype();
5944 }
5945 }
5946
5947 // Set the new prototype of the object.
5948 Object* new_map = real_receiver->map()->CopyDropTransitions();
5949 if (new_map->IsFailure()) return new_map;
5950 Map::cast(new_map)->set_prototype(value);
5951 real_receiver->set_map(Map::cast(new_map));
5952
Kristian Monsen25f61362010-05-21 11:50:48 +01005953 Heap::ClearInstanceofCache();
5954
Andrei Popescu402d9372010-02-26 13:31:12 +00005955 return value;
5956}
5957
5958
Steve Blocka7e24c12009-10-30 11:49:00 +00005959bool JSObject::HasElementPostInterceptor(JSObject* receiver, uint32_t index) {
5960 switch (GetElementsKind()) {
5961 case FAST_ELEMENTS: {
5962 uint32_t length = IsJSArray() ?
5963 static_cast<uint32_t>
5964 (Smi::cast(JSArray::cast(this)->length())->value()) :
5965 static_cast<uint32_t>(FixedArray::cast(elements())->length());
5966 if ((index < length) &&
5967 !FixedArray::cast(elements())->get(index)->IsTheHole()) {
5968 return true;
5969 }
5970 break;
5971 }
5972 case PIXEL_ELEMENTS: {
5973 // TODO(iposva): Add testcase.
5974 PixelArray* pixels = PixelArray::cast(elements());
5975 if (index < static_cast<uint32_t>(pixels->length())) {
5976 return true;
5977 }
5978 break;
5979 }
Steve Block3ce2e202009-11-05 08:53:23 +00005980 case EXTERNAL_BYTE_ELEMENTS:
5981 case EXTERNAL_UNSIGNED_BYTE_ELEMENTS:
5982 case EXTERNAL_SHORT_ELEMENTS:
5983 case EXTERNAL_UNSIGNED_SHORT_ELEMENTS:
5984 case EXTERNAL_INT_ELEMENTS:
5985 case EXTERNAL_UNSIGNED_INT_ELEMENTS:
5986 case EXTERNAL_FLOAT_ELEMENTS: {
5987 // TODO(kbr): Add testcase.
5988 ExternalArray* array = ExternalArray::cast(elements());
5989 if (index < static_cast<uint32_t>(array->length())) {
5990 return true;
5991 }
5992 break;
5993 }
Steve Blocka7e24c12009-10-30 11:49:00 +00005994 case DICTIONARY_ELEMENTS: {
5995 if (element_dictionary()->FindEntry(index)
5996 != NumberDictionary::kNotFound) {
5997 return true;
5998 }
5999 break;
6000 }
6001 default:
6002 UNREACHABLE();
6003 break;
6004 }
6005
6006 // Handle [] on String objects.
6007 if (this->IsStringObjectWithCharacterAt(index)) return true;
6008
6009 Object* pt = GetPrototype();
6010 if (pt == Heap::null_value()) return false;
6011 return JSObject::cast(pt)->HasElementWithReceiver(receiver, index);
6012}
6013
6014
6015bool JSObject::HasElementWithInterceptor(JSObject* receiver, uint32_t index) {
6016 // Make sure that the top context does not change when doing
6017 // callbacks or interceptor calls.
6018 AssertNoContextChange ncc;
6019 HandleScope scope;
6020 Handle<InterceptorInfo> interceptor(GetIndexedInterceptor());
6021 Handle<JSObject> receiver_handle(receiver);
6022 Handle<JSObject> holder_handle(this);
6023 CustomArguments args(interceptor->data(), receiver, this);
6024 v8::AccessorInfo info(args.end());
6025 if (!interceptor->query()->IsUndefined()) {
6026 v8::IndexedPropertyQuery query =
6027 v8::ToCData<v8::IndexedPropertyQuery>(interceptor->query());
6028 LOG(ApiIndexedPropertyAccess("interceptor-indexed-has", this, index));
Iain Merrick75681382010-08-19 15:07:18 +01006029 v8::Handle<v8::Integer> result;
Steve Blocka7e24c12009-10-30 11:49:00 +00006030 {
6031 // Leaving JavaScript.
6032 VMState state(EXTERNAL);
6033 result = query(index, info);
6034 }
Iain Merrick75681382010-08-19 15:07:18 +01006035 if (!result.IsEmpty()) {
6036 ASSERT(result->IsInt32());
6037 return true; // absence of property is signaled by empty handle.
6038 }
Steve Blocka7e24c12009-10-30 11:49:00 +00006039 } else if (!interceptor->getter()->IsUndefined()) {
6040 v8::IndexedPropertyGetter getter =
6041 v8::ToCData<v8::IndexedPropertyGetter>(interceptor->getter());
6042 LOG(ApiIndexedPropertyAccess("interceptor-indexed-has-get", this, index));
6043 v8::Handle<v8::Value> result;
6044 {
6045 // Leaving JavaScript.
6046 VMState state(EXTERNAL);
6047 result = getter(index, info);
6048 }
6049 if (!result.IsEmpty()) return true;
6050 }
6051 return holder_handle->HasElementPostInterceptor(*receiver_handle, index);
6052}
6053
6054
Kristian Monsen0d5e1162010-09-30 15:31:59 +01006055JSObject::LocalElementType JSObject::HasLocalElement(uint32_t index) {
Steve Blocka7e24c12009-10-30 11:49:00 +00006056 // Check access rights if needed.
6057 if (IsAccessCheckNeeded() &&
6058 !Top::MayIndexedAccess(this, index, v8::ACCESS_HAS)) {
6059 Top::ReportFailedAccessCheck(this, v8::ACCESS_HAS);
Kristian Monsen0d5e1162010-09-30 15:31:59 +01006060 return UNDEFINED_ELEMENT;
Steve Blocka7e24c12009-10-30 11:49:00 +00006061 }
6062
6063 // Check for lookup interceptor
6064 if (HasIndexedInterceptor()) {
Kristian Monsen0d5e1162010-09-30 15:31:59 +01006065 return HasElementWithInterceptor(this, index) ? INTERCEPTED_ELEMENT
6066 : UNDEFINED_ELEMENT;
Steve Blocka7e24c12009-10-30 11:49:00 +00006067 }
6068
6069 // Handle [] on String objects.
Kristian Monsen0d5e1162010-09-30 15:31:59 +01006070 if (this->IsStringObjectWithCharacterAt(index)) {
6071 return STRING_CHARACTER_ELEMENT;
6072 }
Steve Blocka7e24c12009-10-30 11:49:00 +00006073
6074 switch (GetElementsKind()) {
6075 case FAST_ELEMENTS: {
6076 uint32_t length = IsJSArray() ?
6077 static_cast<uint32_t>
6078 (Smi::cast(JSArray::cast(this)->length())->value()) :
6079 static_cast<uint32_t>(FixedArray::cast(elements())->length());
Kristian Monsen0d5e1162010-09-30 15:31:59 +01006080 if ((index < length) &&
6081 !FixedArray::cast(elements())->get(index)->IsTheHole()) {
6082 return FAST_ELEMENT;
6083 }
6084 break;
Steve Blocka7e24c12009-10-30 11:49:00 +00006085 }
6086 case PIXEL_ELEMENTS: {
6087 PixelArray* pixels = PixelArray::cast(elements());
Kristian Monsen0d5e1162010-09-30 15:31:59 +01006088 if (index < static_cast<uint32_t>(pixels->length())) return FAST_ELEMENT;
6089 break;
Steve Blocka7e24c12009-10-30 11:49:00 +00006090 }
Steve Block3ce2e202009-11-05 08:53:23 +00006091 case EXTERNAL_BYTE_ELEMENTS:
6092 case EXTERNAL_UNSIGNED_BYTE_ELEMENTS:
6093 case EXTERNAL_SHORT_ELEMENTS:
6094 case EXTERNAL_UNSIGNED_SHORT_ELEMENTS:
6095 case EXTERNAL_INT_ELEMENTS:
6096 case EXTERNAL_UNSIGNED_INT_ELEMENTS:
6097 case EXTERNAL_FLOAT_ELEMENTS: {
6098 ExternalArray* array = ExternalArray::cast(elements());
Kristian Monsen0d5e1162010-09-30 15:31:59 +01006099 if (index < static_cast<uint32_t>(array->length())) return FAST_ELEMENT;
6100 break;
Steve Block3ce2e202009-11-05 08:53:23 +00006101 }
Steve Blocka7e24c12009-10-30 11:49:00 +00006102 case DICTIONARY_ELEMENTS: {
Kristian Monsen0d5e1162010-09-30 15:31:59 +01006103 if (element_dictionary()->FindEntry(index) !=
6104 NumberDictionary::kNotFound) {
6105 return DICTIONARY_ELEMENT;
6106 }
6107 break;
Steve Blocka7e24c12009-10-30 11:49:00 +00006108 }
6109 default:
6110 UNREACHABLE();
6111 break;
6112 }
Kristian Monsen0d5e1162010-09-30 15:31:59 +01006113
6114 return UNDEFINED_ELEMENT;
Steve Blocka7e24c12009-10-30 11:49:00 +00006115}
6116
6117
6118bool JSObject::HasElementWithReceiver(JSObject* receiver, uint32_t index) {
6119 // Check access rights if needed.
6120 if (IsAccessCheckNeeded() &&
6121 !Top::MayIndexedAccess(this, index, v8::ACCESS_HAS)) {
6122 Top::ReportFailedAccessCheck(this, v8::ACCESS_HAS);
6123 return false;
6124 }
6125
6126 // Check for lookup interceptor
6127 if (HasIndexedInterceptor()) {
6128 return HasElementWithInterceptor(receiver, index);
6129 }
6130
6131 switch (GetElementsKind()) {
6132 case FAST_ELEMENTS: {
6133 uint32_t length = IsJSArray() ?
6134 static_cast<uint32_t>
6135 (Smi::cast(JSArray::cast(this)->length())->value()) :
6136 static_cast<uint32_t>(FixedArray::cast(elements())->length());
6137 if ((index < length) &&
6138 !FixedArray::cast(elements())->get(index)->IsTheHole()) return true;
6139 break;
6140 }
6141 case PIXEL_ELEMENTS: {
6142 PixelArray* pixels = PixelArray::cast(elements());
6143 if (index < static_cast<uint32_t>(pixels->length())) {
6144 return true;
6145 }
6146 break;
6147 }
Steve Block3ce2e202009-11-05 08:53:23 +00006148 case EXTERNAL_BYTE_ELEMENTS:
6149 case EXTERNAL_UNSIGNED_BYTE_ELEMENTS:
6150 case EXTERNAL_SHORT_ELEMENTS:
6151 case EXTERNAL_UNSIGNED_SHORT_ELEMENTS:
6152 case EXTERNAL_INT_ELEMENTS:
6153 case EXTERNAL_UNSIGNED_INT_ELEMENTS:
6154 case EXTERNAL_FLOAT_ELEMENTS: {
6155 ExternalArray* array = ExternalArray::cast(elements());
6156 if (index < static_cast<uint32_t>(array->length())) {
6157 return true;
6158 }
6159 break;
6160 }
Steve Blocka7e24c12009-10-30 11:49:00 +00006161 case DICTIONARY_ELEMENTS: {
6162 if (element_dictionary()->FindEntry(index)
6163 != NumberDictionary::kNotFound) {
6164 return true;
6165 }
6166 break;
6167 }
6168 default:
6169 UNREACHABLE();
6170 break;
6171 }
6172
6173 // Handle [] on String objects.
6174 if (this->IsStringObjectWithCharacterAt(index)) return true;
6175
6176 Object* pt = GetPrototype();
6177 if (pt == Heap::null_value()) return false;
6178 return JSObject::cast(pt)->HasElementWithReceiver(receiver, index);
6179}
6180
6181
6182Object* JSObject::SetElementWithInterceptor(uint32_t index, Object* value) {
6183 // Make sure that the top context does not change when doing
6184 // callbacks or interceptor calls.
6185 AssertNoContextChange ncc;
6186 HandleScope scope;
6187 Handle<InterceptorInfo> interceptor(GetIndexedInterceptor());
6188 Handle<JSObject> this_handle(this);
6189 Handle<Object> value_handle(value);
6190 if (!interceptor->setter()->IsUndefined()) {
6191 v8::IndexedPropertySetter setter =
6192 v8::ToCData<v8::IndexedPropertySetter>(interceptor->setter());
6193 LOG(ApiIndexedPropertyAccess("interceptor-indexed-set", this, index));
6194 CustomArguments args(interceptor->data(), this, this);
6195 v8::AccessorInfo info(args.end());
6196 v8::Handle<v8::Value> result;
6197 {
6198 // Leaving JavaScript.
6199 VMState state(EXTERNAL);
6200 result = setter(index, v8::Utils::ToLocal(value_handle), info);
6201 }
6202 RETURN_IF_SCHEDULED_EXCEPTION();
6203 if (!result.IsEmpty()) return *value_handle;
6204 }
6205 Object* raw_result =
6206 this_handle->SetElementWithoutInterceptor(index, *value_handle);
6207 RETURN_IF_SCHEDULED_EXCEPTION();
6208 return raw_result;
6209}
6210
6211
Leon Clarkef7060e22010-06-03 12:02:55 +01006212Object* JSObject::GetElementWithCallback(Object* receiver,
6213 Object* structure,
6214 uint32_t index,
6215 Object* holder) {
6216 ASSERT(!structure->IsProxy());
6217
6218 // api style callbacks.
6219 if (structure->IsAccessorInfo()) {
6220 AccessorInfo* data = AccessorInfo::cast(structure);
6221 Object* fun_obj = data->getter();
6222 v8::AccessorGetter call_fun = v8::ToCData<v8::AccessorGetter>(fun_obj);
6223 HandleScope scope;
6224 Handle<JSObject> self(JSObject::cast(receiver));
6225 Handle<JSObject> holder_handle(JSObject::cast(holder));
6226 Handle<Object> number = Factory::NewNumberFromUint(index);
6227 Handle<String> key(Factory::NumberToString(number));
6228 LOG(ApiNamedPropertyAccess("load", *self, *key));
6229 CustomArguments args(data->data(), *self, *holder_handle);
6230 v8::AccessorInfo info(args.end());
6231 v8::Handle<v8::Value> result;
6232 {
6233 // Leaving JavaScript.
6234 VMState state(EXTERNAL);
6235 result = call_fun(v8::Utils::ToLocal(key), info);
6236 }
6237 RETURN_IF_SCHEDULED_EXCEPTION();
6238 if (result.IsEmpty()) return Heap::undefined_value();
6239 return *v8::Utils::OpenHandle(*result);
6240 }
6241
6242 // __defineGetter__ callback
6243 if (structure->IsFixedArray()) {
6244 Object* getter = FixedArray::cast(structure)->get(kGetterIndex);
6245 if (getter->IsJSFunction()) {
6246 return Object::GetPropertyWithDefinedGetter(receiver,
6247 JSFunction::cast(getter));
6248 }
6249 // Getter is not a function.
6250 return Heap::undefined_value();
6251 }
6252
6253 UNREACHABLE();
6254 return NULL;
6255}
6256
6257
6258Object* JSObject::SetElementWithCallback(Object* structure,
6259 uint32_t index,
6260 Object* value,
6261 JSObject* holder) {
6262 HandleScope scope;
6263
6264 // We should never get here to initialize a const with the hole
6265 // value since a const declaration would conflict with the setter.
6266 ASSERT(!value->IsTheHole());
6267 Handle<Object> value_handle(value);
6268
6269 // To accommodate both the old and the new api we switch on the
6270 // data structure used to store the callbacks. Eventually proxy
6271 // callbacks should be phased out.
6272 ASSERT(!structure->IsProxy());
6273
6274 if (structure->IsAccessorInfo()) {
6275 // api style callbacks
6276 AccessorInfo* data = AccessorInfo::cast(structure);
6277 Object* call_obj = data->setter();
6278 v8::AccessorSetter call_fun = v8::ToCData<v8::AccessorSetter>(call_obj);
6279 if (call_fun == NULL) return value;
6280 Handle<Object> number = Factory::NewNumberFromUint(index);
6281 Handle<String> key(Factory::NumberToString(number));
6282 LOG(ApiNamedPropertyAccess("store", this, *key));
6283 CustomArguments args(data->data(), this, JSObject::cast(holder));
6284 v8::AccessorInfo info(args.end());
6285 {
6286 // Leaving JavaScript.
6287 VMState state(EXTERNAL);
6288 call_fun(v8::Utils::ToLocal(key),
6289 v8::Utils::ToLocal(value_handle),
6290 info);
6291 }
6292 RETURN_IF_SCHEDULED_EXCEPTION();
6293 return *value_handle;
6294 }
6295
6296 if (structure->IsFixedArray()) {
6297 Object* setter = FixedArray::cast(structure)->get(kSetterIndex);
6298 if (setter->IsJSFunction()) {
6299 return SetPropertyWithDefinedSetter(JSFunction::cast(setter), value);
6300 } else {
6301 Handle<Object> holder_handle(holder);
6302 Handle<Object> key(Factory::NewNumberFromUint(index));
6303 Handle<Object> args[2] = { key, holder_handle };
6304 return Top::Throw(*Factory::NewTypeError("no_setter_in_callback",
6305 HandleVector(args, 2)));
6306 }
6307 }
6308
6309 UNREACHABLE();
6310 return NULL;
6311}
6312
6313
Steve Blocka7e24c12009-10-30 11:49:00 +00006314// Adding n elements in fast case is O(n*n).
6315// Note: revisit design to have dual undefined values to capture absent
6316// elements.
6317Object* JSObject::SetFastElement(uint32_t index, Object* value) {
6318 ASSERT(HasFastElements());
6319
Iain Merrick75681382010-08-19 15:07:18 +01006320 Object* elms_obj = EnsureWritableFastElements();
6321 if (elms_obj->IsFailure()) return elms_obj;
6322 FixedArray* elms = FixedArray::cast(elms_obj);
Steve Blocka7e24c12009-10-30 11:49:00 +00006323 uint32_t elms_length = static_cast<uint32_t>(elms->length());
6324
6325 if (!IsJSArray() && (index >= elms_length || elms->get(index)->IsTheHole())) {
Leon Clarkef7060e22010-06-03 12:02:55 +01006326 if (SetElementWithCallbackSetterInPrototypes(index, value)) {
6327 return value;
Steve Blocka7e24c12009-10-30 11:49:00 +00006328 }
6329 }
6330
6331 // Check whether there is extra space in fixed array..
6332 if (index < elms_length) {
6333 elms->set(index, value);
6334 if (IsJSArray()) {
6335 // Update the length of the array if needed.
6336 uint32_t array_length = 0;
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01006337 CHECK(JSArray::cast(this)->length()->ToArrayIndex(&array_length));
Steve Blocka7e24c12009-10-30 11:49:00 +00006338 if (index >= array_length) {
Leon Clarke4515c472010-02-03 11:58:03 +00006339 JSArray::cast(this)->set_length(Smi::FromInt(index + 1));
Steve Blocka7e24c12009-10-30 11:49:00 +00006340 }
6341 }
6342 return value;
6343 }
6344
6345 // Allow gap in fast case.
6346 if ((index - elms_length) < kMaxGap) {
6347 // Try allocating extra space.
6348 int new_capacity = NewElementsCapacity(index+1);
6349 if (new_capacity <= kMaxFastElementsLength ||
6350 !ShouldConvertToSlowElements(new_capacity)) {
6351 ASSERT(static_cast<uint32_t>(new_capacity) > index);
Steve Block8defd9f2010-07-08 12:39:36 +01006352 Object* obj = SetFastElementsCapacityAndLength(new_capacity, index + 1);
Steve Blocka7e24c12009-10-30 11:49:00 +00006353 if (obj->IsFailure()) return obj;
Steve Blocka7e24c12009-10-30 11:49:00 +00006354 FixedArray::cast(elements())->set(index, value);
6355 return value;
6356 }
6357 }
6358
6359 // Otherwise default to slow case.
6360 Object* obj = NormalizeElements();
6361 if (obj->IsFailure()) return obj;
6362 ASSERT(HasDictionaryElements());
6363 return SetElement(index, value);
6364}
6365
Iain Merrick75681382010-08-19 15:07:18 +01006366
Steve Blocka7e24c12009-10-30 11:49:00 +00006367Object* JSObject::SetElement(uint32_t index, Object* value) {
6368 // Check access rights if needed.
6369 if (IsAccessCheckNeeded() &&
6370 !Top::MayIndexedAccess(this, index, v8::ACCESS_SET)) {
Iain Merrick75681382010-08-19 15:07:18 +01006371 HandleScope scope;
6372 Handle<Object> value_handle(value);
Steve Blocka7e24c12009-10-30 11:49:00 +00006373 Top::ReportFailedAccessCheck(this, v8::ACCESS_SET);
Iain Merrick75681382010-08-19 15:07:18 +01006374 return *value_handle;
Steve Blocka7e24c12009-10-30 11:49:00 +00006375 }
6376
6377 if (IsJSGlobalProxy()) {
6378 Object* proto = GetPrototype();
6379 if (proto->IsNull()) return value;
6380 ASSERT(proto->IsJSGlobalObject());
6381 return JSObject::cast(proto)->SetElement(index, value);
6382 }
6383
6384 // Check for lookup interceptor
6385 if (HasIndexedInterceptor()) {
6386 return SetElementWithInterceptor(index, value);
6387 }
6388
6389 return SetElementWithoutInterceptor(index, value);
6390}
6391
6392
6393Object* JSObject::SetElementWithoutInterceptor(uint32_t index, Object* value) {
6394 switch (GetElementsKind()) {
6395 case FAST_ELEMENTS:
6396 // Fast case.
6397 return SetFastElement(index, value);
6398 case PIXEL_ELEMENTS: {
6399 PixelArray* pixels = PixelArray::cast(elements());
6400 return pixels->SetValue(index, value);
6401 }
Steve Block3ce2e202009-11-05 08:53:23 +00006402 case EXTERNAL_BYTE_ELEMENTS: {
6403 ExternalByteArray* array = ExternalByteArray::cast(elements());
6404 return array->SetValue(index, value);
6405 }
6406 case EXTERNAL_UNSIGNED_BYTE_ELEMENTS: {
6407 ExternalUnsignedByteArray* array =
6408 ExternalUnsignedByteArray::cast(elements());
6409 return array->SetValue(index, value);
6410 }
6411 case EXTERNAL_SHORT_ELEMENTS: {
6412 ExternalShortArray* array = ExternalShortArray::cast(elements());
6413 return array->SetValue(index, value);
6414 }
6415 case EXTERNAL_UNSIGNED_SHORT_ELEMENTS: {
6416 ExternalUnsignedShortArray* array =
6417 ExternalUnsignedShortArray::cast(elements());
6418 return array->SetValue(index, value);
6419 }
6420 case EXTERNAL_INT_ELEMENTS: {
6421 ExternalIntArray* array = ExternalIntArray::cast(elements());
6422 return array->SetValue(index, value);
6423 }
6424 case EXTERNAL_UNSIGNED_INT_ELEMENTS: {
6425 ExternalUnsignedIntArray* array =
6426 ExternalUnsignedIntArray::cast(elements());
6427 return array->SetValue(index, value);
6428 }
6429 case EXTERNAL_FLOAT_ELEMENTS: {
6430 ExternalFloatArray* array = ExternalFloatArray::cast(elements());
6431 return array->SetValue(index, value);
6432 }
Steve Blocka7e24c12009-10-30 11:49:00 +00006433 case DICTIONARY_ELEMENTS: {
6434 // Insert element in the dictionary.
6435 FixedArray* elms = FixedArray::cast(elements());
6436 NumberDictionary* dictionary = NumberDictionary::cast(elms);
6437
6438 int entry = dictionary->FindEntry(index);
6439 if (entry != NumberDictionary::kNotFound) {
6440 Object* element = dictionary->ValueAt(entry);
6441 PropertyDetails details = dictionary->DetailsAt(entry);
6442 if (details.type() == CALLBACKS) {
Leon Clarkef7060e22010-06-03 12:02:55 +01006443 return SetElementWithCallback(element, index, value, this);
Steve Blocka7e24c12009-10-30 11:49:00 +00006444 } else {
6445 dictionary->UpdateMaxNumberKey(index);
6446 dictionary->ValueAtPut(entry, value);
6447 }
6448 } else {
6449 // Index not already used. Look for an accessor in the prototype chain.
6450 if (!IsJSArray()) {
Leon Clarkef7060e22010-06-03 12:02:55 +01006451 if (SetElementWithCallbackSetterInPrototypes(index, value)) {
6452 return value;
Steve Blocka7e24c12009-10-30 11:49:00 +00006453 }
6454 }
Steve Block8defd9f2010-07-08 12:39:36 +01006455 // When we set the is_extensible flag to false we always force
6456 // the element into dictionary mode (and force them to stay there).
6457 if (!map()->is_extensible()) {
Ben Murdochf87a2032010-10-22 12:50:53 +01006458 Handle<Object> number(Factory::NewNumberFromUint(index));
Steve Block8defd9f2010-07-08 12:39:36 +01006459 Handle<String> index_string(Factory::NumberToString(number));
6460 Handle<Object> args[1] = { index_string };
6461 return Top::Throw(*Factory::NewTypeError("object_not_extensible",
6462 HandleVector(args, 1)));
6463 }
Steve Blocka7e24c12009-10-30 11:49:00 +00006464 Object* result = dictionary->AtNumberPut(index, value);
6465 if (result->IsFailure()) return result;
6466 if (elms != FixedArray::cast(result)) {
6467 set_elements(FixedArray::cast(result));
6468 }
6469 }
6470
6471 // Update the array length if this JSObject is an array.
6472 if (IsJSArray()) {
6473 JSArray* array = JSArray::cast(this);
6474 Object* return_value = array->JSArrayUpdateLengthFromIndex(index,
6475 value);
6476 if (return_value->IsFailure()) return return_value;
6477 }
6478
6479 // Attempt to put this object back in fast case.
6480 if (ShouldConvertToFastElements()) {
6481 uint32_t new_length = 0;
6482 if (IsJSArray()) {
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01006483 CHECK(JSArray::cast(this)->length()->ToArrayIndex(&new_length));
Steve Blocka7e24c12009-10-30 11:49:00 +00006484 } else {
6485 new_length = NumberDictionary::cast(elements())->max_number_key() + 1;
6486 }
Steve Block8defd9f2010-07-08 12:39:36 +01006487 Object* obj = SetFastElementsCapacityAndLength(new_length, new_length);
Steve Blocka7e24c12009-10-30 11:49:00 +00006488 if (obj->IsFailure()) return obj;
Steve Blocka7e24c12009-10-30 11:49:00 +00006489#ifdef DEBUG
6490 if (FLAG_trace_normalization) {
6491 PrintF("Object elements are fast case again:\n");
6492 Print();
6493 }
6494#endif
6495 }
6496
6497 return value;
6498 }
6499 default:
6500 UNREACHABLE();
6501 break;
6502 }
6503 // All possible cases have been handled above. Add a return to avoid the
6504 // complaints from the compiler.
6505 UNREACHABLE();
6506 return Heap::null_value();
6507}
6508
6509
6510Object* JSArray::JSArrayUpdateLengthFromIndex(uint32_t index, Object* value) {
6511 uint32_t old_len = 0;
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01006512 CHECK(length()->ToArrayIndex(&old_len));
Steve Blocka7e24c12009-10-30 11:49:00 +00006513 // Check to see if we need to update the length. For now, we make
6514 // sure that the length stays within 32-bits (unsigned).
6515 if (index >= old_len && index != 0xffffffff) {
6516 Object* len =
6517 Heap::NumberFromDouble(static_cast<double>(index) + 1);
6518 if (len->IsFailure()) return len;
6519 set_length(len);
6520 }
6521 return value;
6522}
6523
6524
6525Object* JSObject::GetElementPostInterceptor(JSObject* receiver,
6526 uint32_t index) {
6527 // Get element works for both JSObject and JSArray since
6528 // JSArray::length cannot change.
6529 switch (GetElementsKind()) {
6530 case FAST_ELEMENTS: {
6531 FixedArray* elms = FixedArray::cast(elements());
6532 if (index < static_cast<uint32_t>(elms->length())) {
6533 Object* value = elms->get(index);
6534 if (!value->IsTheHole()) return value;
6535 }
6536 break;
6537 }
6538 case PIXEL_ELEMENTS: {
6539 // TODO(iposva): Add testcase and implement.
6540 UNIMPLEMENTED();
6541 break;
6542 }
Steve Block3ce2e202009-11-05 08:53:23 +00006543 case EXTERNAL_BYTE_ELEMENTS:
6544 case EXTERNAL_UNSIGNED_BYTE_ELEMENTS:
6545 case EXTERNAL_SHORT_ELEMENTS:
6546 case EXTERNAL_UNSIGNED_SHORT_ELEMENTS:
6547 case EXTERNAL_INT_ELEMENTS:
6548 case EXTERNAL_UNSIGNED_INT_ELEMENTS:
6549 case EXTERNAL_FLOAT_ELEMENTS: {
6550 // TODO(kbr): Add testcase and implement.
6551 UNIMPLEMENTED();
6552 break;
6553 }
Steve Blocka7e24c12009-10-30 11:49:00 +00006554 case DICTIONARY_ELEMENTS: {
6555 NumberDictionary* dictionary = element_dictionary();
6556 int entry = dictionary->FindEntry(index);
6557 if (entry != NumberDictionary::kNotFound) {
6558 Object* element = dictionary->ValueAt(entry);
6559 PropertyDetails details = dictionary->DetailsAt(entry);
6560 if (details.type() == CALLBACKS) {
Leon Clarkef7060e22010-06-03 12:02:55 +01006561 return GetElementWithCallback(receiver,
6562 element,
6563 index,
6564 this);
Steve Blocka7e24c12009-10-30 11:49:00 +00006565 }
6566 return element;
6567 }
6568 break;
6569 }
6570 default:
6571 UNREACHABLE();
6572 break;
6573 }
6574
6575 // Continue searching via the prototype chain.
6576 Object* pt = GetPrototype();
6577 if (pt == Heap::null_value()) return Heap::undefined_value();
6578 return pt->GetElementWithReceiver(receiver, index);
6579}
6580
6581
6582Object* JSObject::GetElementWithInterceptor(JSObject* receiver,
6583 uint32_t index) {
6584 // Make sure that the top context does not change when doing
6585 // callbacks or interceptor calls.
6586 AssertNoContextChange ncc;
6587 HandleScope scope;
6588 Handle<InterceptorInfo> interceptor(GetIndexedInterceptor());
6589 Handle<JSObject> this_handle(receiver);
6590 Handle<JSObject> holder_handle(this);
6591
6592 if (!interceptor->getter()->IsUndefined()) {
6593 v8::IndexedPropertyGetter getter =
6594 v8::ToCData<v8::IndexedPropertyGetter>(interceptor->getter());
6595 LOG(ApiIndexedPropertyAccess("interceptor-indexed-get", this, index));
6596 CustomArguments args(interceptor->data(), receiver, this);
6597 v8::AccessorInfo info(args.end());
6598 v8::Handle<v8::Value> result;
6599 {
6600 // Leaving JavaScript.
6601 VMState state(EXTERNAL);
6602 result = getter(index, info);
6603 }
6604 RETURN_IF_SCHEDULED_EXCEPTION();
6605 if (!result.IsEmpty()) return *v8::Utils::OpenHandle(*result);
6606 }
6607
6608 Object* raw_result =
6609 holder_handle->GetElementPostInterceptor(*this_handle, index);
6610 RETURN_IF_SCHEDULED_EXCEPTION();
6611 return raw_result;
6612}
6613
6614
6615Object* JSObject::GetElementWithReceiver(JSObject* receiver, uint32_t index) {
6616 // Check access rights if needed.
6617 if (IsAccessCheckNeeded() &&
6618 !Top::MayIndexedAccess(this, index, v8::ACCESS_GET)) {
6619 Top::ReportFailedAccessCheck(this, v8::ACCESS_GET);
6620 return Heap::undefined_value();
6621 }
6622
6623 if (HasIndexedInterceptor()) {
6624 return GetElementWithInterceptor(receiver, index);
6625 }
6626
6627 // Get element works for both JSObject and JSArray since
6628 // JSArray::length cannot change.
6629 switch (GetElementsKind()) {
6630 case FAST_ELEMENTS: {
6631 FixedArray* elms = FixedArray::cast(elements());
6632 if (index < static_cast<uint32_t>(elms->length())) {
6633 Object* value = elms->get(index);
6634 if (!value->IsTheHole()) return value;
6635 }
6636 break;
6637 }
6638 case PIXEL_ELEMENTS: {
6639 PixelArray* pixels = PixelArray::cast(elements());
6640 if (index < static_cast<uint32_t>(pixels->length())) {
6641 uint8_t value = pixels->get(index);
6642 return Smi::FromInt(value);
6643 }
6644 break;
6645 }
Steve Block3ce2e202009-11-05 08:53:23 +00006646 case EXTERNAL_BYTE_ELEMENTS: {
6647 ExternalByteArray* array = ExternalByteArray::cast(elements());
6648 if (index < static_cast<uint32_t>(array->length())) {
6649 int8_t value = array->get(index);
6650 return Smi::FromInt(value);
6651 }
6652 break;
6653 }
6654 case EXTERNAL_UNSIGNED_BYTE_ELEMENTS: {
6655 ExternalUnsignedByteArray* array =
6656 ExternalUnsignedByteArray::cast(elements());
6657 if (index < static_cast<uint32_t>(array->length())) {
6658 uint8_t value = array->get(index);
6659 return Smi::FromInt(value);
6660 }
6661 break;
6662 }
6663 case EXTERNAL_SHORT_ELEMENTS: {
6664 ExternalShortArray* array = ExternalShortArray::cast(elements());
6665 if (index < static_cast<uint32_t>(array->length())) {
6666 int16_t value = array->get(index);
6667 return Smi::FromInt(value);
6668 }
6669 break;
6670 }
6671 case EXTERNAL_UNSIGNED_SHORT_ELEMENTS: {
6672 ExternalUnsignedShortArray* array =
6673 ExternalUnsignedShortArray::cast(elements());
6674 if (index < static_cast<uint32_t>(array->length())) {
6675 uint16_t value = array->get(index);
6676 return Smi::FromInt(value);
6677 }
6678 break;
6679 }
6680 case EXTERNAL_INT_ELEMENTS: {
6681 ExternalIntArray* array = ExternalIntArray::cast(elements());
6682 if (index < static_cast<uint32_t>(array->length())) {
6683 int32_t value = array->get(index);
6684 return Heap::NumberFromInt32(value);
6685 }
6686 break;
6687 }
6688 case EXTERNAL_UNSIGNED_INT_ELEMENTS: {
6689 ExternalUnsignedIntArray* array =
6690 ExternalUnsignedIntArray::cast(elements());
6691 if (index < static_cast<uint32_t>(array->length())) {
6692 uint32_t value = array->get(index);
6693 return Heap::NumberFromUint32(value);
6694 }
6695 break;
6696 }
6697 case EXTERNAL_FLOAT_ELEMENTS: {
6698 ExternalFloatArray* array = ExternalFloatArray::cast(elements());
6699 if (index < static_cast<uint32_t>(array->length())) {
6700 float value = array->get(index);
6701 return Heap::AllocateHeapNumber(value);
6702 }
6703 break;
6704 }
Steve Blocka7e24c12009-10-30 11:49:00 +00006705 case DICTIONARY_ELEMENTS: {
6706 NumberDictionary* dictionary = element_dictionary();
6707 int entry = dictionary->FindEntry(index);
6708 if (entry != NumberDictionary::kNotFound) {
6709 Object* element = dictionary->ValueAt(entry);
6710 PropertyDetails details = dictionary->DetailsAt(entry);
6711 if (details.type() == CALLBACKS) {
Leon Clarkef7060e22010-06-03 12:02:55 +01006712 return GetElementWithCallback(receiver,
6713 element,
6714 index,
6715 this);
Steve Blocka7e24c12009-10-30 11:49:00 +00006716 }
6717 return element;
6718 }
6719 break;
6720 }
6721 }
6722
6723 Object* pt = GetPrototype();
6724 if (pt == Heap::null_value()) return Heap::undefined_value();
6725 return pt->GetElementWithReceiver(receiver, index);
6726}
6727
6728
6729bool JSObject::HasDenseElements() {
6730 int capacity = 0;
6731 int number_of_elements = 0;
6732
6733 switch (GetElementsKind()) {
6734 case FAST_ELEMENTS: {
6735 FixedArray* elms = FixedArray::cast(elements());
6736 capacity = elms->length();
6737 for (int i = 0; i < capacity; i++) {
6738 if (!elms->get(i)->IsTheHole()) number_of_elements++;
6739 }
6740 break;
6741 }
Steve Block3ce2e202009-11-05 08:53:23 +00006742 case PIXEL_ELEMENTS:
6743 case EXTERNAL_BYTE_ELEMENTS:
6744 case EXTERNAL_UNSIGNED_BYTE_ELEMENTS:
6745 case EXTERNAL_SHORT_ELEMENTS:
6746 case EXTERNAL_UNSIGNED_SHORT_ELEMENTS:
6747 case EXTERNAL_INT_ELEMENTS:
6748 case EXTERNAL_UNSIGNED_INT_ELEMENTS:
6749 case EXTERNAL_FLOAT_ELEMENTS: {
Steve Blocka7e24c12009-10-30 11:49:00 +00006750 return true;
6751 }
6752 case DICTIONARY_ELEMENTS: {
6753 NumberDictionary* dictionary = NumberDictionary::cast(elements());
6754 capacity = dictionary->Capacity();
6755 number_of_elements = dictionary->NumberOfElements();
6756 break;
6757 }
6758 default:
6759 UNREACHABLE();
6760 break;
6761 }
6762
6763 if (capacity == 0) return true;
6764 return (number_of_elements > (capacity / 2));
6765}
6766
6767
6768bool JSObject::ShouldConvertToSlowElements(int new_capacity) {
6769 ASSERT(HasFastElements());
6770 // Keep the array in fast case if the current backing storage is
6771 // almost filled and if the new capacity is no more than twice the
6772 // old capacity.
6773 int elements_length = FixedArray::cast(elements())->length();
6774 return !HasDenseElements() || ((new_capacity / 2) > elements_length);
6775}
6776
6777
6778bool JSObject::ShouldConvertToFastElements() {
6779 ASSERT(HasDictionaryElements());
6780 NumberDictionary* dictionary = NumberDictionary::cast(elements());
6781 // If the elements are sparse, we should not go back to fast case.
6782 if (!HasDenseElements()) return false;
6783 // If an element has been added at a very high index in the elements
6784 // dictionary, we cannot go back to fast case.
6785 if (dictionary->requires_slow_elements()) return false;
6786 // An object requiring access checks is never allowed to have fast
6787 // elements. If it had fast elements we would skip security checks.
6788 if (IsAccessCheckNeeded()) return false;
6789 // If the dictionary backing storage takes up roughly half as much
6790 // space as a fast-case backing storage would the array should have
6791 // fast elements.
6792 uint32_t length = 0;
6793 if (IsJSArray()) {
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01006794 CHECK(JSArray::cast(this)->length()->ToArrayIndex(&length));
Steve Blocka7e24c12009-10-30 11:49:00 +00006795 } else {
6796 length = dictionary->max_number_key();
6797 }
6798 return static_cast<uint32_t>(dictionary->Capacity()) >=
6799 (length / (2 * NumberDictionary::kEntrySize));
6800}
6801
6802
6803// Certain compilers request function template instantiation when they
6804// see the definition of the other template functions in the
6805// class. This requires us to have the template functions put
6806// together, so even though this function belongs in objects-debug.cc,
6807// we keep it here instead to satisfy certain compilers.
6808#ifdef DEBUG
6809template<typename Shape, typename Key>
6810void Dictionary<Shape, Key>::Print() {
6811 int capacity = HashTable<Shape, Key>::Capacity();
6812 for (int i = 0; i < capacity; i++) {
6813 Object* k = HashTable<Shape, Key>::KeyAt(i);
6814 if (HashTable<Shape, Key>::IsKey(k)) {
6815 PrintF(" ");
6816 if (k->IsString()) {
6817 String::cast(k)->StringPrint();
6818 } else {
6819 k->ShortPrint();
6820 }
6821 PrintF(": ");
6822 ValueAt(i)->ShortPrint();
6823 PrintF("\n");
6824 }
6825 }
6826}
6827#endif
6828
6829
6830template<typename Shape, typename Key>
6831void Dictionary<Shape, Key>::CopyValuesTo(FixedArray* elements) {
6832 int pos = 0;
6833 int capacity = HashTable<Shape, Key>::Capacity();
Leon Clarke4515c472010-02-03 11:58:03 +00006834 AssertNoAllocation no_gc;
6835 WriteBarrierMode mode = elements->GetWriteBarrierMode(no_gc);
Steve Blocka7e24c12009-10-30 11:49:00 +00006836 for (int i = 0; i < capacity; i++) {
6837 Object* k = Dictionary<Shape, Key>::KeyAt(i);
6838 if (Dictionary<Shape, Key>::IsKey(k)) {
6839 elements->set(pos++, ValueAt(i), mode);
6840 }
6841 }
6842 ASSERT(pos == elements->length());
6843}
6844
6845
6846InterceptorInfo* JSObject::GetNamedInterceptor() {
6847 ASSERT(map()->has_named_interceptor());
6848 JSFunction* constructor = JSFunction::cast(map()->constructor());
Steve Block6ded16b2010-05-10 14:33:55 +01006849 ASSERT(constructor->shared()->IsApiFunction());
Steve Blocka7e24c12009-10-30 11:49:00 +00006850 Object* result =
Steve Block6ded16b2010-05-10 14:33:55 +01006851 constructor->shared()->get_api_func_data()->named_property_handler();
Steve Blocka7e24c12009-10-30 11:49:00 +00006852 return InterceptorInfo::cast(result);
6853}
6854
6855
6856InterceptorInfo* JSObject::GetIndexedInterceptor() {
6857 ASSERT(map()->has_indexed_interceptor());
6858 JSFunction* constructor = JSFunction::cast(map()->constructor());
Steve Block6ded16b2010-05-10 14:33:55 +01006859 ASSERT(constructor->shared()->IsApiFunction());
Steve Blocka7e24c12009-10-30 11:49:00 +00006860 Object* result =
Steve Block6ded16b2010-05-10 14:33:55 +01006861 constructor->shared()->get_api_func_data()->indexed_property_handler();
Steve Blocka7e24c12009-10-30 11:49:00 +00006862 return InterceptorInfo::cast(result);
6863}
6864
6865
6866Object* JSObject::GetPropertyPostInterceptor(JSObject* receiver,
6867 String* name,
6868 PropertyAttributes* attributes) {
6869 // Check local property in holder, ignore interceptor.
6870 LookupResult result;
6871 LocalLookupRealNamedProperty(name, &result);
Andrei Popescu402d9372010-02-26 13:31:12 +00006872 if (result.IsProperty()) {
6873 return GetProperty(receiver, &result, name, attributes);
6874 }
Steve Blocka7e24c12009-10-30 11:49:00 +00006875 // Continue searching via the prototype chain.
6876 Object* pt = GetPrototype();
6877 *attributes = ABSENT;
6878 if (pt == Heap::null_value()) return Heap::undefined_value();
6879 return pt->GetPropertyWithReceiver(receiver, name, attributes);
6880}
6881
6882
Steve Blockd0582a62009-12-15 09:54:21 +00006883Object* JSObject::GetLocalPropertyPostInterceptor(
6884 JSObject* receiver,
6885 String* name,
6886 PropertyAttributes* attributes) {
6887 // Check local property in holder, ignore interceptor.
6888 LookupResult result;
6889 LocalLookupRealNamedProperty(name, &result);
Andrei Popescu402d9372010-02-26 13:31:12 +00006890 if (result.IsProperty()) {
6891 return GetProperty(receiver, &result, name, attributes);
6892 }
6893 return Heap::undefined_value();
Steve Blockd0582a62009-12-15 09:54:21 +00006894}
6895
6896
Steve Blocka7e24c12009-10-30 11:49:00 +00006897Object* JSObject::GetPropertyWithInterceptor(
6898 JSObject* receiver,
6899 String* name,
6900 PropertyAttributes* attributes) {
6901 InterceptorInfo* interceptor = GetNamedInterceptor();
6902 HandleScope scope;
6903 Handle<JSObject> receiver_handle(receiver);
6904 Handle<JSObject> holder_handle(this);
6905 Handle<String> name_handle(name);
6906
6907 if (!interceptor->getter()->IsUndefined()) {
6908 v8::NamedPropertyGetter getter =
6909 v8::ToCData<v8::NamedPropertyGetter>(interceptor->getter());
6910 LOG(ApiNamedPropertyAccess("interceptor-named-get", *holder_handle, name));
6911 CustomArguments args(interceptor->data(), receiver, this);
6912 v8::AccessorInfo info(args.end());
6913 v8::Handle<v8::Value> result;
6914 {
6915 // Leaving JavaScript.
6916 VMState state(EXTERNAL);
6917 result = getter(v8::Utils::ToLocal(name_handle), info);
6918 }
6919 RETURN_IF_SCHEDULED_EXCEPTION();
6920 if (!result.IsEmpty()) {
6921 *attributes = NONE;
6922 return *v8::Utils::OpenHandle(*result);
6923 }
6924 }
6925
6926 Object* result = holder_handle->GetPropertyPostInterceptor(
6927 *receiver_handle,
6928 *name_handle,
6929 attributes);
6930 RETURN_IF_SCHEDULED_EXCEPTION();
6931 return result;
6932}
6933
6934
6935bool JSObject::HasRealNamedProperty(String* key) {
6936 // Check access rights if needed.
6937 if (IsAccessCheckNeeded() &&
6938 !Top::MayNamedAccess(this, key, v8::ACCESS_HAS)) {
6939 Top::ReportFailedAccessCheck(this, v8::ACCESS_HAS);
6940 return false;
6941 }
6942
6943 LookupResult result;
6944 LocalLookupRealNamedProperty(key, &result);
Andrei Popescu402d9372010-02-26 13:31:12 +00006945 return result.IsProperty() && (result.type() != INTERCEPTOR);
Steve Blocka7e24c12009-10-30 11:49:00 +00006946}
6947
6948
6949bool JSObject::HasRealElementProperty(uint32_t index) {
6950 // Check access rights if needed.
6951 if (IsAccessCheckNeeded() &&
6952 !Top::MayIndexedAccess(this, index, v8::ACCESS_HAS)) {
6953 Top::ReportFailedAccessCheck(this, v8::ACCESS_HAS);
6954 return false;
6955 }
6956
6957 // Handle [] on String objects.
6958 if (this->IsStringObjectWithCharacterAt(index)) return true;
6959
6960 switch (GetElementsKind()) {
6961 case FAST_ELEMENTS: {
6962 uint32_t length = IsJSArray() ?
6963 static_cast<uint32_t>(
6964 Smi::cast(JSArray::cast(this)->length())->value()) :
6965 static_cast<uint32_t>(FixedArray::cast(elements())->length());
6966 return (index < length) &&
6967 !FixedArray::cast(elements())->get(index)->IsTheHole();
6968 }
6969 case PIXEL_ELEMENTS: {
6970 PixelArray* pixels = PixelArray::cast(elements());
6971 return index < static_cast<uint32_t>(pixels->length());
6972 }
Steve Block3ce2e202009-11-05 08:53:23 +00006973 case EXTERNAL_BYTE_ELEMENTS:
6974 case EXTERNAL_UNSIGNED_BYTE_ELEMENTS:
6975 case EXTERNAL_SHORT_ELEMENTS:
6976 case EXTERNAL_UNSIGNED_SHORT_ELEMENTS:
6977 case EXTERNAL_INT_ELEMENTS:
6978 case EXTERNAL_UNSIGNED_INT_ELEMENTS:
6979 case EXTERNAL_FLOAT_ELEMENTS: {
6980 ExternalArray* array = ExternalArray::cast(elements());
6981 return index < static_cast<uint32_t>(array->length());
6982 }
Steve Blocka7e24c12009-10-30 11:49:00 +00006983 case DICTIONARY_ELEMENTS: {
6984 return element_dictionary()->FindEntry(index)
6985 != NumberDictionary::kNotFound;
6986 }
6987 default:
6988 UNREACHABLE();
6989 break;
6990 }
6991 // All possibilities have been handled above already.
6992 UNREACHABLE();
6993 return Heap::null_value();
6994}
6995
6996
6997bool JSObject::HasRealNamedCallbackProperty(String* key) {
6998 // Check access rights if needed.
6999 if (IsAccessCheckNeeded() &&
7000 !Top::MayNamedAccess(this, key, v8::ACCESS_HAS)) {
7001 Top::ReportFailedAccessCheck(this, v8::ACCESS_HAS);
7002 return false;
7003 }
7004
7005 LookupResult result;
7006 LocalLookupRealNamedProperty(key, &result);
Andrei Popescu402d9372010-02-26 13:31:12 +00007007 return result.IsProperty() && (result.type() == CALLBACKS);
Steve Blocka7e24c12009-10-30 11:49:00 +00007008}
7009
7010
7011int JSObject::NumberOfLocalProperties(PropertyAttributes filter) {
7012 if (HasFastProperties()) {
7013 DescriptorArray* descs = map()->instance_descriptors();
7014 int result = 0;
7015 for (int i = 0; i < descs->number_of_descriptors(); i++) {
7016 PropertyDetails details = descs->GetDetails(i);
7017 if (details.IsProperty() && (details.attributes() & filter) == 0) {
7018 result++;
7019 }
7020 }
7021 return result;
7022 } else {
7023 return property_dictionary()->NumberOfElementsFilterAttributes(filter);
7024 }
7025}
7026
7027
7028int JSObject::NumberOfEnumProperties() {
7029 return NumberOfLocalProperties(static_cast<PropertyAttributes>(DONT_ENUM));
7030}
7031
7032
7033void FixedArray::SwapPairs(FixedArray* numbers, int i, int j) {
7034 Object* temp = get(i);
7035 set(i, get(j));
7036 set(j, temp);
7037 if (this != numbers) {
7038 temp = numbers->get(i);
7039 numbers->set(i, numbers->get(j));
7040 numbers->set(j, temp);
7041 }
7042}
7043
7044
7045static void InsertionSortPairs(FixedArray* content,
7046 FixedArray* numbers,
7047 int len) {
7048 for (int i = 1; i < len; i++) {
7049 int j = i;
7050 while (j > 0 &&
7051 (NumberToUint32(numbers->get(j - 1)) >
7052 NumberToUint32(numbers->get(j)))) {
7053 content->SwapPairs(numbers, j - 1, j);
7054 j--;
7055 }
7056 }
7057}
7058
7059
7060void HeapSortPairs(FixedArray* content, FixedArray* numbers, int len) {
7061 // In-place heap sort.
7062 ASSERT(content->length() == numbers->length());
7063
7064 // Bottom-up max-heap construction.
7065 for (int i = 1; i < len; ++i) {
7066 int child_index = i;
7067 while (child_index > 0) {
7068 int parent_index = ((child_index + 1) >> 1) - 1;
7069 uint32_t parent_value = NumberToUint32(numbers->get(parent_index));
7070 uint32_t child_value = NumberToUint32(numbers->get(child_index));
7071 if (parent_value < child_value) {
7072 content->SwapPairs(numbers, parent_index, child_index);
7073 } else {
7074 break;
7075 }
7076 child_index = parent_index;
7077 }
7078 }
7079
7080 // Extract elements and create sorted array.
7081 for (int i = len - 1; i > 0; --i) {
7082 // Put max element at the back of the array.
7083 content->SwapPairs(numbers, 0, i);
7084 // Sift down the new top element.
7085 int parent_index = 0;
7086 while (true) {
7087 int child_index = ((parent_index + 1) << 1) - 1;
7088 if (child_index >= i) break;
7089 uint32_t child1_value = NumberToUint32(numbers->get(child_index));
7090 uint32_t child2_value = NumberToUint32(numbers->get(child_index + 1));
7091 uint32_t parent_value = NumberToUint32(numbers->get(parent_index));
7092 if (child_index + 1 >= i || child1_value > child2_value) {
7093 if (parent_value > child1_value) break;
7094 content->SwapPairs(numbers, parent_index, child_index);
7095 parent_index = child_index;
7096 } else {
7097 if (parent_value > child2_value) break;
7098 content->SwapPairs(numbers, parent_index, child_index + 1);
7099 parent_index = child_index + 1;
7100 }
7101 }
7102 }
7103}
7104
7105
7106// Sort this array and the numbers as pairs wrt. the (distinct) numbers.
7107void FixedArray::SortPairs(FixedArray* numbers, uint32_t len) {
7108 ASSERT(this->length() == numbers->length());
7109 // For small arrays, simply use insertion sort.
7110 if (len <= 10) {
7111 InsertionSortPairs(this, numbers, len);
7112 return;
7113 }
7114 // Check the range of indices.
7115 uint32_t min_index = NumberToUint32(numbers->get(0));
7116 uint32_t max_index = min_index;
7117 uint32_t i;
7118 for (i = 1; i < len; i++) {
7119 if (NumberToUint32(numbers->get(i)) < min_index) {
7120 min_index = NumberToUint32(numbers->get(i));
7121 } else if (NumberToUint32(numbers->get(i)) > max_index) {
7122 max_index = NumberToUint32(numbers->get(i));
7123 }
7124 }
7125 if (max_index - min_index + 1 == len) {
7126 // Indices form a contiguous range, unless there are duplicates.
7127 // Do an in-place linear time sort assuming distinct numbers, but
7128 // avoid hanging in case they are not.
7129 for (i = 0; i < len; i++) {
7130 uint32_t p;
7131 uint32_t j = 0;
7132 // While the current element at i is not at its correct position p,
7133 // swap the elements at these two positions.
7134 while ((p = NumberToUint32(numbers->get(i)) - min_index) != i &&
7135 j++ < len) {
7136 SwapPairs(numbers, i, p);
7137 }
7138 }
7139 } else {
7140 HeapSortPairs(this, numbers, len);
7141 return;
7142 }
7143}
7144
7145
7146// Fill in the names of local properties into the supplied storage. The main
7147// purpose of this function is to provide reflection information for the object
7148// mirrors.
7149void JSObject::GetLocalPropertyNames(FixedArray* storage, int index) {
7150 ASSERT(storage->length() >= (NumberOfLocalProperties(NONE) - index));
7151 if (HasFastProperties()) {
7152 DescriptorArray* descs = map()->instance_descriptors();
7153 for (int i = 0; i < descs->number_of_descriptors(); i++) {
7154 if (descs->IsProperty(i)) storage->set(index++, descs->GetKey(i));
7155 }
7156 ASSERT(storage->length() >= index);
7157 } else {
7158 property_dictionary()->CopyKeysTo(storage);
7159 }
7160}
7161
7162
7163int JSObject::NumberOfLocalElements(PropertyAttributes filter) {
7164 return GetLocalElementKeys(NULL, filter);
7165}
7166
7167
7168int JSObject::NumberOfEnumElements() {
Steve Blockd0582a62009-12-15 09:54:21 +00007169 // Fast case for objects with no elements.
7170 if (!IsJSValue() && HasFastElements()) {
7171 uint32_t length = IsJSArray() ?
7172 static_cast<uint32_t>(
7173 Smi::cast(JSArray::cast(this)->length())->value()) :
7174 static_cast<uint32_t>(FixedArray::cast(elements())->length());
7175 if (length == 0) return 0;
7176 }
7177 // Compute the number of enumerable elements.
Steve Blocka7e24c12009-10-30 11:49:00 +00007178 return NumberOfLocalElements(static_cast<PropertyAttributes>(DONT_ENUM));
7179}
7180
7181
7182int JSObject::GetLocalElementKeys(FixedArray* storage,
7183 PropertyAttributes filter) {
7184 int counter = 0;
7185 switch (GetElementsKind()) {
7186 case FAST_ELEMENTS: {
7187 int length = IsJSArray() ?
7188 Smi::cast(JSArray::cast(this)->length())->value() :
7189 FixedArray::cast(elements())->length();
7190 for (int i = 0; i < length; i++) {
7191 if (!FixedArray::cast(elements())->get(i)->IsTheHole()) {
7192 if (storage != NULL) {
Leon Clarke4515c472010-02-03 11:58:03 +00007193 storage->set(counter, Smi::FromInt(i));
Steve Blocka7e24c12009-10-30 11:49:00 +00007194 }
7195 counter++;
7196 }
7197 }
7198 ASSERT(!storage || storage->length() >= counter);
7199 break;
7200 }
7201 case PIXEL_ELEMENTS: {
7202 int length = PixelArray::cast(elements())->length();
7203 while (counter < length) {
7204 if (storage != NULL) {
Leon Clarke4515c472010-02-03 11:58:03 +00007205 storage->set(counter, Smi::FromInt(counter));
Steve Blocka7e24c12009-10-30 11:49:00 +00007206 }
7207 counter++;
7208 }
7209 ASSERT(!storage || storage->length() >= counter);
7210 break;
7211 }
Steve Block3ce2e202009-11-05 08:53:23 +00007212 case EXTERNAL_BYTE_ELEMENTS:
7213 case EXTERNAL_UNSIGNED_BYTE_ELEMENTS:
7214 case EXTERNAL_SHORT_ELEMENTS:
7215 case EXTERNAL_UNSIGNED_SHORT_ELEMENTS:
7216 case EXTERNAL_INT_ELEMENTS:
7217 case EXTERNAL_UNSIGNED_INT_ELEMENTS:
7218 case EXTERNAL_FLOAT_ELEMENTS: {
7219 int length = ExternalArray::cast(elements())->length();
7220 while (counter < length) {
7221 if (storage != NULL) {
Leon Clarke4515c472010-02-03 11:58:03 +00007222 storage->set(counter, Smi::FromInt(counter));
Steve Block3ce2e202009-11-05 08:53:23 +00007223 }
7224 counter++;
7225 }
7226 ASSERT(!storage || storage->length() >= counter);
7227 break;
7228 }
Steve Blocka7e24c12009-10-30 11:49:00 +00007229 case DICTIONARY_ELEMENTS: {
7230 if (storage != NULL) {
7231 element_dictionary()->CopyKeysTo(storage, filter);
7232 }
7233 counter = element_dictionary()->NumberOfElementsFilterAttributes(filter);
7234 break;
7235 }
7236 default:
7237 UNREACHABLE();
7238 break;
7239 }
7240
7241 if (this->IsJSValue()) {
7242 Object* val = JSValue::cast(this)->value();
7243 if (val->IsString()) {
7244 String* str = String::cast(val);
7245 if (storage) {
7246 for (int i = 0; i < str->length(); i++) {
Leon Clarke4515c472010-02-03 11:58:03 +00007247 storage->set(counter + i, Smi::FromInt(i));
Steve Blocka7e24c12009-10-30 11:49:00 +00007248 }
7249 }
7250 counter += str->length();
7251 }
7252 }
7253 ASSERT(!storage || storage->length() == counter);
7254 return counter;
7255}
7256
7257
7258int JSObject::GetEnumElementKeys(FixedArray* storage) {
7259 return GetLocalElementKeys(storage,
7260 static_cast<PropertyAttributes>(DONT_ENUM));
7261}
7262
7263
7264bool NumberDictionaryShape::IsMatch(uint32_t key, Object* other) {
7265 ASSERT(other->IsNumber());
7266 return key == static_cast<uint32_t>(other->Number());
7267}
7268
7269
7270uint32_t NumberDictionaryShape::Hash(uint32_t key) {
7271 return ComputeIntegerHash(key);
7272}
7273
7274
7275uint32_t NumberDictionaryShape::HashForObject(uint32_t key, Object* other) {
7276 ASSERT(other->IsNumber());
7277 return ComputeIntegerHash(static_cast<uint32_t>(other->Number()));
7278}
7279
7280
7281Object* NumberDictionaryShape::AsObject(uint32_t key) {
7282 return Heap::NumberFromUint32(key);
7283}
7284
7285
7286bool StringDictionaryShape::IsMatch(String* key, Object* other) {
7287 // We know that all entries in a hash table had their hash keys created.
7288 // Use that knowledge to have fast failure.
7289 if (key->Hash() != String::cast(other)->Hash()) return false;
7290 return key->Equals(String::cast(other));
7291}
7292
7293
7294uint32_t StringDictionaryShape::Hash(String* key) {
7295 return key->Hash();
7296}
7297
7298
7299uint32_t StringDictionaryShape::HashForObject(String* key, Object* other) {
7300 return String::cast(other)->Hash();
7301}
7302
7303
7304Object* StringDictionaryShape::AsObject(String* key) {
7305 return key;
7306}
7307
7308
7309// StringKey simply carries a string object as key.
7310class StringKey : public HashTableKey {
7311 public:
7312 explicit StringKey(String* string) :
7313 string_(string),
7314 hash_(HashForObject(string)) { }
7315
7316 bool IsMatch(Object* string) {
7317 // We know that all entries in a hash table had their hash keys created.
7318 // Use that knowledge to have fast failure.
7319 if (hash_ != HashForObject(string)) {
7320 return false;
7321 }
7322 return string_->Equals(String::cast(string));
7323 }
7324
7325 uint32_t Hash() { return hash_; }
7326
7327 uint32_t HashForObject(Object* other) { return String::cast(other)->Hash(); }
7328
7329 Object* AsObject() { return string_; }
7330
7331 String* string_;
7332 uint32_t hash_;
7333};
7334
7335
7336// StringSharedKeys are used as keys in the eval cache.
7337class StringSharedKey : public HashTableKey {
7338 public:
7339 StringSharedKey(String* source, SharedFunctionInfo* shared)
7340 : source_(source), shared_(shared) { }
7341
7342 bool IsMatch(Object* other) {
7343 if (!other->IsFixedArray()) return false;
7344 FixedArray* pair = FixedArray::cast(other);
7345 SharedFunctionInfo* shared = SharedFunctionInfo::cast(pair->get(0));
7346 if (shared != shared_) return false;
7347 String* source = String::cast(pair->get(1));
7348 return source->Equals(source_);
7349 }
7350
7351 static uint32_t StringSharedHashHelper(String* source,
7352 SharedFunctionInfo* shared) {
7353 uint32_t hash = source->Hash();
7354 if (shared->HasSourceCode()) {
7355 // Instead of using the SharedFunctionInfo pointer in the hash
7356 // code computation, we use a combination of the hash of the
7357 // script source code and the start and end positions. We do
7358 // this to ensure that the cache entries can survive garbage
7359 // collection.
7360 Script* script = Script::cast(shared->script());
7361 hash ^= String::cast(script->source())->Hash();
7362 hash += shared->start_position();
7363 }
7364 return hash;
7365 }
7366
7367 uint32_t Hash() {
7368 return StringSharedHashHelper(source_, shared_);
7369 }
7370
7371 uint32_t HashForObject(Object* obj) {
7372 FixedArray* pair = FixedArray::cast(obj);
7373 SharedFunctionInfo* shared = SharedFunctionInfo::cast(pair->get(0));
7374 String* source = String::cast(pair->get(1));
7375 return StringSharedHashHelper(source, shared);
7376 }
7377
7378 Object* AsObject() {
7379 Object* obj = Heap::AllocateFixedArray(2);
7380 if (obj->IsFailure()) return obj;
7381 FixedArray* pair = FixedArray::cast(obj);
7382 pair->set(0, shared_);
7383 pair->set(1, source_);
7384 return pair;
7385 }
7386
7387 private:
7388 String* source_;
7389 SharedFunctionInfo* shared_;
7390};
7391
7392
7393// RegExpKey carries the source and flags of a regular expression as key.
7394class RegExpKey : public HashTableKey {
7395 public:
7396 RegExpKey(String* string, JSRegExp::Flags flags)
7397 : string_(string),
7398 flags_(Smi::FromInt(flags.value())) { }
7399
Steve Block3ce2e202009-11-05 08:53:23 +00007400 // Rather than storing the key in the hash table, a pointer to the
7401 // stored value is stored where the key should be. IsMatch then
7402 // compares the search key to the found object, rather than comparing
7403 // a key to a key.
Steve Blocka7e24c12009-10-30 11:49:00 +00007404 bool IsMatch(Object* obj) {
7405 FixedArray* val = FixedArray::cast(obj);
7406 return string_->Equals(String::cast(val->get(JSRegExp::kSourceIndex)))
7407 && (flags_ == val->get(JSRegExp::kFlagsIndex));
7408 }
7409
7410 uint32_t Hash() { return RegExpHash(string_, flags_); }
7411
7412 Object* AsObject() {
7413 // Plain hash maps, which is where regexp keys are used, don't
7414 // use this function.
7415 UNREACHABLE();
7416 return NULL;
7417 }
7418
7419 uint32_t HashForObject(Object* obj) {
7420 FixedArray* val = FixedArray::cast(obj);
7421 return RegExpHash(String::cast(val->get(JSRegExp::kSourceIndex)),
7422 Smi::cast(val->get(JSRegExp::kFlagsIndex)));
7423 }
7424
7425 static uint32_t RegExpHash(String* string, Smi* flags) {
7426 return string->Hash() + flags->value();
7427 }
7428
7429 String* string_;
7430 Smi* flags_;
7431};
7432
7433// Utf8SymbolKey carries a vector of chars as key.
7434class Utf8SymbolKey : public HashTableKey {
7435 public:
7436 explicit Utf8SymbolKey(Vector<const char> string)
Steve Blockd0582a62009-12-15 09:54:21 +00007437 : string_(string), hash_field_(0) { }
Steve Blocka7e24c12009-10-30 11:49:00 +00007438
7439 bool IsMatch(Object* string) {
7440 return String::cast(string)->IsEqualTo(string_);
7441 }
7442
7443 uint32_t Hash() {
Steve Blockd0582a62009-12-15 09:54:21 +00007444 if (hash_field_ != 0) return hash_field_ >> String::kHashShift;
Steve Blocka7e24c12009-10-30 11:49:00 +00007445 unibrow::Utf8InputBuffer<> buffer(string_.start(),
7446 static_cast<unsigned>(string_.length()));
7447 chars_ = buffer.Length();
Steve Blockd0582a62009-12-15 09:54:21 +00007448 hash_field_ = String::ComputeHashField(&buffer, chars_);
7449 uint32_t result = hash_field_ >> String::kHashShift;
Steve Blocka7e24c12009-10-30 11:49:00 +00007450 ASSERT(result != 0); // Ensure that the hash value of 0 is never computed.
7451 return result;
7452 }
7453
7454 uint32_t HashForObject(Object* other) {
7455 return String::cast(other)->Hash();
7456 }
7457
7458 Object* AsObject() {
Steve Blockd0582a62009-12-15 09:54:21 +00007459 if (hash_field_ == 0) Hash();
7460 return Heap::AllocateSymbol(string_, chars_, hash_field_);
Steve Blocka7e24c12009-10-30 11:49:00 +00007461 }
7462
7463 Vector<const char> string_;
Steve Blockd0582a62009-12-15 09:54:21 +00007464 uint32_t hash_field_;
Steve Blocka7e24c12009-10-30 11:49:00 +00007465 int chars_; // Caches the number of characters when computing the hash code.
7466};
7467
7468
7469// SymbolKey carries a string/symbol object as key.
7470class SymbolKey : public HashTableKey {
7471 public:
7472 explicit SymbolKey(String* string) : string_(string) { }
7473
7474 bool IsMatch(Object* string) {
7475 return String::cast(string)->Equals(string_);
7476 }
7477
7478 uint32_t Hash() { return string_->Hash(); }
7479
7480 uint32_t HashForObject(Object* other) {
7481 return String::cast(other)->Hash();
7482 }
7483
7484 Object* AsObject() {
Leon Clarkef7060e22010-06-03 12:02:55 +01007485 // Attempt to flatten the string, so that symbols will most often
7486 // be flat strings.
7487 string_ = string_->TryFlattenGetString();
Steve Blocka7e24c12009-10-30 11:49:00 +00007488 // Transform string to symbol if possible.
7489 Map* map = Heap::SymbolMapForString(string_);
7490 if (map != NULL) {
7491 string_->set_map(map);
7492 ASSERT(string_->IsSymbol());
7493 return string_;
7494 }
7495 // Otherwise allocate a new symbol.
7496 StringInputBuffer buffer(string_);
7497 return Heap::AllocateInternalSymbol(&buffer,
7498 string_->length(),
Steve Blockd0582a62009-12-15 09:54:21 +00007499 string_->hash_field());
Steve Blocka7e24c12009-10-30 11:49:00 +00007500 }
7501
7502 static uint32_t StringHash(Object* obj) {
7503 return String::cast(obj)->Hash();
7504 }
7505
7506 String* string_;
7507};
7508
7509
7510template<typename Shape, typename Key>
7511void HashTable<Shape, Key>::IteratePrefix(ObjectVisitor* v) {
7512 IteratePointers(v, 0, kElementsStartOffset);
7513}
7514
7515
7516template<typename Shape, typename Key>
7517void HashTable<Shape, Key>::IterateElements(ObjectVisitor* v) {
7518 IteratePointers(v,
7519 kElementsStartOffset,
7520 kHeaderSize + length() * kPointerSize);
7521}
7522
7523
7524template<typename Shape, typename Key>
Steve Block6ded16b2010-05-10 14:33:55 +01007525Object* HashTable<Shape, Key>::Allocate(int at_least_space_for,
7526 PretenureFlag pretenure) {
7527 const int kMinCapacity = 32;
7528 int capacity = RoundUpToPowerOf2(at_least_space_for * 2);
7529 if (capacity < kMinCapacity) {
7530 capacity = kMinCapacity; // Guarantee min capacity.
Leon Clarkee46be812010-01-19 14:06:41 +00007531 } else if (capacity > HashTable::kMaxCapacity) {
7532 return Failure::OutOfMemoryException();
7533 }
7534
Steve Block6ded16b2010-05-10 14:33:55 +01007535 Object* obj = Heap::AllocateHashTable(EntryToIndex(capacity), pretenure);
Steve Blocka7e24c12009-10-30 11:49:00 +00007536 if (!obj->IsFailure()) {
7537 HashTable::cast(obj)->SetNumberOfElements(0);
Leon Clarkee46be812010-01-19 14:06:41 +00007538 HashTable::cast(obj)->SetNumberOfDeletedElements(0);
Steve Blocka7e24c12009-10-30 11:49:00 +00007539 HashTable::cast(obj)->SetCapacity(capacity);
7540 }
7541 return obj;
7542}
7543
7544
Leon Clarkee46be812010-01-19 14:06:41 +00007545// Find entry for key otherwise return kNotFound.
Steve Blocka7e24c12009-10-30 11:49:00 +00007546template<typename Shape, typename Key>
7547int HashTable<Shape, Key>::FindEntry(Key key) {
Steve Blocka7e24c12009-10-30 11:49:00 +00007548 uint32_t capacity = Capacity();
Leon Clarkee46be812010-01-19 14:06:41 +00007549 uint32_t entry = FirstProbe(Shape::Hash(key), capacity);
7550 uint32_t count = 1;
7551 // EnsureCapacity will guarantee the hash table is never full.
7552 while (true) {
7553 Object* element = KeyAt(entry);
7554 if (element->IsUndefined()) break; // Empty entry.
7555 if (!element->IsNull() && Shape::IsMatch(key, element)) return entry;
7556 entry = NextProbe(entry, count++, capacity);
Steve Blocka7e24c12009-10-30 11:49:00 +00007557 }
7558 return kNotFound;
7559}
7560
7561
Ben Murdoch3bec4d22010-07-22 14:51:16 +01007562// Find entry for key otherwise return kNotFound.
7563int StringDictionary::FindEntry(String* key) {
7564 if (!key->IsSymbol()) {
7565 return HashTable<StringDictionaryShape, String*>::FindEntry(key);
7566 }
7567
7568 // Optimized for symbol key. Knowledge of the key type allows:
7569 // 1. Move the check if the key is a symbol out of the loop.
7570 // 2. Avoid comparing hash codes in symbol to symbol comparision.
7571 // 3. Detect a case when a dictionary key is not a symbol but the key is.
7572 // In case of positive result the dictionary key may be replaced by
7573 // the symbol with minimal performance penalty. It gives a chance to
7574 // perform further lookups in code stubs (and significant performance boost
7575 // a certain style of code).
7576
7577 // EnsureCapacity will guarantee the hash table is never full.
7578 uint32_t capacity = Capacity();
7579 uint32_t entry = FirstProbe(key->Hash(), capacity);
7580 uint32_t count = 1;
7581
7582 while (true) {
7583 int index = EntryToIndex(entry);
7584 Object* element = get(index);
7585 if (element->IsUndefined()) break; // Empty entry.
7586 if (key == element) return entry;
7587 if (!element->IsSymbol() &&
7588 !element->IsNull() &&
7589 String::cast(element)->Equals(key)) {
7590 // Replace a non-symbol key by the equivalent symbol for faster further
7591 // lookups.
7592 set(index, key);
7593 return entry;
7594 }
7595 ASSERT(element->IsNull() || !String::cast(element)->Equals(key));
7596 entry = NextProbe(entry, count++, capacity);
7597 }
7598 return kNotFound;
7599}
7600
7601
Steve Blocka7e24c12009-10-30 11:49:00 +00007602template<typename Shape, typename Key>
7603Object* HashTable<Shape, Key>::EnsureCapacity(int n, Key key) {
7604 int capacity = Capacity();
7605 int nof = NumberOfElements() + n;
Leon Clarkee46be812010-01-19 14:06:41 +00007606 int nod = NumberOfDeletedElements();
7607 // Return if:
7608 // 50% is still free after adding n elements and
7609 // at most 50% of the free elements are deleted elements.
Steve Block6ded16b2010-05-10 14:33:55 +01007610 if (nod <= (capacity - nof) >> 1) {
7611 int needed_free = nof >> 1;
7612 if (nof + needed_free <= capacity) return this;
7613 }
Steve Blocka7e24c12009-10-30 11:49:00 +00007614
Steve Block6ded16b2010-05-10 14:33:55 +01007615 const int kMinCapacityForPretenure = 256;
7616 bool pretenure =
7617 (capacity > kMinCapacityForPretenure) && !Heap::InNewSpace(this);
7618 Object* obj = Allocate(nof * 2, pretenure ? TENURED : NOT_TENURED);
Steve Blocka7e24c12009-10-30 11:49:00 +00007619 if (obj->IsFailure()) return obj;
Leon Clarke4515c472010-02-03 11:58:03 +00007620
7621 AssertNoAllocation no_gc;
Steve Blocka7e24c12009-10-30 11:49:00 +00007622 HashTable* table = HashTable::cast(obj);
Leon Clarke4515c472010-02-03 11:58:03 +00007623 WriteBarrierMode mode = table->GetWriteBarrierMode(no_gc);
Steve Blocka7e24c12009-10-30 11:49:00 +00007624
7625 // Copy prefix to new array.
7626 for (int i = kPrefixStartIndex;
7627 i < kPrefixStartIndex + Shape::kPrefixSize;
7628 i++) {
7629 table->set(i, get(i), mode);
7630 }
7631 // Rehash the elements.
7632 for (int i = 0; i < capacity; i++) {
7633 uint32_t from_index = EntryToIndex(i);
7634 Object* k = get(from_index);
7635 if (IsKey(k)) {
7636 uint32_t hash = Shape::HashForObject(key, k);
7637 uint32_t insertion_index =
7638 EntryToIndex(table->FindInsertionEntry(hash));
7639 for (int j = 0; j < Shape::kEntrySize; j++) {
7640 table->set(insertion_index + j, get(from_index + j), mode);
7641 }
7642 }
7643 }
7644 table->SetNumberOfElements(NumberOfElements());
Leon Clarkee46be812010-01-19 14:06:41 +00007645 table->SetNumberOfDeletedElements(0);
Steve Blocka7e24c12009-10-30 11:49:00 +00007646 return table;
7647}
7648
7649
7650template<typename Shape, typename Key>
7651uint32_t HashTable<Shape, Key>::FindInsertionEntry(uint32_t hash) {
7652 uint32_t capacity = Capacity();
Leon Clarkee46be812010-01-19 14:06:41 +00007653 uint32_t entry = FirstProbe(hash, capacity);
7654 uint32_t count = 1;
7655 // EnsureCapacity will guarantee the hash table is never full.
7656 while (true) {
7657 Object* element = KeyAt(entry);
7658 if (element->IsUndefined() || element->IsNull()) break;
7659 entry = NextProbe(entry, count++, capacity);
Steve Blocka7e24c12009-10-30 11:49:00 +00007660 }
Steve Blocka7e24c12009-10-30 11:49:00 +00007661 return entry;
7662}
7663
7664// Force instantiation of template instances class.
7665// Please note this list is compiler dependent.
7666
7667template class HashTable<SymbolTableShape, HashTableKey*>;
7668
7669template class HashTable<CompilationCacheShape, HashTableKey*>;
7670
7671template class HashTable<MapCacheShape, HashTableKey*>;
7672
7673template class Dictionary<StringDictionaryShape, String*>;
7674
7675template class Dictionary<NumberDictionaryShape, uint32_t>;
7676
7677template Object* Dictionary<NumberDictionaryShape, uint32_t>::Allocate(
7678 int);
7679
7680template Object* Dictionary<StringDictionaryShape, String*>::Allocate(
7681 int);
7682
7683template Object* Dictionary<NumberDictionaryShape, uint32_t>::AtPut(
7684 uint32_t, Object*);
7685
7686template Object* Dictionary<NumberDictionaryShape, uint32_t>::SlowReverseLookup(
7687 Object*);
7688
7689template Object* Dictionary<StringDictionaryShape, String*>::SlowReverseLookup(
7690 Object*);
7691
7692template void Dictionary<NumberDictionaryShape, uint32_t>::CopyKeysTo(
7693 FixedArray*, PropertyAttributes);
7694
7695template Object* Dictionary<StringDictionaryShape, String*>::DeleteProperty(
7696 int, JSObject::DeleteMode);
7697
7698template Object* Dictionary<NumberDictionaryShape, uint32_t>::DeleteProperty(
7699 int, JSObject::DeleteMode);
7700
7701template void Dictionary<StringDictionaryShape, String*>::CopyKeysTo(
7702 FixedArray*);
7703
7704template int
7705Dictionary<StringDictionaryShape, String*>::NumberOfElementsFilterAttributes(
7706 PropertyAttributes);
7707
7708template Object* Dictionary<StringDictionaryShape, String*>::Add(
7709 String*, Object*, PropertyDetails);
7710
7711template Object*
7712Dictionary<StringDictionaryShape, String*>::GenerateNewEnumerationIndices();
7713
7714template int
7715Dictionary<NumberDictionaryShape, uint32_t>::NumberOfElementsFilterAttributes(
7716 PropertyAttributes);
7717
7718template Object* Dictionary<NumberDictionaryShape, uint32_t>::Add(
7719 uint32_t, Object*, PropertyDetails);
7720
7721template Object* Dictionary<NumberDictionaryShape, uint32_t>::EnsureCapacity(
7722 int, uint32_t);
7723
7724template Object* Dictionary<StringDictionaryShape, String*>::EnsureCapacity(
7725 int, String*);
7726
7727template Object* Dictionary<NumberDictionaryShape, uint32_t>::AddEntry(
7728 uint32_t, Object*, PropertyDetails, uint32_t);
7729
7730template Object* Dictionary<StringDictionaryShape, String*>::AddEntry(
7731 String*, Object*, PropertyDetails, uint32_t);
7732
7733template
7734int Dictionary<NumberDictionaryShape, uint32_t>::NumberOfEnumElements();
7735
7736template
7737int Dictionary<StringDictionaryShape, String*>::NumberOfEnumElements();
7738
Leon Clarkee46be812010-01-19 14:06:41 +00007739template
7740int HashTable<NumberDictionaryShape, uint32_t>::FindEntry(uint32_t);
7741
7742
Steve Blocka7e24c12009-10-30 11:49:00 +00007743// Collates undefined and unexisting elements below limit from position
7744// zero of the elements. The object stays in Dictionary mode.
7745Object* JSObject::PrepareSlowElementsForSort(uint32_t limit) {
7746 ASSERT(HasDictionaryElements());
7747 // Must stay in dictionary mode, either because of requires_slow_elements,
7748 // or because we are not going to sort (and therefore compact) all of the
7749 // elements.
7750 NumberDictionary* dict = element_dictionary();
7751 HeapNumber* result_double = NULL;
7752 if (limit > static_cast<uint32_t>(Smi::kMaxValue)) {
7753 // Allocate space for result before we start mutating the object.
7754 Object* new_double = Heap::AllocateHeapNumber(0.0);
7755 if (new_double->IsFailure()) return new_double;
7756 result_double = HeapNumber::cast(new_double);
7757 }
7758
Steve Block6ded16b2010-05-10 14:33:55 +01007759 Object* obj = NumberDictionary::Allocate(dict->NumberOfElements());
Steve Blocka7e24c12009-10-30 11:49:00 +00007760 if (obj->IsFailure()) return obj;
7761 NumberDictionary* new_dict = NumberDictionary::cast(obj);
7762
7763 AssertNoAllocation no_alloc;
7764
7765 uint32_t pos = 0;
7766 uint32_t undefs = 0;
Steve Block6ded16b2010-05-10 14:33:55 +01007767 int capacity = dict->Capacity();
Steve Blocka7e24c12009-10-30 11:49:00 +00007768 for (int i = 0; i < capacity; i++) {
7769 Object* k = dict->KeyAt(i);
7770 if (dict->IsKey(k)) {
7771 ASSERT(k->IsNumber());
7772 ASSERT(!k->IsSmi() || Smi::cast(k)->value() >= 0);
7773 ASSERT(!k->IsHeapNumber() || HeapNumber::cast(k)->value() >= 0);
7774 ASSERT(!k->IsHeapNumber() || HeapNumber::cast(k)->value() <= kMaxUInt32);
7775 Object* value = dict->ValueAt(i);
7776 PropertyDetails details = dict->DetailsAt(i);
7777 if (details.type() == CALLBACKS) {
7778 // Bail out and do the sorting of undefineds and array holes in JS.
7779 return Smi::FromInt(-1);
7780 }
7781 uint32_t key = NumberToUint32(k);
7782 if (key < limit) {
7783 if (value->IsUndefined()) {
7784 undefs++;
7785 } else {
7786 new_dict->AddNumberEntry(pos, value, details);
7787 pos++;
7788 }
7789 } else {
7790 new_dict->AddNumberEntry(key, value, details);
7791 }
7792 }
7793 }
7794
7795 uint32_t result = pos;
7796 PropertyDetails no_details = PropertyDetails(NONE, NORMAL);
7797 while (undefs > 0) {
7798 new_dict->AddNumberEntry(pos, Heap::undefined_value(), no_details);
7799 pos++;
7800 undefs--;
7801 }
7802
7803 set_elements(new_dict);
7804
7805 if (result <= static_cast<uint32_t>(Smi::kMaxValue)) {
7806 return Smi::FromInt(static_cast<int>(result));
7807 }
7808
7809 ASSERT_NE(NULL, result_double);
7810 result_double->set_value(static_cast<double>(result));
7811 return result_double;
7812}
7813
7814
7815// Collects all defined (non-hole) and non-undefined (array) elements at
7816// the start of the elements array.
7817// If the object is in dictionary mode, it is converted to fast elements
7818// mode.
7819Object* JSObject::PrepareElementsForSort(uint32_t limit) {
Steve Block3ce2e202009-11-05 08:53:23 +00007820 ASSERT(!HasPixelElements() && !HasExternalArrayElements());
Steve Blocka7e24c12009-10-30 11:49:00 +00007821
7822 if (HasDictionaryElements()) {
7823 // Convert to fast elements containing only the existing properties.
7824 // Ordering is irrelevant, since we are going to sort anyway.
7825 NumberDictionary* dict = element_dictionary();
7826 if (IsJSArray() || dict->requires_slow_elements() ||
7827 dict->max_number_key() >= limit) {
7828 return PrepareSlowElementsForSort(limit);
7829 }
7830 // Convert to fast elements.
7831
Steve Block8defd9f2010-07-08 12:39:36 +01007832 Object* obj = map()->GetFastElementsMap();
7833 if (obj->IsFailure()) return obj;
7834 Map* new_map = Map::cast(obj);
7835
Steve Blocka7e24c12009-10-30 11:49:00 +00007836 PretenureFlag tenure = Heap::InNewSpace(this) ? NOT_TENURED: TENURED;
7837 Object* new_array =
7838 Heap::AllocateFixedArray(dict->NumberOfElements(), tenure);
Steve Block8defd9f2010-07-08 12:39:36 +01007839 if (new_array->IsFailure()) return new_array;
Steve Blocka7e24c12009-10-30 11:49:00 +00007840 FixedArray* fast_elements = FixedArray::cast(new_array);
7841 dict->CopyValuesTo(fast_elements);
Steve Block8defd9f2010-07-08 12:39:36 +01007842
7843 set_map(new_map);
Steve Blocka7e24c12009-10-30 11:49:00 +00007844 set_elements(fast_elements);
Iain Merrick75681382010-08-19 15:07:18 +01007845 } else {
7846 Object* obj = EnsureWritableFastElements();
7847 if (obj->IsFailure()) return obj;
Steve Blocka7e24c12009-10-30 11:49:00 +00007848 }
7849 ASSERT(HasFastElements());
7850
7851 // Collect holes at the end, undefined before that and the rest at the
7852 // start, and return the number of non-hole, non-undefined values.
7853
7854 FixedArray* elements = FixedArray::cast(this->elements());
7855 uint32_t elements_length = static_cast<uint32_t>(elements->length());
7856 if (limit > elements_length) {
7857 limit = elements_length ;
7858 }
7859 if (limit == 0) {
7860 return Smi::FromInt(0);
7861 }
7862
7863 HeapNumber* result_double = NULL;
7864 if (limit > static_cast<uint32_t>(Smi::kMaxValue)) {
7865 // Pessimistically allocate space for return value before
7866 // we start mutating the array.
7867 Object* new_double = Heap::AllocateHeapNumber(0.0);
7868 if (new_double->IsFailure()) return new_double;
7869 result_double = HeapNumber::cast(new_double);
7870 }
7871
7872 AssertNoAllocation no_alloc;
7873
7874 // Split elements into defined, undefined and the_hole, in that order.
7875 // Only count locations for undefined and the hole, and fill them afterwards.
Leon Clarke4515c472010-02-03 11:58:03 +00007876 WriteBarrierMode write_barrier = elements->GetWriteBarrierMode(no_alloc);
Steve Blocka7e24c12009-10-30 11:49:00 +00007877 unsigned int undefs = limit;
7878 unsigned int holes = limit;
7879 // Assume most arrays contain no holes and undefined values, so minimize the
7880 // number of stores of non-undefined, non-the-hole values.
7881 for (unsigned int i = 0; i < undefs; i++) {
7882 Object* current = elements->get(i);
7883 if (current->IsTheHole()) {
7884 holes--;
7885 undefs--;
7886 } else if (current->IsUndefined()) {
7887 undefs--;
7888 } else {
7889 continue;
7890 }
7891 // Position i needs to be filled.
7892 while (undefs > i) {
7893 current = elements->get(undefs);
7894 if (current->IsTheHole()) {
7895 holes--;
7896 undefs--;
7897 } else if (current->IsUndefined()) {
7898 undefs--;
7899 } else {
7900 elements->set(i, current, write_barrier);
7901 break;
7902 }
7903 }
7904 }
7905 uint32_t result = undefs;
7906 while (undefs < holes) {
7907 elements->set_undefined(undefs);
7908 undefs++;
7909 }
7910 while (holes < limit) {
7911 elements->set_the_hole(holes);
7912 holes++;
7913 }
7914
7915 if (result <= static_cast<uint32_t>(Smi::kMaxValue)) {
7916 return Smi::FromInt(static_cast<int>(result));
7917 }
7918 ASSERT_NE(NULL, result_double);
7919 result_double->set_value(static_cast<double>(result));
7920 return result_double;
7921}
7922
7923
7924Object* PixelArray::SetValue(uint32_t index, Object* value) {
7925 uint8_t clamped_value = 0;
7926 if (index < static_cast<uint32_t>(length())) {
7927 if (value->IsSmi()) {
7928 int int_value = Smi::cast(value)->value();
7929 if (int_value < 0) {
7930 clamped_value = 0;
7931 } else if (int_value > 255) {
7932 clamped_value = 255;
7933 } else {
7934 clamped_value = static_cast<uint8_t>(int_value);
7935 }
7936 } else if (value->IsHeapNumber()) {
7937 double double_value = HeapNumber::cast(value)->value();
7938 if (!(double_value > 0)) {
7939 // NaN and less than zero clamp to zero.
7940 clamped_value = 0;
7941 } else if (double_value > 255) {
7942 // Greater than 255 clamp to 255.
7943 clamped_value = 255;
7944 } else {
7945 // Other doubles are rounded to the nearest integer.
7946 clamped_value = static_cast<uint8_t>(double_value + 0.5);
7947 }
7948 } else {
7949 // Clamp undefined to zero (default). All other types have been
7950 // converted to a number type further up in the call chain.
7951 ASSERT(value->IsUndefined());
7952 }
7953 set(index, clamped_value);
7954 }
7955 return Smi::FromInt(clamped_value);
7956}
7957
7958
Steve Block3ce2e202009-11-05 08:53:23 +00007959template<typename ExternalArrayClass, typename ValueType>
7960static Object* ExternalArrayIntSetter(ExternalArrayClass* receiver,
7961 uint32_t index,
7962 Object* value) {
7963 ValueType cast_value = 0;
7964 if (index < static_cast<uint32_t>(receiver->length())) {
7965 if (value->IsSmi()) {
7966 int int_value = Smi::cast(value)->value();
7967 cast_value = static_cast<ValueType>(int_value);
7968 } else if (value->IsHeapNumber()) {
7969 double double_value = HeapNumber::cast(value)->value();
7970 cast_value = static_cast<ValueType>(DoubleToInt32(double_value));
7971 } else {
7972 // Clamp undefined to zero (default). All other types have been
7973 // converted to a number type further up in the call chain.
7974 ASSERT(value->IsUndefined());
7975 }
7976 receiver->set(index, cast_value);
7977 }
7978 return Heap::NumberFromInt32(cast_value);
7979}
7980
7981
7982Object* ExternalByteArray::SetValue(uint32_t index, Object* value) {
7983 return ExternalArrayIntSetter<ExternalByteArray, int8_t>
7984 (this, index, value);
7985}
7986
7987
7988Object* ExternalUnsignedByteArray::SetValue(uint32_t index, Object* value) {
7989 return ExternalArrayIntSetter<ExternalUnsignedByteArray, uint8_t>
7990 (this, index, value);
7991}
7992
7993
7994Object* ExternalShortArray::SetValue(uint32_t index, Object* value) {
7995 return ExternalArrayIntSetter<ExternalShortArray, int16_t>
7996 (this, index, value);
7997}
7998
7999
8000Object* ExternalUnsignedShortArray::SetValue(uint32_t index, Object* value) {
8001 return ExternalArrayIntSetter<ExternalUnsignedShortArray, uint16_t>
8002 (this, index, value);
8003}
8004
8005
8006Object* ExternalIntArray::SetValue(uint32_t index, Object* value) {
8007 return ExternalArrayIntSetter<ExternalIntArray, int32_t>
8008 (this, index, value);
8009}
8010
8011
8012Object* ExternalUnsignedIntArray::SetValue(uint32_t index, Object* value) {
8013 uint32_t cast_value = 0;
8014 if (index < static_cast<uint32_t>(length())) {
8015 if (value->IsSmi()) {
8016 int int_value = Smi::cast(value)->value();
8017 cast_value = static_cast<uint32_t>(int_value);
8018 } else if (value->IsHeapNumber()) {
8019 double double_value = HeapNumber::cast(value)->value();
8020 cast_value = static_cast<uint32_t>(DoubleToUint32(double_value));
8021 } else {
8022 // Clamp undefined to zero (default). All other types have been
8023 // converted to a number type further up in the call chain.
8024 ASSERT(value->IsUndefined());
8025 }
8026 set(index, cast_value);
8027 }
8028 return Heap::NumberFromUint32(cast_value);
8029}
8030
8031
8032Object* ExternalFloatArray::SetValue(uint32_t index, Object* value) {
8033 float cast_value = 0;
8034 if (index < static_cast<uint32_t>(length())) {
8035 if (value->IsSmi()) {
8036 int int_value = Smi::cast(value)->value();
8037 cast_value = static_cast<float>(int_value);
8038 } else if (value->IsHeapNumber()) {
8039 double double_value = HeapNumber::cast(value)->value();
8040 cast_value = static_cast<float>(double_value);
8041 } else {
8042 // Clamp undefined to zero (default). All other types have been
8043 // converted to a number type further up in the call chain.
8044 ASSERT(value->IsUndefined());
8045 }
8046 set(index, cast_value);
8047 }
8048 return Heap::AllocateHeapNumber(cast_value);
8049}
8050
8051
Steve Blocka7e24c12009-10-30 11:49:00 +00008052Object* GlobalObject::GetPropertyCell(LookupResult* result) {
8053 ASSERT(!HasFastProperties());
8054 Object* value = property_dictionary()->ValueAt(result->GetDictionaryEntry());
8055 ASSERT(value->IsJSGlobalPropertyCell());
8056 return value;
8057}
8058
8059
8060Object* GlobalObject::EnsurePropertyCell(String* name) {
8061 ASSERT(!HasFastProperties());
8062 int entry = property_dictionary()->FindEntry(name);
8063 if (entry == StringDictionary::kNotFound) {
8064 Object* cell = Heap::AllocateJSGlobalPropertyCell(Heap::the_hole_value());
8065 if (cell->IsFailure()) return cell;
8066 PropertyDetails details(NONE, NORMAL);
8067 details = details.AsDeleted();
8068 Object* dictionary = property_dictionary()->Add(name, cell, details);
8069 if (dictionary->IsFailure()) return dictionary;
8070 set_properties(StringDictionary::cast(dictionary));
8071 return cell;
8072 } else {
8073 Object* value = property_dictionary()->ValueAt(entry);
8074 ASSERT(value->IsJSGlobalPropertyCell());
8075 return value;
8076 }
8077}
8078
8079
8080Object* SymbolTable::LookupString(String* string, Object** s) {
8081 SymbolKey key(string);
8082 return LookupKey(&key, s);
8083}
8084
8085
Steve Blockd0582a62009-12-15 09:54:21 +00008086// This class is used for looking up two character strings in the symbol table.
8087// If we don't have a hit we don't want to waste much time so we unroll the
8088// string hash calculation loop here for speed. Doesn't work if the two
8089// characters form a decimal integer, since such strings have a different hash
8090// algorithm.
8091class TwoCharHashTableKey : public HashTableKey {
8092 public:
8093 TwoCharHashTableKey(uint32_t c1, uint32_t c2)
8094 : c1_(c1), c2_(c2) {
8095 // Char 1.
8096 uint32_t hash = c1 + (c1 << 10);
8097 hash ^= hash >> 6;
8098 // Char 2.
8099 hash += c2;
8100 hash += hash << 10;
8101 hash ^= hash >> 6;
8102 // GetHash.
8103 hash += hash << 3;
8104 hash ^= hash >> 11;
8105 hash += hash << 15;
8106 if (hash == 0) hash = 27;
8107#ifdef DEBUG
8108 StringHasher hasher(2);
8109 hasher.AddCharacter(c1);
8110 hasher.AddCharacter(c2);
8111 // If this assert fails then we failed to reproduce the two-character
8112 // version of the string hashing algorithm above. One reason could be
8113 // that we were passed two digits as characters, since the hash
8114 // algorithm is different in that case.
8115 ASSERT_EQ(static_cast<int>(hasher.GetHash()), static_cast<int>(hash));
8116#endif
8117 hash_ = hash;
8118 }
8119
8120 bool IsMatch(Object* o) {
8121 if (!o->IsString()) return false;
8122 String* other = String::cast(o);
8123 if (other->length() != 2) return false;
8124 if (other->Get(0) != c1_) return false;
8125 return other->Get(1) == c2_;
8126 }
8127
8128 uint32_t Hash() { return hash_; }
8129 uint32_t HashForObject(Object* key) {
8130 if (!key->IsString()) return 0;
8131 return String::cast(key)->Hash();
8132 }
8133
8134 Object* AsObject() {
8135 // The TwoCharHashTableKey is only used for looking in the symbol
8136 // table, not for adding to it.
8137 UNREACHABLE();
8138 return NULL;
8139 }
8140 private:
8141 uint32_t c1_;
8142 uint32_t c2_;
8143 uint32_t hash_;
8144};
8145
8146
Steve Blocka7e24c12009-10-30 11:49:00 +00008147bool SymbolTable::LookupSymbolIfExists(String* string, String** symbol) {
8148 SymbolKey key(string);
8149 int entry = FindEntry(&key);
8150 if (entry == kNotFound) {
8151 return false;
8152 } else {
8153 String* result = String::cast(KeyAt(entry));
8154 ASSERT(StringShape(result).IsSymbol());
8155 *symbol = result;
8156 return true;
8157 }
8158}
8159
8160
Steve Blockd0582a62009-12-15 09:54:21 +00008161bool SymbolTable::LookupTwoCharsSymbolIfExists(uint32_t c1,
8162 uint32_t c2,
8163 String** symbol) {
8164 TwoCharHashTableKey key(c1, c2);
8165 int entry = FindEntry(&key);
8166 if (entry == kNotFound) {
8167 return false;
8168 } else {
8169 String* result = String::cast(KeyAt(entry));
8170 ASSERT(StringShape(result).IsSymbol());
8171 *symbol = result;
8172 return true;
8173 }
8174}
8175
8176
Steve Blocka7e24c12009-10-30 11:49:00 +00008177Object* SymbolTable::LookupSymbol(Vector<const char> str, Object** s) {
8178 Utf8SymbolKey key(str);
8179 return LookupKey(&key, s);
8180}
8181
8182
8183Object* SymbolTable::LookupKey(HashTableKey* key, Object** s) {
8184 int entry = FindEntry(key);
8185
8186 // Symbol already in table.
8187 if (entry != kNotFound) {
8188 *s = KeyAt(entry);
8189 return this;
8190 }
8191
8192 // Adding new symbol. Grow table if needed.
8193 Object* obj = EnsureCapacity(1, key);
8194 if (obj->IsFailure()) return obj;
8195
8196 // Create symbol object.
8197 Object* symbol = key->AsObject();
8198 if (symbol->IsFailure()) return symbol;
8199
8200 // If the symbol table grew as part of EnsureCapacity, obj is not
8201 // the current symbol table and therefore we cannot use
8202 // SymbolTable::cast here.
8203 SymbolTable* table = reinterpret_cast<SymbolTable*>(obj);
8204
8205 // Add the new symbol and return it along with the symbol table.
8206 entry = table->FindInsertionEntry(key->Hash());
8207 table->set(EntryToIndex(entry), symbol);
8208 table->ElementAdded();
8209 *s = symbol;
8210 return table;
8211}
8212
8213
8214Object* CompilationCacheTable::Lookup(String* src) {
8215 StringKey key(src);
8216 int entry = FindEntry(&key);
8217 if (entry == kNotFound) return Heap::undefined_value();
8218 return get(EntryToIndex(entry) + 1);
8219}
8220
8221
8222Object* CompilationCacheTable::LookupEval(String* src, Context* context) {
8223 StringSharedKey key(src, context->closure()->shared());
8224 int entry = FindEntry(&key);
8225 if (entry == kNotFound) return Heap::undefined_value();
8226 return get(EntryToIndex(entry) + 1);
8227}
8228
8229
8230Object* CompilationCacheTable::LookupRegExp(String* src,
8231 JSRegExp::Flags flags) {
8232 RegExpKey key(src, flags);
8233 int entry = FindEntry(&key);
8234 if (entry == kNotFound) return Heap::undefined_value();
8235 return get(EntryToIndex(entry) + 1);
8236}
8237
8238
8239Object* CompilationCacheTable::Put(String* src, Object* value) {
8240 StringKey key(src);
8241 Object* obj = EnsureCapacity(1, &key);
8242 if (obj->IsFailure()) return obj;
8243
8244 CompilationCacheTable* cache =
8245 reinterpret_cast<CompilationCacheTable*>(obj);
8246 int entry = cache->FindInsertionEntry(key.Hash());
8247 cache->set(EntryToIndex(entry), src);
8248 cache->set(EntryToIndex(entry) + 1, value);
8249 cache->ElementAdded();
8250 return cache;
8251}
8252
8253
8254Object* CompilationCacheTable::PutEval(String* src,
8255 Context* context,
8256 Object* value) {
8257 StringSharedKey key(src, context->closure()->shared());
8258 Object* obj = EnsureCapacity(1, &key);
8259 if (obj->IsFailure()) return obj;
8260
8261 CompilationCacheTable* cache =
8262 reinterpret_cast<CompilationCacheTable*>(obj);
8263 int entry = cache->FindInsertionEntry(key.Hash());
8264
8265 Object* k = key.AsObject();
8266 if (k->IsFailure()) return k;
8267
8268 cache->set(EntryToIndex(entry), k);
8269 cache->set(EntryToIndex(entry) + 1, value);
8270 cache->ElementAdded();
8271 return cache;
8272}
8273
8274
8275Object* CompilationCacheTable::PutRegExp(String* src,
8276 JSRegExp::Flags flags,
8277 FixedArray* value) {
8278 RegExpKey key(src, flags);
8279 Object* obj = EnsureCapacity(1, &key);
8280 if (obj->IsFailure()) return obj;
8281
8282 CompilationCacheTable* cache =
8283 reinterpret_cast<CompilationCacheTable*>(obj);
8284 int entry = cache->FindInsertionEntry(key.Hash());
Steve Block3ce2e202009-11-05 08:53:23 +00008285 // We store the value in the key slot, and compare the search key
8286 // to the stored value with a custon IsMatch function during lookups.
Steve Blocka7e24c12009-10-30 11:49:00 +00008287 cache->set(EntryToIndex(entry), value);
8288 cache->set(EntryToIndex(entry) + 1, value);
8289 cache->ElementAdded();
8290 return cache;
8291}
8292
8293
8294// SymbolsKey used for HashTable where key is array of symbols.
8295class SymbolsKey : public HashTableKey {
8296 public:
8297 explicit SymbolsKey(FixedArray* symbols) : symbols_(symbols) { }
8298
8299 bool IsMatch(Object* symbols) {
8300 FixedArray* o = FixedArray::cast(symbols);
8301 int len = symbols_->length();
8302 if (o->length() != len) return false;
8303 for (int i = 0; i < len; i++) {
8304 if (o->get(i) != symbols_->get(i)) return false;
8305 }
8306 return true;
8307 }
8308
8309 uint32_t Hash() { return HashForObject(symbols_); }
8310
8311 uint32_t HashForObject(Object* obj) {
8312 FixedArray* symbols = FixedArray::cast(obj);
8313 int len = symbols->length();
8314 uint32_t hash = 0;
8315 for (int i = 0; i < len; i++) {
8316 hash ^= String::cast(symbols->get(i))->Hash();
8317 }
8318 return hash;
8319 }
8320
8321 Object* AsObject() { return symbols_; }
8322
8323 private:
8324 FixedArray* symbols_;
8325};
8326
8327
8328Object* MapCache::Lookup(FixedArray* array) {
8329 SymbolsKey key(array);
8330 int entry = FindEntry(&key);
8331 if (entry == kNotFound) return Heap::undefined_value();
8332 return get(EntryToIndex(entry) + 1);
8333}
8334
8335
8336Object* MapCache::Put(FixedArray* array, Map* value) {
8337 SymbolsKey key(array);
8338 Object* obj = EnsureCapacity(1, &key);
8339 if (obj->IsFailure()) return obj;
8340
8341 MapCache* cache = reinterpret_cast<MapCache*>(obj);
8342 int entry = cache->FindInsertionEntry(key.Hash());
8343 cache->set(EntryToIndex(entry), array);
8344 cache->set(EntryToIndex(entry) + 1, value);
8345 cache->ElementAdded();
8346 return cache;
8347}
8348
8349
8350template<typename Shape, typename Key>
8351Object* Dictionary<Shape, Key>::Allocate(int at_least_space_for) {
8352 Object* obj = HashTable<Shape, Key>::Allocate(at_least_space_for);
8353 // Initialize the next enumeration index.
8354 if (!obj->IsFailure()) {
8355 Dictionary<Shape, Key>::cast(obj)->
8356 SetNextEnumerationIndex(PropertyDetails::kInitialIndex);
8357 }
8358 return obj;
8359}
8360
8361
8362template<typename Shape, typename Key>
8363Object* Dictionary<Shape, Key>::GenerateNewEnumerationIndices() {
8364 int length = HashTable<Shape, Key>::NumberOfElements();
8365
8366 // Allocate and initialize iteration order array.
8367 Object* obj = Heap::AllocateFixedArray(length);
8368 if (obj->IsFailure()) return obj;
8369 FixedArray* iteration_order = FixedArray::cast(obj);
8370 for (int i = 0; i < length; i++) {
Leon Clarke4515c472010-02-03 11:58:03 +00008371 iteration_order->set(i, Smi::FromInt(i));
Steve Blocka7e24c12009-10-30 11:49:00 +00008372 }
8373
8374 // Allocate array with enumeration order.
8375 obj = Heap::AllocateFixedArray(length);
8376 if (obj->IsFailure()) return obj;
8377 FixedArray* enumeration_order = FixedArray::cast(obj);
8378
8379 // Fill the enumeration order array with property details.
8380 int capacity = HashTable<Shape, Key>::Capacity();
8381 int pos = 0;
8382 for (int i = 0; i < capacity; i++) {
8383 if (Dictionary<Shape, Key>::IsKey(Dictionary<Shape, Key>::KeyAt(i))) {
Leon Clarke4515c472010-02-03 11:58:03 +00008384 enumeration_order->set(pos++, Smi::FromInt(DetailsAt(i).index()));
Steve Blocka7e24c12009-10-30 11:49:00 +00008385 }
8386 }
8387
8388 // Sort the arrays wrt. enumeration order.
8389 iteration_order->SortPairs(enumeration_order, enumeration_order->length());
8390
8391 // Overwrite the enumeration_order with the enumeration indices.
8392 for (int i = 0; i < length; i++) {
8393 int index = Smi::cast(iteration_order->get(i))->value();
8394 int enum_index = PropertyDetails::kInitialIndex + i;
Leon Clarke4515c472010-02-03 11:58:03 +00008395 enumeration_order->set(index, Smi::FromInt(enum_index));
Steve Blocka7e24c12009-10-30 11:49:00 +00008396 }
8397
8398 // Update the dictionary with new indices.
8399 capacity = HashTable<Shape, Key>::Capacity();
8400 pos = 0;
8401 for (int i = 0; i < capacity; i++) {
8402 if (Dictionary<Shape, Key>::IsKey(Dictionary<Shape, Key>::KeyAt(i))) {
8403 int enum_index = Smi::cast(enumeration_order->get(pos++))->value();
8404 PropertyDetails details = DetailsAt(i);
8405 PropertyDetails new_details =
8406 PropertyDetails(details.attributes(), details.type(), enum_index);
8407 DetailsAtPut(i, new_details);
8408 }
8409 }
8410
8411 // Set the next enumeration index.
8412 SetNextEnumerationIndex(PropertyDetails::kInitialIndex+length);
8413 return this;
8414}
8415
8416template<typename Shape, typename Key>
8417Object* Dictionary<Shape, Key>::EnsureCapacity(int n, Key key) {
8418 // Check whether there are enough enumeration indices to add n elements.
8419 if (Shape::kIsEnumerable &&
8420 !PropertyDetails::IsValidIndex(NextEnumerationIndex() + n)) {
8421 // If not, we generate new indices for the properties.
8422 Object* result = GenerateNewEnumerationIndices();
8423 if (result->IsFailure()) return result;
8424 }
8425 return HashTable<Shape, Key>::EnsureCapacity(n, key);
8426}
8427
8428
8429void NumberDictionary::RemoveNumberEntries(uint32_t from, uint32_t to) {
8430 // Do nothing if the interval [from, to) is empty.
8431 if (from >= to) return;
8432
8433 int removed_entries = 0;
8434 Object* sentinel = Heap::null_value();
8435 int capacity = Capacity();
8436 for (int i = 0; i < capacity; i++) {
8437 Object* key = KeyAt(i);
8438 if (key->IsNumber()) {
8439 uint32_t number = static_cast<uint32_t>(key->Number());
8440 if (from <= number && number < to) {
8441 SetEntry(i, sentinel, sentinel, Smi::FromInt(0));
8442 removed_entries++;
8443 }
8444 }
8445 }
8446
8447 // Update the number of elements.
Leon Clarkee46be812010-01-19 14:06:41 +00008448 ElementsRemoved(removed_entries);
Steve Blocka7e24c12009-10-30 11:49:00 +00008449}
8450
8451
8452template<typename Shape, typename Key>
8453Object* Dictionary<Shape, Key>::DeleteProperty(int entry,
8454 JSObject::DeleteMode mode) {
8455 PropertyDetails details = DetailsAt(entry);
8456 // Ignore attributes if forcing a deletion.
8457 if (details.IsDontDelete() && mode == JSObject::NORMAL_DELETION) {
8458 return Heap::false_value();
8459 }
8460 SetEntry(entry, Heap::null_value(), Heap::null_value(), Smi::FromInt(0));
8461 HashTable<Shape, Key>::ElementRemoved();
8462 return Heap::true_value();
8463}
8464
8465
8466template<typename Shape, typename Key>
8467Object* Dictionary<Shape, Key>::AtPut(Key key, Object* value) {
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01008468 int entry = this->FindEntry(key);
Steve Blocka7e24c12009-10-30 11:49:00 +00008469
8470 // If the entry is present set the value;
8471 if (entry != Dictionary<Shape, Key>::kNotFound) {
8472 ValueAtPut(entry, value);
8473 return this;
8474 }
8475
8476 // Check whether the dictionary should be extended.
8477 Object* obj = EnsureCapacity(1, key);
8478 if (obj->IsFailure()) return obj;
8479
8480 Object* k = Shape::AsObject(key);
8481 if (k->IsFailure()) return k;
8482 PropertyDetails details = PropertyDetails(NONE, NORMAL);
8483 return Dictionary<Shape, Key>::cast(obj)->
8484 AddEntry(key, value, details, Shape::Hash(key));
8485}
8486
8487
8488template<typename Shape, typename Key>
8489Object* Dictionary<Shape, Key>::Add(Key key,
8490 Object* value,
8491 PropertyDetails details) {
8492 // Valdate key is absent.
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01008493 SLOW_ASSERT((this->FindEntry(key) == Dictionary<Shape, Key>::kNotFound));
Steve Blocka7e24c12009-10-30 11:49:00 +00008494 // Check whether the dictionary should be extended.
8495 Object* obj = EnsureCapacity(1, key);
8496 if (obj->IsFailure()) return obj;
8497 return Dictionary<Shape, Key>::cast(obj)->
8498 AddEntry(key, value, details, Shape::Hash(key));
8499}
8500
8501
8502// Add a key, value pair to the dictionary.
8503template<typename Shape, typename Key>
8504Object* Dictionary<Shape, Key>::AddEntry(Key key,
8505 Object* value,
8506 PropertyDetails details,
8507 uint32_t hash) {
8508 // Compute the key object.
8509 Object* k = Shape::AsObject(key);
8510 if (k->IsFailure()) return k;
8511
8512 uint32_t entry = Dictionary<Shape, Key>::FindInsertionEntry(hash);
8513 // Insert element at empty or deleted entry
8514 if (!details.IsDeleted() && details.index() == 0 && Shape::kIsEnumerable) {
8515 // Assign an enumeration index to the property and update
8516 // SetNextEnumerationIndex.
8517 int index = NextEnumerationIndex();
8518 details = PropertyDetails(details.attributes(), details.type(), index);
8519 SetNextEnumerationIndex(index + 1);
8520 }
8521 SetEntry(entry, k, value, details);
8522 ASSERT((Dictionary<Shape, Key>::KeyAt(entry)->IsNumber()
8523 || Dictionary<Shape, Key>::KeyAt(entry)->IsString()));
8524 HashTable<Shape, Key>::ElementAdded();
8525 return this;
8526}
8527
8528
8529void NumberDictionary::UpdateMaxNumberKey(uint32_t key) {
8530 // If the dictionary requires slow elements an element has already
8531 // been added at a high index.
8532 if (requires_slow_elements()) return;
8533 // Check if this index is high enough that we should require slow
8534 // elements.
8535 if (key > kRequiresSlowElementsLimit) {
8536 set_requires_slow_elements();
8537 return;
8538 }
8539 // Update max key value.
8540 Object* max_index_object = get(kMaxNumberKeyIndex);
8541 if (!max_index_object->IsSmi() || max_number_key() < key) {
8542 FixedArray::set(kMaxNumberKeyIndex,
Leon Clarke4515c472010-02-03 11:58:03 +00008543 Smi::FromInt(key << kRequiresSlowElementsTagSize));
Steve Blocka7e24c12009-10-30 11:49:00 +00008544 }
8545}
8546
8547
8548Object* NumberDictionary::AddNumberEntry(uint32_t key,
8549 Object* value,
8550 PropertyDetails details) {
8551 UpdateMaxNumberKey(key);
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01008552 SLOW_ASSERT(this->FindEntry(key) == kNotFound);
Steve Blocka7e24c12009-10-30 11:49:00 +00008553 return Add(key, value, details);
8554}
8555
8556
8557Object* NumberDictionary::AtNumberPut(uint32_t key, Object* value) {
8558 UpdateMaxNumberKey(key);
8559 return AtPut(key, value);
8560}
8561
8562
8563Object* NumberDictionary::Set(uint32_t key,
8564 Object* value,
8565 PropertyDetails details) {
8566 int entry = FindEntry(key);
8567 if (entry == kNotFound) return AddNumberEntry(key, value, details);
8568 // Preserve enumeration index.
8569 details = PropertyDetails(details.attributes(),
8570 details.type(),
8571 DetailsAt(entry).index());
Ben Murdochf87a2032010-10-22 12:50:53 +01008572 Object* object_key = NumberDictionaryShape::AsObject(key);
8573 if (object_key->IsFailure()) return object_key;
8574 SetEntry(entry, object_key, value, details);
Steve Blocka7e24c12009-10-30 11:49:00 +00008575 return this;
8576}
8577
8578
8579
8580template<typename Shape, typename Key>
8581int Dictionary<Shape, Key>::NumberOfElementsFilterAttributes(
8582 PropertyAttributes filter) {
8583 int capacity = HashTable<Shape, Key>::Capacity();
8584 int result = 0;
8585 for (int i = 0; i < capacity; i++) {
8586 Object* k = HashTable<Shape, Key>::KeyAt(i);
8587 if (HashTable<Shape, Key>::IsKey(k)) {
8588 PropertyDetails details = DetailsAt(i);
8589 if (details.IsDeleted()) continue;
8590 PropertyAttributes attr = details.attributes();
8591 if ((attr & filter) == 0) result++;
8592 }
8593 }
8594 return result;
8595}
8596
8597
8598template<typename Shape, typename Key>
8599int Dictionary<Shape, Key>::NumberOfEnumElements() {
8600 return NumberOfElementsFilterAttributes(
8601 static_cast<PropertyAttributes>(DONT_ENUM));
8602}
8603
8604
8605template<typename Shape, typename Key>
8606void Dictionary<Shape, Key>::CopyKeysTo(FixedArray* storage,
8607 PropertyAttributes filter) {
8608 ASSERT(storage->length() >= NumberOfEnumElements());
8609 int capacity = HashTable<Shape, Key>::Capacity();
8610 int index = 0;
8611 for (int i = 0; i < capacity; i++) {
8612 Object* k = HashTable<Shape, Key>::KeyAt(i);
8613 if (HashTable<Shape, Key>::IsKey(k)) {
8614 PropertyDetails details = DetailsAt(i);
8615 if (details.IsDeleted()) continue;
8616 PropertyAttributes attr = details.attributes();
8617 if ((attr & filter) == 0) storage->set(index++, k);
8618 }
8619 }
8620 storage->SortPairs(storage, index);
8621 ASSERT(storage->length() >= index);
8622}
8623
8624
8625void StringDictionary::CopyEnumKeysTo(FixedArray* storage,
8626 FixedArray* sort_array) {
8627 ASSERT(storage->length() >= NumberOfEnumElements());
8628 int capacity = Capacity();
8629 int index = 0;
8630 for (int i = 0; i < capacity; i++) {
8631 Object* k = KeyAt(i);
8632 if (IsKey(k)) {
8633 PropertyDetails details = DetailsAt(i);
8634 if (details.IsDeleted() || details.IsDontEnum()) continue;
8635 storage->set(index, k);
Leon Clarke4515c472010-02-03 11:58:03 +00008636 sort_array->set(index, Smi::FromInt(details.index()));
Steve Blocka7e24c12009-10-30 11:49:00 +00008637 index++;
8638 }
8639 }
8640 storage->SortPairs(sort_array, sort_array->length());
8641 ASSERT(storage->length() >= index);
8642}
8643
8644
8645template<typename Shape, typename Key>
8646void Dictionary<Shape, Key>::CopyKeysTo(FixedArray* storage) {
8647 ASSERT(storage->length() >= NumberOfElementsFilterAttributes(
8648 static_cast<PropertyAttributes>(NONE)));
8649 int capacity = HashTable<Shape, Key>::Capacity();
8650 int index = 0;
8651 for (int i = 0; i < capacity; i++) {
8652 Object* k = HashTable<Shape, Key>::KeyAt(i);
8653 if (HashTable<Shape, Key>::IsKey(k)) {
8654 PropertyDetails details = DetailsAt(i);
8655 if (details.IsDeleted()) continue;
8656 storage->set(index++, k);
8657 }
8658 }
8659 ASSERT(storage->length() >= index);
8660}
8661
8662
8663// Backwards lookup (slow).
8664template<typename Shape, typename Key>
8665Object* Dictionary<Shape, Key>::SlowReverseLookup(Object* value) {
8666 int capacity = HashTable<Shape, Key>::Capacity();
8667 for (int i = 0; i < capacity; i++) {
8668 Object* k = HashTable<Shape, Key>::KeyAt(i);
8669 if (Dictionary<Shape, Key>::IsKey(k)) {
8670 Object* e = ValueAt(i);
8671 if (e->IsJSGlobalPropertyCell()) {
8672 e = JSGlobalPropertyCell::cast(e)->value();
8673 }
8674 if (e == value) return k;
8675 }
8676 }
8677 return Heap::undefined_value();
8678}
8679
8680
8681Object* StringDictionary::TransformPropertiesToFastFor(
8682 JSObject* obj, int unused_property_fields) {
8683 // Make sure we preserve dictionary representation if there are too many
8684 // descriptors.
8685 if (NumberOfElements() > DescriptorArray::kMaxNumberOfDescriptors) return obj;
8686
8687 // Figure out if it is necessary to generate new enumeration indices.
8688 int max_enumeration_index =
8689 NextEnumerationIndex() +
8690 (DescriptorArray::kMaxNumberOfDescriptors -
8691 NumberOfElements());
8692 if (!PropertyDetails::IsValidIndex(max_enumeration_index)) {
8693 Object* result = GenerateNewEnumerationIndices();
8694 if (result->IsFailure()) return result;
8695 }
8696
8697 int instance_descriptor_length = 0;
8698 int number_of_fields = 0;
8699
8700 // Compute the length of the instance descriptor.
8701 int capacity = Capacity();
8702 for (int i = 0; i < capacity; i++) {
8703 Object* k = KeyAt(i);
8704 if (IsKey(k)) {
8705 Object* value = ValueAt(i);
8706 PropertyType type = DetailsAt(i).type();
8707 ASSERT(type != FIELD);
8708 instance_descriptor_length++;
Leon Clarkee46be812010-01-19 14:06:41 +00008709 if (type == NORMAL &&
8710 (!value->IsJSFunction() || Heap::InNewSpace(value))) {
8711 number_of_fields += 1;
8712 }
Steve Blocka7e24c12009-10-30 11:49:00 +00008713 }
8714 }
8715
8716 // Allocate the instance descriptor.
8717 Object* descriptors_unchecked =
8718 DescriptorArray::Allocate(instance_descriptor_length);
8719 if (descriptors_unchecked->IsFailure()) return descriptors_unchecked;
8720 DescriptorArray* descriptors = DescriptorArray::cast(descriptors_unchecked);
8721
8722 int inobject_props = obj->map()->inobject_properties();
8723 int number_of_allocated_fields =
8724 number_of_fields + unused_property_fields - inobject_props;
Ben Murdochf87a2032010-10-22 12:50:53 +01008725 if (number_of_allocated_fields < 0) {
8726 // There is enough inobject space for all fields (including unused).
8727 number_of_allocated_fields = 0;
8728 unused_property_fields = inobject_props - number_of_fields;
8729 }
Steve Blocka7e24c12009-10-30 11:49:00 +00008730
8731 // Allocate the fixed array for the fields.
8732 Object* fields = Heap::AllocateFixedArray(number_of_allocated_fields);
8733 if (fields->IsFailure()) return fields;
8734
8735 // Fill in the instance descriptor and the fields.
8736 int next_descriptor = 0;
8737 int current_offset = 0;
8738 for (int i = 0; i < capacity; i++) {
8739 Object* k = KeyAt(i);
8740 if (IsKey(k)) {
8741 Object* value = ValueAt(i);
8742 // Ensure the key is a symbol before writing into the instance descriptor.
8743 Object* key = Heap::LookupSymbol(String::cast(k));
8744 if (key->IsFailure()) return key;
8745 PropertyDetails details = DetailsAt(i);
8746 PropertyType type = details.type();
8747
Leon Clarkee46be812010-01-19 14:06:41 +00008748 if (value->IsJSFunction() && !Heap::InNewSpace(value)) {
Steve Blocka7e24c12009-10-30 11:49:00 +00008749 ConstantFunctionDescriptor d(String::cast(key),
8750 JSFunction::cast(value),
8751 details.attributes(),
8752 details.index());
8753 descriptors->Set(next_descriptor++, &d);
8754 } else if (type == NORMAL) {
8755 if (current_offset < inobject_props) {
8756 obj->InObjectPropertyAtPut(current_offset,
8757 value,
8758 UPDATE_WRITE_BARRIER);
8759 } else {
8760 int offset = current_offset - inobject_props;
8761 FixedArray::cast(fields)->set(offset, value);
8762 }
8763 FieldDescriptor d(String::cast(key),
8764 current_offset++,
8765 details.attributes(),
8766 details.index());
8767 descriptors->Set(next_descriptor++, &d);
8768 } else if (type == CALLBACKS) {
8769 CallbacksDescriptor d(String::cast(key),
8770 value,
8771 details.attributes(),
8772 details.index());
8773 descriptors->Set(next_descriptor++, &d);
8774 } else {
8775 UNREACHABLE();
8776 }
8777 }
8778 }
8779 ASSERT(current_offset == number_of_fields);
8780
8781 descriptors->Sort();
8782 // Allocate new map.
8783 Object* new_map = obj->map()->CopyDropDescriptors();
8784 if (new_map->IsFailure()) return new_map;
8785
8786 // Transform the object.
8787 obj->set_map(Map::cast(new_map));
8788 obj->map()->set_instance_descriptors(descriptors);
8789 obj->map()->set_unused_property_fields(unused_property_fields);
8790
8791 obj->set_properties(FixedArray::cast(fields));
8792 ASSERT(obj->IsJSObject());
8793
8794 descriptors->SetNextEnumerationIndex(NextEnumerationIndex());
8795 // Check that it really works.
8796 ASSERT(obj->HasFastProperties());
8797
8798 return obj;
8799}
8800
8801
8802#ifdef ENABLE_DEBUGGER_SUPPORT
8803// Check if there is a break point at this code position.
8804bool DebugInfo::HasBreakPoint(int code_position) {
8805 // Get the break point info object for this code position.
8806 Object* break_point_info = GetBreakPointInfo(code_position);
8807
8808 // If there is no break point info object or no break points in the break
8809 // point info object there is no break point at this code position.
8810 if (break_point_info->IsUndefined()) return false;
8811 return BreakPointInfo::cast(break_point_info)->GetBreakPointCount() > 0;
8812}
8813
8814
8815// Get the break point info object for this code position.
8816Object* DebugInfo::GetBreakPointInfo(int code_position) {
8817 // Find the index of the break point info object for this code position.
8818 int index = GetBreakPointInfoIndex(code_position);
8819
8820 // Return the break point info object if any.
8821 if (index == kNoBreakPointInfo) return Heap::undefined_value();
8822 return BreakPointInfo::cast(break_points()->get(index));
8823}
8824
8825
8826// Clear a break point at the specified code position.
8827void DebugInfo::ClearBreakPoint(Handle<DebugInfo> debug_info,
8828 int code_position,
8829 Handle<Object> break_point_object) {
8830 Handle<Object> break_point_info(debug_info->GetBreakPointInfo(code_position));
8831 if (break_point_info->IsUndefined()) return;
8832 BreakPointInfo::ClearBreakPoint(
8833 Handle<BreakPointInfo>::cast(break_point_info),
8834 break_point_object);
8835}
8836
8837
8838void DebugInfo::SetBreakPoint(Handle<DebugInfo> debug_info,
8839 int code_position,
8840 int source_position,
8841 int statement_position,
8842 Handle<Object> break_point_object) {
8843 Handle<Object> break_point_info(debug_info->GetBreakPointInfo(code_position));
8844 if (!break_point_info->IsUndefined()) {
8845 BreakPointInfo::SetBreakPoint(
8846 Handle<BreakPointInfo>::cast(break_point_info),
8847 break_point_object);
8848 return;
8849 }
8850
8851 // Adding a new break point for a code position which did not have any
8852 // break points before. Try to find a free slot.
8853 int index = kNoBreakPointInfo;
8854 for (int i = 0; i < debug_info->break_points()->length(); i++) {
8855 if (debug_info->break_points()->get(i)->IsUndefined()) {
8856 index = i;
8857 break;
8858 }
8859 }
8860 if (index == kNoBreakPointInfo) {
8861 // No free slot - extend break point info array.
8862 Handle<FixedArray> old_break_points =
8863 Handle<FixedArray>(FixedArray::cast(debug_info->break_points()));
Steve Blocka7e24c12009-10-30 11:49:00 +00008864 Handle<FixedArray> new_break_points =
Kristian Monsen0d5e1162010-09-30 15:31:59 +01008865 Factory::NewFixedArray(old_break_points->length() +
8866 Debug::kEstimatedNofBreakPointsInFunction);
8867
8868 debug_info->set_break_points(*new_break_points);
Steve Blocka7e24c12009-10-30 11:49:00 +00008869 for (int i = 0; i < old_break_points->length(); i++) {
8870 new_break_points->set(i, old_break_points->get(i));
8871 }
8872 index = old_break_points->length();
8873 }
8874 ASSERT(index != kNoBreakPointInfo);
8875
8876 // Allocate new BreakPointInfo object and set the break point.
8877 Handle<BreakPointInfo> new_break_point_info =
8878 Handle<BreakPointInfo>::cast(Factory::NewStruct(BREAK_POINT_INFO_TYPE));
8879 new_break_point_info->set_code_position(Smi::FromInt(code_position));
8880 new_break_point_info->set_source_position(Smi::FromInt(source_position));
8881 new_break_point_info->
8882 set_statement_position(Smi::FromInt(statement_position));
8883 new_break_point_info->set_break_point_objects(Heap::undefined_value());
8884 BreakPointInfo::SetBreakPoint(new_break_point_info, break_point_object);
8885 debug_info->break_points()->set(index, *new_break_point_info);
8886}
8887
8888
8889// Get the break point objects for a code position.
8890Object* DebugInfo::GetBreakPointObjects(int code_position) {
8891 Object* break_point_info = GetBreakPointInfo(code_position);
8892 if (break_point_info->IsUndefined()) {
8893 return Heap::undefined_value();
8894 }
8895 return BreakPointInfo::cast(break_point_info)->break_point_objects();
8896}
8897
8898
8899// Get the total number of break points.
8900int DebugInfo::GetBreakPointCount() {
8901 if (break_points()->IsUndefined()) return 0;
8902 int count = 0;
8903 for (int i = 0; i < break_points()->length(); i++) {
8904 if (!break_points()->get(i)->IsUndefined()) {
8905 BreakPointInfo* break_point_info =
8906 BreakPointInfo::cast(break_points()->get(i));
8907 count += break_point_info->GetBreakPointCount();
8908 }
8909 }
8910 return count;
8911}
8912
8913
8914Object* DebugInfo::FindBreakPointInfo(Handle<DebugInfo> debug_info,
8915 Handle<Object> break_point_object) {
8916 if (debug_info->break_points()->IsUndefined()) return Heap::undefined_value();
8917 for (int i = 0; i < debug_info->break_points()->length(); i++) {
8918 if (!debug_info->break_points()->get(i)->IsUndefined()) {
8919 Handle<BreakPointInfo> break_point_info =
8920 Handle<BreakPointInfo>(BreakPointInfo::cast(
8921 debug_info->break_points()->get(i)));
8922 if (BreakPointInfo::HasBreakPointObject(break_point_info,
8923 break_point_object)) {
8924 return *break_point_info;
8925 }
8926 }
8927 }
8928 return Heap::undefined_value();
8929}
8930
8931
8932// Find the index of the break point info object for the specified code
8933// position.
8934int DebugInfo::GetBreakPointInfoIndex(int code_position) {
8935 if (break_points()->IsUndefined()) return kNoBreakPointInfo;
8936 for (int i = 0; i < break_points()->length(); i++) {
8937 if (!break_points()->get(i)->IsUndefined()) {
8938 BreakPointInfo* break_point_info =
8939 BreakPointInfo::cast(break_points()->get(i));
8940 if (break_point_info->code_position()->value() == code_position) {
8941 return i;
8942 }
8943 }
8944 }
8945 return kNoBreakPointInfo;
8946}
8947
8948
8949// Remove the specified break point object.
8950void BreakPointInfo::ClearBreakPoint(Handle<BreakPointInfo> break_point_info,
8951 Handle<Object> break_point_object) {
8952 // If there are no break points just ignore.
8953 if (break_point_info->break_point_objects()->IsUndefined()) return;
8954 // If there is a single break point clear it if it is the same.
8955 if (!break_point_info->break_point_objects()->IsFixedArray()) {
8956 if (break_point_info->break_point_objects() == *break_point_object) {
8957 break_point_info->set_break_point_objects(Heap::undefined_value());
8958 }
8959 return;
8960 }
8961 // If there are multiple break points shrink the array
8962 ASSERT(break_point_info->break_point_objects()->IsFixedArray());
8963 Handle<FixedArray> old_array =
8964 Handle<FixedArray>(
8965 FixedArray::cast(break_point_info->break_point_objects()));
8966 Handle<FixedArray> new_array =
8967 Factory::NewFixedArray(old_array->length() - 1);
8968 int found_count = 0;
8969 for (int i = 0; i < old_array->length(); i++) {
8970 if (old_array->get(i) == *break_point_object) {
8971 ASSERT(found_count == 0);
8972 found_count++;
8973 } else {
8974 new_array->set(i - found_count, old_array->get(i));
8975 }
8976 }
8977 // If the break point was found in the list change it.
8978 if (found_count > 0) break_point_info->set_break_point_objects(*new_array);
8979}
8980
8981
8982// Add the specified break point object.
8983void BreakPointInfo::SetBreakPoint(Handle<BreakPointInfo> break_point_info,
8984 Handle<Object> break_point_object) {
8985 // If there was no break point objects before just set it.
8986 if (break_point_info->break_point_objects()->IsUndefined()) {
8987 break_point_info->set_break_point_objects(*break_point_object);
8988 return;
8989 }
8990 // If the break point object is the same as before just ignore.
8991 if (break_point_info->break_point_objects() == *break_point_object) return;
8992 // If there was one break point object before replace with array.
8993 if (!break_point_info->break_point_objects()->IsFixedArray()) {
8994 Handle<FixedArray> array = Factory::NewFixedArray(2);
8995 array->set(0, break_point_info->break_point_objects());
8996 array->set(1, *break_point_object);
8997 break_point_info->set_break_point_objects(*array);
8998 return;
8999 }
9000 // If there was more than one break point before extend array.
9001 Handle<FixedArray> old_array =
9002 Handle<FixedArray>(
9003 FixedArray::cast(break_point_info->break_point_objects()));
9004 Handle<FixedArray> new_array =
9005 Factory::NewFixedArray(old_array->length() + 1);
9006 for (int i = 0; i < old_array->length(); i++) {
9007 // If the break point was there before just ignore.
9008 if (old_array->get(i) == *break_point_object) return;
9009 new_array->set(i, old_array->get(i));
9010 }
9011 // Add the new break point.
9012 new_array->set(old_array->length(), *break_point_object);
9013 break_point_info->set_break_point_objects(*new_array);
9014}
9015
9016
9017bool BreakPointInfo::HasBreakPointObject(
9018 Handle<BreakPointInfo> break_point_info,
9019 Handle<Object> break_point_object) {
9020 // No break point.
9021 if (break_point_info->break_point_objects()->IsUndefined()) return false;
9022 // Single beak point.
9023 if (!break_point_info->break_point_objects()->IsFixedArray()) {
9024 return break_point_info->break_point_objects() == *break_point_object;
9025 }
9026 // Multiple break points.
9027 FixedArray* array = FixedArray::cast(break_point_info->break_point_objects());
9028 for (int i = 0; i < array->length(); i++) {
9029 if (array->get(i) == *break_point_object) {
9030 return true;
9031 }
9032 }
9033 return false;
9034}
9035
9036
9037// Get the number of break points.
9038int BreakPointInfo::GetBreakPointCount() {
9039 // No break point.
9040 if (break_point_objects()->IsUndefined()) return 0;
9041 // Single beak point.
9042 if (!break_point_objects()->IsFixedArray()) return 1;
9043 // Multiple break points.
9044 return FixedArray::cast(break_point_objects())->length();
9045}
9046#endif
9047
9048
9049} } // namespace v8::internal