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