blob: e2fa3b5371db5213cb889f99f030916a22aba083 [file] [log] [blame]
Steve Blocka7e24c12009-10-30 11:49:00 +00001// Copyright 2006-2009 the V8 project authors. All rights reserved.
2// Redistribution and use in source and binary forms, with or without
3// modification, are permitted provided that the following conditions are
4// met:
5//
6// * Redistributions of source code must retain the above copyright
7// notice, this list of conditions and the following disclaimer.
8// * Redistributions in binary form must reproduce the above
9// copyright notice, this list of conditions and the following
10// disclaimer in the documentation and/or other materials provided
11// with the distribution.
12// * Neither the name of Google Inc. nor the names of its
13// contributors may be used to endorse or promote products derived
14// from this software without specific prior written permission.
15//
16// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27
28#include "v8.h"
29
30#include "api.h"
31#include "arguments.h"
32#include "bootstrapper.h"
33#include "debug.h"
34#include "execution.h"
35#include "objects-inl.h"
36#include "macro-assembler.h"
37#include "scanner.h"
38#include "scopeinfo.h"
39#include "string-stream.h"
40
41#ifdef ENABLE_DISASSEMBLER
42#include "disassembler.h"
43#endif
44
45
46namespace v8 {
47namespace internal {
48
49// Getters and setters are stored in a fixed array property. These are
50// constants for their indices.
51const int kGetterIndex = 0;
52const int kSetterIndex = 1;
53
54
55static Object* CreateJSValue(JSFunction* constructor, Object* value) {
56 Object* result = Heap::AllocateJSObject(constructor);
57 if (result->IsFailure()) return result;
58 JSValue::cast(result)->set_value(value);
59 return result;
60}
61
62
63Object* Object::ToObject(Context* global_context) {
64 if (IsNumber()) {
65 return CreateJSValue(global_context->number_function(), this);
66 } else if (IsBoolean()) {
67 return CreateJSValue(global_context->boolean_function(), this);
68 } else if (IsString()) {
69 return CreateJSValue(global_context->string_function(), this);
70 }
71 ASSERT(IsJSObject());
72 return this;
73}
74
75
76Object* Object::ToObject() {
77 Context* global_context = Top::context()->global_context();
78 if (IsJSObject()) {
79 return this;
80 } else if (IsNumber()) {
81 return CreateJSValue(global_context->number_function(), this);
82 } else if (IsBoolean()) {
83 return CreateJSValue(global_context->boolean_function(), this);
84 } else if (IsString()) {
85 return CreateJSValue(global_context->string_function(), this);
86 }
87
88 // Throw a type error.
89 return Failure::InternalError();
90}
91
92
93Object* Object::ToBoolean() {
94 if (IsTrue()) return Heap::true_value();
95 if (IsFalse()) return Heap::false_value();
96 if (IsSmi()) {
97 return Heap::ToBoolean(Smi::cast(this)->value() != 0);
98 }
99 if (IsUndefined() || IsNull()) return Heap::false_value();
100 // Undetectable object is false
101 if (IsUndetectableObject()) {
102 return Heap::false_value();
103 }
104 if (IsString()) {
105 return Heap::ToBoolean(String::cast(this)->length() != 0);
106 }
107 if (IsHeapNumber()) {
108 return HeapNumber::cast(this)->HeapNumberToBoolean();
109 }
110 return Heap::true_value();
111}
112
113
114void Object::Lookup(String* name, LookupResult* result) {
115 if (IsJSObject()) return JSObject::cast(this)->Lookup(name, result);
116 Object* holder = NULL;
117 Context* global_context = Top::context()->global_context();
118 if (IsString()) {
119 holder = global_context->string_function()->instance_prototype();
120 } else if (IsNumber()) {
121 holder = global_context->number_function()->instance_prototype();
122 } else if (IsBoolean()) {
123 holder = global_context->boolean_function()->instance_prototype();
124 }
125 ASSERT(holder != NULL); // Cannot handle null or undefined.
126 JSObject::cast(holder)->Lookup(name, result);
127}
128
129
130Object* Object::GetPropertyWithReceiver(Object* receiver,
131 String* name,
132 PropertyAttributes* attributes) {
133 LookupResult result;
134 Lookup(name, &result);
135 Object* value = GetProperty(receiver, &result, name, attributes);
136 ASSERT(*attributes <= ABSENT);
137 return value;
138}
139
140
141Object* Object::GetPropertyWithCallback(Object* receiver,
142 Object* structure,
143 String* name,
144 Object* holder) {
145 // To accommodate both the old and the new api we switch on the
146 // data structure used to store the callbacks. Eventually proxy
147 // callbacks should be phased out.
148 if (structure->IsProxy()) {
149 AccessorDescriptor* callback =
150 reinterpret_cast<AccessorDescriptor*>(Proxy::cast(structure)->proxy());
151 Object* value = (callback->getter)(receiver, callback->data);
152 RETURN_IF_SCHEDULED_EXCEPTION();
153 return value;
154 }
155
156 // api style callbacks.
157 if (structure->IsAccessorInfo()) {
158 AccessorInfo* data = AccessorInfo::cast(structure);
159 Object* fun_obj = data->getter();
160 v8::AccessorGetter call_fun = v8::ToCData<v8::AccessorGetter>(fun_obj);
161 HandleScope scope;
162 JSObject* self = JSObject::cast(receiver);
163 JSObject* holder_handle = JSObject::cast(holder);
164 Handle<String> key(name);
165 LOG(ApiNamedPropertyAccess("load", self, name));
166 CustomArguments args(data->data(), self, holder_handle);
167 v8::AccessorInfo info(args.end());
168 v8::Handle<v8::Value> result;
169 {
170 // Leaving JavaScript.
171 VMState state(EXTERNAL);
172 result = call_fun(v8::Utils::ToLocal(key), info);
173 }
174 RETURN_IF_SCHEDULED_EXCEPTION();
175 if (result.IsEmpty()) return Heap::undefined_value();
176 return *v8::Utils::OpenHandle(*result);
177 }
178
179 // __defineGetter__ callback
180 if (structure->IsFixedArray()) {
181 Object* getter = FixedArray::cast(structure)->get(kGetterIndex);
182 if (getter->IsJSFunction()) {
183 return Object::GetPropertyWithDefinedGetter(receiver,
184 JSFunction::cast(getter));
185 }
186 // Getter is not a function.
187 return Heap::undefined_value();
188 }
189
190 UNREACHABLE();
191 return 0;
192}
193
194
195Object* Object::GetPropertyWithDefinedGetter(Object* receiver,
196 JSFunction* getter) {
197 HandleScope scope;
198 Handle<JSFunction> fun(JSFunction::cast(getter));
199 Handle<Object> self(receiver);
200#ifdef ENABLE_DEBUGGER_SUPPORT
201 // Handle stepping into a getter if step into is active.
202 if (Debug::StepInActive()) {
203 Debug::HandleStepIn(fun, Handle<Object>::null(), 0, false);
204 }
205#endif
206 bool has_pending_exception;
207 Handle<Object> result =
208 Execution::Call(fun, self, 0, NULL, &has_pending_exception);
209 // Check for pending exception and return the result.
210 if (has_pending_exception) return Failure::Exception();
211 return *result;
212}
213
214
215// Only deal with CALLBACKS and INTERCEPTOR
216Object* JSObject::GetPropertyWithFailedAccessCheck(
217 Object* receiver,
218 LookupResult* result,
219 String* name,
220 PropertyAttributes* attributes) {
221 if (result->IsValid()) {
222 switch (result->type()) {
223 case CALLBACKS: {
224 // Only allow API accessors.
225 Object* obj = result->GetCallbackObject();
226 if (obj->IsAccessorInfo()) {
227 AccessorInfo* info = AccessorInfo::cast(obj);
228 if (info->all_can_read()) {
229 *attributes = result->GetAttributes();
230 return GetPropertyWithCallback(receiver,
231 result->GetCallbackObject(),
232 name,
233 result->holder());
234 }
235 }
236 break;
237 }
238 case NORMAL:
239 case FIELD:
240 case CONSTANT_FUNCTION: {
241 // Search ALL_CAN_READ accessors in prototype chain.
242 LookupResult r;
243 result->holder()->LookupRealNamedPropertyInPrototypes(name, &r);
244 if (r.IsValid()) {
245 return GetPropertyWithFailedAccessCheck(receiver,
246 &r,
247 name,
248 attributes);
249 }
250 break;
251 }
252 case INTERCEPTOR: {
253 // If the object has an interceptor, try real named properties.
254 // No access check in GetPropertyAttributeWithInterceptor.
255 LookupResult r;
256 result->holder()->LookupRealNamedProperty(name, &r);
257 if (r.IsValid()) {
258 return GetPropertyWithFailedAccessCheck(receiver,
259 &r,
260 name,
261 attributes);
262 }
263 }
264 default: {
265 break;
266 }
267 }
268 }
269
270 // No accessible property found.
271 *attributes = ABSENT;
272 Top::ReportFailedAccessCheck(this, v8::ACCESS_GET);
273 return Heap::undefined_value();
274}
275
276
277PropertyAttributes JSObject::GetPropertyAttributeWithFailedAccessCheck(
278 Object* receiver,
279 LookupResult* result,
280 String* name,
281 bool continue_search) {
282 if (result->IsValid()) {
283 switch (result->type()) {
284 case CALLBACKS: {
285 // Only allow API accessors.
286 Object* obj = result->GetCallbackObject();
287 if (obj->IsAccessorInfo()) {
288 AccessorInfo* info = AccessorInfo::cast(obj);
289 if (info->all_can_read()) {
290 return result->GetAttributes();
291 }
292 }
293 break;
294 }
295
296 case NORMAL:
297 case FIELD:
298 case CONSTANT_FUNCTION: {
299 if (!continue_search) break;
300 // Search ALL_CAN_READ accessors in prototype chain.
301 LookupResult r;
302 result->holder()->LookupRealNamedPropertyInPrototypes(name, &r);
303 if (r.IsValid()) {
304 return GetPropertyAttributeWithFailedAccessCheck(receiver,
305 &r,
306 name,
307 continue_search);
308 }
309 break;
310 }
311
312 case INTERCEPTOR: {
313 // If the object has an interceptor, try real named properties.
314 // No access check in GetPropertyAttributeWithInterceptor.
315 LookupResult r;
316 if (continue_search) {
317 result->holder()->LookupRealNamedProperty(name, &r);
318 } else {
319 result->holder()->LocalLookupRealNamedProperty(name, &r);
320 }
321 if (r.IsValid()) {
322 return GetPropertyAttributeWithFailedAccessCheck(receiver,
323 &r,
324 name,
325 continue_search);
326 }
327 break;
328 }
329
330 default: {
331 break;
332 }
333 }
334 }
335
336 Top::ReportFailedAccessCheck(this, v8::ACCESS_HAS);
337 return ABSENT;
338}
339
340
341Object* JSObject::GetLazyProperty(Object* receiver,
342 LookupResult* result,
343 String* name,
344 PropertyAttributes* attributes) {
345 HandleScope scope;
346 Handle<Object> this_handle(this);
347 Handle<Object> receiver_handle(receiver);
348 Handle<String> name_handle(name);
349 bool pending_exception;
350 LoadLazy(Handle<JSObject>(JSObject::cast(result->GetLazyValue())),
351 &pending_exception);
352 if (pending_exception) return Failure::Exception();
353 return this_handle->GetPropertyWithReceiver(*receiver_handle,
354 *name_handle,
355 attributes);
356}
357
358
359Object* JSObject::SetLazyProperty(LookupResult* result,
360 String* name,
361 Object* value,
362 PropertyAttributes attributes) {
363 ASSERT(!IsJSGlobalProxy());
364 HandleScope scope;
365 Handle<JSObject> this_handle(this);
366 Handle<String> name_handle(name);
367 Handle<Object> value_handle(value);
368 bool pending_exception;
369 LoadLazy(Handle<JSObject>(JSObject::cast(result->GetLazyValue())),
370 &pending_exception);
371 if (pending_exception) return Failure::Exception();
372 return this_handle->SetProperty(*name_handle, *value_handle, attributes);
373}
374
375
376Object* JSObject::DeleteLazyProperty(LookupResult* result,
377 String* name,
378 DeleteMode mode) {
379 HandleScope scope;
380 Handle<JSObject> this_handle(this);
381 Handle<String> name_handle(name);
382 bool pending_exception;
383 LoadLazy(Handle<JSObject>(JSObject::cast(result->GetLazyValue())),
384 &pending_exception);
385 if (pending_exception) return Failure::Exception();
386 return this_handle->DeleteProperty(*name_handle, mode);
387}
388
389
390Object* JSObject::GetNormalizedProperty(LookupResult* result) {
391 ASSERT(!HasFastProperties());
392 Object* value = property_dictionary()->ValueAt(result->GetDictionaryEntry());
393 if (IsGlobalObject()) {
394 value = JSGlobalPropertyCell::cast(value)->value();
395 }
396 ASSERT(!value->IsJSGlobalPropertyCell());
397 return value;
398}
399
400
401Object* JSObject::SetNormalizedProperty(LookupResult* result, Object* value) {
402 ASSERT(!HasFastProperties());
403 if (IsGlobalObject()) {
404 JSGlobalPropertyCell* cell =
405 JSGlobalPropertyCell::cast(
406 property_dictionary()->ValueAt(result->GetDictionaryEntry()));
407 cell->set_value(value);
408 } else {
409 property_dictionary()->ValueAtPut(result->GetDictionaryEntry(), value);
410 }
411 return value;
412}
413
414
415Object* JSObject::SetNormalizedProperty(String* name,
416 Object* value,
417 PropertyDetails details) {
418 ASSERT(!HasFastProperties());
419 int entry = property_dictionary()->FindEntry(name);
420 if (entry == StringDictionary::kNotFound) {
421 Object* store_value = value;
422 if (IsGlobalObject()) {
423 store_value = Heap::AllocateJSGlobalPropertyCell(value);
424 if (store_value->IsFailure()) return store_value;
425 }
426 Object* dict = property_dictionary()->Add(name, store_value, details);
427 if (dict->IsFailure()) return dict;
428 set_properties(StringDictionary::cast(dict));
429 return value;
430 }
431 // Preserve enumeration index.
432 details = PropertyDetails(details.attributes(),
433 details.type(),
434 property_dictionary()->DetailsAt(entry).index());
435 if (IsGlobalObject()) {
436 JSGlobalPropertyCell* cell =
437 JSGlobalPropertyCell::cast(property_dictionary()->ValueAt(entry));
438 cell->set_value(value);
439 // Please note we have to update the property details.
440 property_dictionary()->DetailsAtPut(entry, details);
441 } else {
442 property_dictionary()->SetEntry(entry, name, value, details);
443 }
444 return value;
445}
446
447
448Object* JSObject::DeleteNormalizedProperty(String* name, DeleteMode mode) {
449 ASSERT(!HasFastProperties());
450 StringDictionary* dictionary = property_dictionary();
451 int entry = dictionary->FindEntry(name);
452 if (entry != StringDictionary::kNotFound) {
453 // If we have a global object set the cell to the hole.
454 if (IsGlobalObject()) {
455 PropertyDetails details = dictionary->DetailsAt(entry);
456 if (details.IsDontDelete()) {
457 if (mode != FORCE_DELETION) return Heap::false_value();
458 // When forced to delete global properties, we have to make a
459 // map change to invalidate any ICs that think they can load
460 // from the DontDelete cell without checking if it contains
461 // the hole value.
462 Object* new_map = map()->CopyDropDescriptors();
463 if (new_map->IsFailure()) return new_map;
464 set_map(Map::cast(new_map));
465 }
466 JSGlobalPropertyCell* cell =
467 JSGlobalPropertyCell::cast(dictionary->ValueAt(entry));
468 cell->set_value(Heap::the_hole_value());
469 dictionary->DetailsAtPut(entry, details.AsDeleted());
470 } else {
471 return dictionary->DeleteProperty(entry, mode);
472 }
473 }
474 return Heap::true_value();
475}
476
477
478bool JSObject::IsDirty() {
479 Object* cons_obj = map()->constructor();
480 if (!cons_obj->IsJSFunction())
481 return true;
482 JSFunction* fun = JSFunction::cast(cons_obj);
483 if (!fun->shared()->function_data()->IsFunctionTemplateInfo())
484 return true;
485 // If the object is fully fast case and has the same map it was
486 // created with then no changes can have been made to it.
487 return map() != fun->initial_map()
488 || !HasFastElements()
489 || !HasFastProperties();
490}
491
492
493Object* Object::GetProperty(Object* receiver,
494 LookupResult* result,
495 String* name,
496 PropertyAttributes* attributes) {
497 // Make sure that the top context does not change when doing
498 // callbacks or interceptor calls.
499 AssertNoContextChange ncc;
500
501 // Traverse the prototype chain from the current object (this) to
502 // the holder and check for access rights. This avoid traversing the
503 // objects more than once in case of interceptors, because the
504 // holder will always be the interceptor holder and the search may
505 // only continue with a current object just after the interceptor
506 // holder in the prototype chain.
507 Object* last = result->IsValid() ? result->holder() : Heap::null_value();
508 for (Object* current = this; true; current = current->GetPrototype()) {
509 if (current->IsAccessCheckNeeded()) {
510 // Check if we're allowed to read from the current object. Note
511 // that even though we may not actually end up loading the named
512 // property from the current object, we still check that we have
513 // access to it.
514 JSObject* checked = JSObject::cast(current);
515 if (!Top::MayNamedAccess(checked, name, v8::ACCESS_GET)) {
516 return checked->GetPropertyWithFailedAccessCheck(receiver,
517 result,
518 name,
519 attributes);
520 }
521 }
522 // Stop traversing the chain once we reach the last object in the
523 // chain; either the holder of the result or null in case of an
524 // absent property.
525 if (current == last) break;
526 }
527
528 if (!result->IsProperty()) {
529 *attributes = ABSENT;
530 return Heap::undefined_value();
531 }
532 *attributes = result->GetAttributes();
533 if (!result->IsLoaded()) {
534 return JSObject::cast(this)->GetLazyProperty(receiver,
535 result,
536 name,
537 attributes);
538 }
539 Object* value;
540 JSObject* holder = result->holder();
541 switch (result->type()) {
542 case NORMAL:
543 value = holder->GetNormalizedProperty(result);
544 ASSERT(!value->IsTheHole() || result->IsReadOnly());
545 return value->IsTheHole() ? Heap::undefined_value() : value;
546 case FIELD:
547 value = holder->FastPropertyAt(result->GetFieldIndex());
548 ASSERT(!value->IsTheHole() || result->IsReadOnly());
549 return value->IsTheHole() ? Heap::undefined_value() : value;
550 case CONSTANT_FUNCTION:
551 return result->GetConstantFunction();
552 case CALLBACKS:
553 return GetPropertyWithCallback(receiver,
554 result->GetCallbackObject(),
555 name,
556 holder);
557 case INTERCEPTOR: {
558 JSObject* recvr = JSObject::cast(receiver);
559 return holder->GetPropertyWithInterceptor(recvr, name, attributes);
560 }
561 default:
562 UNREACHABLE();
563 return NULL;
564 }
565}
566
567
568Object* Object::GetElementWithReceiver(Object* receiver, uint32_t index) {
569 // Non-JS objects do not have integer indexed properties.
570 if (!IsJSObject()) return Heap::undefined_value();
571 return JSObject::cast(this)->GetElementWithReceiver(JSObject::cast(receiver),
572 index);
573}
574
575
576Object* Object::GetPrototype() {
577 // The object is either a number, a string, a boolean, or a real JS object.
578 if (IsJSObject()) return JSObject::cast(this)->map()->prototype();
579 Context* context = Top::context()->global_context();
580
581 if (IsNumber()) return context->number_function()->instance_prototype();
582 if (IsString()) return context->string_function()->instance_prototype();
583 if (IsBoolean()) {
584 return context->boolean_function()->instance_prototype();
585 } else {
586 return Heap::null_value();
587 }
588}
589
590
591void Object::ShortPrint() {
592 HeapStringAllocator allocator;
593 StringStream accumulator(&allocator);
594 ShortPrint(&accumulator);
595 accumulator.OutputToStdOut();
596}
597
598
599void Object::ShortPrint(StringStream* accumulator) {
600 if (IsSmi()) {
601 Smi::cast(this)->SmiPrint(accumulator);
602 } else if (IsFailure()) {
603 Failure::cast(this)->FailurePrint(accumulator);
604 } else {
605 HeapObject::cast(this)->HeapObjectShortPrint(accumulator);
606 }
607}
608
609
610void Smi::SmiPrint() {
611 PrintF("%d", value());
612}
613
614
615void Smi::SmiPrint(StringStream* accumulator) {
616 accumulator->Add("%d", value());
617}
618
619
620void Failure::FailurePrint(StringStream* accumulator) {
621 accumulator->Add("Failure(%d)", value());
622}
623
624
625void Failure::FailurePrint() {
626 PrintF("Failure(%d)", value());
627}
628
629
630Failure* Failure::RetryAfterGC(int requested_bytes, AllocationSpace space) {
631 ASSERT((space & ~kSpaceTagMask) == 0);
632 // TODO(X64): Stop using Smi validation for non-smi checks, even if they
633 // happen to be identical at the moment.
634
635 int requested = requested_bytes >> kObjectAlignmentBits;
636 int value = (requested << kSpaceTagSize) | space;
637 // We can't very well allocate a heap number in this situation, and if the
638 // requested memory is so large it seems reasonable to say that this is an
639 // out of memory situation. This fixes a crash in
640 // js1_5/Regress/regress-303213.js.
641 if (value >> kSpaceTagSize != requested ||
642 !Smi::IsValid(value) ||
643 value != ((value << kFailureTypeTagSize) >> kFailureTypeTagSize) ||
644 !Smi::IsValid(value << kFailureTypeTagSize)) {
645 Top::context()->mark_out_of_memory();
646 return Failure::OutOfMemoryException();
647 }
648 return Construct(RETRY_AFTER_GC, value);
649}
650
651
652// Should a word be prefixed by 'a' or 'an' in order to read naturally in
653// English? Returns false for non-ASCII or words that don't start with
654// a capital letter. The a/an rule follows pronunciation in English.
655// We don't use the BBC's overcorrect "an historic occasion" though if
656// you speak a dialect you may well say "an 'istoric occasion".
657static bool AnWord(String* str) {
658 if (str->length() == 0) return false; // A nothing.
659 int c0 = str->Get(0);
660 int c1 = str->length() > 1 ? str->Get(1) : 0;
661 if (c0 == 'U') {
662 if (c1 > 'Z') {
663 return true; // An Umpire, but a UTF8String, a U.
664 }
665 } else if (c0 == 'A' || c0 == 'E' || c0 == 'I' || c0 == 'O') {
666 return true; // An Ape, an ABCBook.
667 } else if ((c1 == 0 || (c1 >= 'A' && c1 <= 'Z')) &&
668 (c0 == 'F' || c0 == 'H' || c0 == 'M' || c0 == 'N' || c0 == 'R' ||
669 c0 == 'S' || c0 == 'X')) {
670 return true; // An MP3File, an M.
671 }
672 return false;
673}
674
675
676Object* String::TryFlatten() {
677#ifdef DEBUG
678 // Do not attempt to flatten in debug mode when allocation is not
679 // allowed. This is to avoid an assertion failure when allocating.
680 // Flattening strings is the only case where we always allow
681 // allocation because no GC is performed if the allocation fails.
682 if (!Heap::IsAllocationAllowed()) return this;
683#endif
684
685 switch (StringShape(this).representation_tag()) {
686 case kSlicedStringTag: {
687 SlicedString* ss = SlicedString::cast(this);
688 // The SlicedString constructor should ensure that there are no
689 // SlicedStrings that are constructed directly on top of other
690 // SlicedStrings.
691 String* buf = ss->buffer();
692 ASSERT(!buf->IsSlicedString());
693 Object* ok = buf->TryFlatten();
694 if (ok->IsFailure()) return ok;
695 // Under certain circumstances (TryFlattenIfNotFlat fails in
696 // String::Slice) we can have a cons string under a slice.
697 // In this case we need to get the flat string out of the cons!
698 if (StringShape(String::cast(ok)).IsCons()) {
699 ss->set_buffer(ConsString::cast(ok)->first());
700 }
701 return this;
702 }
703 case kConsStringTag: {
704 ConsString* cs = ConsString::cast(this);
705 if (cs->second()->length() == 0) {
706 return this;
707 }
708 // There's little point in putting the flat string in new space if the
709 // cons string is in old space. It can never get GCed until there is
710 // an old space GC.
711 PretenureFlag tenure = Heap::InNewSpace(this) ? NOT_TENURED : TENURED;
712 int len = length();
713 Object* object;
714 String* result;
715 if (IsAsciiRepresentation()) {
716 object = Heap::AllocateRawAsciiString(len, tenure);
717 if (object->IsFailure()) return object;
718 result = String::cast(object);
719 String* first = cs->first();
720 int first_length = first->length();
721 char* dest = SeqAsciiString::cast(result)->GetChars();
722 WriteToFlat(first, dest, 0, first_length);
723 String* second = cs->second();
724 WriteToFlat(second,
725 dest + first_length,
726 0,
727 len - first_length);
728 } else {
729 object = Heap::AllocateRawTwoByteString(len, tenure);
730 if (object->IsFailure()) return object;
731 result = String::cast(object);
732 uc16* dest = SeqTwoByteString::cast(result)->GetChars();
733 String* first = cs->first();
734 int first_length = first->length();
735 WriteToFlat(first, dest, 0, first_length);
736 String* second = cs->second();
737 WriteToFlat(second,
738 dest + first_length,
739 0,
740 len - first_length);
741 }
742 cs->set_first(result);
743 cs->set_second(Heap::empty_string());
744 return this;
745 }
746 default:
747 return this;
748 }
749}
750
751
752bool String::MakeExternal(v8::String::ExternalStringResource* resource) {
753#ifdef DEBUG
754 { // NOLINT (presubmit.py gets confused about if and braces)
755 // Assert that the resource and the string are equivalent.
756 ASSERT(static_cast<size_t>(this->length()) == resource->length());
757 SmartPointer<uc16> smart_chars = this->ToWideCString();
758 ASSERT(memcmp(*smart_chars,
759 resource->data(),
760 resource->length() * sizeof(**smart_chars)) == 0);
761 }
762#endif // DEBUG
763
764 int size = this->Size(); // Byte size of the original string.
765 if (size < ExternalString::kSize) {
766 // The string is too small to fit an external String in its place. This can
767 // only happen for zero length strings.
768 return false;
769 }
770 ASSERT(size >= ExternalString::kSize);
771 bool is_symbol = this->IsSymbol();
772 int length = this->length();
773
774 // Morph the object to an external string by adjusting the map and
775 // reinitializing the fields.
776 this->set_map(ExternalTwoByteString::StringMap(length));
777 ExternalTwoByteString* self = ExternalTwoByteString::cast(this);
778 self->set_length(length);
779 self->set_resource(resource);
780 // Additionally make the object into an external symbol if the original string
781 // was a symbol to start with.
782 if (is_symbol) {
783 self->Hash(); // Force regeneration of the hash value.
784 // Now morph this external string into a external symbol.
785 self->set_map(ExternalTwoByteString::SymbolMap(length));
786 }
787
788 // Fill the remainder of the string with dead wood.
789 int new_size = this->Size(); // Byte size of the external String object.
790 Heap::CreateFillerObjectAt(this->address() + new_size, size - new_size);
791 return true;
792}
793
794
795bool String::MakeExternal(v8::String::ExternalAsciiStringResource* resource) {
796#ifdef DEBUG
797 { // NOLINT (presubmit.py gets confused about if and braces)
798 // Assert that the resource and the string are equivalent.
799 ASSERT(static_cast<size_t>(this->length()) == resource->length());
800 SmartPointer<char> smart_chars = this->ToCString();
801 ASSERT(memcmp(*smart_chars,
802 resource->data(),
803 resource->length()*sizeof(**smart_chars)) == 0);
804 }
805#endif // DEBUG
806
807 int size = this->Size(); // Byte size of the original string.
808 if (size < ExternalString::kSize) {
809 // The string is too small to fit an external String in its place. This can
810 // only happen for zero length strings.
811 return false;
812 }
813 ASSERT(size >= ExternalString::kSize);
814 bool is_symbol = this->IsSymbol();
815 int length = this->length();
816
817 // Morph the object to an external string by adjusting the map and
818 // reinitializing the fields.
819 this->set_map(ExternalAsciiString::StringMap(length));
820 ExternalAsciiString* self = ExternalAsciiString::cast(this);
821 self->set_length(length);
822 self->set_resource(resource);
823 // Additionally make the object into an external symbol if the original string
824 // was a symbol to start with.
825 if (is_symbol) {
826 self->Hash(); // Force regeneration of the hash value.
827 // Now morph this external string into a external symbol.
828 self->set_map(ExternalAsciiString::SymbolMap(length));
829 }
830
831 // Fill the remainder of the string with dead wood.
832 int new_size = this->Size(); // Byte size of the external String object.
833 Heap::CreateFillerObjectAt(this->address() + new_size, size - new_size);
834 return true;
835}
836
837
838void String::StringShortPrint(StringStream* accumulator) {
839 int len = length();
840 if (len > kMaxMediumStringSize) {
841 accumulator->Add("<Very long string[%u]>", len);
842 return;
843 }
844
845 if (!LooksValid()) {
846 accumulator->Add("<Invalid String>");
847 return;
848 }
849
850 StringInputBuffer buf(this);
851
852 bool truncated = false;
853 if (len > kMaxShortPrintLength) {
854 len = kMaxShortPrintLength;
855 truncated = true;
856 }
857 bool ascii = true;
858 for (int i = 0; i < len; i++) {
859 int c = buf.GetNext();
860
861 if (c < 32 || c >= 127) {
862 ascii = false;
863 }
864 }
865 buf.Reset(this);
866 if (ascii) {
867 accumulator->Add("<String[%u]: ", length());
868 for (int i = 0; i < len; i++) {
869 accumulator->Put(buf.GetNext());
870 }
871 accumulator->Put('>');
872 } else {
873 // Backslash indicates that the string contains control
874 // characters and that backslashes are therefore escaped.
875 accumulator->Add("<String[%u]\\: ", length());
876 for (int i = 0; i < len; i++) {
877 int c = buf.GetNext();
878 if (c == '\n') {
879 accumulator->Add("\\n");
880 } else if (c == '\r') {
881 accumulator->Add("\\r");
882 } else if (c == '\\') {
883 accumulator->Add("\\\\");
884 } else if (c < 32 || c > 126) {
885 accumulator->Add("\\x%02x", c);
886 } else {
887 accumulator->Put(c);
888 }
889 }
890 if (truncated) {
891 accumulator->Put('.');
892 accumulator->Put('.');
893 accumulator->Put('.');
894 }
895 accumulator->Put('>');
896 }
897 return;
898}
899
900
901void JSObject::JSObjectShortPrint(StringStream* accumulator) {
902 switch (map()->instance_type()) {
903 case JS_ARRAY_TYPE: {
904 double length = JSArray::cast(this)->length()->Number();
905 accumulator->Add("<JS array[%u]>", static_cast<uint32_t>(length));
906 break;
907 }
908 case JS_REGEXP_TYPE: {
909 accumulator->Add("<JS RegExp>");
910 break;
911 }
912 case JS_FUNCTION_TYPE: {
913 Object* fun_name = JSFunction::cast(this)->shared()->name();
914 bool printed = false;
915 if (fun_name->IsString()) {
916 String* str = String::cast(fun_name);
917 if (str->length() > 0) {
918 accumulator->Add("<JS Function ");
919 accumulator->Put(str);
920 accumulator->Put('>');
921 printed = true;
922 }
923 }
924 if (!printed) {
925 accumulator->Add("<JS Function>");
926 }
927 break;
928 }
929 // All other JSObjects are rather similar to each other (JSObject,
930 // JSGlobalProxy, JSGlobalObject, JSUndetectableObject, JSValue).
931 default: {
932 Object* constructor = map()->constructor();
933 bool printed = false;
934 if (constructor->IsHeapObject() &&
935 !Heap::Contains(HeapObject::cast(constructor))) {
936 accumulator->Add("!!!INVALID CONSTRUCTOR!!!");
937 } else {
938 bool global_object = IsJSGlobalProxy();
939 if (constructor->IsJSFunction()) {
940 if (!Heap::Contains(JSFunction::cast(constructor)->shared())) {
941 accumulator->Add("!!!INVALID SHARED ON CONSTRUCTOR!!!");
942 } else {
943 Object* constructor_name =
944 JSFunction::cast(constructor)->shared()->name();
945 if (constructor_name->IsString()) {
946 String* str = String::cast(constructor_name);
947 if (str->length() > 0) {
948 bool vowel = AnWord(str);
949 accumulator->Add("<%sa%s ",
950 global_object ? "Global Object: " : "",
951 vowel ? "n" : "");
952 accumulator->Put(str);
953 accumulator->Put('>');
954 printed = true;
955 }
956 }
957 }
958 }
959 if (!printed) {
960 accumulator->Add("<JS %sObject", global_object ? "Global " : "");
961 }
962 }
963 if (IsJSValue()) {
964 accumulator->Add(" value = ");
965 JSValue::cast(this)->value()->ShortPrint(accumulator);
966 }
967 accumulator->Put('>');
968 break;
969 }
970 }
971}
972
973
974void HeapObject::HeapObjectShortPrint(StringStream* accumulator) {
975 // if (!Heap::InNewSpace(this)) PrintF("*", this);
976 if (!Heap::Contains(this)) {
977 accumulator->Add("!!!INVALID POINTER!!!");
978 return;
979 }
980 if (!Heap::Contains(map())) {
981 accumulator->Add("!!!INVALID MAP!!!");
982 return;
983 }
984
985 accumulator->Add("%p ", this);
986
987 if (IsString()) {
988 String::cast(this)->StringShortPrint(accumulator);
989 return;
990 }
991 if (IsJSObject()) {
992 JSObject::cast(this)->JSObjectShortPrint(accumulator);
993 return;
994 }
995 switch (map()->instance_type()) {
996 case MAP_TYPE:
997 accumulator->Add("<Map>");
998 break;
999 case FIXED_ARRAY_TYPE:
1000 accumulator->Add("<FixedArray[%u]>", FixedArray::cast(this)->length());
1001 break;
1002 case BYTE_ARRAY_TYPE:
1003 accumulator->Add("<ByteArray[%u]>", ByteArray::cast(this)->length());
1004 break;
1005 case PIXEL_ARRAY_TYPE:
1006 accumulator->Add("<PixelArray[%u]>", PixelArray::cast(this)->length());
1007 break;
1008 case SHARED_FUNCTION_INFO_TYPE:
1009 accumulator->Add("<SharedFunctionInfo>");
1010 break;
1011#define MAKE_STRUCT_CASE(NAME, Name, name) \
1012 case NAME##_TYPE: \
1013 accumulator->Put('<'); \
1014 accumulator->Add(#Name); \
1015 accumulator->Put('>'); \
1016 break;
1017 STRUCT_LIST(MAKE_STRUCT_CASE)
1018#undef MAKE_STRUCT_CASE
1019 case CODE_TYPE:
1020 accumulator->Add("<Code>");
1021 break;
1022 case ODDBALL_TYPE: {
1023 if (IsUndefined())
1024 accumulator->Add("<undefined>");
1025 else if (IsTheHole())
1026 accumulator->Add("<the hole>");
1027 else if (IsNull())
1028 accumulator->Add("<null>");
1029 else if (IsTrue())
1030 accumulator->Add("<true>");
1031 else if (IsFalse())
1032 accumulator->Add("<false>");
1033 else
1034 accumulator->Add("<Odd Oddball>");
1035 break;
1036 }
1037 case HEAP_NUMBER_TYPE:
1038 accumulator->Add("<Number: ");
1039 HeapNumber::cast(this)->HeapNumberPrint(accumulator);
1040 accumulator->Put('>');
1041 break;
1042 case PROXY_TYPE:
1043 accumulator->Add("<Proxy>");
1044 break;
1045 case JS_GLOBAL_PROPERTY_CELL_TYPE:
1046 accumulator->Add("Cell for ");
1047 JSGlobalPropertyCell::cast(this)->value()->ShortPrint(accumulator);
1048 break;
1049 default:
1050 accumulator->Add("<Other heap object (%d)>", map()->instance_type());
1051 break;
1052 }
1053}
1054
1055
1056int HeapObject::SlowSizeFromMap(Map* map) {
1057 // Avoid calling functions such as FixedArray::cast during GC, which
1058 // read map pointer of this object again.
1059 InstanceType instance_type = map->instance_type();
1060 uint32_t type = static_cast<uint32_t>(instance_type);
1061
1062 if (instance_type < FIRST_NONSTRING_TYPE
1063 && (StringShape(instance_type).IsSequential())) {
1064 if ((type & kStringEncodingMask) == kAsciiStringTag) {
1065 SeqAsciiString* seq_ascii_this = reinterpret_cast<SeqAsciiString*>(this);
1066 return seq_ascii_this->SeqAsciiStringSize(instance_type);
1067 } else {
1068 SeqTwoByteString* self = reinterpret_cast<SeqTwoByteString*>(this);
1069 return self->SeqTwoByteStringSize(instance_type);
1070 }
1071 }
1072
1073 switch (instance_type) {
1074 case FIXED_ARRAY_TYPE:
1075 return reinterpret_cast<FixedArray*>(this)->FixedArraySize();
1076 case BYTE_ARRAY_TYPE:
1077 return reinterpret_cast<ByteArray*>(this)->ByteArraySize();
1078 case CODE_TYPE:
1079 return reinterpret_cast<Code*>(this)->CodeSize();
1080 case MAP_TYPE:
1081 return Map::kSize;
1082 default:
1083 return map->instance_size();
1084 }
1085}
1086
1087
1088void HeapObject::Iterate(ObjectVisitor* v) {
1089 // Handle header
1090 IteratePointer(v, kMapOffset);
1091 // Handle object body
1092 Map* m = map();
1093 IterateBody(m->instance_type(), SizeFromMap(m), v);
1094}
1095
1096
1097void HeapObject::IterateBody(InstanceType type, int object_size,
1098 ObjectVisitor* v) {
1099 // Avoiding <Type>::cast(this) because it accesses the map pointer field.
1100 // During GC, the map pointer field is encoded.
1101 if (type < FIRST_NONSTRING_TYPE) {
1102 switch (type & kStringRepresentationMask) {
1103 case kSeqStringTag:
1104 break;
1105 case kConsStringTag:
1106 reinterpret_cast<ConsString*>(this)->ConsStringIterateBody(v);
1107 break;
1108 case kSlicedStringTag:
1109 reinterpret_cast<SlicedString*>(this)->SlicedStringIterateBody(v);
1110 break;
1111 }
1112 return;
1113 }
1114
1115 switch (type) {
1116 case FIXED_ARRAY_TYPE:
1117 reinterpret_cast<FixedArray*>(this)->FixedArrayIterateBody(v);
1118 break;
1119 case JS_OBJECT_TYPE:
1120 case JS_CONTEXT_EXTENSION_OBJECT_TYPE:
1121 case JS_VALUE_TYPE:
1122 case JS_ARRAY_TYPE:
1123 case JS_REGEXP_TYPE:
1124 case JS_FUNCTION_TYPE:
1125 case JS_GLOBAL_PROXY_TYPE:
1126 case JS_GLOBAL_OBJECT_TYPE:
1127 case JS_BUILTINS_OBJECT_TYPE:
1128 reinterpret_cast<JSObject*>(this)->JSObjectIterateBody(object_size, v);
1129 break;
1130 case ODDBALL_TYPE:
1131 reinterpret_cast<Oddball*>(this)->OddballIterateBody(v);
1132 break;
1133 case PROXY_TYPE:
1134 reinterpret_cast<Proxy*>(this)->ProxyIterateBody(v);
1135 break;
1136 case MAP_TYPE:
1137 reinterpret_cast<Map*>(this)->MapIterateBody(v);
1138 break;
1139 case CODE_TYPE:
1140 reinterpret_cast<Code*>(this)->CodeIterateBody(v);
1141 break;
1142 case JS_GLOBAL_PROPERTY_CELL_TYPE:
1143 reinterpret_cast<JSGlobalPropertyCell*>(this)
1144 ->JSGlobalPropertyCellIterateBody(v);
1145 break;
1146 case HEAP_NUMBER_TYPE:
1147 case FILLER_TYPE:
1148 case BYTE_ARRAY_TYPE:
1149 case PIXEL_ARRAY_TYPE:
1150 break;
1151 case SHARED_FUNCTION_INFO_TYPE: {
1152 SharedFunctionInfo* shared = reinterpret_cast<SharedFunctionInfo*>(this);
1153 shared->SharedFunctionInfoIterateBody(v);
1154 break;
1155 }
1156#define MAKE_STRUCT_CASE(NAME, Name, name) \
1157 case NAME##_TYPE:
1158 STRUCT_LIST(MAKE_STRUCT_CASE)
1159#undef MAKE_STRUCT_CASE
1160 IterateStructBody(object_size, v);
1161 break;
1162 default:
1163 PrintF("Unknown type: %d\n", type);
1164 UNREACHABLE();
1165 }
1166}
1167
1168
1169void HeapObject::IterateStructBody(int object_size, ObjectVisitor* v) {
1170 IteratePointers(v, HeapObject::kHeaderSize, object_size);
1171}
1172
1173
1174Object* HeapNumber::HeapNumberToBoolean() {
1175 // NaN, +0, and -0 should return the false object
1176 switch (fpclassify(value())) {
1177 case FP_NAN: // fall through
1178 case FP_ZERO: return Heap::false_value();
1179 default: return Heap::true_value();
1180 }
1181}
1182
1183
1184void HeapNumber::HeapNumberPrint() {
1185 PrintF("%.16g", Number());
1186}
1187
1188
1189void HeapNumber::HeapNumberPrint(StringStream* accumulator) {
1190 // The Windows version of vsnprintf can allocate when printing a %g string
1191 // into a buffer that may not be big enough. We don't want random memory
1192 // allocation when producing post-crash stack traces, so we print into a
1193 // buffer that is plenty big enough for any floating point number, then
1194 // print that using vsnprintf (which may truncate but never allocate if
1195 // there is no more space in the buffer).
1196 EmbeddedVector<char, 100> buffer;
1197 OS::SNPrintF(buffer, "%.16g", Number());
1198 accumulator->Add("%s", buffer.start());
1199}
1200
1201
1202String* JSObject::class_name() {
1203 if (IsJSFunction()) {
1204 return Heap::function_class_symbol();
1205 }
1206 if (map()->constructor()->IsJSFunction()) {
1207 JSFunction* constructor = JSFunction::cast(map()->constructor());
1208 return String::cast(constructor->shared()->instance_class_name());
1209 }
1210 // If the constructor is not present, return "Object".
1211 return Heap::Object_symbol();
1212}
1213
1214
1215String* JSObject::constructor_name() {
1216 if (IsJSFunction()) {
1217 return Heap::function_class_symbol();
1218 }
1219 if (map()->constructor()->IsJSFunction()) {
1220 JSFunction* constructor = JSFunction::cast(map()->constructor());
1221 String* name = String::cast(constructor->shared()->name());
1222 return name->length() > 0 ? name : constructor->shared()->inferred_name();
1223 }
1224 // If the constructor is not present, return "Object".
1225 return Heap::Object_symbol();
1226}
1227
1228
1229void JSObject::JSObjectIterateBody(int object_size, ObjectVisitor* v) {
1230 // Iterate over all fields in the body. Assumes all are Object*.
1231 IteratePointers(v, kPropertiesOffset, object_size);
1232}
1233
1234
1235Object* JSObject::AddFastPropertyUsingMap(Map* new_map,
1236 String* name,
1237 Object* value) {
1238 int index = new_map->PropertyIndexFor(name);
1239 if (map()->unused_property_fields() == 0) {
1240 ASSERT(map()->unused_property_fields() == 0);
1241 int new_unused = new_map->unused_property_fields();
1242 Object* values =
1243 properties()->CopySize(properties()->length() + new_unused + 1);
1244 if (values->IsFailure()) return values;
1245 set_properties(FixedArray::cast(values));
1246 }
1247 set_map(new_map);
1248 return FastPropertyAtPut(index, value);
1249}
1250
1251
1252Object* JSObject::AddFastProperty(String* name,
1253 Object* value,
1254 PropertyAttributes attributes) {
1255 // Normalize the object if the name is an actual string (not the
1256 // hidden symbols) and is not a real identifier.
1257 StringInputBuffer buffer(name);
1258 if (!Scanner::IsIdentifier(&buffer) && name != Heap::hidden_symbol()) {
1259 Object* obj = NormalizeProperties(CLEAR_INOBJECT_PROPERTIES, 0);
1260 if (obj->IsFailure()) return obj;
1261 return AddSlowProperty(name, value, attributes);
1262 }
1263
1264 DescriptorArray* old_descriptors = map()->instance_descriptors();
1265 // Compute the new index for new field.
1266 int index = map()->NextFreePropertyIndex();
1267
1268 // Allocate new instance descriptors with (name, index) added
1269 FieldDescriptor new_field(name, index, attributes);
1270 Object* new_descriptors =
1271 old_descriptors->CopyInsert(&new_field, REMOVE_TRANSITIONS);
1272 if (new_descriptors->IsFailure()) return new_descriptors;
1273
1274 // Only allow map transition if the object's map is NOT equal to the
1275 // global object_function's map and there is not a transition for name.
1276 bool allow_map_transition =
1277 !old_descriptors->Contains(name) &&
1278 (Top::context()->global_context()->object_function()->map() != map());
1279
1280 ASSERT(index < map()->inobject_properties() ||
1281 (index - map()->inobject_properties()) < properties()->length() ||
1282 map()->unused_property_fields() == 0);
1283 // Allocate a new map for the object.
1284 Object* r = map()->CopyDropDescriptors();
1285 if (r->IsFailure()) return r;
1286 Map* new_map = Map::cast(r);
1287 if (allow_map_transition) {
1288 // Allocate new instance descriptors for the old map with map transition.
1289 MapTransitionDescriptor d(name, Map::cast(new_map), attributes);
1290 Object* r = old_descriptors->CopyInsert(&d, KEEP_TRANSITIONS);
1291 if (r->IsFailure()) return r;
1292 old_descriptors = DescriptorArray::cast(r);
1293 }
1294
1295 if (map()->unused_property_fields() == 0) {
1296 if (properties()->length() > kMaxFastProperties) {
1297 Object* obj = NormalizeProperties(CLEAR_INOBJECT_PROPERTIES, 0);
1298 if (obj->IsFailure()) return obj;
1299 return AddSlowProperty(name, value, attributes);
1300 }
1301 // Make room for the new value
1302 Object* values =
1303 properties()->CopySize(properties()->length() + kFieldsAdded);
1304 if (values->IsFailure()) return values;
1305 set_properties(FixedArray::cast(values));
1306 new_map->set_unused_property_fields(kFieldsAdded - 1);
1307 } else {
1308 new_map->set_unused_property_fields(map()->unused_property_fields() - 1);
1309 }
1310 // We have now allocated all the necessary objects.
1311 // All the changes can be applied at once, so they are atomic.
1312 map()->set_instance_descriptors(old_descriptors);
1313 new_map->set_instance_descriptors(DescriptorArray::cast(new_descriptors));
1314 set_map(new_map);
1315 return FastPropertyAtPut(index, value);
1316}
1317
1318
1319Object* JSObject::AddConstantFunctionProperty(String* name,
1320 JSFunction* function,
1321 PropertyAttributes attributes) {
1322 // Allocate new instance descriptors with (name, function) added
1323 ConstantFunctionDescriptor d(name, function, attributes);
1324 Object* new_descriptors =
1325 map()->instance_descriptors()->CopyInsert(&d, REMOVE_TRANSITIONS);
1326 if (new_descriptors->IsFailure()) return new_descriptors;
1327
1328 // Allocate a new map for the object.
1329 Object* new_map = map()->CopyDropDescriptors();
1330 if (new_map->IsFailure()) return new_map;
1331
1332 DescriptorArray* descriptors = DescriptorArray::cast(new_descriptors);
1333 Map::cast(new_map)->set_instance_descriptors(descriptors);
1334 Map* old_map = map();
1335 set_map(Map::cast(new_map));
1336
1337 // If the old map is the global object map (from new Object()),
1338 // then transitions are not added to it, so we are done.
1339 if (old_map == Top::context()->global_context()->object_function()->map()) {
1340 return function;
1341 }
1342
1343 // Do not add CONSTANT_TRANSITIONS to global objects
1344 if (IsGlobalObject()) {
1345 return function;
1346 }
1347
1348 // Add a CONSTANT_TRANSITION descriptor to the old map,
1349 // so future assignments to this property on other objects
1350 // of the same type will create a normal field, not a constant function.
1351 // Don't do this for special properties, with non-trival attributes.
1352 if (attributes != NONE) {
1353 return function;
1354 }
1355 ConstTransitionDescriptor mark(name);
1356 new_descriptors =
1357 old_map->instance_descriptors()->CopyInsert(&mark, KEEP_TRANSITIONS);
1358 if (new_descriptors->IsFailure()) {
1359 return function; // We have accomplished the main goal, so return success.
1360 }
1361 old_map->set_instance_descriptors(DescriptorArray::cast(new_descriptors));
1362
1363 return function;
1364}
1365
1366
1367// Add property in slow mode
1368Object* JSObject::AddSlowProperty(String* name,
1369 Object* value,
1370 PropertyAttributes attributes) {
1371 ASSERT(!HasFastProperties());
1372 StringDictionary* dict = property_dictionary();
1373 Object* store_value = value;
1374 if (IsGlobalObject()) {
1375 // In case name is an orphaned property reuse the cell.
1376 int entry = dict->FindEntry(name);
1377 if (entry != StringDictionary::kNotFound) {
1378 store_value = dict->ValueAt(entry);
1379 JSGlobalPropertyCell::cast(store_value)->set_value(value);
1380 // Assign an enumeration index to the property and update
1381 // SetNextEnumerationIndex.
1382 int index = dict->NextEnumerationIndex();
1383 PropertyDetails details = PropertyDetails(attributes, NORMAL, index);
1384 dict->SetNextEnumerationIndex(index + 1);
1385 dict->SetEntry(entry, name, store_value, details);
1386 return value;
1387 }
1388 store_value = Heap::AllocateJSGlobalPropertyCell(value);
1389 if (store_value->IsFailure()) return store_value;
1390 JSGlobalPropertyCell::cast(store_value)->set_value(value);
1391 }
1392 PropertyDetails details = PropertyDetails(attributes, NORMAL);
1393 Object* result = dict->Add(name, store_value, details);
1394 if (result->IsFailure()) return result;
1395 if (dict != result) set_properties(StringDictionary::cast(result));
1396 return value;
1397}
1398
1399
1400Object* JSObject::AddProperty(String* name,
1401 Object* value,
1402 PropertyAttributes attributes) {
1403 ASSERT(!IsJSGlobalProxy());
1404 if (HasFastProperties()) {
1405 // Ensure the descriptor array does not get too big.
1406 if (map()->instance_descriptors()->number_of_descriptors() <
1407 DescriptorArray::kMaxNumberOfDescriptors) {
1408 if (value->IsJSFunction()) {
1409 return AddConstantFunctionProperty(name,
1410 JSFunction::cast(value),
1411 attributes);
1412 } else {
1413 return AddFastProperty(name, value, attributes);
1414 }
1415 } else {
1416 // Normalize the object to prevent very large instance descriptors.
1417 // This eliminates unwanted N^2 allocation and lookup behavior.
1418 Object* obj = NormalizeProperties(CLEAR_INOBJECT_PROPERTIES, 0);
1419 if (obj->IsFailure()) return obj;
1420 }
1421 }
1422 return AddSlowProperty(name, value, attributes);
1423}
1424
1425
1426Object* JSObject::SetPropertyPostInterceptor(String* name,
1427 Object* value,
1428 PropertyAttributes attributes) {
1429 // Check local property, ignore interceptor.
1430 LookupResult result;
1431 LocalLookupRealNamedProperty(name, &result);
1432 if (result.IsValid()) return SetProperty(&result, name, value, attributes);
1433 // Add real property.
1434 return AddProperty(name, value, attributes);
1435}
1436
1437
1438Object* JSObject::ReplaceSlowProperty(String* name,
1439 Object* value,
1440 PropertyAttributes attributes) {
1441 StringDictionary* dictionary = property_dictionary();
1442 int old_index = dictionary->FindEntry(name);
1443 int new_enumeration_index = 0; // 0 means "Use the next available index."
1444 if (old_index != -1) {
1445 // All calls to ReplaceSlowProperty have had all transitions removed.
1446 ASSERT(!dictionary->DetailsAt(old_index).IsTransition());
1447 new_enumeration_index = dictionary->DetailsAt(old_index).index();
1448 }
1449
1450 PropertyDetails new_details(attributes, NORMAL, new_enumeration_index);
1451 return SetNormalizedProperty(name, value, new_details);
1452}
1453
1454Object* 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 &&
1487 properties()->length() > kMaxFastProperties) {
1488 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();
1634 return 0;
1635}
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);
1664 if (result->IsValid()) {
1665 if (!result->IsTransitionType() && result->IsReadOnly()) {
1666 result->NotFound();
1667 return;
1668 }
1669 if (result->type() == CALLBACKS) {
1670 return;
1671 }
1672 }
1673 }
1674 result->NotFound();
1675}
1676
1677
1678Object* JSObject::LookupCallbackSetterInPrototypes(uint32_t index) {
1679 for (Object* pt = GetPrototype();
1680 pt != Heap::null_value();
1681 pt = pt->GetPrototype()) {
1682 if (!JSObject::cast(pt)->HasDictionaryElements()) {
1683 continue;
1684 }
1685 NumberDictionary* dictionary = JSObject::cast(pt)->element_dictionary();
1686 int entry = dictionary->FindEntry(index);
1687 if (entry != NumberDictionary::kNotFound) {
1688 Object* element = dictionary->ValueAt(entry);
1689 PropertyDetails details = dictionary->DetailsAt(entry);
1690 if (details.type() == CALLBACKS) {
1691 // Only accessors allowed as elements.
1692 return FixedArray::cast(element)->get(kSetterIndex);
1693 }
1694 }
1695 }
1696 return Heap::undefined_value();
1697}
1698
1699
1700void JSObject::LookupInDescriptor(String* name, LookupResult* result) {
1701 DescriptorArray* descriptors = map()->instance_descriptors();
1702 int number = DescriptorLookupCache::Lookup(descriptors, name);
1703 if (number == DescriptorLookupCache::kAbsent) {
1704 number = descriptors->Search(name);
1705 DescriptorLookupCache::Update(descriptors, name, number);
1706 }
1707 if (number != DescriptorArray::kNotFound) {
1708 result->DescriptorResult(this, descriptors->GetDetails(number), number);
1709 } else {
1710 result->NotFound();
1711 }
1712}
1713
1714
1715void JSObject::LocalLookupRealNamedProperty(String* name,
1716 LookupResult* result) {
1717 if (IsJSGlobalProxy()) {
1718 Object* proto = GetPrototype();
1719 if (proto->IsNull()) return result->NotFound();
1720 ASSERT(proto->IsJSGlobalObject());
1721 return JSObject::cast(proto)->LocalLookupRealNamedProperty(name, result);
1722 }
1723
1724 if (HasFastProperties()) {
1725 LookupInDescriptor(name, result);
1726 if (result->IsValid()) {
1727 ASSERT(result->holder() == this && result->type() != NORMAL);
1728 // Disallow caching for uninitialized constants. These can only
1729 // occur as fields.
1730 if (result->IsReadOnly() && result->type() == FIELD &&
1731 FastPropertyAt(result->GetFieldIndex())->IsTheHole()) {
1732 result->DisallowCaching();
1733 }
1734 return;
1735 }
1736 } else {
1737 int entry = property_dictionary()->FindEntry(name);
1738 if (entry != StringDictionary::kNotFound) {
1739 Object* value = property_dictionary()->ValueAt(entry);
1740 if (IsGlobalObject()) {
1741 PropertyDetails d = property_dictionary()->DetailsAt(entry);
1742 if (d.IsDeleted()) {
1743 result->NotFound();
1744 return;
1745 }
1746 value = JSGlobalPropertyCell::cast(value)->value();
1747 ASSERT(result->IsLoaded());
1748 }
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 }
1755 // Slow case object skipped during lookup. Do not use inline caching.
1756 if (!IsGlobalObject()) result->DisallowCaching();
1757 }
1758 result->NotFound();
1759}
1760
1761
1762void JSObject::LookupRealNamedProperty(String* name, LookupResult* result) {
1763 LocalLookupRealNamedProperty(name, result);
1764 if (result->IsProperty()) return;
1765
1766 LookupRealNamedPropertyInPrototypes(name, result);
1767}
1768
1769
1770void JSObject::LookupRealNamedPropertyInPrototypes(String* name,
1771 LookupResult* result) {
1772 for (Object* pt = GetPrototype();
1773 pt != Heap::null_value();
1774 pt = JSObject::cast(pt)->GetPrototype()) {
1775 JSObject::cast(pt)->LocalLookupRealNamedProperty(name, result);
1776 if (result->IsValid()) {
1777 switch (result->type()) {
1778 case NORMAL:
1779 case FIELD:
1780 case CONSTANT_FUNCTION:
1781 case CALLBACKS:
1782 return;
1783 default: break;
1784 }
1785 }
1786 }
1787 result->NotFound();
1788}
1789
1790
1791// We only need to deal with CALLBACKS and INTERCEPTORS
1792Object* JSObject::SetPropertyWithFailedAccessCheck(LookupResult* result,
1793 String* name,
1794 Object* value) {
1795 if (!result->IsProperty()) {
1796 LookupCallbackSetterInPrototypes(name, result);
1797 }
1798
1799 if (result->IsProperty()) {
1800 if (!result->IsReadOnly()) {
1801 switch (result->type()) {
1802 case CALLBACKS: {
1803 Object* obj = result->GetCallbackObject();
1804 if (obj->IsAccessorInfo()) {
1805 AccessorInfo* info = AccessorInfo::cast(obj);
1806 if (info->all_can_write()) {
1807 return SetPropertyWithCallback(result->GetCallbackObject(),
1808 name,
1809 value,
1810 result->holder());
1811 }
1812 }
1813 break;
1814 }
1815 case INTERCEPTOR: {
1816 // Try lookup real named properties. Note that only property can be
1817 // set is callbacks marked as ALL_CAN_WRITE on the prototype chain.
1818 LookupResult r;
1819 LookupRealNamedProperty(name, &r);
1820 if (r.IsProperty()) {
1821 return SetPropertyWithFailedAccessCheck(&r, name, value);
1822 }
1823 break;
1824 }
1825 default: {
1826 break;
1827 }
1828 }
1829 }
1830 }
1831
1832 Top::ReportFailedAccessCheck(this, v8::ACCESS_SET);
1833 return value;
1834}
1835
1836
1837Object* JSObject::SetProperty(LookupResult* result,
1838 String* name,
1839 Object* value,
1840 PropertyAttributes attributes) {
1841 // Make sure that the top context does not change when doing callbacks or
1842 // interceptor calls.
1843 AssertNoContextChange ncc;
1844
1845 // Check access rights if needed.
1846 if (IsAccessCheckNeeded()
1847 && !Top::MayNamedAccess(this, name, v8::ACCESS_SET)) {
1848 return SetPropertyWithFailedAccessCheck(result, name, value);
1849 }
1850
1851 if (IsJSGlobalProxy()) {
1852 Object* proto = GetPrototype();
1853 if (proto->IsNull()) return value;
1854 ASSERT(proto->IsJSGlobalObject());
1855 return JSObject::cast(proto)->SetProperty(result, name, value, attributes);
1856 }
1857
1858 if (!result->IsProperty() && !IsJSContextExtensionObject()) {
1859 // We could not find a local property so let's check whether there is an
1860 // accessor that wants to handle the property.
1861 LookupResult accessor_result;
1862 LookupCallbackSetterInPrototypes(name, &accessor_result);
1863 if (accessor_result.IsValid()) {
1864 return SetPropertyWithCallback(accessor_result.GetCallbackObject(),
1865 name,
1866 value,
1867 accessor_result.holder());
1868 }
1869 }
1870 if (result->IsNotFound()) {
1871 return AddProperty(name, value, attributes);
1872 }
1873 if (!result->IsLoaded()) {
1874 return SetLazyProperty(result, name, value, attributes);
1875 }
1876 if (result->IsReadOnly() && result->IsProperty()) return value;
1877 // This is a real property that is not read-only, or it is a
1878 // transition or null descriptor and there are no setters in the prototypes.
1879 switch (result->type()) {
1880 case NORMAL:
1881 return SetNormalizedProperty(result, value);
1882 case FIELD:
1883 return FastPropertyAtPut(result->GetFieldIndex(), value);
1884 case MAP_TRANSITION:
1885 if (attributes == result->GetAttributes()) {
1886 // Only use map transition if the attributes match.
1887 return AddFastPropertyUsingMap(result->GetTransitionMap(),
1888 name,
1889 value);
1890 }
1891 return ConvertDescriptorToField(name, value, attributes);
1892 case CONSTANT_FUNCTION:
1893 // Only replace the function if necessary.
1894 if (value == result->GetConstantFunction()) return value;
1895 // Preserve the attributes of this existing property.
1896 attributes = result->GetAttributes();
1897 return ConvertDescriptorToField(name, value, attributes);
1898 case CALLBACKS:
1899 return SetPropertyWithCallback(result->GetCallbackObject(),
1900 name,
1901 value,
1902 result->holder());
1903 case INTERCEPTOR:
1904 return SetPropertyWithInterceptor(name, value, attributes);
1905 case CONSTANT_TRANSITION:
1906 // Replace with a MAP_TRANSITION to a new map with a FIELD, even
1907 // if the value is a function.
1908 return ConvertDescriptorToFieldAndMapTransition(name, value, attributes);
1909 case NULL_DESCRIPTOR:
1910 return ConvertDescriptorToFieldAndMapTransition(name, value, attributes);
1911 default:
1912 UNREACHABLE();
1913 }
1914 UNREACHABLE();
1915 return value;
1916}
1917
1918
1919// Set a real local property, even if it is READ_ONLY. If the property is not
1920// present, add it with attributes NONE. This code is an exact clone of
1921// SetProperty, with the check for IsReadOnly and the check for a
1922// callback setter removed. The two lines looking up the LookupResult
1923// result are also added. If one of the functions is changed, the other
1924// should be.
1925Object* JSObject::IgnoreAttributesAndSetLocalProperty(
1926 String* name,
1927 Object* value,
1928 PropertyAttributes attributes) {
1929 // Make sure that the top context does not change when doing callbacks or
1930 // interceptor calls.
1931 AssertNoContextChange ncc;
1932 // ADDED TO CLONE
1933 LookupResult result_struct;
1934 LocalLookup(name, &result_struct);
1935 LookupResult* result = &result_struct;
1936 // END ADDED TO CLONE
1937 // Check access rights if needed.
1938 if (IsAccessCheckNeeded()
1939 && !Top::MayNamedAccess(this, name, v8::ACCESS_SET)) {
1940 return SetPropertyWithFailedAccessCheck(result, name, value);
1941 }
1942
1943 if (IsJSGlobalProxy()) {
1944 Object* proto = GetPrototype();
1945 if (proto->IsNull()) return value;
1946 ASSERT(proto->IsJSGlobalObject());
1947 return JSObject::cast(proto)->IgnoreAttributesAndSetLocalProperty(
1948 name,
1949 value,
1950 attributes);
1951 }
1952
1953 // Check for accessor in prototype chain removed here in clone.
1954 if (result->IsNotFound()) {
1955 return AddProperty(name, value, attributes);
1956 }
1957 if (!result->IsLoaded()) {
1958 return SetLazyProperty(result, name, value, attributes);
1959 }
1960 // Check of IsReadOnly removed from here in clone.
1961 switch (result->type()) {
1962 case NORMAL:
1963 return SetNormalizedProperty(result, value);
1964 case FIELD:
1965 return FastPropertyAtPut(result->GetFieldIndex(), value);
1966 case MAP_TRANSITION:
1967 if (attributes == result->GetAttributes()) {
1968 // Only use map transition if the attributes match.
1969 return AddFastPropertyUsingMap(result->GetTransitionMap(),
1970 name,
1971 value);
1972 }
1973 return ConvertDescriptorToField(name, value, attributes);
1974 case CONSTANT_FUNCTION:
1975 // Only replace the function if necessary.
1976 if (value == result->GetConstantFunction()) return value;
1977 // Preserve the attributes of this existing property.
1978 attributes = result->GetAttributes();
1979 return ConvertDescriptorToField(name, value, attributes);
1980 case CALLBACKS:
1981 case INTERCEPTOR:
1982 // Override callback in clone
1983 return ConvertDescriptorToField(name, value, attributes);
1984 case CONSTANT_TRANSITION:
1985 // Replace with a MAP_TRANSITION to a new map with a FIELD, even
1986 // if the value is a function.
1987 return ConvertDescriptorToFieldAndMapTransition(name, value, attributes);
1988 case NULL_DESCRIPTOR:
1989 return ConvertDescriptorToFieldAndMapTransition(name, value, attributes);
1990 default:
1991 UNREACHABLE();
1992 }
1993 UNREACHABLE();
1994 return value;
1995}
1996
1997
1998PropertyAttributes JSObject::GetPropertyAttributePostInterceptor(
1999 JSObject* receiver,
2000 String* name,
2001 bool continue_search) {
2002 // Check local property, ignore interceptor.
2003 LookupResult result;
2004 LocalLookupRealNamedProperty(name, &result);
2005 if (result.IsProperty()) return result.GetAttributes();
2006
2007 if (continue_search) {
2008 // Continue searching via the prototype chain.
2009 Object* pt = GetPrototype();
2010 if (pt != Heap::null_value()) {
2011 return JSObject::cast(pt)->
2012 GetPropertyAttributeWithReceiver(receiver, name);
2013 }
2014 }
2015 return ABSENT;
2016}
2017
2018
2019PropertyAttributes JSObject::GetPropertyAttributeWithInterceptor(
2020 JSObject* receiver,
2021 String* name,
2022 bool continue_search) {
2023 // Make sure that the top context does not change when doing
2024 // callbacks or interceptor calls.
2025 AssertNoContextChange ncc;
2026
2027 HandleScope scope;
2028 Handle<InterceptorInfo> interceptor(GetNamedInterceptor());
2029 Handle<JSObject> receiver_handle(receiver);
2030 Handle<JSObject> holder_handle(this);
2031 Handle<String> name_handle(name);
2032 CustomArguments args(interceptor->data(), receiver, this);
2033 v8::AccessorInfo info(args.end());
2034 if (!interceptor->query()->IsUndefined()) {
2035 v8::NamedPropertyQuery query =
2036 v8::ToCData<v8::NamedPropertyQuery>(interceptor->query());
2037 LOG(ApiNamedPropertyAccess("interceptor-named-has", *holder_handle, name));
2038 v8::Handle<v8::Boolean> result;
2039 {
2040 // Leaving JavaScript.
2041 VMState state(EXTERNAL);
2042 result = query(v8::Utils::ToLocal(name_handle), info);
2043 }
2044 if (!result.IsEmpty()) {
2045 // Convert the boolean result to a property attribute
2046 // specification.
2047 return result->IsTrue() ? NONE : ABSENT;
2048 }
2049 } else if (!interceptor->getter()->IsUndefined()) {
2050 v8::NamedPropertyGetter getter =
2051 v8::ToCData<v8::NamedPropertyGetter>(interceptor->getter());
2052 LOG(ApiNamedPropertyAccess("interceptor-named-get-has", this, name));
2053 v8::Handle<v8::Value> result;
2054 {
2055 // Leaving JavaScript.
2056 VMState state(EXTERNAL);
2057 result = getter(v8::Utils::ToLocal(name_handle), info);
2058 }
2059 if (!result.IsEmpty()) return NONE;
2060 }
2061 return holder_handle->GetPropertyAttributePostInterceptor(*receiver_handle,
2062 *name_handle,
2063 continue_search);
2064}
2065
2066
2067PropertyAttributes JSObject::GetPropertyAttributeWithReceiver(
2068 JSObject* receiver,
2069 String* key) {
2070 uint32_t index = 0;
2071 if (key->AsArrayIndex(&index)) {
2072 if (HasElementWithReceiver(receiver, index)) return NONE;
2073 return ABSENT;
2074 }
2075 // Named property.
2076 LookupResult result;
2077 Lookup(key, &result);
2078 return GetPropertyAttribute(receiver, &result, key, true);
2079}
2080
2081
2082PropertyAttributes JSObject::GetPropertyAttribute(JSObject* receiver,
2083 LookupResult* result,
2084 String* name,
2085 bool continue_search) {
2086 // Check access rights if needed.
2087 if (IsAccessCheckNeeded() &&
2088 !Top::MayNamedAccess(this, name, v8::ACCESS_HAS)) {
2089 return GetPropertyAttributeWithFailedAccessCheck(receiver,
2090 result,
2091 name,
2092 continue_search);
2093 }
2094 if (result->IsValid()) {
2095 switch (result->type()) {
2096 case NORMAL: // fall through
2097 case FIELD:
2098 case CONSTANT_FUNCTION:
2099 case CALLBACKS:
2100 return result->GetAttributes();
2101 case INTERCEPTOR:
2102 return result->holder()->
2103 GetPropertyAttributeWithInterceptor(receiver, name, continue_search);
2104 case MAP_TRANSITION:
2105 case CONSTANT_TRANSITION:
2106 case NULL_DESCRIPTOR:
2107 return ABSENT;
2108 default:
2109 UNREACHABLE();
2110 break;
2111 }
2112 }
2113 return ABSENT;
2114}
2115
2116
2117PropertyAttributes JSObject::GetLocalPropertyAttribute(String* name) {
2118 // Check whether the name is an array index.
2119 uint32_t index = 0;
2120 if (name->AsArrayIndex(&index)) {
2121 if (HasLocalElement(index)) return NONE;
2122 return ABSENT;
2123 }
2124 // Named property.
2125 LookupResult result;
2126 LocalLookup(name, &result);
2127 return GetPropertyAttribute(this, &result, name, false);
2128}
2129
2130
2131Object* JSObject::NormalizeProperties(PropertyNormalizationMode mode,
2132 int expected_additional_properties) {
2133 if (!HasFastProperties()) return this;
2134
2135 // The global object is always normalized.
2136 ASSERT(!IsGlobalObject());
2137
2138 // Allocate new content.
2139 int property_count = map()->NumberOfDescribedProperties();
2140 if (expected_additional_properties > 0) {
2141 property_count += expected_additional_properties;
2142 } else {
2143 property_count += 2; // Make space for two more properties.
2144 }
2145 Object* obj =
2146 StringDictionary::Allocate(property_count * 2);
2147 if (obj->IsFailure()) return obj;
2148 StringDictionary* dictionary = StringDictionary::cast(obj);
2149
2150 DescriptorArray* descs = map()->instance_descriptors();
2151 for (int i = 0; i < descs->number_of_descriptors(); i++) {
2152 PropertyDetails details = descs->GetDetails(i);
2153 switch (details.type()) {
2154 case CONSTANT_FUNCTION: {
2155 PropertyDetails d =
2156 PropertyDetails(details.attributes(), NORMAL, details.index());
2157 Object* value = descs->GetConstantFunction(i);
2158 Object* result = dictionary->Add(descs->GetKey(i), value, d);
2159 if (result->IsFailure()) return result;
2160 dictionary = StringDictionary::cast(result);
2161 break;
2162 }
2163 case FIELD: {
2164 PropertyDetails d =
2165 PropertyDetails(details.attributes(), NORMAL, details.index());
2166 Object* value = FastPropertyAt(descs->GetFieldIndex(i));
2167 Object* result = dictionary->Add(descs->GetKey(i), value, d);
2168 if (result->IsFailure()) return result;
2169 dictionary = StringDictionary::cast(result);
2170 break;
2171 }
2172 case CALLBACKS: {
2173 PropertyDetails d =
2174 PropertyDetails(details.attributes(), CALLBACKS, details.index());
2175 Object* value = descs->GetCallbacksObject(i);
2176 Object* result = dictionary->Add(descs->GetKey(i), value, d);
2177 if (result->IsFailure()) return result;
2178 dictionary = StringDictionary::cast(result);
2179 break;
2180 }
2181 case MAP_TRANSITION:
2182 case CONSTANT_TRANSITION:
2183 case NULL_DESCRIPTOR:
2184 case INTERCEPTOR:
2185 break;
2186 default:
2187 UNREACHABLE();
2188 }
2189 }
2190
2191 // Copy the next enumeration index from instance descriptor.
2192 int index = map()->instance_descriptors()->NextEnumerationIndex();
2193 dictionary->SetNextEnumerationIndex(index);
2194
2195 // Allocate new map.
2196 obj = map()->CopyDropDescriptors();
2197 if (obj->IsFailure()) return obj;
2198 Map* new_map = Map::cast(obj);
2199
2200 // Clear inobject properties if needed by adjusting the instance size and
2201 // putting in a filler object instead of the inobject properties.
2202 if (mode == CLEAR_INOBJECT_PROPERTIES && map()->inobject_properties() > 0) {
2203 int instance_size_delta = map()->inobject_properties() * kPointerSize;
2204 int new_instance_size = map()->instance_size() - instance_size_delta;
2205 new_map->set_inobject_properties(0);
2206 new_map->set_instance_size(new_instance_size);
2207 Heap::CreateFillerObjectAt(this->address() + new_instance_size,
2208 instance_size_delta);
2209 }
2210 new_map->set_unused_property_fields(0);
2211
2212 // We have now successfully allocated all the necessary objects.
2213 // Changes can now be made with the guarantee that all of them take effect.
2214 set_map(new_map);
2215 map()->set_instance_descriptors(Heap::empty_descriptor_array());
2216
2217 set_properties(dictionary);
2218
2219 Counters::props_to_dictionary.Increment();
2220
2221#ifdef DEBUG
2222 if (FLAG_trace_normalization) {
2223 PrintF("Object properties have been normalized:\n");
2224 Print();
2225 }
2226#endif
2227 return this;
2228}
2229
2230
2231Object* JSObject::TransformToFastProperties(int unused_property_fields) {
2232 if (HasFastProperties()) return this;
2233 ASSERT(!IsGlobalObject());
2234 return property_dictionary()->
2235 TransformPropertiesToFastFor(this, unused_property_fields);
2236}
2237
2238
2239Object* JSObject::NormalizeElements() {
2240 ASSERT(!HasPixelElements());
2241 if (HasDictionaryElements()) return this;
2242
2243 // Get number of entries.
2244 FixedArray* array = FixedArray::cast(elements());
2245
2246 // Compute the effective length.
2247 int length = IsJSArray() ?
2248 Smi::cast(JSArray::cast(this)->length())->value() :
2249 array->length();
2250 Object* obj = NumberDictionary::Allocate(length);
2251 if (obj->IsFailure()) return obj;
2252 NumberDictionary* dictionary = NumberDictionary::cast(obj);
2253 // Copy entries.
2254 for (int i = 0; i < length; i++) {
2255 Object* value = array->get(i);
2256 if (!value->IsTheHole()) {
2257 PropertyDetails details = PropertyDetails(NONE, NORMAL);
2258 Object* result = dictionary->AddNumberEntry(i, array->get(i), details);
2259 if (result->IsFailure()) return result;
2260 dictionary = NumberDictionary::cast(result);
2261 }
2262 }
2263 // Switch to using the dictionary as the backing storage for elements.
2264 set_elements(dictionary);
2265
2266 Counters::elements_to_dictionary.Increment();
2267
2268#ifdef DEBUG
2269 if (FLAG_trace_normalization) {
2270 PrintF("Object elements have been normalized:\n");
2271 Print();
2272 }
2273#endif
2274
2275 return this;
2276}
2277
2278
2279Object* JSObject::DeletePropertyPostInterceptor(String* name, DeleteMode mode) {
2280 // Check local property, ignore interceptor.
2281 LookupResult result;
2282 LocalLookupRealNamedProperty(name, &result);
2283 if (!result.IsValid()) return Heap::true_value();
2284
2285 // Normalize object if needed.
2286 Object* obj = NormalizeProperties(CLEAR_INOBJECT_PROPERTIES, 0);
2287 if (obj->IsFailure()) return obj;
2288
2289 return DeleteNormalizedProperty(name, mode);
2290}
2291
2292
2293Object* JSObject::DeletePropertyWithInterceptor(String* name) {
2294 HandleScope scope;
2295 Handle<InterceptorInfo> interceptor(GetNamedInterceptor());
2296 Handle<String> name_handle(name);
2297 Handle<JSObject> this_handle(this);
2298 if (!interceptor->deleter()->IsUndefined()) {
2299 v8::NamedPropertyDeleter deleter =
2300 v8::ToCData<v8::NamedPropertyDeleter>(interceptor->deleter());
2301 LOG(ApiNamedPropertyAccess("interceptor-named-delete", *this_handle, name));
2302 CustomArguments args(interceptor->data(), this, this);
2303 v8::AccessorInfo info(args.end());
2304 v8::Handle<v8::Boolean> result;
2305 {
2306 // Leaving JavaScript.
2307 VMState state(EXTERNAL);
2308 result = deleter(v8::Utils::ToLocal(name_handle), info);
2309 }
2310 RETURN_IF_SCHEDULED_EXCEPTION();
2311 if (!result.IsEmpty()) {
2312 ASSERT(result->IsBoolean());
2313 return *v8::Utils::OpenHandle(*result);
2314 }
2315 }
2316 Object* raw_result =
2317 this_handle->DeletePropertyPostInterceptor(*name_handle, NORMAL_DELETION);
2318 RETURN_IF_SCHEDULED_EXCEPTION();
2319 return raw_result;
2320}
2321
2322
2323Object* JSObject::DeleteElementPostInterceptor(uint32_t index,
2324 DeleteMode mode) {
2325 ASSERT(!HasPixelElements());
2326 switch (GetElementsKind()) {
2327 case FAST_ELEMENTS: {
2328 uint32_t length = IsJSArray() ?
2329 static_cast<uint32_t>(Smi::cast(JSArray::cast(this)->length())->value()) :
2330 static_cast<uint32_t>(FixedArray::cast(elements())->length());
2331 if (index < length) {
2332 FixedArray::cast(elements())->set_the_hole(index);
2333 }
2334 break;
2335 }
2336 case DICTIONARY_ELEMENTS: {
2337 NumberDictionary* dictionary = element_dictionary();
2338 int entry = dictionary->FindEntry(index);
2339 if (entry != NumberDictionary::kNotFound) {
2340 return dictionary->DeleteProperty(entry, mode);
2341 }
2342 break;
2343 }
2344 default:
2345 UNREACHABLE();
2346 break;
2347 }
2348 return Heap::true_value();
2349}
2350
2351
2352Object* JSObject::DeleteElementWithInterceptor(uint32_t index) {
2353 // Make sure that the top context does not change when doing
2354 // callbacks or interceptor calls.
2355 AssertNoContextChange ncc;
2356 HandleScope scope;
2357 Handle<InterceptorInfo> interceptor(GetIndexedInterceptor());
2358 if (interceptor->deleter()->IsUndefined()) return Heap::false_value();
2359 v8::IndexedPropertyDeleter deleter =
2360 v8::ToCData<v8::IndexedPropertyDeleter>(interceptor->deleter());
2361 Handle<JSObject> this_handle(this);
2362 LOG(ApiIndexedPropertyAccess("interceptor-indexed-delete", this, index));
2363 CustomArguments args(interceptor->data(), this, this);
2364 v8::AccessorInfo info(args.end());
2365 v8::Handle<v8::Boolean> result;
2366 {
2367 // Leaving JavaScript.
2368 VMState state(EXTERNAL);
2369 result = deleter(index, info);
2370 }
2371 RETURN_IF_SCHEDULED_EXCEPTION();
2372 if (!result.IsEmpty()) {
2373 ASSERT(result->IsBoolean());
2374 return *v8::Utils::OpenHandle(*result);
2375 }
2376 Object* raw_result =
2377 this_handle->DeleteElementPostInterceptor(index, NORMAL_DELETION);
2378 RETURN_IF_SCHEDULED_EXCEPTION();
2379 return raw_result;
2380}
2381
2382
2383Object* JSObject::DeleteElement(uint32_t index, DeleteMode mode) {
2384 // Check access rights if needed.
2385 if (IsAccessCheckNeeded() &&
2386 !Top::MayIndexedAccess(this, index, v8::ACCESS_DELETE)) {
2387 Top::ReportFailedAccessCheck(this, v8::ACCESS_DELETE);
2388 return Heap::false_value();
2389 }
2390
2391 if (IsJSGlobalProxy()) {
2392 Object* proto = GetPrototype();
2393 if (proto->IsNull()) return Heap::false_value();
2394 ASSERT(proto->IsJSGlobalObject());
2395 return JSGlobalObject::cast(proto)->DeleteElement(index, mode);
2396 }
2397
2398 if (HasIndexedInterceptor()) {
2399 // Skip interceptor if forcing deletion.
2400 if (mode == FORCE_DELETION) {
2401 return DeleteElementPostInterceptor(index, mode);
2402 }
2403 return DeleteElementWithInterceptor(index);
2404 }
2405
2406 switch (GetElementsKind()) {
2407 case FAST_ELEMENTS: {
2408 uint32_t length = IsJSArray() ?
2409 static_cast<uint32_t>(Smi::cast(JSArray::cast(this)->length())->value()) :
2410 static_cast<uint32_t>(FixedArray::cast(elements())->length());
2411 if (index < length) {
2412 FixedArray::cast(elements())->set_the_hole(index);
2413 }
2414 break;
2415 }
2416 case PIXEL_ELEMENTS: {
2417 // Pixel elements cannot be deleted. Just silently ignore here.
2418 break;
2419 }
2420 case DICTIONARY_ELEMENTS: {
2421 NumberDictionary* dictionary = element_dictionary();
2422 int entry = dictionary->FindEntry(index);
2423 if (entry != NumberDictionary::kNotFound) {
2424 return dictionary->DeleteProperty(entry, mode);
2425 }
2426 break;
2427 }
2428 default:
2429 UNREACHABLE();
2430 break;
2431 }
2432 return Heap::true_value();
2433}
2434
2435
2436Object* JSObject::DeleteProperty(String* name, DeleteMode mode) {
2437 // ECMA-262, 3rd, 8.6.2.5
2438 ASSERT(name->IsString());
2439
2440 // Check access rights if needed.
2441 if (IsAccessCheckNeeded() &&
2442 !Top::MayNamedAccess(this, name, v8::ACCESS_DELETE)) {
2443 Top::ReportFailedAccessCheck(this, v8::ACCESS_DELETE);
2444 return Heap::false_value();
2445 }
2446
2447 if (IsJSGlobalProxy()) {
2448 Object* proto = GetPrototype();
2449 if (proto->IsNull()) return Heap::false_value();
2450 ASSERT(proto->IsJSGlobalObject());
2451 return JSGlobalObject::cast(proto)->DeleteProperty(name, mode);
2452 }
2453
2454 uint32_t index = 0;
2455 if (name->AsArrayIndex(&index)) {
2456 return DeleteElement(index, mode);
2457 } else {
2458 LookupResult result;
2459 LocalLookup(name, &result);
2460 if (!result.IsValid()) return Heap::true_value();
2461 // Ignore attributes if forcing a deletion.
2462 if (result.IsDontDelete() && mode != FORCE_DELETION) {
2463 return Heap::false_value();
2464 }
2465 // Check for interceptor.
2466 if (result.type() == INTERCEPTOR) {
2467 // Skip interceptor if forcing a deletion.
2468 if (mode == FORCE_DELETION) {
2469 return DeletePropertyPostInterceptor(name, mode);
2470 }
2471 return DeletePropertyWithInterceptor(name);
2472 }
2473 if (!result.IsLoaded()) {
2474 return JSObject::cast(this)->DeleteLazyProperty(&result,
2475 name,
2476 mode);
2477 }
2478 // Normalize object if needed.
2479 Object* obj = NormalizeProperties(CLEAR_INOBJECT_PROPERTIES, 0);
2480 if (obj->IsFailure()) return obj;
2481 // Make sure the properties are normalized before removing the entry.
2482 return DeleteNormalizedProperty(name, mode);
2483 }
2484}
2485
2486
2487// Check whether this object references another object.
2488bool JSObject::ReferencesObject(Object* obj) {
2489 AssertNoAllocation no_alloc;
2490
2491 // Is the object the constructor for this object?
2492 if (map()->constructor() == obj) {
2493 return true;
2494 }
2495
2496 // Is the object the prototype for this object?
2497 if (map()->prototype() == obj) {
2498 return true;
2499 }
2500
2501 // Check if the object is among the named properties.
2502 Object* key = SlowReverseLookup(obj);
2503 if (key != Heap::undefined_value()) {
2504 return true;
2505 }
2506
2507 // Check if the object is among the indexed properties.
2508 switch (GetElementsKind()) {
2509 case PIXEL_ELEMENTS:
2510 // Raw pixels do not reference other objects.
2511 break;
2512 case FAST_ELEMENTS: {
2513 int length = IsJSArray() ?
2514 Smi::cast(JSArray::cast(this)->length())->value() :
2515 FixedArray::cast(elements())->length();
2516 for (int i = 0; i < length; i++) {
2517 Object* element = FixedArray::cast(elements())->get(i);
2518 if (!element->IsTheHole() && element == obj) {
2519 return true;
2520 }
2521 }
2522 break;
2523 }
2524 case DICTIONARY_ELEMENTS: {
2525 key = element_dictionary()->SlowReverseLookup(obj);
2526 if (key != Heap::undefined_value()) {
2527 return true;
2528 }
2529 break;
2530 }
2531 default:
2532 UNREACHABLE();
2533 break;
2534 }
2535
2536 // For functions check the context. Boilerplate functions do
2537 // not have to be traversed since they have no real context.
2538 if (IsJSFunction() && !JSFunction::cast(this)->IsBoilerplate()) {
2539 // Get the constructor function for arguments array.
2540 JSObject* arguments_boilerplate =
2541 Top::context()->global_context()->arguments_boilerplate();
2542 JSFunction* arguments_function =
2543 JSFunction::cast(arguments_boilerplate->map()->constructor());
2544
2545 // Get the context and don't check if it is the global context.
2546 JSFunction* f = JSFunction::cast(this);
2547 Context* context = f->context();
2548 if (context->IsGlobalContext()) {
2549 return false;
2550 }
2551
2552 // Check the non-special context slots.
2553 for (int i = Context::MIN_CONTEXT_SLOTS; i < context->length(); i++) {
2554 // Only check JS objects.
2555 if (context->get(i)->IsJSObject()) {
2556 JSObject* ctxobj = JSObject::cast(context->get(i));
2557 // If it is an arguments array check the content.
2558 if (ctxobj->map()->constructor() == arguments_function) {
2559 if (ctxobj->ReferencesObject(obj)) {
2560 return true;
2561 }
2562 } else if (ctxobj == obj) {
2563 return true;
2564 }
2565 }
2566 }
2567
2568 // Check the context extension if any.
2569 if (context->has_extension()) {
2570 return context->extension()->ReferencesObject(obj);
2571 }
2572 }
2573
2574 // No references to object.
2575 return false;
2576}
2577
2578
2579// Tests for the fast common case for property enumeration:
2580// - this object has an enum cache
2581// - this object has no elements
2582// - no prototype has enumerable properties/elements
2583// - neither this object nor any prototype has interceptors
2584bool JSObject::IsSimpleEnum() {
2585 JSObject* arguments_boilerplate =
2586 Top::context()->global_context()->arguments_boilerplate();
2587 JSFunction* arguments_function =
2588 JSFunction::cast(arguments_boilerplate->map()->constructor());
2589 if (IsAccessCheckNeeded()) return false;
2590 if (map()->constructor() == arguments_function) return false;
2591
2592 for (Object* o = this;
2593 o != Heap::null_value();
2594 o = JSObject::cast(o)->GetPrototype()) {
2595 JSObject* curr = JSObject::cast(o);
2596 if (!curr->HasFastProperties()) return false;
2597 if (!curr->map()->instance_descriptors()->HasEnumCache()) return false;
2598 if (curr->NumberOfEnumElements() > 0) return false;
2599 if (curr->HasNamedInterceptor()) return false;
2600 if (curr->HasIndexedInterceptor()) return false;
2601 if (curr != this) {
2602 FixedArray* curr_fixed_array =
2603 FixedArray::cast(curr->map()->instance_descriptors()->GetEnumCache());
2604 if (curr_fixed_array->length() > 0) {
2605 return false;
2606 }
2607 }
2608 }
2609 return true;
2610}
2611
2612
2613int Map::NumberOfDescribedProperties() {
2614 int result = 0;
2615 DescriptorArray* descs = instance_descriptors();
2616 for (int i = 0; i < descs->number_of_descriptors(); i++) {
2617 if (descs->IsProperty(i)) result++;
2618 }
2619 return result;
2620}
2621
2622
2623int Map::PropertyIndexFor(String* name) {
2624 DescriptorArray* descs = instance_descriptors();
2625 for (int i = 0; i < descs->number_of_descriptors(); i++) {
2626 if (name->Equals(descs->GetKey(i)) && !descs->IsNullDescriptor(i)) {
2627 return descs->GetFieldIndex(i);
2628 }
2629 }
2630 return -1;
2631}
2632
2633
2634int Map::NextFreePropertyIndex() {
2635 int max_index = -1;
2636 DescriptorArray* descs = instance_descriptors();
2637 for (int i = 0; i < descs->number_of_descriptors(); i++) {
2638 if (descs->GetType(i) == FIELD) {
2639 int current_index = descs->GetFieldIndex(i);
2640 if (current_index > max_index) max_index = current_index;
2641 }
2642 }
2643 return max_index + 1;
2644}
2645
2646
2647AccessorDescriptor* Map::FindAccessor(String* name) {
2648 DescriptorArray* descs = instance_descriptors();
2649 for (int i = 0; i < descs->number_of_descriptors(); i++) {
2650 if (name->Equals(descs->GetKey(i)) && descs->GetType(i) == CALLBACKS) {
2651 return descs->GetCallbacks(i);
2652 }
2653 }
2654 return NULL;
2655}
2656
2657
2658void JSObject::LocalLookup(String* name, LookupResult* result) {
2659 ASSERT(name->IsString());
2660
2661 if (IsJSGlobalProxy()) {
2662 Object* proto = GetPrototype();
2663 if (proto->IsNull()) return result->NotFound();
2664 ASSERT(proto->IsJSGlobalObject());
2665 return JSObject::cast(proto)->LocalLookup(name, result);
2666 }
2667
2668 // Do not use inline caching if the object is a non-global object
2669 // that requires access checks.
2670 if (!IsJSGlobalProxy() && IsAccessCheckNeeded()) {
2671 result->DisallowCaching();
2672 }
2673
2674 // Check __proto__ before interceptor.
2675 if (name->Equals(Heap::Proto_symbol()) && !IsJSContextExtensionObject()) {
2676 result->ConstantResult(this);
2677 return;
2678 }
2679
2680 // Check for lookup interceptor except when bootstrapping.
2681 if (HasNamedInterceptor() && !Bootstrapper::IsActive()) {
2682 result->InterceptorResult(this);
2683 return;
2684 }
2685
2686 LocalLookupRealNamedProperty(name, result);
2687}
2688
2689
2690void JSObject::Lookup(String* name, LookupResult* result) {
2691 // Ecma-262 3rd 8.6.2.4
2692 for (Object* current = this;
2693 current != Heap::null_value();
2694 current = JSObject::cast(current)->GetPrototype()) {
2695 JSObject::cast(current)->LocalLookup(name, result);
2696 if (result->IsValid() && !result->IsTransitionType()) return;
2697 }
2698 result->NotFound();
2699}
2700
2701
2702// Search object and it's prototype chain for callback properties.
2703void JSObject::LookupCallback(String* name, LookupResult* result) {
2704 for (Object* current = this;
2705 current != Heap::null_value();
2706 current = JSObject::cast(current)->GetPrototype()) {
2707 JSObject::cast(current)->LocalLookupRealNamedProperty(name, result);
2708 if (result->IsValid() && result->type() == CALLBACKS) return;
2709 }
2710 result->NotFound();
2711}
2712
2713
2714Object* JSObject::DefineGetterSetter(String* name,
2715 PropertyAttributes attributes) {
2716 // Make sure that the top context does not change when doing callbacks or
2717 // interceptor calls.
2718 AssertNoContextChange ncc;
2719
2720 // Check access rights if needed.
2721 if (IsAccessCheckNeeded() &&
2722 !Top::MayNamedAccess(this, name, v8::ACCESS_SET)) {
2723 Top::ReportFailedAccessCheck(this, v8::ACCESS_SET);
2724 return Heap::undefined_value();
2725 }
2726
2727 // Try to flatten before operating on the string.
2728 name->TryFlattenIfNotFlat();
2729
2730 // Check if there is an API defined callback object which prohibits
2731 // callback overwriting in this object or it's prototype chain.
2732 // This mechanism is needed for instance in a browser setting, where
2733 // certain accessors such as window.location should not be allowed
2734 // to be overwritten because allowing overwriting could potentially
2735 // cause security problems.
2736 LookupResult callback_result;
2737 LookupCallback(name, &callback_result);
2738 if (callback_result.IsValid()) {
2739 Object* obj = callback_result.GetCallbackObject();
2740 if (obj->IsAccessorInfo() &&
2741 AccessorInfo::cast(obj)->prohibits_overwriting()) {
2742 return Heap::undefined_value();
2743 }
2744 }
2745
2746 uint32_t index;
2747 bool is_element = name->AsArrayIndex(&index);
2748 if (is_element && IsJSArray()) return Heap::undefined_value();
2749
2750 if (is_element) {
2751 switch (GetElementsKind()) {
2752 case FAST_ELEMENTS:
2753 break;
2754 case PIXEL_ELEMENTS:
2755 // Ignore getters and setters on pixel elements.
2756 return Heap::undefined_value();
2757 case DICTIONARY_ELEMENTS: {
2758 // Lookup the index.
2759 NumberDictionary* dictionary = element_dictionary();
2760 int entry = dictionary->FindEntry(index);
2761 if (entry != NumberDictionary::kNotFound) {
2762 Object* result = dictionary->ValueAt(entry);
2763 PropertyDetails details = dictionary->DetailsAt(entry);
2764 if (details.IsReadOnly()) return Heap::undefined_value();
2765 if (details.type() == CALLBACKS) {
2766 // Only accessors allowed as elements.
2767 ASSERT(result->IsFixedArray());
2768 return result;
2769 }
2770 }
2771 break;
2772 }
2773 default:
2774 UNREACHABLE();
2775 break;
2776 }
2777 } else {
2778 // Lookup the name.
2779 LookupResult result;
2780 LocalLookup(name, &result);
2781 if (result.IsValid()) {
2782 if (result.IsReadOnly()) return Heap::undefined_value();
2783 if (result.type() == CALLBACKS) {
2784 Object* obj = result.GetCallbackObject();
2785 if (obj->IsFixedArray()) return obj;
2786 }
2787 }
2788 }
2789
2790 // Allocate the fixed array to hold getter and setter.
2791 Object* structure = Heap::AllocateFixedArray(2, TENURED);
2792 if (structure->IsFailure()) return structure;
2793 PropertyDetails details = PropertyDetails(attributes, CALLBACKS);
2794
2795 if (is_element) {
2796 // Normalize object to make this operation simple.
2797 Object* ok = NormalizeElements();
2798 if (ok->IsFailure()) return ok;
2799
2800 // Update the dictionary with the new CALLBACKS property.
2801 Object* dict =
2802 element_dictionary()->Set(index, structure, details);
2803 if (dict->IsFailure()) return dict;
2804
2805 // If name is an index we need to stay in slow case.
2806 NumberDictionary* elements = NumberDictionary::cast(dict);
2807 elements->set_requires_slow_elements();
2808 // Set the potential new dictionary on the object.
2809 set_elements(NumberDictionary::cast(dict));
2810 } else {
2811 // Normalize object to make this operation simple.
2812 Object* ok = NormalizeProperties(CLEAR_INOBJECT_PROPERTIES, 0);
2813 if (ok->IsFailure()) return ok;
2814
2815 // For the global object allocate a new map to invalidate the global inline
2816 // caches which have a global property cell reference directly in the code.
2817 if (IsGlobalObject()) {
2818 Object* new_map = map()->CopyDropDescriptors();
2819 if (new_map->IsFailure()) return new_map;
2820 set_map(Map::cast(new_map));
2821 }
2822
2823 // Update the dictionary with the new CALLBACKS property.
2824 return SetNormalizedProperty(name, structure, details);
2825 }
2826
2827 return structure;
2828}
2829
2830
2831Object* JSObject::DefineAccessor(String* name, bool is_getter, JSFunction* fun,
2832 PropertyAttributes attributes) {
2833 // Check access rights if needed.
2834 if (IsAccessCheckNeeded() &&
2835 !Top::MayNamedAccess(this, name, v8::ACCESS_HAS)) {
2836 Top::ReportFailedAccessCheck(this, v8::ACCESS_HAS);
2837 return Heap::undefined_value();
2838 }
2839
2840 if (IsJSGlobalProxy()) {
2841 Object* proto = GetPrototype();
2842 if (proto->IsNull()) return this;
2843 ASSERT(proto->IsJSGlobalObject());
2844 return JSObject::cast(proto)->DefineAccessor(name, is_getter,
2845 fun, attributes);
2846 }
2847
2848 Object* array = DefineGetterSetter(name, attributes);
2849 if (array->IsFailure() || array->IsUndefined()) return array;
2850 FixedArray::cast(array)->set(is_getter ? 0 : 1, fun);
2851 return this;
2852}
2853
2854
2855Object* JSObject::LookupAccessor(String* name, bool is_getter) {
2856 // Make sure that the top context does not change when doing callbacks or
2857 // interceptor calls.
2858 AssertNoContextChange ncc;
2859
2860 // Check access rights if needed.
2861 if (IsAccessCheckNeeded() &&
2862 !Top::MayNamedAccess(this, name, v8::ACCESS_HAS)) {
2863 Top::ReportFailedAccessCheck(this, v8::ACCESS_HAS);
2864 return Heap::undefined_value();
2865 }
2866
2867 // Make the lookup and include prototypes.
2868 int accessor_index = is_getter ? kGetterIndex : kSetterIndex;
2869 uint32_t index;
2870 if (name->AsArrayIndex(&index)) {
2871 for (Object* obj = this;
2872 obj != Heap::null_value();
2873 obj = JSObject::cast(obj)->GetPrototype()) {
2874 JSObject* js_object = JSObject::cast(obj);
2875 if (js_object->HasDictionaryElements()) {
2876 NumberDictionary* dictionary = js_object->element_dictionary();
2877 int entry = dictionary->FindEntry(index);
2878 if (entry != NumberDictionary::kNotFound) {
2879 Object* element = dictionary->ValueAt(entry);
2880 PropertyDetails details = dictionary->DetailsAt(entry);
2881 if (details.type() == CALLBACKS) {
2882 // Only accessors allowed as elements.
2883 return FixedArray::cast(element)->get(accessor_index);
2884 }
2885 }
2886 }
2887 }
2888 } else {
2889 for (Object* obj = this;
2890 obj != Heap::null_value();
2891 obj = JSObject::cast(obj)->GetPrototype()) {
2892 LookupResult result;
2893 JSObject::cast(obj)->LocalLookup(name, &result);
2894 if (result.IsValid()) {
2895 if (result.IsReadOnly()) return Heap::undefined_value();
2896 if (result.type() == CALLBACKS) {
2897 Object* obj = result.GetCallbackObject();
2898 if (obj->IsFixedArray()) {
2899 return FixedArray::cast(obj)->get(accessor_index);
2900 }
2901 }
2902 }
2903 }
2904 }
2905 return Heap::undefined_value();
2906}
2907
2908
2909Object* JSObject::SlowReverseLookup(Object* value) {
2910 if (HasFastProperties()) {
2911 DescriptorArray* descs = map()->instance_descriptors();
2912 for (int i = 0; i < descs->number_of_descriptors(); i++) {
2913 if (descs->GetType(i) == FIELD) {
2914 if (FastPropertyAt(descs->GetFieldIndex(i)) == value) {
2915 return descs->GetKey(i);
2916 }
2917 } else if (descs->GetType(i) == CONSTANT_FUNCTION) {
2918 if (descs->GetConstantFunction(i) == value) {
2919 return descs->GetKey(i);
2920 }
2921 }
2922 }
2923 return Heap::undefined_value();
2924 } else {
2925 return property_dictionary()->SlowReverseLookup(value);
2926 }
2927}
2928
2929
2930Object* Map::CopyDropDescriptors() {
2931 Object* result = Heap::AllocateMap(instance_type(), instance_size());
2932 if (result->IsFailure()) return result;
2933 Map::cast(result)->set_prototype(prototype());
2934 Map::cast(result)->set_constructor(constructor());
2935 // Don't copy descriptors, so map transitions always remain a forest.
2936 // If we retained the same descriptors we would have two maps
2937 // pointing to the same transition which is bad because the garbage
2938 // collector relies on being able to reverse pointers from transitions
2939 // to maps. If properties need to be retained use CopyDropTransitions.
2940 Map::cast(result)->set_instance_descriptors(Heap::empty_descriptor_array());
2941 // Please note instance_type and instance_size are set when allocated.
2942 Map::cast(result)->set_inobject_properties(inobject_properties());
2943 Map::cast(result)->set_unused_property_fields(unused_property_fields());
2944
2945 // If the map has pre-allocated properties always start out with a descriptor
2946 // array describing these properties.
2947 if (pre_allocated_property_fields() > 0) {
2948 ASSERT(constructor()->IsJSFunction());
2949 JSFunction* ctor = JSFunction::cast(constructor());
2950 Object* descriptors =
2951 ctor->initial_map()->instance_descriptors()->RemoveTransitions();
2952 if (descriptors->IsFailure()) return descriptors;
2953 Map::cast(result)->set_instance_descriptors(
2954 DescriptorArray::cast(descriptors));
2955 Map::cast(result)->set_pre_allocated_property_fields(
2956 pre_allocated_property_fields());
2957 }
2958 Map::cast(result)->set_bit_field(bit_field());
2959 Map::cast(result)->set_bit_field2(bit_field2());
2960 Map::cast(result)->ClearCodeCache();
2961 return result;
2962}
2963
2964
2965Object* Map::CopyDropTransitions() {
2966 Object* new_map = CopyDropDescriptors();
2967 if (new_map->IsFailure()) return new_map;
2968 Object* descriptors = instance_descriptors()->RemoveTransitions();
2969 if (descriptors->IsFailure()) return descriptors;
2970 cast(new_map)->set_instance_descriptors(DescriptorArray::cast(descriptors));
2971 return cast(new_map);
2972}
2973
2974
2975Object* Map::UpdateCodeCache(String* name, Code* code) {
2976 ASSERT(code->ic_state() == MONOMORPHIC);
2977 FixedArray* cache = code_cache();
2978
2979 // When updating the code cache we disregard the type encoded in the
2980 // flags. This allows call constant stubs to overwrite call field
2981 // stubs, etc.
2982 Code::Flags flags = Code::RemoveTypeFromFlags(code->flags());
2983
2984 // First check whether we can update existing code cache without
2985 // extending it.
2986 int length = cache->length();
2987 int deleted_index = -1;
2988 for (int i = 0; i < length; i += 2) {
2989 Object* key = cache->get(i);
2990 if (key->IsNull()) {
2991 if (deleted_index < 0) deleted_index = i;
2992 continue;
2993 }
2994 if (key->IsUndefined()) {
2995 if (deleted_index >= 0) i = deleted_index;
2996 cache->set(i + 0, name);
2997 cache->set(i + 1, code);
2998 return this;
2999 }
3000 if (name->Equals(String::cast(key))) {
3001 Code::Flags found = Code::cast(cache->get(i + 1))->flags();
3002 if (Code::RemoveTypeFromFlags(found) == flags) {
3003 cache->set(i + 1, code);
3004 return this;
3005 }
3006 }
3007 }
3008
3009 // Reached the end of the code cache. If there were deleted
3010 // elements, reuse the space for the first of them.
3011 if (deleted_index >= 0) {
3012 cache->set(deleted_index + 0, name);
3013 cache->set(deleted_index + 1, code);
3014 return this;
3015 }
3016
3017 // Extend the code cache with some new entries (at least one).
3018 int new_length = length + ((length >> 1) & ~1) + 2;
3019 ASSERT((new_length & 1) == 0); // must be a multiple of two
3020 Object* result = cache->CopySize(new_length);
3021 if (result->IsFailure()) return result;
3022
3023 // Add the (name, code) pair to the new cache.
3024 cache = FixedArray::cast(result);
3025 cache->set(length + 0, name);
3026 cache->set(length + 1, code);
3027 set_code_cache(cache);
3028 return this;
3029}
3030
3031
3032Object* Map::FindInCodeCache(String* name, Code::Flags flags) {
3033 FixedArray* cache = code_cache();
3034 int length = cache->length();
3035 for (int i = 0; i < length; i += 2) {
3036 Object* key = cache->get(i);
3037 // Skip deleted elements.
3038 if (key->IsNull()) continue;
3039 if (key->IsUndefined()) return key;
3040 if (name->Equals(String::cast(key))) {
3041 Code* code = Code::cast(cache->get(i + 1));
3042 if (code->flags() == flags) return code;
3043 }
3044 }
3045 return Heap::undefined_value();
3046}
3047
3048
3049int Map::IndexInCodeCache(Code* code) {
3050 FixedArray* array = code_cache();
3051 int len = array->length();
3052 for (int i = 0; i < len; i += 2) {
3053 if (array->get(i + 1) == code) return i + 1;
3054 }
3055 return -1;
3056}
3057
3058
3059void Map::RemoveFromCodeCache(int index) {
3060 FixedArray* array = code_cache();
3061 ASSERT(array->length() >= index && array->get(index)->IsCode());
3062 // Use null instead of undefined for deleted elements to distinguish
3063 // deleted elements from unused elements. This distinction is used
3064 // when looking up in the cache and when updating the cache.
3065 array->set_null(index - 1); // key
3066 array->set_null(index); // code
3067}
3068
3069
3070void FixedArray::FixedArrayIterateBody(ObjectVisitor* v) {
3071 IteratePointers(v, kHeaderSize, kHeaderSize + length() * kPointerSize);
3072}
3073
3074
3075static bool HasKey(FixedArray* array, Object* key) {
3076 int len0 = array->length();
3077 for (int i = 0; i < len0; i++) {
3078 Object* element = array->get(i);
3079 if (element->IsSmi() && key->IsSmi() && (element == key)) return true;
3080 if (element->IsString() &&
3081 key->IsString() && String::cast(element)->Equals(String::cast(key))) {
3082 return true;
3083 }
3084 }
3085 return false;
3086}
3087
3088
3089Object* FixedArray::AddKeysFromJSArray(JSArray* array) {
3090 ASSERT(!array->HasPixelElements());
3091 switch (array->GetElementsKind()) {
3092 case JSObject::FAST_ELEMENTS:
3093 return UnionOfKeys(FixedArray::cast(array->elements()));
3094 case JSObject::DICTIONARY_ELEMENTS: {
3095 NumberDictionary* dict = array->element_dictionary();
3096 int size = dict->NumberOfElements();
3097
3098 // Allocate a temporary fixed array.
3099 Object* object = Heap::AllocateFixedArray(size);
3100 if (object->IsFailure()) return object;
3101 FixedArray* key_array = FixedArray::cast(object);
3102
3103 int capacity = dict->Capacity();
3104 int pos = 0;
3105 // Copy the elements from the JSArray to the temporary fixed array.
3106 for (int i = 0; i < capacity; i++) {
3107 if (dict->IsKey(dict->KeyAt(i))) {
3108 key_array->set(pos++, dict->ValueAt(i));
3109 }
3110 }
3111 // Compute the union of this and the temporary fixed array.
3112 return UnionOfKeys(key_array);
3113 }
3114 default:
3115 UNREACHABLE();
3116 }
3117 UNREACHABLE();
3118 return Heap::null_value(); // Failure case needs to "return" a value.
3119}
3120
3121
3122Object* FixedArray::UnionOfKeys(FixedArray* other) {
3123 int len0 = length();
3124 int len1 = other->length();
3125 // Optimize if either is empty.
3126 if (len0 == 0) return other;
3127 if (len1 == 0) return this;
3128
3129 // Compute how many elements are not in this.
3130 int extra = 0;
3131 for (int y = 0; y < len1; y++) {
3132 Object* value = other->get(y);
3133 if (!value->IsTheHole() && !HasKey(this, value)) extra++;
3134 }
3135
3136 if (extra == 0) return this;
3137
3138 // Allocate the result
3139 Object* obj = Heap::AllocateFixedArray(len0 + extra);
3140 if (obj->IsFailure()) return obj;
3141 // Fill in the content
3142 FixedArray* result = FixedArray::cast(obj);
3143 WriteBarrierMode mode = result->GetWriteBarrierMode();
3144 for (int i = 0; i < len0; i++) {
3145 result->set(i, get(i), mode);
3146 }
3147 // Fill in the extra keys.
3148 int index = 0;
3149 for (int y = 0; y < len1; y++) {
3150 Object* value = other->get(y);
3151 if (!value->IsTheHole() && !HasKey(this, value)) {
3152 result->set(len0 + index, other->get(y), mode);
3153 index++;
3154 }
3155 }
3156 ASSERT(extra == index);
3157 return result;
3158}
3159
3160
3161Object* FixedArray::CopySize(int new_length) {
3162 if (new_length == 0) return Heap::empty_fixed_array();
3163 Object* obj = Heap::AllocateFixedArray(new_length);
3164 if (obj->IsFailure()) return obj;
3165 FixedArray* result = FixedArray::cast(obj);
3166 // Copy the content
3167 int len = length();
3168 if (new_length < len) len = new_length;
3169 result->set_map(map());
3170 WriteBarrierMode mode = result->GetWriteBarrierMode();
3171 for (int i = 0; i < len; i++) {
3172 result->set(i, get(i), mode);
3173 }
3174 return result;
3175}
3176
3177
3178void FixedArray::CopyTo(int pos, FixedArray* dest, int dest_pos, int len) {
3179 WriteBarrierMode mode = dest->GetWriteBarrierMode();
3180 for (int index = 0; index < len; index++) {
3181 dest->set(dest_pos+index, get(pos+index), mode);
3182 }
3183}
3184
3185
3186#ifdef DEBUG
3187bool FixedArray::IsEqualTo(FixedArray* other) {
3188 if (length() != other->length()) return false;
3189 for (int i = 0 ; i < length(); ++i) {
3190 if (get(i) != other->get(i)) return false;
3191 }
3192 return true;
3193}
3194#endif
3195
3196
3197Object* DescriptorArray::Allocate(int number_of_descriptors) {
3198 if (number_of_descriptors == 0) {
3199 return Heap::empty_descriptor_array();
3200 }
3201 // Allocate the array of keys.
3202 Object* array = Heap::AllocateFixedArray(ToKeyIndex(number_of_descriptors));
3203 if (array->IsFailure()) return array;
3204 // Do not use DescriptorArray::cast on incomplete object.
3205 FixedArray* result = FixedArray::cast(array);
3206
3207 // Allocate the content array and set it in the descriptor array.
3208 array = Heap::AllocateFixedArray(number_of_descriptors << 1);
3209 if (array->IsFailure()) return array;
3210 result->set(kContentArrayIndex, array);
3211 result->set(kEnumerationIndexIndex,
3212 Smi::FromInt(PropertyDetails::kInitialIndex),
3213 SKIP_WRITE_BARRIER);
3214 return result;
3215}
3216
3217
3218void DescriptorArray::SetEnumCache(FixedArray* bridge_storage,
3219 FixedArray* new_cache) {
3220 ASSERT(bridge_storage->length() >= kEnumCacheBridgeLength);
3221 if (HasEnumCache()) {
3222 FixedArray::cast(get(kEnumerationIndexIndex))->
3223 set(kEnumCacheBridgeCacheIndex, new_cache);
3224 } else {
3225 if (IsEmpty()) return; // Do nothing for empty descriptor array.
3226 FixedArray::cast(bridge_storage)->
3227 set(kEnumCacheBridgeCacheIndex, new_cache);
3228 fast_set(FixedArray::cast(bridge_storage),
3229 kEnumCacheBridgeEnumIndex,
3230 get(kEnumerationIndexIndex));
3231 set(kEnumerationIndexIndex, bridge_storage);
3232 }
3233}
3234
3235
3236Object* DescriptorArray::CopyInsert(Descriptor* descriptor,
3237 TransitionFlag transition_flag) {
3238 // Transitions are only kept when inserting another transition.
3239 // This precondition is not required by this function's implementation, but
3240 // is currently required by the semantics of maps, so we check it.
3241 // Conversely, we filter after replacing, so replacing a transition and
3242 // removing all other transitions is not supported.
3243 bool remove_transitions = transition_flag == REMOVE_TRANSITIONS;
3244 ASSERT(remove_transitions == !descriptor->GetDetails().IsTransition());
3245 ASSERT(descriptor->GetDetails().type() != NULL_DESCRIPTOR);
3246
3247 // Ensure the key is a symbol.
3248 Object* result = descriptor->KeyToSymbol();
3249 if (result->IsFailure()) return result;
3250
3251 int transitions = 0;
3252 int null_descriptors = 0;
3253 if (remove_transitions) {
3254 for (int i = 0; i < number_of_descriptors(); i++) {
3255 if (IsTransition(i)) transitions++;
3256 if (IsNullDescriptor(i)) null_descriptors++;
3257 }
3258 } else {
3259 for (int i = 0; i < number_of_descriptors(); i++) {
3260 if (IsNullDescriptor(i)) null_descriptors++;
3261 }
3262 }
3263 int new_size = number_of_descriptors() - transitions - null_descriptors;
3264
3265 // If key is in descriptor, we replace it in-place when filtering.
3266 // Count a null descriptor for key as inserted, not replaced.
3267 int index = Search(descriptor->GetKey());
3268 const bool inserting = (index == kNotFound);
3269 const bool replacing = !inserting;
3270 bool keep_enumeration_index = false;
3271 if (inserting) {
3272 ++new_size;
3273 }
3274 if (replacing) {
3275 // We are replacing an existing descriptor. We keep the enumeration
3276 // index of a visible property.
3277 PropertyType t = PropertyDetails(GetDetails(index)).type();
3278 if (t == CONSTANT_FUNCTION ||
3279 t == FIELD ||
3280 t == CALLBACKS ||
3281 t == INTERCEPTOR) {
3282 keep_enumeration_index = true;
3283 } else if (remove_transitions) {
3284 // Replaced descriptor has been counted as removed if it is
3285 // a transition that will be replaced. Adjust count in this case.
3286 ++new_size;
3287 }
3288 }
3289 result = Allocate(new_size);
3290 if (result->IsFailure()) return result;
3291 DescriptorArray* new_descriptors = DescriptorArray::cast(result);
3292 // Set the enumeration index in the descriptors and set the enumeration index
3293 // in the result.
3294 int enumeration_index = NextEnumerationIndex();
3295 if (!descriptor->GetDetails().IsTransition()) {
3296 if (keep_enumeration_index) {
3297 descriptor->SetEnumerationIndex(
3298 PropertyDetails(GetDetails(index)).index());
3299 } else {
3300 descriptor->SetEnumerationIndex(enumeration_index);
3301 ++enumeration_index;
3302 }
3303 }
3304 new_descriptors->SetNextEnumerationIndex(enumeration_index);
3305
3306 // Copy the descriptors, filtering out transitions and null descriptors,
3307 // and inserting or replacing a descriptor.
3308 uint32_t descriptor_hash = descriptor->GetKey()->Hash();
3309 int from_index = 0;
3310 int to_index = 0;
3311
3312 for (; from_index < number_of_descriptors(); from_index++) {
3313 String* key = GetKey(from_index);
3314 if (key->Hash() > descriptor_hash || key == descriptor->GetKey()) {
3315 break;
3316 }
3317 if (IsNullDescriptor(from_index)) continue;
3318 if (remove_transitions && IsTransition(from_index)) continue;
3319 new_descriptors->CopyFrom(to_index++, this, from_index);
3320 }
3321
3322 new_descriptors->Set(to_index++, descriptor);
3323 if (replacing) from_index++;
3324
3325 for (; from_index < number_of_descriptors(); from_index++) {
3326 if (IsNullDescriptor(from_index)) continue;
3327 if (remove_transitions && IsTransition(from_index)) continue;
3328 new_descriptors->CopyFrom(to_index++, this, from_index);
3329 }
3330
3331 ASSERT(to_index == new_descriptors->number_of_descriptors());
3332 SLOW_ASSERT(new_descriptors->IsSortedNoDuplicates());
3333
3334 return new_descriptors;
3335}
3336
3337
3338Object* DescriptorArray::RemoveTransitions() {
3339 // Remove all transitions and null descriptors. Return a copy of the array
3340 // with all transitions removed, or a Failure object if the new array could
3341 // not be allocated.
3342
3343 // Compute the size of the map transition entries to be removed.
3344 int num_removed = 0;
3345 for (int i = 0; i < number_of_descriptors(); i++) {
3346 if (!IsProperty(i)) num_removed++;
3347 }
3348
3349 // Allocate the new descriptor array.
3350 Object* result = Allocate(number_of_descriptors() - num_removed);
3351 if (result->IsFailure()) return result;
3352 DescriptorArray* new_descriptors = DescriptorArray::cast(result);
3353
3354 // Copy the content.
3355 int next_descriptor = 0;
3356 for (int i = 0; i < number_of_descriptors(); i++) {
3357 if (IsProperty(i)) new_descriptors->CopyFrom(next_descriptor++, this, i);
3358 }
3359 ASSERT(next_descriptor == new_descriptors->number_of_descriptors());
3360
3361 return new_descriptors;
3362}
3363
3364
3365void DescriptorArray::Sort() {
3366 // In-place heap sort.
3367 int len = number_of_descriptors();
3368
3369 // Bottom-up max-heap construction.
3370 for (int i = 1; i < len; ++i) {
3371 int child_index = i;
3372 while (child_index > 0) {
3373 int parent_index = ((child_index + 1) >> 1) - 1;
3374 uint32_t parent_hash = GetKey(parent_index)->Hash();
3375 uint32_t child_hash = GetKey(child_index)->Hash();
3376 if (parent_hash < child_hash) {
3377 Swap(parent_index, child_index);
3378 } else {
3379 break;
3380 }
3381 child_index = parent_index;
3382 }
3383 }
3384
3385 // Extract elements and create sorted array.
3386 for (int i = len - 1; i > 0; --i) {
3387 // Put max element at the back of the array.
3388 Swap(0, i);
3389 // Sift down the new top element.
3390 int parent_index = 0;
3391 while (true) {
3392 int child_index = ((parent_index + 1) << 1) - 1;
3393 if (child_index >= i) break;
3394 uint32_t child1_hash = GetKey(child_index)->Hash();
3395 uint32_t child2_hash = GetKey(child_index + 1)->Hash();
3396 uint32_t parent_hash = GetKey(parent_index)->Hash();
3397 if (child_index + 1 >= i || child1_hash > child2_hash) {
3398 if (parent_hash > child1_hash) break;
3399 Swap(parent_index, child_index);
3400 parent_index = child_index;
3401 } else {
3402 if (parent_hash > child2_hash) break;
3403 Swap(parent_index, child_index + 1);
3404 parent_index = child_index + 1;
3405 }
3406 }
3407 }
3408
3409 SLOW_ASSERT(IsSortedNoDuplicates());
3410}
3411
3412
3413int DescriptorArray::BinarySearch(String* name, int low, int high) {
3414 uint32_t hash = name->Hash();
3415
3416 while (low <= high) {
3417 int mid = (low + high) / 2;
3418 String* mid_name = GetKey(mid);
3419 uint32_t mid_hash = mid_name->Hash();
3420
3421 if (mid_hash > hash) {
3422 high = mid - 1;
3423 continue;
3424 }
3425 if (mid_hash < hash) {
3426 low = mid + 1;
3427 continue;
3428 }
3429 // Found an element with the same hash-code.
3430 ASSERT(hash == mid_hash);
3431 // There might be more, so we find the first one and
3432 // check them all to see if we have a match.
3433 if (name == mid_name && !is_null_descriptor(mid)) return mid;
3434 while ((mid > low) && (GetKey(mid - 1)->Hash() == hash)) mid--;
3435 for (; (mid <= high) && (GetKey(mid)->Hash() == hash); mid++) {
3436 if (GetKey(mid)->Equals(name) && !is_null_descriptor(mid)) return mid;
3437 }
3438 break;
3439 }
3440 return kNotFound;
3441}
3442
3443
3444int DescriptorArray::LinearSearch(String* name, int len) {
3445 uint32_t hash = name->Hash();
3446 for (int number = 0; number < len; number++) {
3447 String* entry = GetKey(number);
3448 if ((entry->Hash() == hash) &&
3449 name->Equals(entry) &&
3450 !is_null_descriptor(number)) {
3451 return number;
3452 }
3453 }
3454 return kNotFound;
3455}
3456
3457
3458#ifdef DEBUG
3459bool DescriptorArray::IsEqualTo(DescriptorArray* other) {
3460 if (IsEmpty()) return other->IsEmpty();
3461 if (other->IsEmpty()) return false;
3462 if (length() != other->length()) return false;
3463 for (int i = 0; i < length(); ++i) {
3464 if (get(i) != other->get(i) && i != kContentArrayIndex) return false;
3465 }
3466 return GetContentArray()->IsEqualTo(other->GetContentArray());
3467}
3468#endif
3469
3470
3471static StaticResource<StringInputBuffer> string_input_buffer;
3472
3473
3474bool String::LooksValid() {
3475 if (!Heap::Contains(this)) return false;
3476 return true;
3477}
3478
3479
3480int String::Utf8Length() {
3481 if (IsAsciiRepresentation()) return length();
3482 // Attempt to flatten before accessing the string. It probably
3483 // doesn't make Utf8Length faster, but it is very likely that
3484 // the string will be accessed later (for example by WriteUtf8)
3485 // so it's still a good idea.
3486 TryFlattenIfNotFlat();
3487 Access<StringInputBuffer> buffer(&string_input_buffer);
3488 buffer->Reset(0, this);
3489 int result = 0;
3490 while (buffer->has_more())
3491 result += unibrow::Utf8::Length(buffer->GetNext());
3492 return result;
3493}
3494
3495
3496Vector<const char> String::ToAsciiVector() {
3497 ASSERT(IsAsciiRepresentation());
3498 ASSERT(IsFlat());
3499
3500 int offset = 0;
3501 int length = this->length();
3502 StringRepresentationTag string_tag = StringShape(this).representation_tag();
3503 String* string = this;
3504 if (string_tag == kSlicedStringTag) {
3505 SlicedString* sliced = SlicedString::cast(string);
3506 offset += sliced->start();
3507 string = sliced->buffer();
3508 string_tag = StringShape(string).representation_tag();
3509 } else if (string_tag == kConsStringTag) {
3510 ConsString* cons = ConsString::cast(string);
3511 ASSERT(cons->second()->length() == 0);
3512 string = cons->first();
3513 string_tag = StringShape(string).representation_tag();
3514 }
3515 if (string_tag == kSeqStringTag) {
3516 SeqAsciiString* seq = SeqAsciiString::cast(string);
3517 char* start = seq->GetChars();
3518 return Vector<const char>(start + offset, length);
3519 }
3520 ASSERT(string_tag == kExternalStringTag);
3521 ExternalAsciiString* ext = ExternalAsciiString::cast(string);
3522 const char* start = ext->resource()->data();
3523 return Vector<const char>(start + offset, length);
3524}
3525
3526
3527Vector<const uc16> String::ToUC16Vector() {
3528 ASSERT(IsTwoByteRepresentation());
3529 ASSERT(IsFlat());
3530
3531 int offset = 0;
3532 int length = this->length();
3533 StringRepresentationTag string_tag = StringShape(this).representation_tag();
3534 String* string = this;
3535 if (string_tag == kSlicedStringTag) {
3536 SlicedString* sliced = SlicedString::cast(string);
3537 offset += sliced->start();
3538 string = String::cast(sliced->buffer());
3539 string_tag = StringShape(string).representation_tag();
3540 } else if (string_tag == kConsStringTag) {
3541 ConsString* cons = ConsString::cast(string);
3542 ASSERT(cons->second()->length() == 0);
3543 string = cons->first();
3544 string_tag = StringShape(string).representation_tag();
3545 }
3546 if (string_tag == kSeqStringTag) {
3547 SeqTwoByteString* seq = SeqTwoByteString::cast(string);
3548 return Vector<const uc16>(seq->GetChars() + offset, length);
3549 }
3550 ASSERT(string_tag == kExternalStringTag);
3551 ExternalTwoByteString* ext = ExternalTwoByteString::cast(string);
3552 const uc16* start =
3553 reinterpret_cast<const uc16*>(ext->resource()->data());
3554 return Vector<const uc16>(start + offset, length);
3555}
3556
3557
3558SmartPointer<char> String::ToCString(AllowNullsFlag allow_nulls,
3559 RobustnessFlag robust_flag,
3560 int offset,
3561 int length,
3562 int* length_return) {
3563 ASSERT(NativeAllocationChecker::allocation_allowed());
3564 if (robust_flag == ROBUST_STRING_TRAVERSAL && !LooksValid()) {
3565 return SmartPointer<char>(NULL);
3566 }
3567
3568 // Negative length means the to the end of the string.
3569 if (length < 0) length = kMaxInt - offset;
3570
3571 // Compute the size of the UTF-8 string. Start at the specified offset.
3572 Access<StringInputBuffer> buffer(&string_input_buffer);
3573 buffer->Reset(offset, this);
3574 int character_position = offset;
3575 int utf8_bytes = 0;
3576 while (buffer->has_more()) {
3577 uint16_t character = buffer->GetNext();
3578 if (character_position < offset + length) {
3579 utf8_bytes += unibrow::Utf8::Length(character);
3580 }
3581 character_position++;
3582 }
3583
3584 if (length_return) {
3585 *length_return = utf8_bytes;
3586 }
3587
3588 char* result = NewArray<char>(utf8_bytes + 1);
3589
3590 // Convert the UTF-16 string to a UTF-8 buffer. Start at the specified offset.
3591 buffer->Rewind();
3592 buffer->Seek(offset);
3593 character_position = offset;
3594 int utf8_byte_position = 0;
3595 while (buffer->has_more()) {
3596 uint16_t character = buffer->GetNext();
3597 if (character_position < offset + length) {
3598 if (allow_nulls == DISALLOW_NULLS && character == 0) {
3599 character = ' ';
3600 }
3601 utf8_byte_position +=
3602 unibrow::Utf8::Encode(result + utf8_byte_position, character);
3603 }
3604 character_position++;
3605 }
3606 result[utf8_byte_position] = 0;
3607 return SmartPointer<char>(result);
3608}
3609
3610
3611SmartPointer<char> String::ToCString(AllowNullsFlag allow_nulls,
3612 RobustnessFlag robust_flag,
3613 int* length_return) {
3614 return ToCString(allow_nulls, robust_flag, 0, -1, length_return);
3615}
3616
3617
3618const uc16* String::GetTwoByteData() {
3619 return GetTwoByteData(0);
3620}
3621
3622
3623const uc16* String::GetTwoByteData(unsigned start) {
3624 ASSERT(!IsAsciiRepresentation());
3625 switch (StringShape(this).representation_tag()) {
3626 case kSeqStringTag:
3627 return SeqTwoByteString::cast(this)->SeqTwoByteStringGetData(start);
3628 case kExternalStringTag:
3629 return ExternalTwoByteString::cast(this)->
3630 ExternalTwoByteStringGetData(start);
3631 case kSlicedStringTag: {
3632 SlicedString* sliced_string = SlicedString::cast(this);
3633 String* buffer = sliced_string->buffer();
3634 if (StringShape(buffer).IsCons()) {
3635 ConsString* cs = ConsString::cast(buffer);
3636 // Flattened string.
3637 ASSERT(cs->second()->length() == 0);
3638 buffer = cs->first();
3639 }
3640 return buffer->GetTwoByteData(start + sliced_string->start());
3641 }
3642 case kConsStringTag:
3643 UNREACHABLE();
3644 return NULL;
3645 }
3646 UNREACHABLE();
3647 return NULL;
3648}
3649
3650
3651SmartPointer<uc16> String::ToWideCString(RobustnessFlag robust_flag) {
3652 ASSERT(NativeAllocationChecker::allocation_allowed());
3653
3654 if (robust_flag == ROBUST_STRING_TRAVERSAL && !LooksValid()) {
3655 return SmartPointer<uc16>();
3656 }
3657
3658 Access<StringInputBuffer> buffer(&string_input_buffer);
3659 buffer->Reset(this);
3660
3661 uc16* result = NewArray<uc16>(length() + 1);
3662
3663 int i = 0;
3664 while (buffer->has_more()) {
3665 uint16_t character = buffer->GetNext();
3666 result[i++] = character;
3667 }
3668 result[i] = 0;
3669 return SmartPointer<uc16>(result);
3670}
3671
3672
3673const uc16* SeqTwoByteString::SeqTwoByteStringGetData(unsigned start) {
3674 return reinterpret_cast<uc16*>(
3675 reinterpret_cast<char*>(this) - kHeapObjectTag + kHeaderSize) + start;
3676}
3677
3678
3679void SeqTwoByteString::SeqTwoByteStringReadBlockIntoBuffer(ReadBlockBuffer* rbb,
3680 unsigned* offset_ptr,
3681 unsigned max_chars) {
3682 unsigned chars_read = 0;
3683 unsigned offset = *offset_ptr;
3684 while (chars_read < max_chars) {
3685 uint16_t c = *reinterpret_cast<uint16_t*>(
3686 reinterpret_cast<char*>(this) -
3687 kHeapObjectTag + kHeaderSize + offset * kShortSize);
3688 if (c <= kMaxAsciiCharCode) {
3689 // Fast case for ASCII characters. Cursor is an input output argument.
3690 if (!unibrow::CharacterStream::EncodeAsciiCharacter(c,
3691 rbb->util_buffer,
3692 rbb->capacity,
3693 rbb->cursor)) {
3694 break;
3695 }
3696 } else {
3697 if (!unibrow::CharacterStream::EncodeNonAsciiCharacter(c,
3698 rbb->util_buffer,
3699 rbb->capacity,
3700 rbb->cursor)) {
3701 break;
3702 }
3703 }
3704 offset++;
3705 chars_read++;
3706 }
3707 *offset_ptr = offset;
3708 rbb->remaining += chars_read;
3709}
3710
3711
3712const unibrow::byte* SeqAsciiString::SeqAsciiStringReadBlock(
3713 unsigned* remaining,
3714 unsigned* offset_ptr,
3715 unsigned max_chars) {
3716 const unibrow::byte* b = reinterpret_cast<unibrow::byte*>(this) -
3717 kHeapObjectTag + kHeaderSize + *offset_ptr * kCharSize;
3718 *remaining = max_chars;
3719 *offset_ptr += max_chars;
3720 return b;
3721}
3722
3723
3724// This will iterate unless the block of string data spans two 'halves' of
3725// a ConsString, in which case it will recurse. Since the block of string
3726// data to be read has a maximum size this limits the maximum recursion
3727// depth to something sane. Since C++ does not have tail call recursion
3728// elimination, the iteration must be explicit. Since this is not an
3729// -IntoBuffer method it can delegate to one of the efficient
3730// *AsciiStringReadBlock routines.
3731const unibrow::byte* ConsString::ConsStringReadBlock(ReadBlockBuffer* rbb,
3732 unsigned* offset_ptr,
3733 unsigned max_chars) {
3734 ConsString* current = this;
3735 unsigned offset = *offset_ptr;
3736 int offset_correction = 0;
3737
3738 while (true) {
3739 String* left = current->first();
3740 unsigned left_length = (unsigned)left->length();
3741 if (left_length > offset &&
3742 (max_chars <= left_length - offset ||
3743 (rbb->capacity <= left_length - offset &&
3744 (max_chars = left_length - offset, true)))) { // comma operator!
3745 // Left hand side only - iterate unless we have reached the bottom of
3746 // the cons tree. The assignment on the left of the comma operator is
3747 // in order to make use of the fact that the -IntoBuffer routines can
3748 // produce at most 'capacity' characters. This enables us to postpone
3749 // the point where we switch to the -IntoBuffer routines (below) in order
3750 // to maximize the chances of delegating a big chunk of work to the
3751 // efficient *AsciiStringReadBlock routines.
3752 if (StringShape(left).IsCons()) {
3753 current = ConsString::cast(left);
3754 continue;
3755 } else {
3756 const unibrow::byte* answer =
3757 String::ReadBlock(left, rbb, &offset, max_chars);
3758 *offset_ptr = offset + offset_correction;
3759 return answer;
3760 }
3761 } else if (left_length <= offset) {
3762 // Right hand side only - iterate unless we have reached the bottom of
3763 // the cons tree.
3764 String* right = current->second();
3765 offset -= left_length;
3766 offset_correction += left_length;
3767 if (StringShape(right).IsCons()) {
3768 current = ConsString::cast(right);
3769 continue;
3770 } else {
3771 const unibrow::byte* answer =
3772 String::ReadBlock(right, rbb, &offset, max_chars);
3773 *offset_ptr = offset + offset_correction;
3774 return answer;
3775 }
3776 } else {
3777 // The block to be read spans two sides of the ConsString, so we call the
3778 // -IntoBuffer version, which will recurse. The -IntoBuffer methods
3779 // are able to assemble data from several part strings because they use
3780 // the util_buffer to store their data and never return direct pointers
3781 // to their storage. We don't try to read more than the buffer capacity
3782 // here or we can get too much recursion.
3783 ASSERT(rbb->remaining == 0);
3784 ASSERT(rbb->cursor == 0);
3785 current->ConsStringReadBlockIntoBuffer(
3786 rbb,
3787 &offset,
3788 max_chars > rbb->capacity ? rbb->capacity : max_chars);
3789 *offset_ptr = offset + offset_correction;
3790 return rbb->util_buffer;
3791 }
3792 }
3793}
3794
3795
3796const unibrow::byte* SlicedString::SlicedStringReadBlock(ReadBlockBuffer* rbb,
3797 unsigned* offset_ptr,
3798 unsigned max_chars) {
3799 String* backing = buffer();
3800 unsigned offset = start() + *offset_ptr;
3801 unsigned length = backing->length();
3802 if (max_chars > length - offset) {
3803 max_chars = length - offset;
3804 }
3805 const unibrow::byte* answer =
3806 String::ReadBlock(backing, rbb, &offset, max_chars);
3807 *offset_ptr = offset - start();
3808 return answer;
3809}
3810
3811
3812uint16_t ExternalAsciiString::ExternalAsciiStringGet(int index) {
3813 ASSERT(index >= 0 && index < length());
3814 return resource()->data()[index];
3815}
3816
3817
3818const unibrow::byte* ExternalAsciiString::ExternalAsciiStringReadBlock(
3819 unsigned* remaining,
3820 unsigned* offset_ptr,
3821 unsigned max_chars) {
3822 // Cast const char* to unibrow::byte* (signedness difference).
3823 const unibrow::byte* b =
3824 reinterpret_cast<const unibrow::byte*>(resource()->data()) + *offset_ptr;
3825 *remaining = max_chars;
3826 *offset_ptr += max_chars;
3827 return b;
3828}
3829
3830
3831const uc16* ExternalTwoByteString::ExternalTwoByteStringGetData(
3832 unsigned start) {
3833 return resource()->data() + start;
3834}
3835
3836
3837uint16_t ExternalTwoByteString::ExternalTwoByteStringGet(int index) {
3838 ASSERT(index >= 0 && index < length());
3839 return resource()->data()[index];
3840}
3841
3842
3843void ExternalTwoByteString::ExternalTwoByteStringReadBlockIntoBuffer(
3844 ReadBlockBuffer* rbb,
3845 unsigned* offset_ptr,
3846 unsigned max_chars) {
3847 unsigned chars_read = 0;
3848 unsigned offset = *offset_ptr;
3849 const uint16_t* data = resource()->data();
3850 while (chars_read < max_chars) {
3851 uint16_t c = data[offset];
3852 if (c <= kMaxAsciiCharCode) {
3853 // Fast case for ASCII characters. Cursor is an input output argument.
3854 if (!unibrow::CharacterStream::EncodeAsciiCharacter(c,
3855 rbb->util_buffer,
3856 rbb->capacity,
3857 rbb->cursor))
3858 break;
3859 } else {
3860 if (!unibrow::CharacterStream::EncodeNonAsciiCharacter(c,
3861 rbb->util_buffer,
3862 rbb->capacity,
3863 rbb->cursor))
3864 break;
3865 }
3866 offset++;
3867 chars_read++;
3868 }
3869 *offset_ptr = offset;
3870 rbb->remaining += chars_read;
3871}
3872
3873
3874void SeqAsciiString::SeqAsciiStringReadBlockIntoBuffer(ReadBlockBuffer* rbb,
3875 unsigned* offset_ptr,
3876 unsigned max_chars) {
3877 unsigned capacity = rbb->capacity - rbb->cursor;
3878 if (max_chars > capacity) max_chars = capacity;
3879 memcpy(rbb->util_buffer + rbb->cursor,
3880 reinterpret_cast<char*>(this) - kHeapObjectTag + kHeaderSize +
3881 *offset_ptr * kCharSize,
3882 max_chars);
3883 rbb->remaining += max_chars;
3884 *offset_ptr += max_chars;
3885 rbb->cursor += max_chars;
3886}
3887
3888
3889void ExternalAsciiString::ExternalAsciiStringReadBlockIntoBuffer(
3890 ReadBlockBuffer* rbb,
3891 unsigned* offset_ptr,
3892 unsigned max_chars) {
3893 unsigned capacity = rbb->capacity - rbb->cursor;
3894 if (max_chars > capacity) max_chars = capacity;
3895 memcpy(rbb->util_buffer + rbb->cursor,
3896 resource()->data() + *offset_ptr,
3897 max_chars);
3898 rbb->remaining += max_chars;
3899 *offset_ptr += max_chars;
3900 rbb->cursor += max_chars;
3901}
3902
3903
3904// This method determines the type of string involved and then copies
3905// a whole chunk of characters into a buffer, or returns a pointer to a buffer
3906// where they can be found. The pointer is not necessarily valid across a GC
3907// (see AsciiStringReadBlock).
3908const unibrow::byte* String::ReadBlock(String* input,
3909 ReadBlockBuffer* rbb,
3910 unsigned* offset_ptr,
3911 unsigned max_chars) {
3912 ASSERT(*offset_ptr <= static_cast<unsigned>(input->length()));
3913 if (max_chars == 0) {
3914 rbb->remaining = 0;
3915 return NULL;
3916 }
3917 switch (StringShape(input).representation_tag()) {
3918 case kSeqStringTag:
3919 if (input->IsAsciiRepresentation()) {
3920 SeqAsciiString* str = SeqAsciiString::cast(input);
3921 return str->SeqAsciiStringReadBlock(&rbb->remaining,
3922 offset_ptr,
3923 max_chars);
3924 } else {
3925 SeqTwoByteString* str = SeqTwoByteString::cast(input);
3926 str->SeqTwoByteStringReadBlockIntoBuffer(rbb,
3927 offset_ptr,
3928 max_chars);
3929 return rbb->util_buffer;
3930 }
3931 case kConsStringTag:
3932 return ConsString::cast(input)->ConsStringReadBlock(rbb,
3933 offset_ptr,
3934 max_chars);
3935 case kSlicedStringTag:
3936 return SlicedString::cast(input)->SlicedStringReadBlock(rbb,
3937 offset_ptr,
3938 max_chars);
3939 case kExternalStringTag:
3940 if (input->IsAsciiRepresentation()) {
3941 return ExternalAsciiString::cast(input)->ExternalAsciiStringReadBlock(
3942 &rbb->remaining,
3943 offset_ptr,
3944 max_chars);
3945 } else {
3946 ExternalTwoByteString::cast(input)->
3947 ExternalTwoByteStringReadBlockIntoBuffer(rbb,
3948 offset_ptr,
3949 max_chars);
3950 return rbb->util_buffer;
3951 }
3952 default:
3953 break;
3954 }
3955
3956 UNREACHABLE();
3957 return 0;
3958}
3959
3960
3961Relocatable* Relocatable::top_ = NULL;
3962
3963
3964void Relocatable::PostGarbageCollectionProcessing() {
3965 Relocatable* current = top_;
3966 while (current != NULL) {
3967 current->PostGarbageCollection();
3968 current = current->prev_;
3969 }
3970}
3971
3972
3973// Reserve space for statics needing saving and restoring.
3974int Relocatable::ArchiveSpacePerThread() {
3975 return sizeof(top_);
3976}
3977
3978
3979// Archive statics that are thread local.
3980char* Relocatable::ArchiveState(char* to) {
3981 *reinterpret_cast<Relocatable**>(to) = top_;
3982 top_ = NULL;
3983 return to + ArchiveSpacePerThread();
3984}
3985
3986
3987// Restore statics that are thread local.
3988char* Relocatable::RestoreState(char* from) {
3989 top_ = *reinterpret_cast<Relocatable**>(from);
3990 return from + ArchiveSpacePerThread();
3991}
3992
3993
3994char* Relocatable::Iterate(ObjectVisitor* v, char* thread_storage) {
3995 Relocatable* top = *reinterpret_cast<Relocatable**>(thread_storage);
3996 Iterate(v, top);
3997 return thread_storage + ArchiveSpacePerThread();
3998}
3999
4000
4001void Relocatable::Iterate(ObjectVisitor* v) {
4002 Iterate(v, top_);
4003}
4004
4005
4006void Relocatable::Iterate(ObjectVisitor* v, Relocatable* top) {
4007 Relocatable* current = top;
4008 while (current != NULL) {
4009 current->IterateInstance(v);
4010 current = current->prev_;
4011 }
4012}
4013
4014
4015FlatStringReader::FlatStringReader(Handle<String> str)
4016 : str_(str.location()),
4017 length_(str->length()) {
4018 PostGarbageCollection();
4019}
4020
4021
4022FlatStringReader::FlatStringReader(Vector<const char> input)
4023 : str_(0),
4024 is_ascii_(true),
4025 length_(input.length()),
4026 start_(input.start()) { }
4027
4028
4029void FlatStringReader::PostGarbageCollection() {
4030 if (str_ == NULL) return;
4031 Handle<String> str(str_);
4032 ASSERT(str->IsFlat());
4033 is_ascii_ = str->IsAsciiRepresentation();
4034 if (is_ascii_) {
4035 start_ = str->ToAsciiVector().start();
4036 } else {
4037 start_ = str->ToUC16Vector().start();
4038 }
4039}
4040
4041
4042void StringInputBuffer::Seek(unsigned pos) {
4043 Reset(pos, input_);
4044}
4045
4046
4047void SafeStringInputBuffer::Seek(unsigned pos) {
4048 Reset(pos, input_);
4049}
4050
4051
4052// This method determines the type of string involved and then copies
4053// a whole chunk of characters into a buffer. It can be used with strings
4054// that have been glued together to form a ConsString and which must cooperate
4055// to fill up a buffer.
4056void String::ReadBlockIntoBuffer(String* input,
4057 ReadBlockBuffer* rbb,
4058 unsigned* offset_ptr,
4059 unsigned max_chars) {
4060 ASSERT(*offset_ptr <= (unsigned)input->length());
4061 if (max_chars == 0) return;
4062
4063 switch (StringShape(input).representation_tag()) {
4064 case kSeqStringTag:
4065 if (input->IsAsciiRepresentation()) {
4066 SeqAsciiString::cast(input)->SeqAsciiStringReadBlockIntoBuffer(rbb,
4067 offset_ptr,
4068 max_chars);
4069 return;
4070 } else {
4071 SeqTwoByteString::cast(input)->SeqTwoByteStringReadBlockIntoBuffer(rbb,
4072 offset_ptr,
4073 max_chars);
4074 return;
4075 }
4076 case kConsStringTag:
4077 ConsString::cast(input)->ConsStringReadBlockIntoBuffer(rbb,
4078 offset_ptr,
4079 max_chars);
4080 return;
4081 case kSlicedStringTag:
4082 SlicedString::cast(input)->SlicedStringReadBlockIntoBuffer(rbb,
4083 offset_ptr,
4084 max_chars);
4085 return;
4086 case kExternalStringTag:
4087 if (input->IsAsciiRepresentation()) {
4088 ExternalAsciiString::cast(input)->
4089 ExternalAsciiStringReadBlockIntoBuffer(rbb, offset_ptr, max_chars);
4090 } else {
4091 ExternalTwoByteString::cast(input)->
4092 ExternalTwoByteStringReadBlockIntoBuffer(rbb,
4093 offset_ptr,
4094 max_chars);
4095 }
4096 return;
4097 default:
4098 break;
4099 }
4100
4101 UNREACHABLE();
4102 return;
4103}
4104
4105
4106const unibrow::byte* String::ReadBlock(String* input,
4107 unibrow::byte* util_buffer,
4108 unsigned capacity,
4109 unsigned* remaining,
4110 unsigned* offset_ptr) {
4111 ASSERT(*offset_ptr <= (unsigned)input->length());
4112 unsigned chars = input->length() - *offset_ptr;
4113 ReadBlockBuffer rbb(util_buffer, 0, capacity, 0);
4114 const unibrow::byte* answer = ReadBlock(input, &rbb, offset_ptr, chars);
4115 ASSERT(rbb.remaining <= static_cast<unsigned>(input->length()));
4116 *remaining = rbb.remaining;
4117 return answer;
4118}
4119
4120
4121const unibrow::byte* String::ReadBlock(String** raw_input,
4122 unibrow::byte* util_buffer,
4123 unsigned capacity,
4124 unsigned* remaining,
4125 unsigned* offset_ptr) {
4126 Handle<String> input(raw_input);
4127 ASSERT(*offset_ptr <= (unsigned)input->length());
4128 unsigned chars = input->length() - *offset_ptr;
4129 if (chars > capacity) chars = capacity;
4130 ReadBlockBuffer rbb(util_buffer, 0, capacity, 0);
4131 ReadBlockIntoBuffer(*input, &rbb, offset_ptr, chars);
4132 ASSERT(rbb.remaining <= static_cast<unsigned>(input->length()));
4133 *remaining = rbb.remaining;
4134 return rbb.util_buffer;
4135}
4136
4137
4138// This will iterate unless the block of string data spans two 'halves' of
4139// a ConsString, in which case it will recurse. Since the block of string
4140// data to be read has a maximum size this limits the maximum recursion
4141// depth to something sane. Since C++ does not have tail call recursion
4142// elimination, the iteration must be explicit.
4143void ConsString::ConsStringReadBlockIntoBuffer(ReadBlockBuffer* rbb,
4144 unsigned* offset_ptr,
4145 unsigned max_chars) {
4146 ConsString* current = this;
4147 unsigned offset = *offset_ptr;
4148 int offset_correction = 0;
4149
4150 while (true) {
4151 String* left = current->first();
4152 unsigned left_length = (unsigned)left->length();
4153 if (left_length > offset &&
4154 max_chars <= left_length - offset) {
4155 // Left hand side only - iterate unless we have reached the bottom of
4156 // the cons tree.
4157 if (StringShape(left).IsCons()) {
4158 current = ConsString::cast(left);
4159 continue;
4160 } else {
4161 String::ReadBlockIntoBuffer(left, rbb, &offset, max_chars);
4162 *offset_ptr = offset + offset_correction;
4163 return;
4164 }
4165 } else if (left_length <= offset) {
4166 // Right hand side only - iterate unless we have reached the bottom of
4167 // the cons tree.
4168 offset -= left_length;
4169 offset_correction += left_length;
4170 String* right = current->second();
4171 if (StringShape(right).IsCons()) {
4172 current = ConsString::cast(right);
4173 continue;
4174 } else {
4175 String::ReadBlockIntoBuffer(right, rbb, &offset, max_chars);
4176 *offset_ptr = offset + offset_correction;
4177 return;
4178 }
4179 } else {
4180 // The block to be read spans two sides of the ConsString, so we recurse.
4181 // First recurse on the left.
4182 max_chars -= left_length - offset;
4183 String::ReadBlockIntoBuffer(left, rbb, &offset, left_length - offset);
4184 // We may have reached the max or there may not have been enough space
4185 // in the buffer for the characters in the left hand side.
4186 if (offset == left_length) {
4187 // Recurse on the right.
4188 String* right = String::cast(current->second());
4189 offset -= left_length;
4190 offset_correction += left_length;
4191 String::ReadBlockIntoBuffer(right, rbb, &offset, max_chars);
4192 }
4193 *offset_ptr = offset + offset_correction;
4194 return;
4195 }
4196 }
4197}
4198
4199
4200void SlicedString::SlicedStringReadBlockIntoBuffer(ReadBlockBuffer* rbb,
4201 unsigned* offset_ptr,
4202 unsigned max_chars) {
4203 String* backing = buffer();
4204 unsigned offset = start() + *offset_ptr;
4205 unsigned length = backing->length();
4206 if (max_chars > length - offset) {
4207 max_chars = length - offset;
4208 }
4209 String::ReadBlockIntoBuffer(backing, rbb, &offset, max_chars);
4210 *offset_ptr = offset - start();
4211}
4212
4213
4214void ConsString::ConsStringIterateBody(ObjectVisitor* v) {
4215 IteratePointers(v, kFirstOffset, kSecondOffset + kPointerSize);
4216}
4217
4218
4219void JSGlobalPropertyCell::JSGlobalPropertyCellIterateBody(ObjectVisitor* v) {
4220 IteratePointers(v, kValueOffset, kValueOffset + kPointerSize);
4221}
4222
4223
4224uint16_t ConsString::ConsStringGet(int index) {
4225 ASSERT(index >= 0 && index < this->length());
4226
4227 // Check for a flattened cons string
4228 if (second()->length() == 0) {
4229 String* left = first();
4230 return left->Get(index);
4231 }
4232
4233 String* string = String::cast(this);
4234
4235 while (true) {
4236 if (StringShape(string).IsCons()) {
4237 ConsString* cons_string = ConsString::cast(string);
4238 String* left = cons_string->first();
4239 if (left->length() > index) {
4240 string = left;
4241 } else {
4242 index -= left->length();
4243 string = cons_string->second();
4244 }
4245 } else {
4246 return string->Get(index);
4247 }
4248 }
4249
4250 UNREACHABLE();
4251 return 0;
4252}
4253
4254
4255template <typename sinkchar>
4256void String::WriteToFlat(String* src,
4257 sinkchar* sink,
4258 int f,
4259 int t) {
4260 String* source = src;
4261 int from = f;
4262 int to = t;
4263 while (true) {
4264 ASSERT(0 <= from && from <= to && to <= source->length());
4265 switch (StringShape(source).full_representation_tag()) {
4266 case kAsciiStringTag | kExternalStringTag: {
4267 CopyChars(sink,
4268 ExternalAsciiString::cast(source)->resource()->data() + from,
4269 to - from);
4270 return;
4271 }
4272 case kTwoByteStringTag | kExternalStringTag: {
4273 const uc16* data =
4274 ExternalTwoByteString::cast(source)->resource()->data();
4275 CopyChars(sink,
4276 data + from,
4277 to - from);
4278 return;
4279 }
4280 case kAsciiStringTag | kSeqStringTag: {
4281 CopyChars(sink,
4282 SeqAsciiString::cast(source)->GetChars() + from,
4283 to - from);
4284 return;
4285 }
4286 case kTwoByteStringTag | kSeqStringTag: {
4287 CopyChars(sink,
4288 SeqTwoByteString::cast(source)->GetChars() + from,
4289 to - from);
4290 return;
4291 }
4292 case kAsciiStringTag | kSlicedStringTag:
4293 case kTwoByteStringTag | kSlicedStringTag: {
4294 SlicedString* sliced_string = SlicedString::cast(source);
4295 int start = sliced_string->start();
4296 from += start;
4297 to += start;
4298 source = String::cast(sliced_string->buffer());
4299 break;
4300 }
4301 case kAsciiStringTag | kConsStringTag:
4302 case kTwoByteStringTag | kConsStringTag: {
4303 ConsString* cons_string = ConsString::cast(source);
4304 String* first = cons_string->first();
4305 int boundary = first->length();
4306 if (to - boundary >= boundary - from) {
4307 // Right hand side is longer. Recurse over left.
4308 if (from < boundary) {
4309 WriteToFlat(first, sink, from, boundary);
4310 sink += boundary - from;
4311 from = 0;
4312 } else {
4313 from -= boundary;
4314 }
4315 to -= boundary;
4316 source = cons_string->second();
4317 } else {
4318 // Left hand side is longer. Recurse over right.
4319 if (to > boundary) {
4320 String* second = cons_string->second();
4321 WriteToFlat(second,
4322 sink + boundary - from,
4323 0,
4324 to - boundary);
4325 to = boundary;
4326 }
4327 source = first;
4328 }
4329 break;
4330 }
4331 }
4332 }
4333}
4334
4335
4336void SlicedString::SlicedStringIterateBody(ObjectVisitor* v) {
4337 IteratePointer(v, kBufferOffset);
4338}
4339
4340
4341uint16_t SlicedString::SlicedStringGet(int index) {
4342 ASSERT(index >= 0 && index < this->length());
4343 // Delegate to the buffer string.
4344 String* underlying = buffer();
4345 return underlying->Get(start() + index);
4346}
4347
4348
4349template <typename IteratorA, typename IteratorB>
4350static inline bool CompareStringContents(IteratorA* ia, IteratorB* ib) {
4351 // General slow case check. We know that the ia and ib iterators
4352 // have the same length.
4353 while (ia->has_more()) {
4354 uc32 ca = ia->GetNext();
4355 uc32 cb = ib->GetNext();
4356 if (ca != cb)
4357 return false;
4358 }
4359 return true;
4360}
4361
4362
4363// Compares the contents of two strings by reading and comparing
4364// int-sized blocks of characters.
4365template <typename Char>
4366static inline bool CompareRawStringContents(Vector<Char> a, Vector<Char> b) {
4367 int length = a.length();
4368 ASSERT_EQ(length, b.length());
4369 const Char* pa = a.start();
4370 const Char* pb = b.start();
4371 int i = 0;
4372#ifndef V8_HOST_CAN_READ_UNALIGNED
4373 // If this architecture isn't comfortable reading unaligned ints
4374 // then we have to check that the strings are aligned before
4375 // comparing them blockwise.
4376 const int kAlignmentMask = sizeof(uint32_t) - 1; // NOLINT
4377 uint32_t pa_addr = reinterpret_cast<uint32_t>(pa);
4378 uint32_t pb_addr = reinterpret_cast<uint32_t>(pb);
4379 if (((pa_addr & kAlignmentMask) | (pb_addr & kAlignmentMask)) == 0) {
4380#endif
4381 const int kStepSize = sizeof(int) / sizeof(Char); // NOLINT
4382 int endpoint = length - kStepSize;
4383 // Compare blocks until we reach near the end of the string.
4384 for (; i <= endpoint; i += kStepSize) {
4385 uint32_t wa = *reinterpret_cast<const uint32_t*>(pa + i);
4386 uint32_t wb = *reinterpret_cast<const uint32_t*>(pb + i);
4387 if (wa != wb) {
4388 return false;
4389 }
4390 }
4391#ifndef V8_HOST_CAN_READ_UNALIGNED
4392 }
4393#endif
4394 // Compare the remaining characters that didn't fit into a block.
4395 for (; i < length; i++) {
4396 if (a[i] != b[i]) {
4397 return false;
4398 }
4399 }
4400 return true;
4401}
4402
4403
4404static StringInputBuffer string_compare_buffer_b;
4405
4406
4407template <typename IteratorA>
4408static inline bool CompareStringContentsPartial(IteratorA* ia, String* b) {
4409 if (b->IsFlat()) {
4410 if (b->IsAsciiRepresentation()) {
4411 VectorIterator<char> ib(b->ToAsciiVector());
4412 return CompareStringContents(ia, &ib);
4413 } else {
4414 VectorIterator<uc16> ib(b->ToUC16Vector());
4415 return CompareStringContents(ia, &ib);
4416 }
4417 } else {
4418 string_compare_buffer_b.Reset(0, b);
4419 return CompareStringContents(ia, &string_compare_buffer_b);
4420 }
4421}
4422
4423
4424static StringInputBuffer string_compare_buffer_a;
4425
4426
4427bool String::SlowEquals(String* other) {
4428 // Fast check: negative check with lengths.
4429 int len = length();
4430 if (len != other->length()) return false;
4431 if (len == 0) return true;
4432
4433 // Fast check: if hash code is computed for both strings
4434 // a fast negative check can be performed.
4435 if (HasHashCode() && other->HasHashCode()) {
4436 if (Hash() != other->Hash()) return false;
4437 }
4438
4439 if (StringShape(this).IsSequentialAscii() &&
4440 StringShape(other).IsSequentialAscii()) {
4441 const char* str1 = SeqAsciiString::cast(this)->GetChars();
4442 const char* str2 = SeqAsciiString::cast(other)->GetChars();
4443 return CompareRawStringContents(Vector<const char>(str1, len),
4444 Vector<const char>(str2, len));
4445 }
4446
4447 if (this->IsFlat()) {
4448 if (IsAsciiRepresentation()) {
4449 Vector<const char> vec1 = this->ToAsciiVector();
4450 if (other->IsFlat()) {
4451 if (other->IsAsciiRepresentation()) {
4452 Vector<const char> vec2 = other->ToAsciiVector();
4453 return CompareRawStringContents(vec1, vec2);
4454 } else {
4455 VectorIterator<char> buf1(vec1);
4456 VectorIterator<uc16> ib(other->ToUC16Vector());
4457 return CompareStringContents(&buf1, &ib);
4458 }
4459 } else {
4460 VectorIterator<char> buf1(vec1);
4461 string_compare_buffer_b.Reset(0, other);
4462 return CompareStringContents(&buf1, &string_compare_buffer_b);
4463 }
4464 } else {
4465 Vector<const uc16> vec1 = this->ToUC16Vector();
4466 if (other->IsFlat()) {
4467 if (other->IsAsciiRepresentation()) {
4468 VectorIterator<uc16> buf1(vec1);
4469 VectorIterator<char> ib(other->ToAsciiVector());
4470 return CompareStringContents(&buf1, &ib);
4471 } else {
4472 Vector<const uc16> vec2(other->ToUC16Vector());
4473 return CompareRawStringContents(vec1, vec2);
4474 }
4475 } else {
4476 VectorIterator<uc16> buf1(vec1);
4477 string_compare_buffer_b.Reset(0, other);
4478 return CompareStringContents(&buf1, &string_compare_buffer_b);
4479 }
4480 }
4481 } else {
4482 string_compare_buffer_a.Reset(0, this);
4483 return CompareStringContentsPartial(&string_compare_buffer_a, other);
4484 }
4485}
4486
4487
4488bool String::MarkAsUndetectable() {
4489 if (StringShape(this).IsSymbol()) return false;
4490
4491 Map* map = this->map();
4492 if (map == Heap::short_string_map()) {
4493 this->set_map(Heap::undetectable_short_string_map());
4494 return true;
4495 } else if (map == Heap::medium_string_map()) {
4496 this->set_map(Heap::undetectable_medium_string_map());
4497 return true;
4498 } else if (map == Heap::long_string_map()) {
4499 this->set_map(Heap::undetectable_long_string_map());
4500 return true;
4501 } else if (map == Heap::short_ascii_string_map()) {
4502 this->set_map(Heap::undetectable_short_ascii_string_map());
4503 return true;
4504 } else if (map == Heap::medium_ascii_string_map()) {
4505 this->set_map(Heap::undetectable_medium_ascii_string_map());
4506 return true;
4507 } else if (map == Heap::long_ascii_string_map()) {
4508 this->set_map(Heap::undetectable_long_ascii_string_map());
4509 return true;
4510 }
4511 // Rest cannot be marked as undetectable
4512 return false;
4513}
4514
4515
4516bool String::IsEqualTo(Vector<const char> str) {
4517 int slen = length();
4518 Access<Scanner::Utf8Decoder> decoder(Scanner::utf8_decoder());
4519 decoder->Reset(str.start(), str.length());
4520 int i;
4521 for (i = 0; i < slen && decoder->has_more(); i++) {
4522 uc32 r = decoder->GetNext();
4523 if (Get(i) != r) return false;
4524 }
4525 return i == slen && !decoder->has_more();
4526}
4527
4528
4529uint32_t String::ComputeAndSetHash() {
4530 // Should only be called if hash code has not yet been computed.
4531 ASSERT(!(length_field() & kHashComputedMask));
4532
4533 // Compute the hash code.
4534 StringInputBuffer buffer(this);
4535 uint32_t field = ComputeLengthAndHashField(&buffer, length());
4536
4537 // Store the hash code in the object.
4538 set_length_field(field);
4539
4540 // Check the hash code is there.
4541 ASSERT(length_field() & kHashComputedMask);
4542 uint32_t result = field >> kHashShift;
4543 ASSERT(result != 0); // Ensure that the hash value of 0 is never computed.
4544 return result;
4545}
4546
4547
4548bool String::ComputeArrayIndex(unibrow::CharacterStream* buffer,
4549 uint32_t* index,
4550 int length) {
4551 if (length == 0 || length > kMaxArrayIndexSize) return false;
4552 uc32 ch = buffer->GetNext();
4553
4554 // If the string begins with a '0' character, it must only consist
4555 // of it to be a legal array index.
4556 if (ch == '0') {
4557 *index = 0;
4558 return length == 1;
4559 }
4560
4561 // Convert string to uint32 array index; character by character.
4562 int d = ch - '0';
4563 if (d < 0 || d > 9) return false;
4564 uint32_t result = d;
4565 while (buffer->has_more()) {
4566 d = buffer->GetNext() - '0';
4567 if (d < 0 || d > 9) return false;
4568 // Check that the new result is below the 32 bit limit.
4569 if (result > 429496729U - ((d > 5) ? 1 : 0)) return false;
4570 result = (result * 10) + d;
4571 }
4572
4573 *index = result;
4574 return true;
4575}
4576
4577
4578bool String::SlowAsArrayIndex(uint32_t* index) {
4579 if (length() <= kMaxCachedArrayIndexLength) {
4580 Hash(); // force computation of hash code
4581 uint32_t field = length_field();
4582 if ((field & kIsArrayIndexMask) == 0) return false;
4583 *index = (field & ((1 << kShortLengthShift) - 1)) >> kLongLengthShift;
4584 return true;
4585 } else {
4586 StringInputBuffer buffer(this);
4587 return ComputeArrayIndex(&buffer, index, length());
4588 }
4589}
4590
4591
4592static inline uint32_t HashField(uint32_t hash, bool is_array_index) {
4593 uint32_t result =
4594 (hash << String::kLongLengthShift) | String::kHashComputedMask;
4595 if (is_array_index) result |= String::kIsArrayIndexMask;
4596 return result;
4597}
4598
4599
4600uint32_t StringHasher::GetHashField() {
4601 ASSERT(is_valid());
4602 if (length_ <= String::kMaxShortStringSize) {
4603 uint32_t payload;
4604 if (is_array_index()) {
4605 payload = v8::internal::HashField(array_index(), true);
4606 } else {
4607 payload = v8::internal::HashField(GetHash(), false);
4608 }
4609 return (payload & ((1 << String::kShortLengthShift) - 1)) |
4610 (length_ << String::kShortLengthShift);
4611 } else if (length_ <= String::kMaxMediumStringSize) {
4612 uint32_t payload = v8::internal::HashField(GetHash(), false);
4613 return (payload & ((1 << String::kMediumLengthShift) - 1)) |
4614 (length_ << String::kMediumLengthShift);
4615 } else {
4616 return v8::internal::HashField(length_, false);
4617 }
4618}
4619
4620
4621uint32_t String::ComputeLengthAndHashField(unibrow::CharacterStream* buffer,
4622 int length) {
4623 StringHasher hasher(length);
4624
4625 // Very long strings have a trivial hash that doesn't inspect the
4626 // string contents.
4627 if (hasher.has_trivial_hash()) {
4628 return hasher.GetHashField();
4629 }
4630
4631 // Do the iterative array index computation as long as there is a
4632 // chance this is an array index.
4633 while (buffer->has_more() && hasher.is_array_index()) {
4634 hasher.AddCharacter(buffer->GetNext());
4635 }
4636
4637 // Process the remaining characters without updating the array
4638 // index.
4639 while (buffer->has_more()) {
4640 hasher.AddCharacterNoIndex(buffer->GetNext());
4641 }
4642
4643 return hasher.GetHashField();
4644}
4645
4646
4647Object* String::Slice(int start, int end) {
4648 if (start == 0 && end == length()) return this;
4649 if (StringShape(this).representation_tag() == kSlicedStringTag) {
4650 // Translate slices of a SlicedString into slices of the
4651 // underlying string buffer.
4652 SlicedString* str = SlicedString::cast(this);
4653 String* buf = str->buffer();
4654 return Heap::AllocateSlicedString(buf,
4655 str->start() + start,
4656 str->start() + end);
4657 }
4658 Object* result = Heap::AllocateSlicedString(this, start, end);
4659 if (result->IsFailure()) {
4660 return result;
4661 }
4662 // Due to the way we retry after GC on allocation failure we are not allowed
4663 // to fail on allocation after this point. This is the one-allocation rule.
4664
4665 // Try to flatten a cons string that is under the sliced string.
4666 // This is to avoid memory leaks and possible stack overflows caused by
4667 // building 'towers' of sliced strings on cons strings.
4668 // This may fail due to an allocation failure (when a GC is needed), but it
4669 // will succeed often enough to avoid the problem. We only have to do this
4670 // if Heap::AllocateSlicedString actually returned a SlicedString. It will
4671 // return flat strings for small slices for efficiency reasons.
4672 String* answer = String::cast(result);
4673 if (StringShape(answer).IsSliced() &&
4674 StringShape(this).representation_tag() == kConsStringTag) {
4675 TryFlatten();
4676 // If the flatten succeeded we might as well make the sliced string point
4677 // to the flat string rather than the cons string.
4678 String* second = ConsString::cast(this)->second();
4679 if (second->length() == 0) {
4680 SlicedString::cast(answer)->set_buffer(ConsString::cast(this)->first());
4681 }
4682 }
4683 return answer;
4684}
4685
4686
4687void String::PrintOn(FILE* file) {
4688 int length = this->length();
4689 for (int i = 0; i < length; i++) {
4690 fprintf(file, "%c", Get(i));
4691 }
4692}
4693
4694
4695void Map::CreateBackPointers() {
4696 DescriptorArray* descriptors = instance_descriptors();
4697 for (int i = 0; i < descriptors->number_of_descriptors(); i++) {
4698 if (descriptors->GetType(i) == MAP_TRANSITION) {
4699 // Get target.
4700 Map* target = Map::cast(descriptors->GetValue(i));
4701#ifdef DEBUG
4702 // Verify target.
4703 Object* source_prototype = prototype();
4704 Object* target_prototype = target->prototype();
4705 ASSERT(source_prototype->IsJSObject() ||
4706 source_prototype->IsMap() ||
4707 source_prototype->IsNull());
4708 ASSERT(target_prototype->IsJSObject() ||
4709 target_prototype->IsNull());
4710 ASSERT(source_prototype->IsMap() ||
4711 source_prototype == target_prototype);
4712#endif
4713 // Point target back to source. set_prototype() will not let us set
4714 // the prototype to a map, as we do here.
4715 *RawField(target, kPrototypeOffset) = this;
4716 }
4717 }
4718}
4719
4720
4721void Map::ClearNonLiveTransitions(Object* real_prototype) {
4722 // Live DescriptorArray objects will be marked, so we must use
4723 // low-level accessors to get and modify their data.
4724 DescriptorArray* d = reinterpret_cast<DescriptorArray*>(
4725 *RawField(this, Map::kInstanceDescriptorsOffset));
4726 if (d == Heap::raw_unchecked_empty_descriptor_array()) return;
4727 Smi* NullDescriptorDetails =
4728 PropertyDetails(NONE, NULL_DESCRIPTOR).AsSmi();
4729 FixedArray* contents = reinterpret_cast<FixedArray*>(
4730 d->get(DescriptorArray::kContentArrayIndex));
4731 ASSERT(contents->length() >= 2);
4732 for (int i = 0; i < contents->length(); i += 2) {
4733 // If the pair (value, details) is a map transition,
4734 // check if the target is live. If not, null the descriptor.
4735 // Also drop the back pointer for that map transition, so that this
4736 // map is not reached again by following a back pointer from a
4737 // non-live object.
4738 PropertyDetails details(Smi::cast(contents->get(i + 1)));
4739 if (details.type() == MAP_TRANSITION) {
4740 Map* target = reinterpret_cast<Map*>(contents->get(i));
4741 ASSERT(target->IsHeapObject());
4742 if (!target->IsMarked()) {
4743 ASSERT(target->IsMap());
4744 contents->set(i + 1, NullDescriptorDetails, SKIP_WRITE_BARRIER);
4745 contents->set(i, Heap::null_value(), SKIP_WRITE_BARRIER);
4746 ASSERT(target->prototype() == this ||
4747 target->prototype() == real_prototype);
4748 // Getter prototype() is read-only, set_prototype() has side effects.
4749 *RawField(target, Map::kPrototypeOffset) = real_prototype;
4750 }
4751 }
4752 }
4753}
4754
4755
4756void Map::MapIterateBody(ObjectVisitor* v) {
4757 // Assumes all Object* members are contiguously allocated!
4758 IteratePointers(v, kPrototypeOffset, kCodeCacheOffset + kPointerSize);
4759}
4760
4761
4762Object* JSFunction::SetInstancePrototype(Object* value) {
4763 ASSERT(value->IsJSObject());
4764
4765 if (has_initial_map()) {
4766 initial_map()->set_prototype(value);
4767 } else {
4768 // Put the value in the initial map field until an initial map is
4769 // needed. At that point, a new initial map is created and the
4770 // prototype is put into the initial map where it belongs.
4771 set_prototype_or_initial_map(value);
4772 }
4773 return value;
4774}
4775
4776
4777
4778Object* JSFunction::SetPrototype(Object* value) {
4779 Object* construct_prototype = value;
4780
4781 // If the value is not a JSObject, store the value in the map's
4782 // constructor field so it can be accessed. Also, set the prototype
4783 // used for constructing objects to the original object prototype.
4784 // See ECMA-262 13.2.2.
4785 if (!value->IsJSObject()) {
4786 // Copy the map so this does not affect unrelated functions.
4787 // Remove map transitions because they point to maps with a
4788 // different prototype.
4789 Object* new_map = map()->CopyDropTransitions();
4790 if (new_map->IsFailure()) return new_map;
4791 set_map(Map::cast(new_map));
4792 map()->set_constructor(value);
4793 map()->set_non_instance_prototype(true);
4794 construct_prototype =
4795 Top::context()->global_context()->initial_object_prototype();
4796 } else {
4797 map()->set_non_instance_prototype(false);
4798 }
4799
4800 return SetInstancePrototype(construct_prototype);
4801}
4802
4803
4804Object* JSFunction::SetInstanceClassName(String* name) {
4805 shared()->set_instance_class_name(name);
4806 return this;
4807}
4808
4809
4810Context* JSFunction::GlobalContextFromLiterals(FixedArray* literals) {
4811 return Context::cast(literals->get(JSFunction::kLiteralGlobalContextIndex));
4812}
4813
4814
4815void Oddball::OddballIterateBody(ObjectVisitor* v) {
4816 // Assumes all Object* members are contiguously allocated!
4817 IteratePointers(v, kToStringOffset, kToNumberOffset + kPointerSize);
4818}
4819
4820
4821Object* Oddball::Initialize(const char* to_string, Object* to_number) {
4822 Object* symbol = Heap::LookupAsciiSymbol(to_string);
4823 if (symbol->IsFailure()) return symbol;
4824 set_to_string(String::cast(symbol));
4825 set_to_number(to_number);
4826 return this;
4827}
4828
4829
4830bool SharedFunctionInfo::HasSourceCode() {
4831 return !script()->IsUndefined() &&
4832 !Script::cast(script())->source()->IsUndefined();
4833}
4834
4835
4836Object* SharedFunctionInfo::GetSourceCode() {
4837 HandleScope scope;
4838 if (script()->IsUndefined()) return Heap::undefined_value();
4839 Object* source = Script::cast(script())->source();
4840 if (source->IsUndefined()) return Heap::undefined_value();
4841 return *SubString(Handle<String>(String::cast(source)),
4842 start_position(), end_position());
4843}
4844
4845
4846int SharedFunctionInfo::CalculateInstanceSize() {
4847 int instance_size =
4848 JSObject::kHeaderSize +
4849 expected_nof_properties() * kPointerSize;
4850 if (instance_size > JSObject::kMaxInstanceSize) {
4851 instance_size = JSObject::kMaxInstanceSize;
4852 }
4853 return instance_size;
4854}
4855
4856
4857int SharedFunctionInfo::CalculateInObjectProperties() {
4858 return (CalculateInstanceSize() - JSObject::kHeaderSize) / kPointerSize;
4859}
4860
4861
4862void SharedFunctionInfo::SetThisPropertyAssignmentsInfo(
4863 bool only_this_property_assignments,
4864 bool only_simple_this_property_assignments,
4865 FixedArray* assignments) {
4866 set_compiler_hints(BooleanBit::set(compiler_hints(),
4867 kHasOnlyThisPropertyAssignments,
4868 only_this_property_assignments));
4869 set_compiler_hints(BooleanBit::set(compiler_hints(),
4870 kHasOnlySimpleThisPropertyAssignments,
4871 only_simple_this_property_assignments));
4872 set_this_property_assignments(assignments);
4873 set_this_property_assignments_count(assignments->length() / 3);
4874}
4875
4876
4877void SharedFunctionInfo::ClearThisPropertyAssignmentsInfo() {
4878 set_compiler_hints(BooleanBit::set(compiler_hints(),
4879 kHasOnlyThisPropertyAssignments,
4880 false));
4881 set_compiler_hints(BooleanBit::set(compiler_hints(),
4882 kHasOnlySimpleThisPropertyAssignments,
4883 false));
4884 set_this_property_assignments(Heap::undefined_value());
4885 set_this_property_assignments_count(0);
4886}
4887
4888
4889String* SharedFunctionInfo::GetThisPropertyAssignmentName(int index) {
4890 Object* obj = this_property_assignments();
4891 ASSERT(obj->IsFixedArray());
4892 ASSERT(index < this_property_assignments_count());
4893 obj = FixedArray::cast(obj)->get(index * 3);
4894 ASSERT(obj->IsString());
4895 return String::cast(obj);
4896}
4897
4898
4899bool SharedFunctionInfo::IsThisPropertyAssignmentArgument(int index) {
4900 Object* obj = this_property_assignments();
4901 ASSERT(obj->IsFixedArray());
4902 ASSERT(index < this_property_assignments_count());
4903 obj = FixedArray::cast(obj)->get(index * 3 + 1);
4904 return Smi::cast(obj)->value() != -1;
4905}
4906
4907
4908int SharedFunctionInfo::GetThisPropertyAssignmentArgument(int index) {
4909 ASSERT(IsThisPropertyAssignmentArgument(index));
4910 Object* obj =
4911 FixedArray::cast(this_property_assignments())->get(index * 3 + 1);
4912 return Smi::cast(obj)->value();
4913}
4914
4915
4916Object* SharedFunctionInfo::GetThisPropertyAssignmentConstant(int index) {
4917 ASSERT(!IsThisPropertyAssignmentArgument(index));
4918 Object* obj =
4919 FixedArray::cast(this_property_assignments())->get(index * 3 + 2);
4920 return obj;
4921}
4922
4923
4924
4925// Support function for printing the source code to a StringStream
4926// without any allocation in the heap.
4927void SharedFunctionInfo::SourceCodePrint(StringStream* accumulator,
4928 int max_length) {
4929 // For some native functions there is no source.
4930 if (script()->IsUndefined() ||
4931 Script::cast(script())->source()->IsUndefined()) {
4932 accumulator->Add("<No Source>");
4933 return;
4934 }
4935
4936 // Get the slice of the source for this function.
4937 // Don't use String::cast because we don't want more assertion errors while
4938 // we are already creating a stack dump.
4939 String* script_source =
4940 reinterpret_cast<String*>(Script::cast(script())->source());
4941
4942 if (!script_source->LooksValid()) {
4943 accumulator->Add("<Invalid Source>");
4944 return;
4945 }
4946
4947 if (!is_toplevel()) {
4948 accumulator->Add("function ");
4949 Object* name = this->name();
4950 if (name->IsString() && String::cast(name)->length() > 0) {
4951 accumulator->PrintName(name);
4952 }
4953 }
4954
4955 int len = end_position() - start_position();
4956 if (len > max_length) {
4957 accumulator->Put(script_source,
4958 start_position(),
4959 start_position() + max_length);
4960 accumulator->Add("...\n");
4961 } else {
4962 accumulator->Put(script_source, start_position(), end_position());
4963 }
4964}
4965
4966
4967void SharedFunctionInfo::SharedFunctionInfoIterateBody(ObjectVisitor* v) {
4968 IteratePointers(v, kNameOffset, kConstructStubOffset + kPointerSize);
4969 IteratePointers(v, kInstanceClassNameOffset, kScriptOffset + kPointerSize);
4970 IteratePointers(v, kDebugInfoOffset, kInferredNameOffset + kPointerSize);
4971 IteratePointers(v, kThisPropertyAssignmentsOffset,
4972 kThisPropertyAssignmentsOffset + kPointerSize);
4973}
4974
4975
4976void ObjectVisitor::VisitCodeTarget(RelocInfo* rinfo) {
4977 ASSERT(RelocInfo::IsCodeTarget(rinfo->rmode()));
4978 Object* target = Code::GetCodeFromTargetAddress(rinfo->target_address());
4979 Object* old_target = target;
4980 VisitPointer(&target);
4981 CHECK_EQ(target, old_target); // VisitPointer doesn't change Code* *target.
4982}
4983
4984
4985void ObjectVisitor::VisitDebugTarget(RelocInfo* rinfo) {
4986 ASSERT(RelocInfo::IsJSReturn(rinfo->rmode()) && rinfo->IsCallInstruction());
4987 Object* target = Code::GetCodeFromTargetAddress(rinfo->call_address());
4988 Object* old_target = target;
4989 VisitPointer(&target);
4990 CHECK_EQ(target, old_target); // VisitPointer doesn't change Code* *target.
4991}
4992
4993
4994void Code::CodeIterateBody(ObjectVisitor* v) {
4995 int mode_mask = RelocInfo::kCodeTargetMask |
4996 RelocInfo::ModeMask(RelocInfo::EMBEDDED_OBJECT) |
4997 RelocInfo::ModeMask(RelocInfo::EXTERNAL_REFERENCE) |
4998 RelocInfo::ModeMask(RelocInfo::JS_RETURN) |
4999 RelocInfo::ModeMask(RelocInfo::RUNTIME_ENTRY);
5000
5001 for (RelocIterator it(this, mode_mask); !it.done(); it.next()) {
5002 RelocInfo::Mode rmode = it.rinfo()->rmode();
5003 if (rmode == RelocInfo::EMBEDDED_OBJECT) {
5004 v->VisitPointer(it.rinfo()->target_object_address());
5005 } else if (RelocInfo::IsCodeTarget(rmode)) {
5006 v->VisitCodeTarget(it.rinfo());
5007 } else if (rmode == RelocInfo::EXTERNAL_REFERENCE) {
5008 v->VisitExternalReference(it.rinfo()->target_reference_address());
5009#ifdef ENABLE_DEBUGGER_SUPPORT
5010 } else if (Debug::has_break_points() &&
5011 RelocInfo::IsJSReturn(rmode) &&
5012 it.rinfo()->IsCallInstruction()) {
5013 v->VisitDebugTarget(it.rinfo());
5014#endif
5015 } else if (rmode == RelocInfo::RUNTIME_ENTRY) {
5016 v->VisitRuntimeEntry(it.rinfo());
5017 }
5018 }
5019
5020 ScopeInfo<>::IterateScopeInfo(this, v);
5021}
5022
5023
5024void Code::Relocate(int delta) {
5025 for (RelocIterator it(this, RelocInfo::kApplyMask); !it.done(); it.next()) {
5026 it.rinfo()->apply(delta);
5027 }
5028 CPU::FlushICache(instruction_start(), instruction_size());
5029}
5030
5031
5032void Code::CopyFrom(const CodeDesc& desc) {
5033 // copy code
5034 memmove(instruction_start(), desc.buffer, desc.instr_size);
5035
5036 // fill gap with zero bytes
5037 { byte* p = instruction_start() + desc.instr_size;
5038 byte* q = relocation_start();
5039 while (p < q) {
5040 *p++ = 0;
5041 }
5042 }
5043
5044 // copy reloc info
5045 memmove(relocation_start(),
5046 desc.buffer + desc.buffer_size - desc.reloc_size,
5047 desc.reloc_size);
5048
5049 // unbox handles and relocate
5050 int delta = instruction_start() - desc.buffer;
5051 int mode_mask = RelocInfo::kCodeTargetMask |
5052 RelocInfo::ModeMask(RelocInfo::EMBEDDED_OBJECT) |
5053 RelocInfo::kApplyMask;
5054 for (RelocIterator it(this, mode_mask); !it.done(); it.next()) {
5055 RelocInfo::Mode mode = it.rinfo()->rmode();
5056 if (mode == RelocInfo::EMBEDDED_OBJECT) {
5057 Object** p = reinterpret_cast<Object**>(it.rinfo()->target_object());
5058 it.rinfo()->set_target_object(*p);
5059 } else if (RelocInfo::IsCodeTarget(mode)) {
5060 // rewrite code handles in inline cache targets to direct
5061 // pointers to the first instruction in the code object
5062 Object** p = reinterpret_cast<Object**>(it.rinfo()->target_object());
5063 Code* code = Code::cast(*p);
5064 it.rinfo()->set_target_address(code->instruction_start());
5065 } else {
5066 it.rinfo()->apply(delta);
5067 }
5068 }
5069 CPU::FlushICache(instruction_start(), instruction_size());
5070}
5071
5072
5073// Locate the source position which is closest to the address in the code. This
5074// is using the source position information embedded in the relocation info.
5075// The position returned is relative to the beginning of the script where the
5076// source for this function is found.
5077int Code::SourcePosition(Address pc) {
5078 int distance = kMaxInt;
5079 int position = RelocInfo::kNoPosition; // Initially no position found.
5080 // Run through all the relocation info to find the best matching source
5081 // position. All the code needs to be considered as the sequence of the
5082 // instructions in the code does not necessarily follow the same order as the
5083 // source.
5084 RelocIterator it(this, RelocInfo::kPositionMask);
5085 while (!it.done()) {
5086 // Only look at positions after the current pc.
5087 if (it.rinfo()->pc() < pc) {
5088 // Get position and distance.
5089 int dist = pc - it.rinfo()->pc();
5090 int pos = it.rinfo()->data();
5091 // If this position is closer than the current candidate or if it has the
5092 // same distance as the current candidate and the position is higher then
5093 // this position is the new candidate.
5094 if ((dist < distance) ||
5095 (dist == distance && pos > position)) {
5096 position = pos;
5097 distance = dist;
5098 }
5099 }
5100 it.next();
5101 }
5102 return position;
5103}
5104
5105
5106// Same as Code::SourcePosition above except it only looks for statement
5107// positions.
5108int Code::SourceStatementPosition(Address pc) {
5109 // First find the position as close as possible using all position
5110 // information.
5111 int position = SourcePosition(pc);
5112 // Now find the closest statement position before the position.
5113 int statement_position = 0;
5114 RelocIterator it(this, RelocInfo::kPositionMask);
5115 while (!it.done()) {
5116 if (RelocInfo::IsStatementPosition(it.rinfo()->rmode())) {
5117 int p = it.rinfo()->data();
5118 if (statement_position < p && p <= position) {
5119 statement_position = p;
5120 }
5121 }
5122 it.next();
5123 }
5124 return statement_position;
5125}
5126
5127
5128#ifdef ENABLE_DISASSEMBLER
5129// Identify kind of code.
5130const char* Code::Kind2String(Kind kind) {
5131 switch (kind) {
5132 case FUNCTION: return "FUNCTION";
5133 case STUB: return "STUB";
5134 case BUILTIN: return "BUILTIN";
5135 case LOAD_IC: return "LOAD_IC";
5136 case KEYED_LOAD_IC: return "KEYED_LOAD_IC";
5137 case STORE_IC: return "STORE_IC";
5138 case KEYED_STORE_IC: return "KEYED_STORE_IC";
5139 case CALL_IC: return "CALL_IC";
5140 }
5141 UNREACHABLE();
5142 return NULL;
5143}
5144
5145
5146const char* Code::ICState2String(InlineCacheState state) {
5147 switch (state) {
5148 case UNINITIALIZED: return "UNINITIALIZED";
5149 case PREMONOMORPHIC: return "PREMONOMORPHIC";
5150 case MONOMORPHIC: return "MONOMORPHIC";
5151 case MONOMORPHIC_PROTOTYPE_FAILURE: return "MONOMORPHIC_PROTOTYPE_FAILURE";
5152 case MEGAMORPHIC: return "MEGAMORPHIC";
5153 case DEBUG_BREAK: return "DEBUG_BREAK";
5154 case DEBUG_PREPARE_STEP_IN: return "DEBUG_PREPARE_STEP_IN";
5155 }
5156 UNREACHABLE();
5157 return NULL;
5158}
5159
5160
5161const char* Code::PropertyType2String(PropertyType type) {
5162 switch (type) {
5163 case NORMAL: return "NORMAL";
5164 case FIELD: return "FIELD";
5165 case CONSTANT_FUNCTION: return "CONSTANT_FUNCTION";
5166 case CALLBACKS: return "CALLBACKS";
5167 case INTERCEPTOR: return "INTERCEPTOR";
5168 case MAP_TRANSITION: return "MAP_TRANSITION";
5169 case CONSTANT_TRANSITION: return "CONSTANT_TRANSITION";
5170 case NULL_DESCRIPTOR: return "NULL_DESCRIPTOR";
5171 }
5172 UNREACHABLE();
5173 return NULL;
5174}
5175
5176void Code::Disassemble(const char* name) {
5177 PrintF("kind = %s\n", Kind2String(kind()));
5178 if (is_inline_cache_stub()) {
5179 PrintF("ic_state = %s\n", ICState2String(ic_state()));
5180 PrintF("ic_in_loop = %d\n", ic_in_loop() == IN_LOOP);
5181 if (ic_state() == MONOMORPHIC) {
5182 PrintF("type = %s\n", PropertyType2String(type()));
5183 }
5184 }
5185 if ((name != NULL) && (name[0] != '\0')) {
5186 PrintF("name = %s\n", name);
5187 }
5188
5189 PrintF("Instructions (size = %d)\n", instruction_size());
5190 Disassembler::Decode(NULL, this);
5191 PrintF("\n");
5192
5193 PrintF("RelocInfo (size = %d)\n", relocation_size());
5194 for (RelocIterator it(this); !it.done(); it.next())
5195 it.rinfo()->Print();
5196 PrintF("\n");
5197}
5198#endif // ENABLE_DISASSEMBLER
5199
5200
5201void JSObject::SetFastElements(FixedArray* elems) {
5202 // We should never end in here with a pixel array.
5203 ASSERT(!HasPixelElements());
5204#ifdef DEBUG
5205 // Check the provided array is filled with the_hole.
5206 uint32_t len = static_cast<uint32_t>(elems->length());
5207 for (uint32_t i = 0; i < len; i++) ASSERT(elems->get(i)->IsTheHole());
5208#endif
5209 WriteBarrierMode mode = elems->GetWriteBarrierMode();
5210 switch (GetElementsKind()) {
5211 case FAST_ELEMENTS: {
5212 FixedArray* old_elements = FixedArray::cast(elements());
5213 uint32_t old_length = static_cast<uint32_t>(old_elements->length());
5214 // Fill out the new array with this content and array holes.
5215 for (uint32_t i = 0; i < old_length; i++) {
5216 elems->set(i, old_elements->get(i), mode);
5217 }
5218 break;
5219 }
5220 case DICTIONARY_ELEMENTS: {
5221 NumberDictionary* dictionary = NumberDictionary::cast(elements());
5222 for (int i = 0; i < dictionary->Capacity(); i++) {
5223 Object* key = dictionary->KeyAt(i);
5224 if (key->IsNumber()) {
5225 uint32_t entry = static_cast<uint32_t>(key->Number());
5226 elems->set(entry, dictionary->ValueAt(i), mode);
5227 }
5228 }
5229 break;
5230 }
5231 default:
5232 UNREACHABLE();
5233 break;
5234 }
5235 set_elements(elems);
5236}
5237
5238
5239Object* JSObject::SetSlowElements(Object* len) {
5240 // We should never end in here with a pixel array.
5241 ASSERT(!HasPixelElements());
5242
5243 uint32_t new_length = static_cast<uint32_t>(len->Number());
5244
5245 switch (GetElementsKind()) {
5246 case FAST_ELEMENTS: {
5247 // Make sure we never try to shrink dense arrays into sparse arrays.
5248 ASSERT(static_cast<uint32_t>(FixedArray::cast(elements())->length()) <=
5249 new_length);
5250 Object* obj = NormalizeElements();
5251 if (obj->IsFailure()) return obj;
5252
5253 // Update length for JSArrays.
5254 if (IsJSArray()) JSArray::cast(this)->set_length(len);
5255 break;
5256 }
5257 case DICTIONARY_ELEMENTS: {
5258 if (IsJSArray()) {
5259 uint32_t old_length =
5260 static_cast<uint32_t>(JSArray::cast(this)->length()->Number());
5261 element_dictionary()->RemoveNumberEntries(new_length, old_length),
5262 JSArray::cast(this)->set_length(len);
5263 }
5264 break;
5265 }
5266 default:
5267 UNREACHABLE();
5268 break;
5269 }
5270 return this;
5271}
5272
5273
5274Object* JSArray::Initialize(int capacity) {
5275 ASSERT(capacity >= 0);
5276 set_length(Smi::FromInt(0), SKIP_WRITE_BARRIER);
5277 FixedArray* new_elements;
5278 if (capacity == 0) {
5279 new_elements = Heap::empty_fixed_array();
5280 } else {
5281 Object* obj = Heap::AllocateFixedArrayWithHoles(capacity);
5282 if (obj->IsFailure()) return obj;
5283 new_elements = FixedArray::cast(obj);
5284 }
5285 set_elements(new_elements);
5286 return this;
5287}
5288
5289
5290void JSArray::Expand(int required_size) {
5291 Handle<JSArray> self(this);
5292 Handle<FixedArray> old_backing(FixedArray::cast(elements()));
5293 int old_size = old_backing->length();
5294 // Doubling in size would be overkill, but leave some slack to avoid
5295 // constantly growing.
5296 int new_size = required_size + (required_size >> 3);
5297 Handle<FixedArray> new_backing = Factory::NewFixedArray(new_size);
5298 // Can't use this any more now because we may have had a GC!
5299 for (int i = 0; i < old_size; i++) new_backing->set(i, old_backing->get(i));
5300 self->SetContent(*new_backing);
5301}
5302
5303
5304// Computes the new capacity when expanding the elements of a JSObject.
5305static int NewElementsCapacity(int old_capacity) {
5306 // (old_capacity + 50%) + 16
5307 return old_capacity + (old_capacity >> 1) + 16;
5308}
5309
5310
5311static Object* ArrayLengthRangeError() {
5312 HandleScope scope;
5313 return Top::Throw(*Factory::NewRangeError("invalid_array_length",
5314 HandleVector<Object>(NULL, 0)));
5315}
5316
5317
5318Object* JSObject::SetElementsLength(Object* len) {
5319 // We should never end in here with a pixel array.
5320 ASSERT(!HasPixelElements());
5321
5322 Object* smi_length = len->ToSmi();
5323 if (smi_length->IsSmi()) {
5324 int value = Smi::cast(smi_length)->value();
5325 if (value < 0) return ArrayLengthRangeError();
5326 switch (GetElementsKind()) {
5327 case FAST_ELEMENTS: {
5328 int old_capacity = FixedArray::cast(elements())->length();
5329 if (value <= old_capacity) {
5330 if (IsJSArray()) {
5331 int old_length = FastD2I(JSArray::cast(this)->length()->Number());
5332 // NOTE: We may be able to optimize this by removing the
5333 // last part of the elements backing storage array and
5334 // setting the capacity to the new size.
5335 for (int i = value; i < old_length; i++) {
5336 FixedArray::cast(elements())->set_the_hole(i);
5337 }
5338 JSArray::cast(this)->set_length(smi_length, SKIP_WRITE_BARRIER);
5339 }
5340 return this;
5341 }
5342 int min = NewElementsCapacity(old_capacity);
5343 int new_capacity = value > min ? value : min;
5344 if (new_capacity <= kMaxFastElementsLength ||
5345 !ShouldConvertToSlowElements(new_capacity)) {
5346 Object* obj = Heap::AllocateFixedArrayWithHoles(new_capacity);
5347 if (obj->IsFailure()) return obj;
5348 if (IsJSArray()) JSArray::cast(this)->set_length(smi_length,
5349 SKIP_WRITE_BARRIER);
5350 SetFastElements(FixedArray::cast(obj));
5351 return this;
5352 }
5353 break;
5354 }
5355 case DICTIONARY_ELEMENTS: {
5356 if (IsJSArray()) {
5357 if (value == 0) {
5358 // If the length of a slow array is reset to zero, we clear
5359 // the array and flush backing storage. This has the added
5360 // benefit that the array returns to fast mode.
5361 initialize_elements();
5362 } else {
5363 // Remove deleted elements.
5364 uint32_t old_length =
5365 static_cast<uint32_t>(JSArray::cast(this)->length()->Number());
5366 element_dictionary()->RemoveNumberEntries(value, old_length);
5367 }
5368 JSArray::cast(this)->set_length(smi_length, SKIP_WRITE_BARRIER);
5369 }
5370 return this;
5371 }
5372 default:
5373 UNREACHABLE();
5374 break;
5375 }
5376 }
5377
5378 // General slow case.
5379 if (len->IsNumber()) {
5380 uint32_t length;
5381 if (Array::IndexFromObject(len, &length)) {
5382 return SetSlowElements(len);
5383 } else {
5384 return ArrayLengthRangeError();
5385 }
5386 }
5387
5388 // len is not a number so make the array size one and
5389 // set only element to len.
5390 Object* obj = Heap::AllocateFixedArray(1);
5391 if (obj->IsFailure()) return obj;
5392 FixedArray::cast(obj)->set(0, len);
5393 if (IsJSArray()) JSArray::cast(this)->set_length(Smi::FromInt(1),
5394 SKIP_WRITE_BARRIER);
5395 set_elements(FixedArray::cast(obj));
5396 return this;
5397}
5398
5399
5400bool JSObject::HasElementPostInterceptor(JSObject* receiver, uint32_t index) {
5401 switch (GetElementsKind()) {
5402 case FAST_ELEMENTS: {
5403 uint32_t length = IsJSArray() ?
5404 static_cast<uint32_t>
5405 (Smi::cast(JSArray::cast(this)->length())->value()) :
5406 static_cast<uint32_t>(FixedArray::cast(elements())->length());
5407 if ((index < length) &&
5408 !FixedArray::cast(elements())->get(index)->IsTheHole()) {
5409 return true;
5410 }
5411 break;
5412 }
5413 case PIXEL_ELEMENTS: {
5414 // TODO(iposva): Add testcase.
5415 PixelArray* pixels = PixelArray::cast(elements());
5416 if (index < static_cast<uint32_t>(pixels->length())) {
5417 return true;
5418 }
5419 break;
5420 }
5421 case DICTIONARY_ELEMENTS: {
5422 if (element_dictionary()->FindEntry(index)
5423 != NumberDictionary::kNotFound) {
5424 return true;
5425 }
5426 break;
5427 }
5428 default:
5429 UNREACHABLE();
5430 break;
5431 }
5432
5433 // Handle [] on String objects.
5434 if (this->IsStringObjectWithCharacterAt(index)) return true;
5435
5436 Object* pt = GetPrototype();
5437 if (pt == Heap::null_value()) return false;
5438 return JSObject::cast(pt)->HasElementWithReceiver(receiver, index);
5439}
5440
5441
5442bool JSObject::HasElementWithInterceptor(JSObject* receiver, uint32_t index) {
5443 // Make sure that the top context does not change when doing
5444 // callbacks or interceptor calls.
5445 AssertNoContextChange ncc;
5446 HandleScope scope;
5447 Handle<InterceptorInfo> interceptor(GetIndexedInterceptor());
5448 Handle<JSObject> receiver_handle(receiver);
5449 Handle<JSObject> holder_handle(this);
5450 CustomArguments args(interceptor->data(), receiver, this);
5451 v8::AccessorInfo info(args.end());
5452 if (!interceptor->query()->IsUndefined()) {
5453 v8::IndexedPropertyQuery query =
5454 v8::ToCData<v8::IndexedPropertyQuery>(interceptor->query());
5455 LOG(ApiIndexedPropertyAccess("interceptor-indexed-has", this, index));
5456 v8::Handle<v8::Boolean> result;
5457 {
5458 // Leaving JavaScript.
5459 VMState state(EXTERNAL);
5460 result = query(index, info);
5461 }
5462 if (!result.IsEmpty()) return result->IsTrue();
5463 } else if (!interceptor->getter()->IsUndefined()) {
5464 v8::IndexedPropertyGetter getter =
5465 v8::ToCData<v8::IndexedPropertyGetter>(interceptor->getter());
5466 LOG(ApiIndexedPropertyAccess("interceptor-indexed-has-get", this, index));
5467 v8::Handle<v8::Value> result;
5468 {
5469 // Leaving JavaScript.
5470 VMState state(EXTERNAL);
5471 result = getter(index, info);
5472 }
5473 if (!result.IsEmpty()) return true;
5474 }
5475 return holder_handle->HasElementPostInterceptor(*receiver_handle, index);
5476}
5477
5478
5479bool JSObject::HasLocalElement(uint32_t index) {
5480 // Check access rights if needed.
5481 if (IsAccessCheckNeeded() &&
5482 !Top::MayIndexedAccess(this, index, v8::ACCESS_HAS)) {
5483 Top::ReportFailedAccessCheck(this, v8::ACCESS_HAS);
5484 return false;
5485 }
5486
5487 // Check for lookup interceptor
5488 if (HasIndexedInterceptor()) {
5489 return HasElementWithInterceptor(this, index);
5490 }
5491
5492 // Handle [] on String objects.
5493 if (this->IsStringObjectWithCharacterAt(index)) return true;
5494
5495 switch (GetElementsKind()) {
5496 case FAST_ELEMENTS: {
5497 uint32_t length = IsJSArray() ?
5498 static_cast<uint32_t>
5499 (Smi::cast(JSArray::cast(this)->length())->value()) :
5500 static_cast<uint32_t>(FixedArray::cast(elements())->length());
5501 return (index < length) &&
5502 !FixedArray::cast(elements())->get(index)->IsTheHole();
5503 }
5504 case PIXEL_ELEMENTS: {
5505 PixelArray* pixels = PixelArray::cast(elements());
5506 return (index < static_cast<uint32_t>(pixels->length()));
5507 }
5508 case DICTIONARY_ELEMENTS: {
5509 return element_dictionary()->FindEntry(index)
5510 != NumberDictionary::kNotFound;
5511 }
5512 default:
5513 UNREACHABLE();
5514 break;
5515 }
5516 UNREACHABLE();
5517 return Heap::null_value();
5518}
5519
5520
5521bool JSObject::HasElementWithReceiver(JSObject* receiver, uint32_t index) {
5522 // Check access rights if needed.
5523 if (IsAccessCheckNeeded() &&
5524 !Top::MayIndexedAccess(this, index, v8::ACCESS_HAS)) {
5525 Top::ReportFailedAccessCheck(this, v8::ACCESS_HAS);
5526 return false;
5527 }
5528
5529 // Check for lookup interceptor
5530 if (HasIndexedInterceptor()) {
5531 return HasElementWithInterceptor(receiver, index);
5532 }
5533
5534 switch (GetElementsKind()) {
5535 case FAST_ELEMENTS: {
5536 uint32_t length = IsJSArray() ?
5537 static_cast<uint32_t>
5538 (Smi::cast(JSArray::cast(this)->length())->value()) :
5539 static_cast<uint32_t>(FixedArray::cast(elements())->length());
5540 if ((index < length) &&
5541 !FixedArray::cast(elements())->get(index)->IsTheHole()) return true;
5542 break;
5543 }
5544 case PIXEL_ELEMENTS: {
5545 PixelArray* pixels = PixelArray::cast(elements());
5546 if (index < static_cast<uint32_t>(pixels->length())) {
5547 return true;
5548 }
5549 break;
5550 }
5551 case DICTIONARY_ELEMENTS: {
5552 if (element_dictionary()->FindEntry(index)
5553 != NumberDictionary::kNotFound) {
5554 return true;
5555 }
5556 break;
5557 }
5558 default:
5559 UNREACHABLE();
5560 break;
5561 }
5562
5563 // Handle [] on String objects.
5564 if (this->IsStringObjectWithCharacterAt(index)) return true;
5565
5566 Object* pt = GetPrototype();
5567 if (pt == Heap::null_value()) return false;
5568 return JSObject::cast(pt)->HasElementWithReceiver(receiver, index);
5569}
5570
5571
5572Object* JSObject::SetElementWithInterceptor(uint32_t index, Object* value) {
5573 // Make sure that the top context does not change when doing
5574 // callbacks or interceptor calls.
5575 AssertNoContextChange ncc;
5576 HandleScope scope;
5577 Handle<InterceptorInfo> interceptor(GetIndexedInterceptor());
5578 Handle<JSObject> this_handle(this);
5579 Handle<Object> value_handle(value);
5580 if (!interceptor->setter()->IsUndefined()) {
5581 v8::IndexedPropertySetter setter =
5582 v8::ToCData<v8::IndexedPropertySetter>(interceptor->setter());
5583 LOG(ApiIndexedPropertyAccess("interceptor-indexed-set", this, index));
5584 CustomArguments args(interceptor->data(), this, this);
5585 v8::AccessorInfo info(args.end());
5586 v8::Handle<v8::Value> result;
5587 {
5588 // Leaving JavaScript.
5589 VMState state(EXTERNAL);
5590 result = setter(index, v8::Utils::ToLocal(value_handle), info);
5591 }
5592 RETURN_IF_SCHEDULED_EXCEPTION();
5593 if (!result.IsEmpty()) return *value_handle;
5594 }
5595 Object* raw_result =
5596 this_handle->SetElementWithoutInterceptor(index, *value_handle);
5597 RETURN_IF_SCHEDULED_EXCEPTION();
5598 return raw_result;
5599}
5600
5601
5602// Adding n elements in fast case is O(n*n).
5603// Note: revisit design to have dual undefined values to capture absent
5604// elements.
5605Object* JSObject::SetFastElement(uint32_t index, Object* value) {
5606 ASSERT(HasFastElements());
5607
5608 FixedArray* elms = FixedArray::cast(elements());
5609 uint32_t elms_length = static_cast<uint32_t>(elms->length());
5610
5611 if (!IsJSArray() && (index >= elms_length || elms->get(index)->IsTheHole())) {
5612 Object* setter = LookupCallbackSetterInPrototypes(index);
5613 if (setter->IsJSFunction()) {
5614 return SetPropertyWithDefinedSetter(JSFunction::cast(setter), value);
5615 }
5616 }
5617
5618 // Check whether there is extra space in fixed array..
5619 if (index < elms_length) {
5620 elms->set(index, value);
5621 if (IsJSArray()) {
5622 // Update the length of the array if needed.
5623 uint32_t array_length = 0;
5624 CHECK(Array::IndexFromObject(JSArray::cast(this)->length(),
5625 &array_length));
5626 if (index >= array_length) {
5627 JSArray::cast(this)->set_length(Smi::FromInt(index + 1),
5628 SKIP_WRITE_BARRIER);
5629 }
5630 }
5631 return value;
5632 }
5633
5634 // Allow gap in fast case.
5635 if ((index - elms_length) < kMaxGap) {
5636 // Try allocating extra space.
5637 int new_capacity = NewElementsCapacity(index+1);
5638 if (new_capacity <= kMaxFastElementsLength ||
5639 !ShouldConvertToSlowElements(new_capacity)) {
5640 ASSERT(static_cast<uint32_t>(new_capacity) > index);
5641 Object* obj = Heap::AllocateFixedArrayWithHoles(new_capacity);
5642 if (obj->IsFailure()) return obj;
5643 SetFastElements(FixedArray::cast(obj));
5644 if (IsJSArray()) JSArray::cast(this)->set_length(Smi::FromInt(index + 1),
5645 SKIP_WRITE_BARRIER);
5646 FixedArray::cast(elements())->set(index, value);
5647 return value;
5648 }
5649 }
5650
5651 // Otherwise default to slow case.
5652 Object* obj = NormalizeElements();
5653 if (obj->IsFailure()) return obj;
5654 ASSERT(HasDictionaryElements());
5655 return SetElement(index, value);
5656}
5657
5658Object* JSObject::SetElement(uint32_t index, Object* value) {
5659 // Check access rights if needed.
5660 if (IsAccessCheckNeeded() &&
5661 !Top::MayIndexedAccess(this, index, v8::ACCESS_SET)) {
5662 Top::ReportFailedAccessCheck(this, v8::ACCESS_SET);
5663 return value;
5664 }
5665
5666 if (IsJSGlobalProxy()) {
5667 Object* proto = GetPrototype();
5668 if (proto->IsNull()) return value;
5669 ASSERT(proto->IsJSGlobalObject());
5670 return JSObject::cast(proto)->SetElement(index, value);
5671 }
5672
5673 // Check for lookup interceptor
5674 if (HasIndexedInterceptor()) {
5675 return SetElementWithInterceptor(index, value);
5676 }
5677
5678 return SetElementWithoutInterceptor(index, value);
5679}
5680
5681
5682Object* JSObject::SetElementWithoutInterceptor(uint32_t index, Object* value) {
5683 switch (GetElementsKind()) {
5684 case FAST_ELEMENTS:
5685 // Fast case.
5686 return SetFastElement(index, value);
5687 case PIXEL_ELEMENTS: {
5688 PixelArray* pixels = PixelArray::cast(elements());
5689 return pixels->SetValue(index, value);
5690 }
5691 case DICTIONARY_ELEMENTS: {
5692 // Insert element in the dictionary.
5693 FixedArray* elms = FixedArray::cast(elements());
5694 NumberDictionary* dictionary = NumberDictionary::cast(elms);
5695
5696 int entry = dictionary->FindEntry(index);
5697 if (entry != NumberDictionary::kNotFound) {
5698 Object* element = dictionary->ValueAt(entry);
5699 PropertyDetails details = dictionary->DetailsAt(entry);
5700 if (details.type() == CALLBACKS) {
5701 // Only accessors allowed as elements.
5702 FixedArray* structure = FixedArray::cast(element);
5703 if (structure->get(kSetterIndex)->IsJSFunction()) {
5704 JSFunction* setter = JSFunction::cast(structure->get(kSetterIndex));
5705 return SetPropertyWithDefinedSetter(setter, value);
5706 } else {
5707 Handle<Object> self(this);
5708 Handle<Object> key(Factory::NewNumberFromUint(index));
5709 Handle<Object> args[2] = { key, self };
5710 return Top::Throw(*Factory::NewTypeError("no_setter_in_callback",
5711 HandleVector(args, 2)));
5712 }
5713 } else {
5714 dictionary->UpdateMaxNumberKey(index);
5715 dictionary->ValueAtPut(entry, value);
5716 }
5717 } else {
5718 // Index not already used. Look for an accessor in the prototype chain.
5719 if (!IsJSArray()) {
5720 Object* setter = LookupCallbackSetterInPrototypes(index);
5721 if (setter->IsJSFunction()) {
5722 return SetPropertyWithDefinedSetter(JSFunction::cast(setter),
5723 value);
5724 }
5725 }
5726 Object* result = dictionary->AtNumberPut(index, value);
5727 if (result->IsFailure()) return result;
5728 if (elms != FixedArray::cast(result)) {
5729 set_elements(FixedArray::cast(result));
5730 }
5731 }
5732
5733 // Update the array length if this JSObject is an array.
5734 if (IsJSArray()) {
5735 JSArray* array = JSArray::cast(this);
5736 Object* return_value = array->JSArrayUpdateLengthFromIndex(index,
5737 value);
5738 if (return_value->IsFailure()) return return_value;
5739 }
5740
5741 // Attempt to put this object back in fast case.
5742 if (ShouldConvertToFastElements()) {
5743 uint32_t new_length = 0;
5744 if (IsJSArray()) {
5745 CHECK(Array::IndexFromObject(JSArray::cast(this)->length(),
5746 &new_length));
5747 JSArray::cast(this)->set_length(Smi::FromInt(new_length));
5748 } else {
5749 new_length = NumberDictionary::cast(elements())->max_number_key() + 1;
5750 }
5751 Object* obj = Heap::AllocateFixedArrayWithHoles(new_length);
5752 if (obj->IsFailure()) return obj;
5753 SetFastElements(FixedArray::cast(obj));
5754#ifdef DEBUG
5755 if (FLAG_trace_normalization) {
5756 PrintF("Object elements are fast case again:\n");
5757 Print();
5758 }
5759#endif
5760 }
5761
5762 return value;
5763 }
5764 default:
5765 UNREACHABLE();
5766 break;
5767 }
5768 // All possible cases have been handled above. Add a return to avoid the
5769 // complaints from the compiler.
5770 UNREACHABLE();
5771 return Heap::null_value();
5772}
5773
5774
5775Object* JSArray::JSArrayUpdateLengthFromIndex(uint32_t index, Object* value) {
5776 uint32_t old_len = 0;
5777 CHECK(Array::IndexFromObject(length(), &old_len));
5778 // Check to see if we need to update the length. For now, we make
5779 // sure that the length stays within 32-bits (unsigned).
5780 if (index >= old_len && index != 0xffffffff) {
5781 Object* len =
5782 Heap::NumberFromDouble(static_cast<double>(index) + 1);
5783 if (len->IsFailure()) return len;
5784 set_length(len);
5785 }
5786 return value;
5787}
5788
5789
5790Object* JSObject::GetElementPostInterceptor(JSObject* receiver,
5791 uint32_t index) {
5792 // Get element works for both JSObject and JSArray since
5793 // JSArray::length cannot change.
5794 switch (GetElementsKind()) {
5795 case FAST_ELEMENTS: {
5796 FixedArray* elms = FixedArray::cast(elements());
5797 if (index < static_cast<uint32_t>(elms->length())) {
5798 Object* value = elms->get(index);
5799 if (!value->IsTheHole()) return value;
5800 }
5801 break;
5802 }
5803 case PIXEL_ELEMENTS: {
5804 // TODO(iposva): Add testcase and implement.
5805 UNIMPLEMENTED();
5806 break;
5807 }
5808 case DICTIONARY_ELEMENTS: {
5809 NumberDictionary* dictionary = element_dictionary();
5810 int entry = dictionary->FindEntry(index);
5811 if (entry != NumberDictionary::kNotFound) {
5812 Object* element = dictionary->ValueAt(entry);
5813 PropertyDetails details = dictionary->DetailsAt(entry);
5814 if (details.type() == CALLBACKS) {
5815 // Only accessors allowed as elements.
5816 FixedArray* structure = FixedArray::cast(element);
5817 Object* getter = structure->get(kGetterIndex);
5818 if (getter->IsJSFunction()) {
5819 return GetPropertyWithDefinedGetter(receiver,
5820 JSFunction::cast(getter));
5821 } else {
5822 // Getter is not a function.
5823 return Heap::undefined_value();
5824 }
5825 }
5826 return element;
5827 }
5828 break;
5829 }
5830 default:
5831 UNREACHABLE();
5832 break;
5833 }
5834
5835 // Continue searching via the prototype chain.
5836 Object* pt = GetPrototype();
5837 if (pt == Heap::null_value()) return Heap::undefined_value();
5838 return pt->GetElementWithReceiver(receiver, index);
5839}
5840
5841
5842Object* JSObject::GetElementWithInterceptor(JSObject* receiver,
5843 uint32_t index) {
5844 // Make sure that the top context does not change when doing
5845 // callbacks or interceptor calls.
5846 AssertNoContextChange ncc;
5847 HandleScope scope;
5848 Handle<InterceptorInfo> interceptor(GetIndexedInterceptor());
5849 Handle<JSObject> this_handle(receiver);
5850 Handle<JSObject> holder_handle(this);
5851
5852 if (!interceptor->getter()->IsUndefined()) {
5853 v8::IndexedPropertyGetter getter =
5854 v8::ToCData<v8::IndexedPropertyGetter>(interceptor->getter());
5855 LOG(ApiIndexedPropertyAccess("interceptor-indexed-get", this, index));
5856 CustomArguments args(interceptor->data(), receiver, this);
5857 v8::AccessorInfo info(args.end());
5858 v8::Handle<v8::Value> result;
5859 {
5860 // Leaving JavaScript.
5861 VMState state(EXTERNAL);
5862 result = getter(index, info);
5863 }
5864 RETURN_IF_SCHEDULED_EXCEPTION();
5865 if (!result.IsEmpty()) return *v8::Utils::OpenHandle(*result);
5866 }
5867
5868 Object* raw_result =
5869 holder_handle->GetElementPostInterceptor(*this_handle, index);
5870 RETURN_IF_SCHEDULED_EXCEPTION();
5871 return raw_result;
5872}
5873
5874
5875Object* JSObject::GetElementWithReceiver(JSObject* receiver, uint32_t index) {
5876 // Check access rights if needed.
5877 if (IsAccessCheckNeeded() &&
5878 !Top::MayIndexedAccess(this, index, v8::ACCESS_GET)) {
5879 Top::ReportFailedAccessCheck(this, v8::ACCESS_GET);
5880 return Heap::undefined_value();
5881 }
5882
5883 if (HasIndexedInterceptor()) {
5884 return GetElementWithInterceptor(receiver, index);
5885 }
5886
5887 // Get element works for both JSObject and JSArray since
5888 // JSArray::length cannot change.
5889 switch (GetElementsKind()) {
5890 case FAST_ELEMENTS: {
5891 FixedArray* elms = FixedArray::cast(elements());
5892 if (index < static_cast<uint32_t>(elms->length())) {
5893 Object* value = elms->get(index);
5894 if (!value->IsTheHole()) return value;
5895 }
5896 break;
5897 }
5898 case PIXEL_ELEMENTS: {
5899 PixelArray* pixels = PixelArray::cast(elements());
5900 if (index < static_cast<uint32_t>(pixels->length())) {
5901 uint8_t value = pixels->get(index);
5902 return Smi::FromInt(value);
5903 }
5904 break;
5905 }
5906 case DICTIONARY_ELEMENTS: {
5907 NumberDictionary* dictionary = element_dictionary();
5908 int entry = dictionary->FindEntry(index);
5909 if (entry != NumberDictionary::kNotFound) {
5910 Object* element = dictionary->ValueAt(entry);
5911 PropertyDetails details = dictionary->DetailsAt(entry);
5912 if (details.type() == CALLBACKS) {
5913 // Only accessors allowed as elements.
5914 FixedArray* structure = FixedArray::cast(element);
5915 Object* getter = structure->get(kGetterIndex);
5916 if (getter->IsJSFunction()) {
5917 return GetPropertyWithDefinedGetter(receiver,
5918 JSFunction::cast(getter));
5919 } else {
5920 // Getter is not a function.
5921 return Heap::undefined_value();
5922 }
5923 }
5924 return element;
5925 }
5926 break;
5927 }
5928 }
5929
5930 Object* pt = GetPrototype();
5931 if (pt == Heap::null_value()) return Heap::undefined_value();
5932 return pt->GetElementWithReceiver(receiver, index);
5933}
5934
5935
5936bool JSObject::HasDenseElements() {
5937 int capacity = 0;
5938 int number_of_elements = 0;
5939
5940 switch (GetElementsKind()) {
5941 case FAST_ELEMENTS: {
5942 FixedArray* elms = FixedArray::cast(elements());
5943 capacity = elms->length();
5944 for (int i = 0; i < capacity; i++) {
5945 if (!elms->get(i)->IsTheHole()) number_of_elements++;
5946 }
5947 break;
5948 }
5949 case PIXEL_ELEMENTS: {
5950 return true;
5951 }
5952 case DICTIONARY_ELEMENTS: {
5953 NumberDictionary* dictionary = NumberDictionary::cast(elements());
5954 capacity = dictionary->Capacity();
5955 number_of_elements = dictionary->NumberOfElements();
5956 break;
5957 }
5958 default:
5959 UNREACHABLE();
5960 break;
5961 }
5962
5963 if (capacity == 0) return true;
5964 return (number_of_elements > (capacity / 2));
5965}
5966
5967
5968bool JSObject::ShouldConvertToSlowElements(int new_capacity) {
5969 ASSERT(HasFastElements());
5970 // Keep the array in fast case if the current backing storage is
5971 // almost filled and if the new capacity is no more than twice the
5972 // old capacity.
5973 int elements_length = FixedArray::cast(elements())->length();
5974 return !HasDenseElements() || ((new_capacity / 2) > elements_length);
5975}
5976
5977
5978bool JSObject::ShouldConvertToFastElements() {
5979 ASSERT(HasDictionaryElements());
5980 NumberDictionary* dictionary = NumberDictionary::cast(elements());
5981 // If the elements are sparse, we should not go back to fast case.
5982 if (!HasDenseElements()) return false;
5983 // If an element has been added at a very high index in the elements
5984 // dictionary, we cannot go back to fast case.
5985 if (dictionary->requires_slow_elements()) return false;
5986 // An object requiring access checks is never allowed to have fast
5987 // elements. If it had fast elements we would skip security checks.
5988 if (IsAccessCheckNeeded()) return false;
5989 // If the dictionary backing storage takes up roughly half as much
5990 // space as a fast-case backing storage would the array should have
5991 // fast elements.
5992 uint32_t length = 0;
5993 if (IsJSArray()) {
5994 CHECK(Array::IndexFromObject(JSArray::cast(this)->length(), &length));
5995 } else {
5996 length = dictionary->max_number_key();
5997 }
5998 return static_cast<uint32_t>(dictionary->Capacity()) >=
5999 (length / (2 * NumberDictionary::kEntrySize));
6000}
6001
6002
6003// Certain compilers request function template instantiation when they
6004// see the definition of the other template functions in the
6005// class. This requires us to have the template functions put
6006// together, so even though this function belongs in objects-debug.cc,
6007// we keep it here instead to satisfy certain compilers.
6008#ifdef DEBUG
6009template<typename Shape, typename Key>
6010void Dictionary<Shape, Key>::Print() {
6011 int capacity = HashTable<Shape, Key>::Capacity();
6012 for (int i = 0; i < capacity; i++) {
6013 Object* k = HashTable<Shape, Key>::KeyAt(i);
6014 if (HashTable<Shape, Key>::IsKey(k)) {
6015 PrintF(" ");
6016 if (k->IsString()) {
6017 String::cast(k)->StringPrint();
6018 } else {
6019 k->ShortPrint();
6020 }
6021 PrintF(": ");
6022 ValueAt(i)->ShortPrint();
6023 PrintF("\n");
6024 }
6025 }
6026}
6027#endif
6028
6029
6030template<typename Shape, typename Key>
6031void Dictionary<Shape, Key>::CopyValuesTo(FixedArray* elements) {
6032 int pos = 0;
6033 int capacity = HashTable<Shape, Key>::Capacity();
6034 WriteBarrierMode mode = elements->GetWriteBarrierMode();
6035 for (int i = 0; i < capacity; i++) {
6036 Object* k = Dictionary<Shape, Key>::KeyAt(i);
6037 if (Dictionary<Shape, Key>::IsKey(k)) {
6038 elements->set(pos++, ValueAt(i), mode);
6039 }
6040 }
6041 ASSERT(pos == elements->length());
6042}
6043
6044
6045InterceptorInfo* JSObject::GetNamedInterceptor() {
6046 ASSERT(map()->has_named_interceptor());
6047 JSFunction* constructor = JSFunction::cast(map()->constructor());
6048 Object* template_info = constructor->shared()->function_data();
6049 Object* result =
6050 FunctionTemplateInfo::cast(template_info)->named_property_handler();
6051 return InterceptorInfo::cast(result);
6052}
6053
6054
6055InterceptorInfo* JSObject::GetIndexedInterceptor() {
6056 ASSERT(map()->has_indexed_interceptor());
6057 JSFunction* constructor = JSFunction::cast(map()->constructor());
6058 Object* template_info = constructor->shared()->function_data();
6059 Object* result =
6060 FunctionTemplateInfo::cast(template_info)->indexed_property_handler();
6061 return InterceptorInfo::cast(result);
6062}
6063
6064
6065Object* JSObject::GetPropertyPostInterceptor(JSObject* receiver,
6066 String* name,
6067 PropertyAttributes* attributes) {
6068 // Check local property in holder, ignore interceptor.
6069 LookupResult result;
6070 LocalLookupRealNamedProperty(name, &result);
6071 if (result.IsValid()) return GetProperty(receiver, &result, name, attributes);
6072 // Continue searching via the prototype chain.
6073 Object* pt = GetPrototype();
6074 *attributes = ABSENT;
6075 if (pt == Heap::null_value()) return Heap::undefined_value();
6076 return pt->GetPropertyWithReceiver(receiver, name, attributes);
6077}
6078
6079
6080Object* JSObject::GetPropertyWithInterceptor(
6081 JSObject* receiver,
6082 String* name,
6083 PropertyAttributes* attributes) {
6084 InterceptorInfo* interceptor = GetNamedInterceptor();
6085 HandleScope scope;
6086 Handle<JSObject> receiver_handle(receiver);
6087 Handle<JSObject> holder_handle(this);
6088 Handle<String> name_handle(name);
6089
6090 if (!interceptor->getter()->IsUndefined()) {
6091 v8::NamedPropertyGetter getter =
6092 v8::ToCData<v8::NamedPropertyGetter>(interceptor->getter());
6093 LOG(ApiNamedPropertyAccess("interceptor-named-get", *holder_handle, name));
6094 CustomArguments args(interceptor->data(), receiver, this);
6095 v8::AccessorInfo info(args.end());
6096 v8::Handle<v8::Value> result;
6097 {
6098 // Leaving JavaScript.
6099 VMState state(EXTERNAL);
6100 result = getter(v8::Utils::ToLocal(name_handle), info);
6101 }
6102 RETURN_IF_SCHEDULED_EXCEPTION();
6103 if (!result.IsEmpty()) {
6104 *attributes = NONE;
6105 return *v8::Utils::OpenHandle(*result);
6106 }
6107 }
6108
6109 Object* result = holder_handle->GetPropertyPostInterceptor(
6110 *receiver_handle,
6111 *name_handle,
6112 attributes);
6113 RETURN_IF_SCHEDULED_EXCEPTION();
6114 return result;
6115}
6116
6117
6118bool JSObject::HasRealNamedProperty(String* key) {
6119 // Check access rights if needed.
6120 if (IsAccessCheckNeeded() &&
6121 !Top::MayNamedAccess(this, key, v8::ACCESS_HAS)) {
6122 Top::ReportFailedAccessCheck(this, v8::ACCESS_HAS);
6123 return false;
6124 }
6125
6126 LookupResult result;
6127 LocalLookupRealNamedProperty(key, &result);
6128 if (result.IsValid()) {
6129 switch (result.type()) {
6130 case NORMAL: // fall through.
6131 case FIELD: // fall through.
6132 case CALLBACKS: // fall through.
6133 case CONSTANT_FUNCTION:
6134 return true;
6135 case INTERCEPTOR:
6136 case MAP_TRANSITION:
6137 case CONSTANT_TRANSITION:
6138 case NULL_DESCRIPTOR:
6139 return false;
6140 default:
6141 UNREACHABLE();
6142 }
6143 }
6144
6145 return false;
6146}
6147
6148
6149bool JSObject::HasRealElementProperty(uint32_t index) {
6150 // Check access rights if needed.
6151 if (IsAccessCheckNeeded() &&
6152 !Top::MayIndexedAccess(this, index, v8::ACCESS_HAS)) {
6153 Top::ReportFailedAccessCheck(this, v8::ACCESS_HAS);
6154 return false;
6155 }
6156
6157 // Handle [] on String objects.
6158 if (this->IsStringObjectWithCharacterAt(index)) return true;
6159
6160 switch (GetElementsKind()) {
6161 case FAST_ELEMENTS: {
6162 uint32_t length = IsJSArray() ?
6163 static_cast<uint32_t>(
6164 Smi::cast(JSArray::cast(this)->length())->value()) :
6165 static_cast<uint32_t>(FixedArray::cast(elements())->length());
6166 return (index < length) &&
6167 !FixedArray::cast(elements())->get(index)->IsTheHole();
6168 }
6169 case PIXEL_ELEMENTS: {
6170 PixelArray* pixels = PixelArray::cast(elements());
6171 return index < static_cast<uint32_t>(pixels->length());
6172 }
6173 case DICTIONARY_ELEMENTS: {
6174 return element_dictionary()->FindEntry(index)
6175 != NumberDictionary::kNotFound;
6176 }
6177 default:
6178 UNREACHABLE();
6179 break;
6180 }
6181 // All possibilities have been handled above already.
6182 UNREACHABLE();
6183 return Heap::null_value();
6184}
6185
6186
6187bool JSObject::HasRealNamedCallbackProperty(String* key) {
6188 // Check access rights if needed.
6189 if (IsAccessCheckNeeded() &&
6190 !Top::MayNamedAccess(this, key, v8::ACCESS_HAS)) {
6191 Top::ReportFailedAccessCheck(this, v8::ACCESS_HAS);
6192 return false;
6193 }
6194
6195 LookupResult result;
6196 LocalLookupRealNamedProperty(key, &result);
6197 return result.IsValid() && (result.type() == CALLBACKS);
6198}
6199
6200
6201int JSObject::NumberOfLocalProperties(PropertyAttributes filter) {
6202 if (HasFastProperties()) {
6203 DescriptorArray* descs = map()->instance_descriptors();
6204 int result = 0;
6205 for (int i = 0; i < descs->number_of_descriptors(); i++) {
6206 PropertyDetails details = descs->GetDetails(i);
6207 if (details.IsProperty() && (details.attributes() & filter) == 0) {
6208 result++;
6209 }
6210 }
6211 return result;
6212 } else {
6213 return property_dictionary()->NumberOfElementsFilterAttributes(filter);
6214 }
6215}
6216
6217
6218int JSObject::NumberOfEnumProperties() {
6219 return NumberOfLocalProperties(static_cast<PropertyAttributes>(DONT_ENUM));
6220}
6221
6222
6223void FixedArray::SwapPairs(FixedArray* numbers, int i, int j) {
6224 Object* temp = get(i);
6225 set(i, get(j));
6226 set(j, temp);
6227 if (this != numbers) {
6228 temp = numbers->get(i);
6229 numbers->set(i, numbers->get(j));
6230 numbers->set(j, temp);
6231 }
6232}
6233
6234
6235static void InsertionSortPairs(FixedArray* content,
6236 FixedArray* numbers,
6237 int len) {
6238 for (int i = 1; i < len; i++) {
6239 int j = i;
6240 while (j > 0 &&
6241 (NumberToUint32(numbers->get(j - 1)) >
6242 NumberToUint32(numbers->get(j)))) {
6243 content->SwapPairs(numbers, j - 1, j);
6244 j--;
6245 }
6246 }
6247}
6248
6249
6250void HeapSortPairs(FixedArray* content, FixedArray* numbers, int len) {
6251 // In-place heap sort.
6252 ASSERT(content->length() == numbers->length());
6253
6254 // Bottom-up max-heap construction.
6255 for (int i = 1; i < len; ++i) {
6256 int child_index = i;
6257 while (child_index > 0) {
6258 int parent_index = ((child_index + 1) >> 1) - 1;
6259 uint32_t parent_value = NumberToUint32(numbers->get(parent_index));
6260 uint32_t child_value = NumberToUint32(numbers->get(child_index));
6261 if (parent_value < child_value) {
6262 content->SwapPairs(numbers, parent_index, child_index);
6263 } else {
6264 break;
6265 }
6266 child_index = parent_index;
6267 }
6268 }
6269
6270 // Extract elements and create sorted array.
6271 for (int i = len - 1; i > 0; --i) {
6272 // Put max element at the back of the array.
6273 content->SwapPairs(numbers, 0, i);
6274 // Sift down the new top element.
6275 int parent_index = 0;
6276 while (true) {
6277 int child_index = ((parent_index + 1) << 1) - 1;
6278 if (child_index >= i) break;
6279 uint32_t child1_value = NumberToUint32(numbers->get(child_index));
6280 uint32_t child2_value = NumberToUint32(numbers->get(child_index + 1));
6281 uint32_t parent_value = NumberToUint32(numbers->get(parent_index));
6282 if (child_index + 1 >= i || child1_value > child2_value) {
6283 if (parent_value > child1_value) break;
6284 content->SwapPairs(numbers, parent_index, child_index);
6285 parent_index = child_index;
6286 } else {
6287 if (parent_value > child2_value) break;
6288 content->SwapPairs(numbers, parent_index, child_index + 1);
6289 parent_index = child_index + 1;
6290 }
6291 }
6292 }
6293}
6294
6295
6296// Sort this array and the numbers as pairs wrt. the (distinct) numbers.
6297void FixedArray::SortPairs(FixedArray* numbers, uint32_t len) {
6298 ASSERT(this->length() == numbers->length());
6299 // For small arrays, simply use insertion sort.
6300 if (len <= 10) {
6301 InsertionSortPairs(this, numbers, len);
6302 return;
6303 }
6304 // Check the range of indices.
6305 uint32_t min_index = NumberToUint32(numbers->get(0));
6306 uint32_t max_index = min_index;
6307 uint32_t i;
6308 for (i = 1; i < len; i++) {
6309 if (NumberToUint32(numbers->get(i)) < min_index) {
6310 min_index = NumberToUint32(numbers->get(i));
6311 } else if (NumberToUint32(numbers->get(i)) > max_index) {
6312 max_index = NumberToUint32(numbers->get(i));
6313 }
6314 }
6315 if (max_index - min_index + 1 == len) {
6316 // Indices form a contiguous range, unless there are duplicates.
6317 // Do an in-place linear time sort assuming distinct numbers, but
6318 // avoid hanging in case they are not.
6319 for (i = 0; i < len; i++) {
6320 uint32_t p;
6321 uint32_t j = 0;
6322 // While the current element at i is not at its correct position p,
6323 // swap the elements at these two positions.
6324 while ((p = NumberToUint32(numbers->get(i)) - min_index) != i &&
6325 j++ < len) {
6326 SwapPairs(numbers, i, p);
6327 }
6328 }
6329 } else {
6330 HeapSortPairs(this, numbers, len);
6331 return;
6332 }
6333}
6334
6335
6336// Fill in the names of local properties into the supplied storage. The main
6337// purpose of this function is to provide reflection information for the object
6338// mirrors.
6339void JSObject::GetLocalPropertyNames(FixedArray* storage, int index) {
6340 ASSERT(storage->length() >= (NumberOfLocalProperties(NONE) - index));
6341 if (HasFastProperties()) {
6342 DescriptorArray* descs = map()->instance_descriptors();
6343 for (int i = 0; i < descs->number_of_descriptors(); i++) {
6344 if (descs->IsProperty(i)) storage->set(index++, descs->GetKey(i));
6345 }
6346 ASSERT(storage->length() >= index);
6347 } else {
6348 property_dictionary()->CopyKeysTo(storage);
6349 }
6350}
6351
6352
6353int JSObject::NumberOfLocalElements(PropertyAttributes filter) {
6354 return GetLocalElementKeys(NULL, filter);
6355}
6356
6357
6358int JSObject::NumberOfEnumElements() {
6359 return NumberOfLocalElements(static_cast<PropertyAttributes>(DONT_ENUM));
6360}
6361
6362
6363int JSObject::GetLocalElementKeys(FixedArray* storage,
6364 PropertyAttributes filter) {
6365 int counter = 0;
6366 switch (GetElementsKind()) {
6367 case FAST_ELEMENTS: {
6368 int length = IsJSArray() ?
6369 Smi::cast(JSArray::cast(this)->length())->value() :
6370 FixedArray::cast(elements())->length();
6371 for (int i = 0; i < length; i++) {
6372 if (!FixedArray::cast(elements())->get(i)->IsTheHole()) {
6373 if (storage != NULL) {
6374 storage->set(counter, Smi::FromInt(i), SKIP_WRITE_BARRIER);
6375 }
6376 counter++;
6377 }
6378 }
6379 ASSERT(!storage || storage->length() >= counter);
6380 break;
6381 }
6382 case PIXEL_ELEMENTS: {
6383 int length = PixelArray::cast(elements())->length();
6384 while (counter < length) {
6385 if (storage != NULL) {
6386 storage->set(counter, Smi::FromInt(counter), SKIP_WRITE_BARRIER);
6387 }
6388 counter++;
6389 }
6390 ASSERT(!storage || storage->length() >= counter);
6391 break;
6392 }
6393 case DICTIONARY_ELEMENTS: {
6394 if (storage != NULL) {
6395 element_dictionary()->CopyKeysTo(storage, filter);
6396 }
6397 counter = element_dictionary()->NumberOfElementsFilterAttributes(filter);
6398 break;
6399 }
6400 default:
6401 UNREACHABLE();
6402 break;
6403 }
6404
6405 if (this->IsJSValue()) {
6406 Object* val = JSValue::cast(this)->value();
6407 if (val->IsString()) {
6408 String* str = String::cast(val);
6409 if (storage) {
6410 for (int i = 0; i < str->length(); i++) {
6411 storage->set(counter + i, Smi::FromInt(i), SKIP_WRITE_BARRIER);
6412 }
6413 }
6414 counter += str->length();
6415 }
6416 }
6417 ASSERT(!storage || storage->length() == counter);
6418 return counter;
6419}
6420
6421
6422int JSObject::GetEnumElementKeys(FixedArray* storage) {
6423 return GetLocalElementKeys(storage,
6424 static_cast<PropertyAttributes>(DONT_ENUM));
6425}
6426
6427
6428bool NumberDictionaryShape::IsMatch(uint32_t key, Object* other) {
6429 ASSERT(other->IsNumber());
6430 return key == static_cast<uint32_t>(other->Number());
6431}
6432
6433
6434uint32_t NumberDictionaryShape::Hash(uint32_t key) {
6435 return ComputeIntegerHash(key);
6436}
6437
6438
6439uint32_t NumberDictionaryShape::HashForObject(uint32_t key, Object* other) {
6440 ASSERT(other->IsNumber());
6441 return ComputeIntegerHash(static_cast<uint32_t>(other->Number()));
6442}
6443
6444
6445Object* NumberDictionaryShape::AsObject(uint32_t key) {
6446 return Heap::NumberFromUint32(key);
6447}
6448
6449
6450bool StringDictionaryShape::IsMatch(String* key, Object* other) {
6451 // We know that all entries in a hash table had their hash keys created.
6452 // Use that knowledge to have fast failure.
6453 if (key->Hash() != String::cast(other)->Hash()) return false;
6454 return key->Equals(String::cast(other));
6455}
6456
6457
6458uint32_t StringDictionaryShape::Hash(String* key) {
6459 return key->Hash();
6460}
6461
6462
6463uint32_t StringDictionaryShape::HashForObject(String* key, Object* other) {
6464 return String::cast(other)->Hash();
6465}
6466
6467
6468Object* StringDictionaryShape::AsObject(String* key) {
6469 return key;
6470}
6471
6472
6473// StringKey simply carries a string object as key.
6474class StringKey : public HashTableKey {
6475 public:
6476 explicit StringKey(String* string) :
6477 string_(string),
6478 hash_(HashForObject(string)) { }
6479
6480 bool IsMatch(Object* string) {
6481 // We know that all entries in a hash table had their hash keys created.
6482 // Use that knowledge to have fast failure.
6483 if (hash_ != HashForObject(string)) {
6484 return false;
6485 }
6486 return string_->Equals(String::cast(string));
6487 }
6488
6489 uint32_t Hash() { return hash_; }
6490
6491 uint32_t HashForObject(Object* other) { return String::cast(other)->Hash(); }
6492
6493 Object* AsObject() { return string_; }
6494
6495 String* string_;
6496 uint32_t hash_;
6497};
6498
6499
6500// StringSharedKeys are used as keys in the eval cache.
6501class StringSharedKey : public HashTableKey {
6502 public:
6503 StringSharedKey(String* source, SharedFunctionInfo* shared)
6504 : source_(source), shared_(shared) { }
6505
6506 bool IsMatch(Object* other) {
6507 if (!other->IsFixedArray()) return false;
6508 FixedArray* pair = FixedArray::cast(other);
6509 SharedFunctionInfo* shared = SharedFunctionInfo::cast(pair->get(0));
6510 if (shared != shared_) return false;
6511 String* source = String::cast(pair->get(1));
6512 return source->Equals(source_);
6513 }
6514
6515 static uint32_t StringSharedHashHelper(String* source,
6516 SharedFunctionInfo* shared) {
6517 uint32_t hash = source->Hash();
6518 if (shared->HasSourceCode()) {
6519 // Instead of using the SharedFunctionInfo pointer in the hash
6520 // code computation, we use a combination of the hash of the
6521 // script source code and the start and end positions. We do
6522 // this to ensure that the cache entries can survive garbage
6523 // collection.
6524 Script* script = Script::cast(shared->script());
6525 hash ^= String::cast(script->source())->Hash();
6526 hash += shared->start_position();
6527 }
6528 return hash;
6529 }
6530
6531 uint32_t Hash() {
6532 return StringSharedHashHelper(source_, shared_);
6533 }
6534
6535 uint32_t HashForObject(Object* obj) {
6536 FixedArray* pair = FixedArray::cast(obj);
6537 SharedFunctionInfo* shared = SharedFunctionInfo::cast(pair->get(0));
6538 String* source = String::cast(pair->get(1));
6539 return StringSharedHashHelper(source, shared);
6540 }
6541
6542 Object* AsObject() {
6543 Object* obj = Heap::AllocateFixedArray(2);
6544 if (obj->IsFailure()) return obj;
6545 FixedArray* pair = FixedArray::cast(obj);
6546 pair->set(0, shared_);
6547 pair->set(1, source_);
6548 return pair;
6549 }
6550
6551 private:
6552 String* source_;
6553 SharedFunctionInfo* shared_;
6554};
6555
6556
6557// RegExpKey carries the source and flags of a regular expression as key.
6558class RegExpKey : public HashTableKey {
6559 public:
6560 RegExpKey(String* string, JSRegExp::Flags flags)
6561 : string_(string),
6562 flags_(Smi::FromInt(flags.value())) { }
6563
6564 bool IsMatch(Object* obj) {
6565 FixedArray* val = FixedArray::cast(obj);
6566 return string_->Equals(String::cast(val->get(JSRegExp::kSourceIndex)))
6567 && (flags_ == val->get(JSRegExp::kFlagsIndex));
6568 }
6569
6570 uint32_t Hash() { return RegExpHash(string_, flags_); }
6571
6572 Object* AsObject() {
6573 // Plain hash maps, which is where regexp keys are used, don't
6574 // use this function.
6575 UNREACHABLE();
6576 return NULL;
6577 }
6578
6579 uint32_t HashForObject(Object* obj) {
6580 FixedArray* val = FixedArray::cast(obj);
6581 return RegExpHash(String::cast(val->get(JSRegExp::kSourceIndex)),
6582 Smi::cast(val->get(JSRegExp::kFlagsIndex)));
6583 }
6584
6585 static uint32_t RegExpHash(String* string, Smi* flags) {
6586 return string->Hash() + flags->value();
6587 }
6588
6589 String* string_;
6590 Smi* flags_;
6591};
6592
6593// Utf8SymbolKey carries a vector of chars as key.
6594class Utf8SymbolKey : public HashTableKey {
6595 public:
6596 explicit Utf8SymbolKey(Vector<const char> string)
6597 : string_(string), length_field_(0) { }
6598
6599 bool IsMatch(Object* string) {
6600 return String::cast(string)->IsEqualTo(string_);
6601 }
6602
6603 uint32_t Hash() {
6604 if (length_field_ != 0) return length_field_ >> String::kHashShift;
6605 unibrow::Utf8InputBuffer<> buffer(string_.start(),
6606 static_cast<unsigned>(string_.length()));
6607 chars_ = buffer.Length();
6608 length_field_ = String::ComputeLengthAndHashField(&buffer, chars_);
6609 uint32_t result = length_field_ >> String::kHashShift;
6610 ASSERT(result != 0); // Ensure that the hash value of 0 is never computed.
6611 return result;
6612 }
6613
6614 uint32_t HashForObject(Object* other) {
6615 return String::cast(other)->Hash();
6616 }
6617
6618 Object* AsObject() {
6619 if (length_field_ == 0) Hash();
6620 return Heap::AllocateSymbol(string_, chars_, length_field_);
6621 }
6622
6623 Vector<const char> string_;
6624 uint32_t length_field_;
6625 int chars_; // Caches the number of characters when computing the hash code.
6626};
6627
6628
6629// SymbolKey carries a string/symbol object as key.
6630class SymbolKey : public HashTableKey {
6631 public:
6632 explicit SymbolKey(String* string) : string_(string) { }
6633
6634 bool IsMatch(Object* string) {
6635 return String::cast(string)->Equals(string_);
6636 }
6637
6638 uint32_t Hash() { return string_->Hash(); }
6639
6640 uint32_t HashForObject(Object* other) {
6641 return String::cast(other)->Hash();
6642 }
6643
6644 Object* AsObject() {
6645 // If the string is a cons string, attempt to flatten it so that
6646 // symbols will most often be flat strings.
6647 if (StringShape(string_).IsCons()) {
6648 ConsString* cons_string = ConsString::cast(string_);
6649 cons_string->TryFlatten();
6650 if (cons_string->second()->length() == 0) {
6651 string_ = cons_string->first();
6652 }
6653 }
6654 // Transform string to symbol if possible.
6655 Map* map = Heap::SymbolMapForString(string_);
6656 if (map != NULL) {
6657 string_->set_map(map);
6658 ASSERT(string_->IsSymbol());
6659 return string_;
6660 }
6661 // Otherwise allocate a new symbol.
6662 StringInputBuffer buffer(string_);
6663 return Heap::AllocateInternalSymbol(&buffer,
6664 string_->length(),
6665 string_->length_field());
6666 }
6667
6668 static uint32_t StringHash(Object* obj) {
6669 return String::cast(obj)->Hash();
6670 }
6671
6672 String* string_;
6673};
6674
6675
6676template<typename Shape, typename Key>
6677void HashTable<Shape, Key>::IteratePrefix(ObjectVisitor* v) {
6678 IteratePointers(v, 0, kElementsStartOffset);
6679}
6680
6681
6682template<typename Shape, typename Key>
6683void HashTable<Shape, Key>::IterateElements(ObjectVisitor* v) {
6684 IteratePointers(v,
6685 kElementsStartOffset,
6686 kHeaderSize + length() * kPointerSize);
6687}
6688
6689
6690template<typename Shape, typename Key>
6691Object* HashTable<Shape, Key>::Allocate(
6692 int at_least_space_for) {
6693 int capacity = RoundUpToPowerOf2(at_least_space_for);
6694 if (capacity < 4) capacity = 4; // Guarantee min capacity.
6695 Object* obj = Heap::AllocateHashTable(EntryToIndex(capacity));
6696 if (!obj->IsFailure()) {
6697 HashTable::cast(obj)->SetNumberOfElements(0);
6698 HashTable::cast(obj)->SetCapacity(capacity);
6699 }
6700 return obj;
6701}
6702
6703
6704
6705// Find entry for key otherwise return -1.
6706template<typename Shape, typename Key>
6707int HashTable<Shape, Key>::FindEntry(Key key) {
6708 uint32_t nof = NumberOfElements();
6709 if (nof == 0) return kNotFound; // Bail out if empty.
6710
6711 uint32_t capacity = Capacity();
6712 uint32_t hash = Shape::Hash(key);
6713 uint32_t entry = GetProbe(hash, 0, capacity);
6714
6715 Object* element = KeyAt(entry);
6716 uint32_t passed_elements = 0;
6717 if (!element->IsNull()) {
6718 if (!element->IsUndefined() && Shape::IsMatch(key, element)) return entry;
6719 if (++passed_elements == nof) return kNotFound;
6720 }
6721 for (uint32_t i = 1; !element->IsUndefined(); i++) {
6722 entry = GetProbe(hash, i, capacity);
6723 element = KeyAt(entry);
6724 if (!element->IsNull()) {
6725 if (!element->IsUndefined() && Shape::IsMatch(key, element)) return entry;
6726 if (++passed_elements == nof) return kNotFound;
6727 }
6728 }
6729 return kNotFound;
6730}
6731
6732
6733template<typename Shape, typename Key>
6734Object* HashTable<Shape, Key>::EnsureCapacity(int n, Key key) {
6735 int capacity = Capacity();
6736 int nof = NumberOfElements() + n;
6737 // Make sure 50% is free
6738 if (nof + (nof >> 1) <= capacity) return this;
6739
6740 Object* obj = Allocate(nof * 2);
6741 if (obj->IsFailure()) return obj;
6742 HashTable* table = HashTable::cast(obj);
6743 WriteBarrierMode mode = table->GetWriteBarrierMode();
6744
6745 // Copy prefix to new array.
6746 for (int i = kPrefixStartIndex;
6747 i < kPrefixStartIndex + Shape::kPrefixSize;
6748 i++) {
6749 table->set(i, get(i), mode);
6750 }
6751 // Rehash the elements.
6752 for (int i = 0; i < capacity; i++) {
6753 uint32_t from_index = EntryToIndex(i);
6754 Object* k = get(from_index);
6755 if (IsKey(k)) {
6756 uint32_t hash = Shape::HashForObject(key, k);
6757 uint32_t insertion_index =
6758 EntryToIndex(table->FindInsertionEntry(hash));
6759 for (int j = 0; j < Shape::kEntrySize; j++) {
6760 table->set(insertion_index + j, get(from_index + j), mode);
6761 }
6762 }
6763 }
6764 table->SetNumberOfElements(NumberOfElements());
6765 return table;
6766}
6767
6768
6769template<typename Shape, typename Key>
6770uint32_t HashTable<Shape, Key>::FindInsertionEntry(uint32_t hash) {
6771 uint32_t capacity = Capacity();
6772 uint32_t entry = GetProbe(hash, 0, capacity);
6773 Object* element = KeyAt(entry);
6774
6775 for (uint32_t i = 1; !(element->IsUndefined() || element->IsNull()); i++) {
6776 entry = GetProbe(hash, i, capacity);
6777 element = KeyAt(entry);
6778 }
6779
6780 return entry;
6781}
6782
6783// Force instantiation of template instances class.
6784// Please note this list is compiler dependent.
6785
6786template class HashTable<SymbolTableShape, HashTableKey*>;
6787
6788template class HashTable<CompilationCacheShape, HashTableKey*>;
6789
6790template class HashTable<MapCacheShape, HashTableKey*>;
6791
6792template class Dictionary<StringDictionaryShape, String*>;
6793
6794template class Dictionary<NumberDictionaryShape, uint32_t>;
6795
6796template Object* Dictionary<NumberDictionaryShape, uint32_t>::Allocate(
6797 int);
6798
6799template Object* Dictionary<StringDictionaryShape, String*>::Allocate(
6800 int);
6801
6802template Object* Dictionary<NumberDictionaryShape, uint32_t>::AtPut(
6803 uint32_t, Object*);
6804
6805template Object* Dictionary<NumberDictionaryShape, uint32_t>::SlowReverseLookup(
6806 Object*);
6807
6808template Object* Dictionary<StringDictionaryShape, String*>::SlowReverseLookup(
6809 Object*);
6810
6811template void Dictionary<NumberDictionaryShape, uint32_t>::CopyKeysTo(
6812 FixedArray*, PropertyAttributes);
6813
6814template Object* Dictionary<StringDictionaryShape, String*>::DeleteProperty(
6815 int, JSObject::DeleteMode);
6816
6817template Object* Dictionary<NumberDictionaryShape, uint32_t>::DeleteProperty(
6818 int, JSObject::DeleteMode);
6819
6820template void Dictionary<StringDictionaryShape, String*>::CopyKeysTo(
6821 FixedArray*);
6822
6823template int
6824Dictionary<StringDictionaryShape, String*>::NumberOfElementsFilterAttributes(
6825 PropertyAttributes);
6826
6827template Object* Dictionary<StringDictionaryShape, String*>::Add(
6828 String*, Object*, PropertyDetails);
6829
6830template Object*
6831Dictionary<StringDictionaryShape, String*>::GenerateNewEnumerationIndices();
6832
6833template int
6834Dictionary<NumberDictionaryShape, uint32_t>::NumberOfElementsFilterAttributes(
6835 PropertyAttributes);
6836
6837template Object* Dictionary<NumberDictionaryShape, uint32_t>::Add(
6838 uint32_t, Object*, PropertyDetails);
6839
6840template Object* Dictionary<NumberDictionaryShape, uint32_t>::EnsureCapacity(
6841 int, uint32_t);
6842
6843template Object* Dictionary<StringDictionaryShape, String*>::EnsureCapacity(
6844 int, String*);
6845
6846template Object* Dictionary<NumberDictionaryShape, uint32_t>::AddEntry(
6847 uint32_t, Object*, PropertyDetails, uint32_t);
6848
6849template Object* Dictionary<StringDictionaryShape, String*>::AddEntry(
6850 String*, Object*, PropertyDetails, uint32_t);
6851
6852template
6853int Dictionary<NumberDictionaryShape, uint32_t>::NumberOfEnumElements();
6854
6855template
6856int Dictionary<StringDictionaryShape, String*>::NumberOfEnumElements();
6857
6858// Collates undefined and unexisting elements below limit from position
6859// zero of the elements. The object stays in Dictionary mode.
6860Object* JSObject::PrepareSlowElementsForSort(uint32_t limit) {
6861 ASSERT(HasDictionaryElements());
6862 // Must stay in dictionary mode, either because of requires_slow_elements,
6863 // or because we are not going to sort (and therefore compact) all of the
6864 // elements.
6865 NumberDictionary* dict = element_dictionary();
6866 HeapNumber* result_double = NULL;
6867 if (limit > static_cast<uint32_t>(Smi::kMaxValue)) {
6868 // Allocate space for result before we start mutating the object.
6869 Object* new_double = Heap::AllocateHeapNumber(0.0);
6870 if (new_double->IsFailure()) return new_double;
6871 result_double = HeapNumber::cast(new_double);
6872 }
6873
6874 int capacity = dict->Capacity();
6875 Object* obj = NumberDictionary::Allocate(dict->Capacity());
6876 if (obj->IsFailure()) return obj;
6877 NumberDictionary* new_dict = NumberDictionary::cast(obj);
6878
6879 AssertNoAllocation no_alloc;
6880
6881 uint32_t pos = 0;
6882 uint32_t undefs = 0;
6883 for (int i = 0; i < capacity; i++) {
6884 Object* k = dict->KeyAt(i);
6885 if (dict->IsKey(k)) {
6886 ASSERT(k->IsNumber());
6887 ASSERT(!k->IsSmi() || Smi::cast(k)->value() >= 0);
6888 ASSERT(!k->IsHeapNumber() || HeapNumber::cast(k)->value() >= 0);
6889 ASSERT(!k->IsHeapNumber() || HeapNumber::cast(k)->value() <= kMaxUInt32);
6890 Object* value = dict->ValueAt(i);
6891 PropertyDetails details = dict->DetailsAt(i);
6892 if (details.type() == CALLBACKS) {
6893 // Bail out and do the sorting of undefineds and array holes in JS.
6894 return Smi::FromInt(-1);
6895 }
6896 uint32_t key = NumberToUint32(k);
6897 if (key < limit) {
6898 if (value->IsUndefined()) {
6899 undefs++;
6900 } else {
6901 new_dict->AddNumberEntry(pos, value, details);
6902 pos++;
6903 }
6904 } else {
6905 new_dict->AddNumberEntry(key, value, details);
6906 }
6907 }
6908 }
6909
6910 uint32_t result = pos;
6911 PropertyDetails no_details = PropertyDetails(NONE, NORMAL);
6912 while (undefs > 0) {
6913 new_dict->AddNumberEntry(pos, Heap::undefined_value(), no_details);
6914 pos++;
6915 undefs--;
6916 }
6917
6918 set_elements(new_dict);
6919
6920 if (result <= static_cast<uint32_t>(Smi::kMaxValue)) {
6921 return Smi::FromInt(static_cast<int>(result));
6922 }
6923
6924 ASSERT_NE(NULL, result_double);
6925 result_double->set_value(static_cast<double>(result));
6926 return result_double;
6927}
6928
6929
6930// Collects all defined (non-hole) and non-undefined (array) elements at
6931// the start of the elements array.
6932// If the object is in dictionary mode, it is converted to fast elements
6933// mode.
6934Object* JSObject::PrepareElementsForSort(uint32_t limit) {
6935 ASSERT(!HasPixelElements());
6936
6937 if (HasDictionaryElements()) {
6938 // Convert to fast elements containing only the existing properties.
6939 // Ordering is irrelevant, since we are going to sort anyway.
6940 NumberDictionary* dict = element_dictionary();
6941 if (IsJSArray() || dict->requires_slow_elements() ||
6942 dict->max_number_key() >= limit) {
6943 return PrepareSlowElementsForSort(limit);
6944 }
6945 // Convert to fast elements.
6946
6947 PretenureFlag tenure = Heap::InNewSpace(this) ? NOT_TENURED: TENURED;
6948 Object* new_array =
6949 Heap::AllocateFixedArray(dict->NumberOfElements(), tenure);
6950 if (new_array->IsFailure()) {
6951 return new_array;
6952 }
6953 FixedArray* fast_elements = FixedArray::cast(new_array);
6954 dict->CopyValuesTo(fast_elements);
6955 set_elements(fast_elements);
6956 }
6957 ASSERT(HasFastElements());
6958
6959 // Collect holes at the end, undefined before that and the rest at the
6960 // start, and return the number of non-hole, non-undefined values.
6961
6962 FixedArray* elements = FixedArray::cast(this->elements());
6963 uint32_t elements_length = static_cast<uint32_t>(elements->length());
6964 if (limit > elements_length) {
6965 limit = elements_length ;
6966 }
6967 if (limit == 0) {
6968 return Smi::FromInt(0);
6969 }
6970
6971 HeapNumber* result_double = NULL;
6972 if (limit > static_cast<uint32_t>(Smi::kMaxValue)) {
6973 // Pessimistically allocate space for return value before
6974 // we start mutating the array.
6975 Object* new_double = Heap::AllocateHeapNumber(0.0);
6976 if (new_double->IsFailure()) return new_double;
6977 result_double = HeapNumber::cast(new_double);
6978 }
6979
6980 AssertNoAllocation no_alloc;
6981
6982 // Split elements into defined, undefined and the_hole, in that order.
6983 // Only count locations for undefined and the hole, and fill them afterwards.
6984 WriteBarrierMode write_barrier = elements->GetWriteBarrierMode();
6985 unsigned int undefs = limit;
6986 unsigned int holes = limit;
6987 // Assume most arrays contain no holes and undefined values, so minimize the
6988 // number of stores of non-undefined, non-the-hole values.
6989 for (unsigned int i = 0; i < undefs; i++) {
6990 Object* current = elements->get(i);
6991 if (current->IsTheHole()) {
6992 holes--;
6993 undefs--;
6994 } else if (current->IsUndefined()) {
6995 undefs--;
6996 } else {
6997 continue;
6998 }
6999 // Position i needs to be filled.
7000 while (undefs > i) {
7001 current = elements->get(undefs);
7002 if (current->IsTheHole()) {
7003 holes--;
7004 undefs--;
7005 } else if (current->IsUndefined()) {
7006 undefs--;
7007 } else {
7008 elements->set(i, current, write_barrier);
7009 break;
7010 }
7011 }
7012 }
7013 uint32_t result = undefs;
7014 while (undefs < holes) {
7015 elements->set_undefined(undefs);
7016 undefs++;
7017 }
7018 while (holes < limit) {
7019 elements->set_the_hole(holes);
7020 holes++;
7021 }
7022
7023 if (result <= static_cast<uint32_t>(Smi::kMaxValue)) {
7024 return Smi::FromInt(static_cast<int>(result));
7025 }
7026 ASSERT_NE(NULL, result_double);
7027 result_double->set_value(static_cast<double>(result));
7028 return result_double;
7029}
7030
7031
7032Object* PixelArray::SetValue(uint32_t index, Object* value) {
7033 uint8_t clamped_value = 0;
7034 if (index < static_cast<uint32_t>(length())) {
7035 if (value->IsSmi()) {
7036 int int_value = Smi::cast(value)->value();
7037 if (int_value < 0) {
7038 clamped_value = 0;
7039 } else if (int_value > 255) {
7040 clamped_value = 255;
7041 } else {
7042 clamped_value = static_cast<uint8_t>(int_value);
7043 }
7044 } else if (value->IsHeapNumber()) {
7045 double double_value = HeapNumber::cast(value)->value();
7046 if (!(double_value > 0)) {
7047 // NaN and less than zero clamp to zero.
7048 clamped_value = 0;
7049 } else if (double_value > 255) {
7050 // Greater than 255 clamp to 255.
7051 clamped_value = 255;
7052 } else {
7053 // Other doubles are rounded to the nearest integer.
7054 clamped_value = static_cast<uint8_t>(double_value + 0.5);
7055 }
7056 } else {
7057 // Clamp undefined to zero (default). All other types have been
7058 // converted to a number type further up in the call chain.
7059 ASSERT(value->IsUndefined());
7060 }
7061 set(index, clamped_value);
7062 }
7063 return Smi::FromInt(clamped_value);
7064}
7065
7066
7067Object* GlobalObject::GetPropertyCell(LookupResult* result) {
7068 ASSERT(!HasFastProperties());
7069 Object* value = property_dictionary()->ValueAt(result->GetDictionaryEntry());
7070 ASSERT(value->IsJSGlobalPropertyCell());
7071 return value;
7072}
7073
7074
7075Object* GlobalObject::EnsurePropertyCell(String* name) {
7076 ASSERT(!HasFastProperties());
7077 int entry = property_dictionary()->FindEntry(name);
7078 if (entry == StringDictionary::kNotFound) {
7079 Object* cell = Heap::AllocateJSGlobalPropertyCell(Heap::the_hole_value());
7080 if (cell->IsFailure()) return cell;
7081 PropertyDetails details(NONE, NORMAL);
7082 details = details.AsDeleted();
7083 Object* dictionary = property_dictionary()->Add(name, cell, details);
7084 if (dictionary->IsFailure()) return dictionary;
7085 set_properties(StringDictionary::cast(dictionary));
7086 return cell;
7087 } else {
7088 Object* value = property_dictionary()->ValueAt(entry);
7089 ASSERT(value->IsJSGlobalPropertyCell());
7090 return value;
7091 }
7092}
7093
7094
7095Object* SymbolTable::LookupString(String* string, Object** s) {
7096 SymbolKey key(string);
7097 return LookupKey(&key, s);
7098}
7099
7100
7101bool SymbolTable::LookupSymbolIfExists(String* string, String** symbol) {
7102 SymbolKey key(string);
7103 int entry = FindEntry(&key);
7104 if (entry == kNotFound) {
7105 return false;
7106 } else {
7107 String* result = String::cast(KeyAt(entry));
7108 ASSERT(StringShape(result).IsSymbol());
7109 *symbol = result;
7110 return true;
7111 }
7112}
7113
7114
7115Object* SymbolTable::LookupSymbol(Vector<const char> str, Object** s) {
7116 Utf8SymbolKey key(str);
7117 return LookupKey(&key, s);
7118}
7119
7120
7121Object* SymbolTable::LookupKey(HashTableKey* key, Object** s) {
7122 int entry = FindEntry(key);
7123
7124 // Symbol already in table.
7125 if (entry != kNotFound) {
7126 *s = KeyAt(entry);
7127 return this;
7128 }
7129
7130 // Adding new symbol. Grow table if needed.
7131 Object* obj = EnsureCapacity(1, key);
7132 if (obj->IsFailure()) return obj;
7133
7134 // Create symbol object.
7135 Object* symbol = key->AsObject();
7136 if (symbol->IsFailure()) return symbol;
7137
7138 // If the symbol table grew as part of EnsureCapacity, obj is not
7139 // the current symbol table and therefore we cannot use
7140 // SymbolTable::cast here.
7141 SymbolTable* table = reinterpret_cast<SymbolTable*>(obj);
7142
7143 // Add the new symbol and return it along with the symbol table.
7144 entry = table->FindInsertionEntry(key->Hash());
7145 table->set(EntryToIndex(entry), symbol);
7146 table->ElementAdded();
7147 *s = symbol;
7148 return table;
7149}
7150
7151
7152Object* CompilationCacheTable::Lookup(String* src) {
7153 StringKey key(src);
7154 int entry = FindEntry(&key);
7155 if (entry == kNotFound) return Heap::undefined_value();
7156 return get(EntryToIndex(entry) + 1);
7157}
7158
7159
7160Object* CompilationCacheTable::LookupEval(String* src, Context* context) {
7161 StringSharedKey key(src, context->closure()->shared());
7162 int entry = FindEntry(&key);
7163 if (entry == kNotFound) return Heap::undefined_value();
7164 return get(EntryToIndex(entry) + 1);
7165}
7166
7167
7168Object* CompilationCacheTable::LookupRegExp(String* src,
7169 JSRegExp::Flags flags) {
7170 RegExpKey key(src, flags);
7171 int entry = FindEntry(&key);
7172 if (entry == kNotFound) return Heap::undefined_value();
7173 return get(EntryToIndex(entry) + 1);
7174}
7175
7176
7177Object* CompilationCacheTable::Put(String* src, Object* value) {
7178 StringKey key(src);
7179 Object* obj = EnsureCapacity(1, &key);
7180 if (obj->IsFailure()) return obj;
7181
7182 CompilationCacheTable* cache =
7183 reinterpret_cast<CompilationCacheTable*>(obj);
7184 int entry = cache->FindInsertionEntry(key.Hash());
7185 cache->set(EntryToIndex(entry), src);
7186 cache->set(EntryToIndex(entry) + 1, value);
7187 cache->ElementAdded();
7188 return cache;
7189}
7190
7191
7192Object* CompilationCacheTable::PutEval(String* src,
7193 Context* context,
7194 Object* value) {
7195 StringSharedKey key(src, context->closure()->shared());
7196 Object* obj = EnsureCapacity(1, &key);
7197 if (obj->IsFailure()) return obj;
7198
7199 CompilationCacheTable* cache =
7200 reinterpret_cast<CompilationCacheTable*>(obj);
7201 int entry = cache->FindInsertionEntry(key.Hash());
7202
7203 Object* k = key.AsObject();
7204 if (k->IsFailure()) return k;
7205
7206 cache->set(EntryToIndex(entry), k);
7207 cache->set(EntryToIndex(entry) + 1, value);
7208 cache->ElementAdded();
7209 return cache;
7210}
7211
7212
7213Object* CompilationCacheTable::PutRegExp(String* src,
7214 JSRegExp::Flags flags,
7215 FixedArray* value) {
7216 RegExpKey key(src, flags);
7217 Object* obj = EnsureCapacity(1, &key);
7218 if (obj->IsFailure()) return obj;
7219
7220 CompilationCacheTable* cache =
7221 reinterpret_cast<CompilationCacheTable*>(obj);
7222 int entry = cache->FindInsertionEntry(key.Hash());
7223 cache->set(EntryToIndex(entry), value);
7224 cache->set(EntryToIndex(entry) + 1, value);
7225 cache->ElementAdded();
7226 return cache;
7227}
7228
7229
7230// SymbolsKey used for HashTable where key is array of symbols.
7231class SymbolsKey : public HashTableKey {
7232 public:
7233 explicit SymbolsKey(FixedArray* symbols) : symbols_(symbols) { }
7234
7235 bool IsMatch(Object* symbols) {
7236 FixedArray* o = FixedArray::cast(symbols);
7237 int len = symbols_->length();
7238 if (o->length() != len) return false;
7239 for (int i = 0; i < len; i++) {
7240 if (o->get(i) != symbols_->get(i)) return false;
7241 }
7242 return true;
7243 }
7244
7245 uint32_t Hash() { return HashForObject(symbols_); }
7246
7247 uint32_t HashForObject(Object* obj) {
7248 FixedArray* symbols = FixedArray::cast(obj);
7249 int len = symbols->length();
7250 uint32_t hash = 0;
7251 for (int i = 0; i < len; i++) {
7252 hash ^= String::cast(symbols->get(i))->Hash();
7253 }
7254 return hash;
7255 }
7256
7257 Object* AsObject() { return symbols_; }
7258
7259 private:
7260 FixedArray* symbols_;
7261};
7262
7263
7264Object* MapCache::Lookup(FixedArray* array) {
7265 SymbolsKey key(array);
7266 int entry = FindEntry(&key);
7267 if (entry == kNotFound) return Heap::undefined_value();
7268 return get(EntryToIndex(entry) + 1);
7269}
7270
7271
7272Object* MapCache::Put(FixedArray* array, Map* value) {
7273 SymbolsKey key(array);
7274 Object* obj = EnsureCapacity(1, &key);
7275 if (obj->IsFailure()) return obj;
7276
7277 MapCache* cache = reinterpret_cast<MapCache*>(obj);
7278 int entry = cache->FindInsertionEntry(key.Hash());
7279 cache->set(EntryToIndex(entry), array);
7280 cache->set(EntryToIndex(entry) + 1, value);
7281 cache->ElementAdded();
7282 return cache;
7283}
7284
7285
7286template<typename Shape, typename Key>
7287Object* Dictionary<Shape, Key>::Allocate(int at_least_space_for) {
7288 Object* obj = HashTable<Shape, Key>::Allocate(at_least_space_for);
7289 // Initialize the next enumeration index.
7290 if (!obj->IsFailure()) {
7291 Dictionary<Shape, Key>::cast(obj)->
7292 SetNextEnumerationIndex(PropertyDetails::kInitialIndex);
7293 }
7294 return obj;
7295}
7296
7297
7298template<typename Shape, typename Key>
7299Object* Dictionary<Shape, Key>::GenerateNewEnumerationIndices() {
7300 int length = HashTable<Shape, Key>::NumberOfElements();
7301
7302 // Allocate and initialize iteration order array.
7303 Object* obj = Heap::AllocateFixedArray(length);
7304 if (obj->IsFailure()) return obj;
7305 FixedArray* iteration_order = FixedArray::cast(obj);
7306 for (int i = 0; i < length; i++) {
7307 iteration_order->set(i, Smi::FromInt(i), SKIP_WRITE_BARRIER);
7308 }
7309
7310 // Allocate array with enumeration order.
7311 obj = Heap::AllocateFixedArray(length);
7312 if (obj->IsFailure()) return obj;
7313 FixedArray* enumeration_order = FixedArray::cast(obj);
7314
7315 // Fill the enumeration order array with property details.
7316 int capacity = HashTable<Shape, Key>::Capacity();
7317 int pos = 0;
7318 for (int i = 0; i < capacity; i++) {
7319 if (Dictionary<Shape, Key>::IsKey(Dictionary<Shape, Key>::KeyAt(i))) {
7320 enumeration_order->set(pos++,
7321 Smi::FromInt(DetailsAt(i).index()),
7322 SKIP_WRITE_BARRIER);
7323 }
7324 }
7325
7326 // Sort the arrays wrt. enumeration order.
7327 iteration_order->SortPairs(enumeration_order, enumeration_order->length());
7328
7329 // Overwrite the enumeration_order with the enumeration indices.
7330 for (int i = 0; i < length; i++) {
7331 int index = Smi::cast(iteration_order->get(i))->value();
7332 int enum_index = PropertyDetails::kInitialIndex + i;
7333 enumeration_order->set(index,
7334 Smi::FromInt(enum_index),
7335 SKIP_WRITE_BARRIER);
7336 }
7337
7338 // Update the dictionary with new indices.
7339 capacity = HashTable<Shape, Key>::Capacity();
7340 pos = 0;
7341 for (int i = 0; i < capacity; i++) {
7342 if (Dictionary<Shape, Key>::IsKey(Dictionary<Shape, Key>::KeyAt(i))) {
7343 int enum_index = Smi::cast(enumeration_order->get(pos++))->value();
7344 PropertyDetails details = DetailsAt(i);
7345 PropertyDetails new_details =
7346 PropertyDetails(details.attributes(), details.type(), enum_index);
7347 DetailsAtPut(i, new_details);
7348 }
7349 }
7350
7351 // Set the next enumeration index.
7352 SetNextEnumerationIndex(PropertyDetails::kInitialIndex+length);
7353 return this;
7354}
7355
7356template<typename Shape, typename Key>
7357Object* Dictionary<Shape, Key>::EnsureCapacity(int n, Key key) {
7358 // Check whether there are enough enumeration indices to add n elements.
7359 if (Shape::kIsEnumerable &&
7360 !PropertyDetails::IsValidIndex(NextEnumerationIndex() + n)) {
7361 // If not, we generate new indices for the properties.
7362 Object* result = GenerateNewEnumerationIndices();
7363 if (result->IsFailure()) return result;
7364 }
7365 return HashTable<Shape, Key>::EnsureCapacity(n, key);
7366}
7367
7368
7369void NumberDictionary::RemoveNumberEntries(uint32_t from, uint32_t to) {
7370 // Do nothing if the interval [from, to) is empty.
7371 if (from >= to) return;
7372
7373 int removed_entries = 0;
7374 Object* sentinel = Heap::null_value();
7375 int capacity = Capacity();
7376 for (int i = 0; i < capacity; i++) {
7377 Object* key = KeyAt(i);
7378 if (key->IsNumber()) {
7379 uint32_t number = static_cast<uint32_t>(key->Number());
7380 if (from <= number && number < to) {
7381 SetEntry(i, sentinel, sentinel, Smi::FromInt(0));
7382 removed_entries++;
7383 }
7384 }
7385 }
7386
7387 // Update the number of elements.
7388 SetNumberOfElements(NumberOfElements() - removed_entries);
7389}
7390
7391
7392template<typename Shape, typename Key>
7393Object* Dictionary<Shape, Key>::DeleteProperty(int entry,
7394 JSObject::DeleteMode mode) {
7395 PropertyDetails details = DetailsAt(entry);
7396 // Ignore attributes if forcing a deletion.
7397 if (details.IsDontDelete() && mode == JSObject::NORMAL_DELETION) {
7398 return Heap::false_value();
7399 }
7400 SetEntry(entry, Heap::null_value(), Heap::null_value(), Smi::FromInt(0));
7401 HashTable<Shape, Key>::ElementRemoved();
7402 return Heap::true_value();
7403}
7404
7405
7406template<typename Shape, typename Key>
7407Object* Dictionary<Shape, Key>::AtPut(Key key, Object* value) {
7408 int entry = FindEntry(key);
7409
7410 // If the entry is present set the value;
7411 if (entry != Dictionary<Shape, Key>::kNotFound) {
7412 ValueAtPut(entry, value);
7413 return this;
7414 }
7415
7416 // Check whether the dictionary should be extended.
7417 Object* obj = EnsureCapacity(1, key);
7418 if (obj->IsFailure()) return obj;
7419
7420 Object* k = Shape::AsObject(key);
7421 if (k->IsFailure()) return k;
7422 PropertyDetails details = PropertyDetails(NONE, NORMAL);
7423 return Dictionary<Shape, Key>::cast(obj)->
7424 AddEntry(key, value, details, Shape::Hash(key));
7425}
7426
7427
7428template<typename Shape, typename Key>
7429Object* Dictionary<Shape, Key>::Add(Key key,
7430 Object* value,
7431 PropertyDetails details) {
7432 // Valdate key is absent.
7433 SLOW_ASSERT((FindEntry(key) == Dictionary<Shape, Key>::kNotFound));
7434 // Check whether the dictionary should be extended.
7435 Object* obj = EnsureCapacity(1, key);
7436 if (obj->IsFailure()) return obj;
7437 return Dictionary<Shape, Key>::cast(obj)->
7438 AddEntry(key, value, details, Shape::Hash(key));
7439}
7440
7441
7442// Add a key, value pair to the dictionary.
7443template<typename Shape, typename Key>
7444Object* Dictionary<Shape, Key>::AddEntry(Key key,
7445 Object* value,
7446 PropertyDetails details,
7447 uint32_t hash) {
7448 // Compute the key object.
7449 Object* k = Shape::AsObject(key);
7450 if (k->IsFailure()) return k;
7451
7452 uint32_t entry = Dictionary<Shape, Key>::FindInsertionEntry(hash);
7453 // Insert element at empty or deleted entry
7454 if (!details.IsDeleted() && details.index() == 0 && Shape::kIsEnumerable) {
7455 // Assign an enumeration index to the property and update
7456 // SetNextEnumerationIndex.
7457 int index = NextEnumerationIndex();
7458 details = PropertyDetails(details.attributes(), details.type(), index);
7459 SetNextEnumerationIndex(index + 1);
7460 }
7461 SetEntry(entry, k, value, details);
7462 ASSERT((Dictionary<Shape, Key>::KeyAt(entry)->IsNumber()
7463 || Dictionary<Shape, Key>::KeyAt(entry)->IsString()));
7464 HashTable<Shape, Key>::ElementAdded();
7465 return this;
7466}
7467
7468
7469void NumberDictionary::UpdateMaxNumberKey(uint32_t key) {
7470 // If the dictionary requires slow elements an element has already
7471 // been added at a high index.
7472 if (requires_slow_elements()) return;
7473 // Check if this index is high enough that we should require slow
7474 // elements.
7475 if (key > kRequiresSlowElementsLimit) {
7476 set_requires_slow_elements();
7477 return;
7478 }
7479 // Update max key value.
7480 Object* max_index_object = get(kMaxNumberKeyIndex);
7481 if (!max_index_object->IsSmi() || max_number_key() < key) {
7482 FixedArray::set(kMaxNumberKeyIndex,
7483 Smi::FromInt(key << kRequiresSlowElementsTagSize),
7484 SKIP_WRITE_BARRIER);
7485 }
7486}
7487
7488
7489Object* NumberDictionary::AddNumberEntry(uint32_t key,
7490 Object* value,
7491 PropertyDetails details) {
7492 UpdateMaxNumberKey(key);
7493 SLOW_ASSERT(FindEntry(key) == kNotFound);
7494 return Add(key, value, details);
7495}
7496
7497
7498Object* NumberDictionary::AtNumberPut(uint32_t key, Object* value) {
7499 UpdateMaxNumberKey(key);
7500 return AtPut(key, value);
7501}
7502
7503
7504Object* NumberDictionary::Set(uint32_t key,
7505 Object* value,
7506 PropertyDetails details) {
7507 int entry = FindEntry(key);
7508 if (entry == kNotFound) return AddNumberEntry(key, value, details);
7509 // Preserve enumeration index.
7510 details = PropertyDetails(details.attributes(),
7511 details.type(),
7512 DetailsAt(entry).index());
7513 SetEntry(entry, NumberDictionaryShape::AsObject(key), value, details);
7514 return this;
7515}
7516
7517
7518
7519template<typename Shape, typename Key>
7520int Dictionary<Shape, Key>::NumberOfElementsFilterAttributes(
7521 PropertyAttributes filter) {
7522 int capacity = HashTable<Shape, Key>::Capacity();
7523 int result = 0;
7524 for (int i = 0; i < capacity; i++) {
7525 Object* k = HashTable<Shape, Key>::KeyAt(i);
7526 if (HashTable<Shape, Key>::IsKey(k)) {
7527 PropertyDetails details = DetailsAt(i);
7528 if (details.IsDeleted()) continue;
7529 PropertyAttributes attr = details.attributes();
7530 if ((attr & filter) == 0) result++;
7531 }
7532 }
7533 return result;
7534}
7535
7536
7537template<typename Shape, typename Key>
7538int Dictionary<Shape, Key>::NumberOfEnumElements() {
7539 return NumberOfElementsFilterAttributes(
7540 static_cast<PropertyAttributes>(DONT_ENUM));
7541}
7542
7543
7544template<typename Shape, typename Key>
7545void Dictionary<Shape, Key>::CopyKeysTo(FixedArray* storage,
7546 PropertyAttributes filter) {
7547 ASSERT(storage->length() >= NumberOfEnumElements());
7548 int capacity = HashTable<Shape, Key>::Capacity();
7549 int index = 0;
7550 for (int i = 0; i < capacity; i++) {
7551 Object* k = HashTable<Shape, Key>::KeyAt(i);
7552 if (HashTable<Shape, Key>::IsKey(k)) {
7553 PropertyDetails details = DetailsAt(i);
7554 if (details.IsDeleted()) continue;
7555 PropertyAttributes attr = details.attributes();
7556 if ((attr & filter) == 0) storage->set(index++, k);
7557 }
7558 }
7559 storage->SortPairs(storage, index);
7560 ASSERT(storage->length() >= index);
7561}
7562
7563
7564void StringDictionary::CopyEnumKeysTo(FixedArray* storage,
7565 FixedArray* sort_array) {
7566 ASSERT(storage->length() >= NumberOfEnumElements());
7567 int capacity = Capacity();
7568 int index = 0;
7569 for (int i = 0; i < capacity; i++) {
7570 Object* k = KeyAt(i);
7571 if (IsKey(k)) {
7572 PropertyDetails details = DetailsAt(i);
7573 if (details.IsDeleted() || details.IsDontEnum()) continue;
7574 storage->set(index, k);
7575 sort_array->set(index,
7576 Smi::FromInt(details.index()),
7577 SKIP_WRITE_BARRIER);
7578 index++;
7579 }
7580 }
7581 storage->SortPairs(sort_array, sort_array->length());
7582 ASSERT(storage->length() >= index);
7583}
7584
7585
7586template<typename Shape, typename Key>
7587void Dictionary<Shape, Key>::CopyKeysTo(FixedArray* storage) {
7588 ASSERT(storage->length() >= NumberOfElementsFilterAttributes(
7589 static_cast<PropertyAttributes>(NONE)));
7590 int capacity = HashTable<Shape, Key>::Capacity();
7591 int index = 0;
7592 for (int i = 0; i < capacity; i++) {
7593 Object* k = HashTable<Shape, Key>::KeyAt(i);
7594 if (HashTable<Shape, Key>::IsKey(k)) {
7595 PropertyDetails details = DetailsAt(i);
7596 if (details.IsDeleted()) continue;
7597 storage->set(index++, k);
7598 }
7599 }
7600 ASSERT(storage->length() >= index);
7601}
7602
7603
7604// Backwards lookup (slow).
7605template<typename Shape, typename Key>
7606Object* Dictionary<Shape, Key>::SlowReverseLookup(Object* value) {
7607 int capacity = HashTable<Shape, Key>::Capacity();
7608 for (int i = 0; i < capacity; i++) {
7609 Object* k = HashTable<Shape, Key>::KeyAt(i);
7610 if (Dictionary<Shape, Key>::IsKey(k)) {
7611 Object* e = ValueAt(i);
7612 if (e->IsJSGlobalPropertyCell()) {
7613 e = JSGlobalPropertyCell::cast(e)->value();
7614 }
7615 if (e == value) return k;
7616 }
7617 }
7618 return Heap::undefined_value();
7619}
7620
7621
7622Object* StringDictionary::TransformPropertiesToFastFor(
7623 JSObject* obj, int unused_property_fields) {
7624 // Make sure we preserve dictionary representation if there are too many
7625 // descriptors.
7626 if (NumberOfElements() > DescriptorArray::kMaxNumberOfDescriptors) return obj;
7627
7628 // Figure out if it is necessary to generate new enumeration indices.
7629 int max_enumeration_index =
7630 NextEnumerationIndex() +
7631 (DescriptorArray::kMaxNumberOfDescriptors -
7632 NumberOfElements());
7633 if (!PropertyDetails::IsValidIndex(max_enumeration_index)) {
7634 Object* result = GenerateNewEnumerationIndices();
7635 if (result->IsFailure()) return result;
7636 }
7637
7638 int instance_descriptor_length = 0;
7639 int number_of_fields = 0;
7640
7641 // Compute the length of the instance descriptor.
7642 int capacity = Capacity();
7643 for (int i = 0; i < capacity; i++) {
7644 Object* k = KeyAt(i);
7645 if (IsKey(k)) {
7646 Object* value = ValueAt(i);
7647 PropertyType type = DetailsAt(i).type();
7648 ASSERT(type != FIELD);
7649 instance_descriptor_length++;
7650 if (type == NORMAL && !value->IsJSFunction()) number_of_fields += 1;
7651 }
7652 }
7653
7654 // Allocate the instance descriptor.
7655 Object* descriptors_unchecked =
7656 DescriptorArray::Allocate(instance_descriptor_length);
7657 if (descriptors_unchecked->IsFailure()) return descriptors_unchecked;
7658 DescriptorArray* descriptors = DescriptorArray::cast(descriptors_unchecked);
7659
7660 int inobject_props = obj->map()->inobject_properties();
7661 int number_of_allocated_fields =
7662 number_of_fields + unused_property_fields - inobject_props;
7663
7664 // Allocate the fixed array for the fields.
7665 Object* fields = Heap::AllocateFixedArray(number_of_allocated_fields);
7666 if (fields->IsFailure()) return fields;
7667
7668 // Fill in the instance descriptor and the fields.
7669 int next_descriptor = 0;
7670 int current_offset = 0;
7671 for (int i = 0; i < capacity; i++) {
7672 Object* k = KeyAt(i);
7673 if (IsKey(k)) {
7674 Object* value = ValueAt(i);
7675 // Ensure the key is a symbol before writing into the instance descriptor.
7676 Object* key = Heap::LookupSymbol(String::cast(k));
7677 if (key->IsFailure()) return key;
7678 PropertyDetails details = DetailsAt(i);
7679 PropertyType type = details.type();
7680
7681 if (value->IsJSFunction()) {
7682 ConstantFunctionDescriptor d(String::cast(key),
7683 JSFunction::cast(value),
7684 details.attributes(),
7685 details.index());
7686 descriptors->Set(next_descriptor++, &d);
7687 } else if (type == NORMAL) {
7688 if (current_offset < inobject_props) {
7689 obj->InObjectPropertyAtPut(current_offset,
7690 value,
7691 UPDATE_WRITE_BARRIER);
7692 } else {
7693 int offset = current_offset - inobject_props;
7694 FixedArray::cast(fields)->set(offset, value);
7695 }
7696 FieldDescriptor d(String::cast(key),
7697 current_offset++,
7698 details.attributes(),
7699 details.index());
7700 descriptors->Set(next_descriptor++, &d);
7701 } else if (type == CALLBACKS) {
7702 CallbacksDescriptor d(String::cast(key),
7703 value,
7704 details.attributes(),
7705 details.index());
7706 descriptors->Set(next_descriptor++, &d);
7707 } else {
7708 UNREACHABLE();
7709 }
7710 }
7711 }
7712 ASSERT(current_offset == number_of_fields);
7713
7714 descriptors->Sort();
7715 // Allocate new map.
7716 Object* new_map = obj->map()->CopyDropDescriptors();
7717 if (new_map->IsFailure()) return new_map;
7718
7719 // Transform the object.
7720 obj->set_map(Map::cast(new_map));
7721 obj->map()->set_instance_descriptors(descriptors);
7722 obj->map()->set_unused_property_fields(unused_property_fields);
7723
7724 obj->set_properties(FixedArray::cast(fields));
7725 ASSERT(obj->IsJSObject());
7726
7727 descriptors->SetNextEnumerationIndex(NextEnumerationIndex());
7728 // Check that it really works.
7729 ASSERT(obj->HasFastProperties());
7730
7731 return obj;
7732}
7733
7734
7735#ifdef ENABLE_DEBUGGER_SUPPORT
7736// Check if there is a break point at this code position.
7737bool DebugInfo::HasBreakPoint(int code_position) {
7738 // Get the break point info object for this code position.
7739 Object* break_point_info = GetBreakPointInfo(code_position);
7740
7741 // If there is no break point info object or no break points in the break
7742 // point info object there is no break point at this code position.
7743 if (break_point_info->IsUndefined()) return false;
7744 return BreakPointInfo::cast(break_point_info)->GetBreakPointCount() > 0;
7745}
7746
7747
7748// Get the break point info object for this code position.
7749Object* DebugInfo::GetBreakPointInfo(int code_position) {
7750 // Find the index of the break point info object for this code position.
7751 int index = GetBreakPointInfoIndex(code_position);
7752
7753 // Return the break point info object if any.
7754 if (index == kNoBreakPointInfo) return Heap::undefined_value();
7755 return BreakPointInfo::cast(break_points()->get(index));
7756}
7757
7758
7759// Clear a break point at the specified code position.
7760void DebugInfo::ClearBreakPoint(Handle<DebugInfo> debug_info,
7761 int code_position,
7762 Handle<Object> break_point_object) {
7763 Handle<Object> break_point_info(debug_info->GetBreakPointInfo(code_position));
7764 if (break_point_info->IsUndefined()) return;
7765 BreakPointInfo::ClearBreakPoint(
7766 Handle<BreakPointInfo>::cast(break_point_info),
7767 break_point_object);
7768}
7769
7770
7771void DebugInfo::SetBreakPoint(Handle<DebugInfo> debug_info,
7772 int code_position,
7773 int source_position,
7774 int statement_position,
7775 Handle<Object> break_point_object) {
7776 Handle<Object> break_point_info(debug_info->GetBreakPointInfo(code_position));
7777 if (!break_point_info->IsUndefined()) {
7778 BreakPointInfo::SetBreakPoint(
7779 Handle<BreakPointInfo>::cast(break_point_info),
7780 break_point_object);
7781 return;
7782 }
7783
7784 // Adding a new break point for a code position which did not have any
7785 // break points before. Try to find a free slot.
7786 int index = kNoBreakPointInfo;
7787 for (int i = 0; i < debug_info->break_points()->length(); i++) {
7788 if (debug_info->break_points()->get(i)->IsUndefined()) {
7789 index = i;
7790 break;
7791 }
7792 }
7793 if (index == kNoBreakPointInfo) {
7794 // No free slot - extend break point info array.
7795 Handle<FixedArray> old_break_points =
7796 Handle<FixedArray>(FixedArray::cast(debug_info->break_points()));
7797 debug_info->set_break_points(*Factory::NewFixedArray(
7798 old_break_points->length() +
7799 Debug::kEstimatedNofBreakPointsInFunction));
7800 Handle<FixedArray> new_break_points =
7801 Handle<FixedArray>(FixedArray::cast(debug_info->break_points()));
7802 for (int i = 0; i < old_break_points->length(); i++) {
7803 new_break_points->set(i, old_break_points->get(i));
7804 }
7805 index = old_break_points->length();
7806 }
7807 ASSERT(index != kNoBreakPointInfo);
7808
7809 // Allocate new BreakPointInfo object and set the break point.
7810 Handle<BreakPointInfo> new_break_point_info =
7811 Handle<BreakPointInfo>::cast(Factory::NewStruct(BREAK_POINT_INFO_TYPE));
7812 new_break_point_info->set_code_position(Smi::FromInt(code_position));
7813 new_break_point_info->set_source_position(Smi::FromInt(source_position));
7814 new_break_point_info->
7815 set_statement_position(Smi::FromInt(statement_position));
7816 new_break_point_info->set_break_point_objects(Heap::undefined_value());
7817 BreakPointInfo::SetBreakPoint(new_break_point_info, break_point_object);
7818 debug_info->break_points()->set(index, *new_break_point_info);
7819}
7820
7821
7822// Get the break point objects for a code position.
7823Object* DebugInfo::GetBreakPointObjects(int code_position) {
7824 Object* break_point_info = GetBreakPointInfo(code_position);
7825 if (break_point_info->IsUndefined()) {
7826 return Heap::undefined_value();
7827 }
7828 return BreakPointInfo::cast(break_point_info)->break_point_objects();
7829}
7830
7831
7832// Get the total number of break points.
7833int DebugInfo::GetBreakPointCount() {
7834 if (break_points()->IsUndefined()) return 0;
7835 int count = 0;
7836 for (int i = 0; i < break_points()->length(); i++) {
7837 if (!break_points()->get(i)->IsUndefined()) {
7838 BreakPointInfo* break_point_info =
7839 BreakPointInfo::cast(break_points()->get(i));
7840 count += break_point_info->GetBreakPointCount();
7841 }
7842 }
7843 return count;
7844}
7845
7846
7847Object* DebugInfo::FindBreakPointInfo(Handle<DebugInfo> debug_info,
7848 Handle<Object> break_point_object) {
7849 if (debug_info->break_points()->IsUndefined()) return Heap::undefined_value();
7850 for (int i = 0; i < debug_info->break_points()->length(); i++) {
7851 if (!debug_info->break_points()->get(i)->IsUndefined()) {
7852 Handle<BreakPointInfo> break_point_info =
7853 Handle<BreakPointInfo>(BreakPointInfo::cast(
7854 debug_info->break_points()->get(i)));
7855 if (BreakPointInfo::HasBreakPointObject(break_point_info,
7856 break_point_object)) {
7857 return *break_point_info;
7858 }
7859 }
7860 }
7861 return Heap::undefined_value();
7862}
7863
7864
7865// Find the index of the break point info object for the specified code
7866// position.
7867int DebugInfo::GetBreakPointInfoIndex(int code_position) {
7868 if (break_points()->IsUndefined()) return kNoBreakPointInfo;
7869 for (int i = 0; i < break_points()->length(); i++) {
7870 if (!break_points()->get(i)->IsUndefined()) {
7871 BreakPointInfo* break_point_info =
7872 BreakPointInfo::cast(break_points()->get(i));
7873 if (break_point_info->code_position()->value() == code_position) {
7874 return i;
7875 }
7876 }
7877 }
7878 return kNoBreakPointInfo;
7879}
7880
7881
7882// Remove the specified break point object.
7883void BreakPointInfo::ClearBreakPoint(Handle<BreakPointInfo> break_point_info,
7884 Handle<Object> break_point_object) {
7885 // If there are no break points just ignore.
7886 if (break_point_info->break_point_objects()->IsUndefined()) return;
7887 // If there is a single break point clear it if it is the same.
7888 if (!break_point_info->break_point_objects()->IsFixedArray()) {
7889 if (break_point_info->break_point_objects() == *break_point_object) {
7890 break_point_info->set_break_point_objects(Heap::undefined_value());
7891 }
7892 return;
7893 }
7894 // If there are multiple break points shrink the array
7895 ASSERT(break_point_info->break_point_objects()->IsFixedArray());
7896 Handle<FixedArray> old_array =
7897 Handle<FixedArray>(
7898 FixedArray::cast(break_point_info->break_point_objects()));
7899 Handle<FixedArray> new_array =
7900 Factory::NewFixedArray(old_array->length() - 1);
7901 int found_count = 0;
7902 for (int i = 0; i < old_array->length(); i++) {
7903 if (old_array->get(i) == *break_point_object) {
7904 ASSERT(found_count == 0);
7905 found_count++;
7906 } else {
7907 new_array->set(i - found_count, old_array->get(i));
7908 }
7909 }
7910 // If the break point was found in the list change it.
7911 if (found_count > 0) break_point_info->set_break_point_objects(*new_array);
7912}
7913
7914
7915// Add the specified break point object.
7916void BreakPointInfo::SetBreakPoint(Handle<BreakPointInfo> break_point_info,
7917 Handle<Object> break_point_object) {
7918 // If there was no break point objects before just set it.
7919 if (break_point_info->break_point_objects()->IsUndefined()) {
7920 break_point_info->set_break_point_objects(*break_point_object);
7921 return;
7922 }
7923 // If the break point object is the same as before just ignore.
7924 if (break_point_info->break_point_objects() == *break_point_object) return;
7925 // If there was one break point object before replace with array.
7926 if (!break_point_info->break_point_objects()->IsFixedArray()) {
7927 Handle<FixedArray> array = Factory::NewFixedArray(2);
7928 array->set(0, break_point_info->break_point_objects());
7929 array->set(1, *break_point_object);
7930 break_point_info->set_break_point_objects(*array);
7931 return;
7932 }
7933 // If there was more than one break point before extend array.
7934 Handle<FixedArray> old_array =
7935 Handle<FixedArray>(
7936 FixedArray::cast(break_point_info->break_point_objects()));
7937 Handle<FixedArray> new_array =
7938 Factory::NewFixedArray(old_array->length() + 1);
7939 for (int i = 0; i < old_array->length(); i++) {
7940 // If the break point was there before just ignore.
7941 if (old_array->get(i) == *break_point_object) return;
7942 new_array->set(i, old_array->get(i));
7943 }
7944 // Add the new break point.
7945 new_array->set(old_array->length(), *break_point_object);
7946 break_point_info->set_break_point_objects(*new_array);
7947}
7948
7949
7950bool BreakPointInfo::HasBreakPointObject(
7951 Handle<BreakPointInfo> break_point_info,
7952 Handle<Object> break_point_object) {
7953 // No break point.
7954 if (break_point_info->break_point_objects()->IsUndefined()) return false;
7955 // Single beak point.
7956 if (!break_point_info->break_point_objects()->IsFixedArray()) {
7957 return break_point_info->break_point_objects() == *break_point_object;
7958 }
7959 // Multiple break points.
7960 FixedArray* array = FixedArray::cast(break_point_info->break_point_objects());
7961 for (int i = 0; i < array->length(); i++) {
7962 if (array->get(i) == *break_point_object) {
7963 return true;
7964 }
7965 }
7966 return false;
7967}
7968
7969
7970// Get the number of break points.
7971int BreakPointInfo::GetBreakPointCount() {
7972 // No break point.
7973 if (break_point_objects()->IsUndefined()) return 0;
7974 // Single beak point.
7975 if (!break_point_objects()->IsFixedArray()) return 1;
7976 // Multiple break points.
7977 return FixedArray::cast(break_point_objects())->length();
7978}
7979#endif
7980
7981
7982} } // namespace v8::internal