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