blob: 5003b4f8c30b76d10c0bfeb29b3ed7c0c9736ce8 [file] [log] [blame]
Ben Murdochf87a2032010-10-22 12:50:53 +01001// Copyright 2010 the V8 project authors. All rights reserved.
Steve Blocka7e24c12009-10-30 11:49:00 +00002// Redistribution and use in source and binary forms, with or without
3// modification, are permitted provided that the following conditions are
4// met:
5//
6// * Redistributions of source code must retain the above copyright
7// notice, this list of conditions and the following disclaimer.
8// * Redistributions in binary form must reproduce the above
9// copyright notice, this list of conditions and the following
10// disclaimer in the documentation and/or other materials provided
11// with the distribution.
12// * Neither the name of Google Inc. nor the names of its
13// contributors may be used to endorse or promote products derived
14// from this software without specific prior written permission.
15//
16// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27
28#include "v8.h"
29
30#include "api.h"
31#include "arguments.h"
32#include "bootstrapper.h"
Ben Murdochb0fe1622011-05-05 13:52:32 +010033#include "codegen.h"
Steve Blocka7e24c12009-10-30 11:49:00 +000034#include "debug.h"
Ben Murdochb0fe1622011-05-05 13:52:32 +010035#include "deoptimizer.h"
Steve Blocka7e24c12009-10-30 11:49:00 +000036#include "execution.h"
Ben Murdochb0fe1622011-05-05 13:52:32 +010037#include "full-codegen.h"
38#include "hydrogen.h"
Steve Blocka7e24c12009-10-30 11:49:00 +000039#include "objects-inl.h"
Iain Merrick75681382010-08-19 15:07:18 +010040#include "objects-visiting.h"
Steve Blocka7e24c12009-10-30 11:49:00 +000041#include "macro-assembler.h"
Ben Murdochb0fe1622011-05-05 13:52:32 +010042#include "safepoint-table.h"
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -080043#include "scanner-base.h"
Steve Blocka7e24c12009-10-30 11:49:00 +000044#include "scopeinfo.h"
45#include "string-stream.h"
Steve Blockd0582a62009-12-15 09:54:21 +000046#include "utils.h"
Ben Murdochb0fe1622011-05-05 13:52:32 +010047#include "vm-state-inl.h"
Steve Blocka7e24c12009-10-30 11:49:00 +000048
49#ifdef ENABLE_DISASSEMBLER
Ben Murdochb0fe1622011-05-05 13:52:32 +010050#include "disasm.h"
Steve Blocka7e24c12009-10-30 11:49:00 +000051#include "disassembler.h"
52#endif
53
54
55namespace v8 {
56namespace internal {
57
58// Getters and setters are stored in a fixed array property. These are
59// constants for their indices.
60const int kGetterIndex = 0;
61const int kSetterIndex = 1;
62
63
John Reck59135872010-11-02 12:39:01 -070064MUST_USE_RESULT static MaybeObject* CreateJSValue(JSFunction* constructor,
65 Object* value) {
66 Object* result;
67 { MaybeObject* maybe_result = Heap::AllocateJSObject(constructor);
68 if (!maybe_result->ToObject(&result)) return maybe_result;
69 }
Steve Blocka7e24c12009-10-30 11:49:00 +000070 JSValue::cast(result)->set_value(value);
71 return result;
72}
73
74
John Reck59135872010-11-02 12:39:01 -070075MaybeObject* Object::ToObject(Context* global_context) {
Steve Blocka7e24c12009-10-30 11:49:00 +000076 if (IsNumber()) {
77 return CreateJSValue(global_context->number_function(), this);
78 } else if (IsBoolean()) {
79 return CreateJSValue(global_context->boolean_function(), this);
80 } else if (IsString()) {
81 return CreateJSValue(global_context->string_function(), this);
82 }
83 ASSERT(IsJSObject());
84 return this;
85}
86
87
John Reck59135872010-11-02 12:39:01 -070088MaybeObject* Object::ToObject() {
Steve Blocka7e24c12009-10-30 11:49:00 +000089 Context* global_context = Top::context()->global_context();
90 if (IsJSObject()) {
91 return this;
92 } else if (IsNumber()) {
93 return CreateJSValue(global_context->number_function(), this);
94 } else if (IsBoolean()) {
95 return CreateJSValue(global_context->boolean_function(), this);
96 } else if (IsString()) {
97 return CreateJSValue(global_context->string_function(), this);
98 }
99
100 // Throw a type error.
101 return Failure::InternalError();
102}
103
104
105Object* Object::ToBoolean() {
106 if (IsTrue()) return Heap::true_value();
107 if (IsFalse()) return Heap::false_value();
108 if (IsSmi()) {
109 return Heap::ToBoolean(Smi::cast(this)->value() != 0);
110 }
111 if (IsUndefined() || IsNull()) return Heap::false_value();
112 // Undetectable object is false
113 if (IsUndetectableObject()) {
114 return Heap::false_value();
115 }
116 if (IsString()) {
117 return Heap::ToBoolean(String::cast(this)->length() != 0);
118 }
119 if (IsHeapNumber()) {
120 return HeapNumber::cast(this)->HeapNumberToBoolean();
121 }
122 return Heap::true_value();
123}
124
125
126void Object::Lookup(String* name, LookupResult* result) {
127 if (IsJSObject()) return JSObject::cast(this)->Lookup(name, result);
128 Object* holder = NULL;
129 Context* global_context = Top::context()->global_context();
130 if (IsString()) {
131 holder = global_context->string_function()->instance_prototype();
132 } else if (IsNumber()) {
133 holder = global_context->number_function()->instance_prototype();
134 } else if (IsBoolean()) {
135 holder = global_context->boolean_function()->instance_prototype();
136 }
137 ASSERT(holder != NULL); // Cannot handle null or undefined.
138 JSObject::cast(holder)->Lookup(name, result);
139}
140
141
John Reck59135872010-11-02 12:39:01 -0700142MaybeObject* Object::GetPropertyWithReceiver(Object* receiver,
143 String* name,
144 PropertyAttributes* attributes) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000145 LookupResult result;
146 Lookup(name, &result);
John Reck59135872010-11-02 12:39:01 -0700147 MaybeObject* value = GetProperty(receiver, &result, name, attributes);
Steve Blocka7e24c12009-10-30 11:49:00 +0000148 ASSERT(*attributes <= ABSENT);
149 return value;
150}
151
152
John Reck59135872010-11-02 12:39:01 -0700153MaybeObject* Object::GetPropertyWithCallback(Object* receiver,
154 Object* structure,
155 String* name,
156 Object* holder) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000157 // To accommodate both the old and the new api we switch on the
158 // data structure used to store the callbacks. Eventually proxy
159 // callbacks should be phased out.
160 if (structure->IsProxy()) {
161 AccessorDescriptor* callback =
162 reinterpret_cast<AccessorDescriptor*>(Proxy::cast(structure)->proxy());
John Reck59135872010-11-02 12:39:01 -0700163 MaybeObject* value = (callback->getter)(receiver, callback->data);
Steve Blocka7e24c12009-10-30 11:49:00 +0000164 RETURN_IF_SCHEDULED_EXCEPTION();
165 return value;
166 }
167
168 // api style callbacks.
169 if (structure->IsAccessorInfo()) {
170 AccessorInfo* data = AccessorInfo::cast(structure);
171 Object* fun_obj = data->getter();
172 v8::AccessorGetter call_fun = v8::ToCData<v8::AccessorGetter>(fun_obj);
173 HandleScope scope;
174 JSObject* self = JSObject::cast(receiver);
175 JSObject* holder_handle = JSObject::cast(holder);
176 Handle<String> key(name);
177 LOG(ApiNamedPropertyAccess("load", self, name));
178 CustomArguments args(data->data(), self, holder_handle);
179 v8::AccessorInfo info(args.end());
180 v8::Handle<v8::Value> result;
181 {
182 // Leaving JavaScript.
183 VMState state(EXTERNAL);
184 result = call_fun(v8::Utils::ToLocal(key), info);
185 }
186 RETURN_IF_SCHEDULED_EXCEPTION();
187 if (result.IsEmpty()) return Heap::undefined_value();
188 return *v8::Utils::OpenHandle(*result);
189 }
190
191 // __defineGetter__ callback
192 if (structure->IsFixedArray()) {
193 Object* getter = FixedArray::cast(structure)->get(kGetterIndex);
194 if (getter->IsJSFunction()) {
195 return Object::GetPropertyWithDefinedGetter(receiver,
196 JSFunction::cast(getter));
197 }
198 // Getter is not a function.
199 return Heap::undefined_value();
200 }
201
202 UNREACHABLE();
Leon Clarkef7060e22010-06-03 12:02:55 +0100203 return NULL;
Steve Blocka7e24c12009-10-30 11:49:00 +0000204}
205
206
John Reck59135872010-11-02 12:39:01 -0700207MaybeObject* Object::GetPropertyWithDefinedGetter(Object* receiver,
208 JSFunction* getter) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000209 HandleScope scope;
210 Handle<JSFunction> fun(JSFunction::cast(getter));
211 Handle<Object> self(receiver);
212#ifdef ENABLE_DEBUGGER_SUPPORT
213 // Handle stepping into a getter if step into is active.
214 if (Debug::StepInActive()) {
215 Debug::HandleStepIn(fun, Handle<Object>::null(), 0, false);
216 }
217#endif
218 bool has_pending_exception;
219 Handle<Object> result =
220 Execution::Call(fun, self, 0, NULL, &has_pending_exception);
221 // Check for pending exception and return the result.
222 if (has_pending_exception) return Failure::Exception();
223 return *result;
224}
225
226
227// Only deal with CALLBACKS and INTERCEPTOR
John Reck59135872010-11-02 12:39:01 -0700228MaybeObject* JSObject::GetPropertyWithFailedAccessCheck(
Steve Blocka7e24c12009-10-30 11:49:00 +0000229 Object* receiver,
230 LookupResult* result,
231 String* name,
232 PropertyAttributes* attributes) {
Andrei Popescu402d9372010-02-26 13:31:12 +0000233 if (result->IsProperty()) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000234 switch (result->type()) {
235 case CALLBACKS: {
236 // Only allow API accessors.
237 Object* obj = result->GetCallbackObject();
238 if (obj->IsAccessorInfo()) {
239 AccessorInfo* info = AccessorInfo::cast(obj);
240 if (info->all_can_read()) {
241 *attributes = result->GetAttributes();
242 return GetPropertyWithCallback(receiver,
243 result->GetCallbackObject(),
244 name,
245 result->holder());
246 }
247 }
248 break;
249 }
250 case NORMAL:
251 case FIELD:
252 case CONSTANT_FUNCTION: {
253 // Search ALL_CAN_READ accessors in prototype chain.
254 LookupResult r;
255 result->holder()->LookupRealNamedPropertyInPrototypes(name, &r);
Andrei Popescu402d9372010-02-26 13:31:12 +0000256 if (r.IsProperty()) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000257 return GetPropertyWithFailedAccessCheck(receiver,
258 &r,
259 name,
260 attributes);
261 }
262 break;
263 }
264 case INTERCEPTOR: {
265 // If the object has an interceptor, try real named properties.
266 // No access check in GetPropertyAttributeWithInterceptor.
267 LookupResult r;
268 result->holder()->LookupRealNamedProperty(name, &r);
Andrei Popescu402d9372010-02-26 13:31:12 +0000269 if (r.IsProperty()) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000270 return GetPropertyWithFailedAccessCheck(receiver,
271 &r,
272 name,
273 attributes);
274 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000275 break;
276 }
Andrei Popescu402d9372010-02-26 13:31:12 +0000277 default:
278 UNREACHABLE();
Steve Blocka7e24c12009-10-30 11:49:00 +0000279 }
280 }
281
282 // No accessible property found.
283 *attributes = ABSENT;
284 Top::ReportFailedAccessCheck(this, v8::ACCESS_GET);
285 return Heap::undefined_value();
286}
287
288
289PropertyAttributes JSObject::GetPropertyAttributeWithFailedAccessCheck(
290 Object* receiver,
291 LookupResult* result,
292 String* name,
293 bool continue_search) {
Andrei Popescu402d9372010-02-26 13:31:12 +0000294 if (result->IsProperty()) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000295 switch (result->type()) {
296 case CALLBACKS: {
297 // Only allow API accessors.
298 Object* obj = result->GetCallbackObject();
299 if (obj->IsAccessorInfo()) {
300 AccessorInfo* info = AccessorInfo::cast(obj);
301 if (info->all_can_read()) {
302 return result->GetAttributes();
303 }
304 }
305 break;
306 }
307
308 case NORMAL:
309 case FIELD:
310 case CONSTANT_FUNCTION: {
311 if (!continue_search) break;
312 // Search ALL_CAN_READ accessors in prototype chain.
313 LookupResult r;
314 result->holder()->LookupRealNamedPropertyInPrototypes(name, &r);
Andrei Popescu402d9372010-02-26 13:31:12 +0000315 if (r.IsProperty()) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000316 return GetPropertyAttributeWithFailedAccessCheck(receiver,
317 &r,
318 name,
319 continue_search);
320 }
321 break;
322 }
323
324 case INTERCEPTOR: {
325 // If the object has an interceptor, try real named properties.
326 // No access check in GetPropertyAttributeWithInterceptor.
327 LookupResult r;
328 if (continue_search) {
329 result->holder()->LookupRealNamedProperty(name, &r);
330 } else {
331 result->holder()->LocalLookupRealNamedProperty(name, &r);
332 }
Andrei Popescu402d9372010-02-26 13:31:12 +0000333 if (r.IsProperty()) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000334 return GetPropertyAttributeWithFailedAccessCheck(receiver,
335 &r,
336 name,
337 continue_search);
338 }
339 break;
340 }
341
Andrei Popescu402d9372010-02-26 13:31:12 +0000342 default:
343 UNREACHABLE();
Steve Blocka7e24c12009-10-30 11:49:00 +0000344 }
345 }
346
347 Top::ReportFailedAccessCheck(this, v8::ACCESS_HAS);
348 return ABSENT;
349}
350
351
Steve Blocka7e24c12009-10-30 11:49:00 +0000352Object* JSObject::GetNormalizedProperty(LookupResult* result) {
353 ASSERT(!HasFastProperties());
354 Object* value = property_dictionary()->ValueAt(result->GetDictionaryEntry());
355 if (IsGlobalObject()) {
356 value = JSGlobalPropertyCell::cast(value)->value();
357 }
358 ASSERT(!value->IsJSGlobalPropertyCell());
359 return value;
360}
361
362
363Object* JSObject::SetNormalizedProperty(LookupResult* result, Object* value) {
364 ASSERT(!HasFastProperties());
365 if (IsGlobalObject()) {
366 JSGlobalPropertyCell* cell =
367 JSGlobalPropertyCell::cast(
368 property_dictionary()->ValueAt(result->GetDictionaryEntry()));
369 cell->set_value(value);
370 } else {
371 property_dictionary()->ValueAtPut(result->GetDictionaryEntry(), value);
372 }
373 return value;
374}
375
376
John Reck59135872010-11-02 12:39:01 -0700377MaybeObject* JSObject::SetNormalizedProperty(String* name,
378 Object* value,
379 PropertyDetails details) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000380 ASSERT(!HasFastProperties());
381 int entry = property_dictionary()->FindEntry(name);
382 if (entry == StringDictionary::kNotFound) {
383 Object* store_value = value;
384 if (IsGlobalObject()) {
John Reck59135872010-11-02 12:39:01 -0700385 { MaybeObject* maybe_store_value =
386 Heap::AllocateJSGlobalPropertyCell(value);
387 if (!maybe_store_value->ToObject(&store_value)) {
388 return maybe_store_value;
389 }
390 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000391 }
John Reck59135872010-11-02 12:39:01 -0700392 Object* dict;
393 { MaybeObject* maybe_dict =
394 property_dictionary()->Add(name, store_value, details);
395 if (!maybe_dict->ToObject(&dict)) return maybe_dict;
396 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000397 set_properties(StringDictionary::cast(dict));
398 return value;
399 }
400 // Preserve enumeration index.
401 details = PropertyDetails(details.attributes(),
402 details.type(),
403 property_dictionary()->DetailsAt(entry).index());
404 if (IsGlobalObject()) {
405 JSGlobalPropertyCell* cell =
406 JSGlobalPropertyCell::cast(property_dictionary()->ValueAt(entry));
407 cell->set_value(value);
408 // Please note we have to update the property details.
409 property_dictionary()->DetailsAtPut(entry, details);
410 } else {
411 property_dictionary()->SetEntry(entry, name, value, details);
412 }
413 return value;
414}
415
416
John Reck59135872010-11-02 12:39:01 -0700417MaybeObject* JSObject::DeleteNormalizedProperty(String* name, DeleteMode mode) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000418 ASSERT(!HasFastProperties());
419 StringDictionary* dictionary = property_dictionary();
420 int entry = dictionary->FindEntry(name);
421 if (entry != StringDictionary::kNotFound) {
422 // If we have a global object set the cell to the hole.
423 if (IsGlobalObject()) {
424 PropertyDetails details = dictionary->DetailsAt(entry);
425 if (details.IsDontDelete()) {
426 if (mode != FORCE_DELETION) return Heap::false_value();
427 // When forced to delete global properties, we have to make a
428 // map change to invalidate any ICs that think they can load
429 // from the DontDelete cell without checking if it contains
430 // the hole value.
John Reck59135872010-11-02 12:39:01 -0700431 Object* new_map;
432 { MaybeObject* maybe_new_map = map()->CopyDropDescriptors();
433 if (!maybe_new_map->ToObject(&new_map)) return maybe_new_map;
434 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000435 set_map(Map::cast(new_map));
436 }
437 JSGlobalPropertyCell* cell =
438 JSGlobalPropertyCell::cast(dictionary->ValueAt(entry));
439 cell->set_value(Heap::the_hole_value());
440 dictionary->DetailsAtPut(entry, details.AsDeleted());
441 } else {
442 return dictionary->DeleteProperty(entry, mode);
443 }
444 }
445 return Heap::true_value();
446}
447
448
449bool JSObject::IsDirty() {
450 Object* cons_obj = map()->constructor();
451 if (!cons_obj->IsJSFunction())
452 return true;
453 JSFunction* fun = JSFunction::cast(cons_obj);
Steve Block6ded16b2010-05-10 14:33:55 +0100454 if (!fun->shared()->IsApiFunction())
Steve Blocka7e24c12009-10-30 11:49:00 +0000455 return true;
456 // If the object is fully fast case and has the same map it was
457 // created with then no changes can have been made to it.
458 return map() != fun->initial_map()
459 || !HasFastElements()
460 || !HasFastProperties();
461}
462
463
John Reck59135872010-11-02 12:39:01 -0700464MaybeObject* Object::GetProperty(Object* receiver,
465 LookupResult* result,
466 String* name,
467 PropertyAttributes* attributes) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000468 // Make sure that the top context does not change when doing
469 // callbacks or interceptor calls.
470 AssertNoContextChange ncc;
471
472 // Traverse the prototype chain from the current object (this) to
473 // the holder and check for access rights. This avoid traversing the
474 // objects more than once in case of interceptors, because the
475 // holder will always be the interceptor holder and the search may
476 // only continue with a current object just after the interceptor
477 // holder in the prototype chain.
Andrei Popescu402d9372010-02-26 13:31:12 +0000478 Object* last = result->IsProperty() ? result->holder() : Heap::null_value();
Steve Blocka7e24c12009-10-30 11:49:00 +0000479 for (Object* current = this; true; current = current->GetPrototype()) {
480 if (current->IsAccessCheckNeeded()) {
481 // Check if we're allowed to read from the current object. Note
482 // that even though we may not actually end up loading the named
483 // property from the current object, we still check that we have
484 // access to it.
485 JSObject* checked = JSObject::cast(current);
486 if (!Top::MayNamedAccess(checked, name, v8::ACCESS_GET)) {
487 return checked->GetPropertyWithFailedAccessCheck(receiver,
488 result,
489 name,
490 attributes);
491 }
492 }
493 // Stop traversing the chain once we reach the last object in the
494 // chain; either the holder of the result or null in case of an
495 // absent property.
496 if (current == last) break;
497 }
498
499 if (!result->IsProperty()) {
500 *attributes = ABSENT;
501 return Heap::undefined_value();
502 }
503 *attributes = result->GetAttributes();
Steve Blocka7e24c12009-10-30 11:49:00 +0000504 Object* value;
505 JSObject* holder = result->holder();
506 switch (result->type()) {
507 case NORMAL:
508 value = holder->GetNormalizedProperty(result);
509 ASSERT(!value->IsTheHole() || result->IsReadOnly());
510 return value->IsTheHole() ? Heap::undefined_value() : value;
511 case FIELD:
512 value = holder->FastPropertyAt(result->GetFieldIndex());
513 ASSERT(!value->IsTheHole() || result->IsReadOnly());
514 return value->IsTheHole() ? Heap::undefined_value() : value;
515 case CONSTANT_FUNCTION:
516 return result->GetConstantFunction();
517 case CALLBACKS:
518 return GetPropertyWithCallback(receiver,
519 result->GetCallbackObject(),
520 name,
521 holder);
522 case INTERCEPTOR: {
523 JSObject* recvr = JSObject::cast(receiver);
524 return holder->GetPropertyWithInterceptor(recvr, name, attributes);
525 }
526 default:
527 UNREACHABLE();
528 return NULL;
529 }
530}
531
532
John Reck59135872010-11-02 12:39:01 -0700533MaybeObject* Object::GetElementWithReceiver(Object* receiver, uint32_t index) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000534 // Non-JS objects do not have integer indexed properties.
535 if (!IsJSObject()) return Heap::undefined_value();
536 return JSObject::cast(this)->GetElementWithReceiver(JSObject::cast(receiver),
537 index);
538}
539
540
541Object* Object::GetPrototype() {
542 // The object is either a number, a string, a boolean, or a real JS object.
543 if (IsJSObject()) return JSObject::cast(this)->map()->prototype();
544 Context* context = Top::context()->global_context();
545
546 if (IsNumber()) return context->number_function()->instance_prototype();
547 if (IsString()) return context->string_function()->instance_prototype();
548 if (IsBoolean()) {
549 return context->boolean_function()->instance_prototype();
550 } else {
551 return Heap::null_value();
552 }
553}
554
555
Ben Murdochb0fe1622011-05-05 13:52:32 +0100556void Object::ShortPrint(FILE* out) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000557 HeapStringAllocator allocator;
558 StringStream accumulator(&allocator);
559 ShortPrint(&accumulator);
Ben Murdochb0fe1622011-05-05 13:52:32 +0100560 accumulator.OutputToFile(out);
Steve Blocka7e24c12009-10-30 11:49:00 +0000561}
562
563
564void Object::ShortPrint(StringStream* accumulator) {
565 if (IsSmi()) {
566 Smi::cast(this)->SmiPrint(accumulator);
567 } else if (IsFailure()) {
568 Failure::cast(this)->FailurePrint(accumulator);
569 } else {
570 HeapObject::cast(this)->HeapObjectShortPrint(accumulator);
571 }
572}
573
574
Ben Murdochb0fe1622011-05-05 13:52:32 +0100575void Smi::SmiPrint(FILE* out) {
576 PrintF(out, "%d", value());
Steve Blocka7e24c12009-10-30 11:49:00 +0000577}
578
579
580void Smi::SmiPrint(StringStream* accumulator) {
581 accumulator->Add("%d", value());
582}
583
584
585void Failure::FailurePrint(StringStream* accumulator) {
Steve Block3ce2e202009-11-05 08:53:23 +0000586 accumulator->Add("Failure(%p)", reinterpret_cast<void*>(value()));
Steve Blocka7e24c12009-10-30 11:49:00 +0000587}
588
589
Ben Murdochb0fe1622011-05-05 13:52:32 +0100590void Failure::FailurePrint(FILE* out) {
591 PrintF(out, "Failure(%p)", reinterpret_cast<void*>(value()));
Steve Blocka7e24c12009-10-30 11:49:00 +0000592}
593
594
Steve Blocka7e24c12009-10-30 11:49:00 +0000595// Should a word be prefixed by 'a' or 'an' in order to read naturally in
596// English? Returns false for non-ASCII or words that don't start with
597// a capital letter. The a/an rule follows pronunciation in English.
598// We don't use the BBC's overcorrect "an historic occasion" though if
599// you speak a dialect you may well say "an 'istoric occasion".
600static bool AnWord(String* str) {
601 if (str->length() == 0) return false; // A nothing.
602 int c0 = str->Get(0);
603 int c1 = str->length() > 1 ? str->Get(1) : 0;
604 if (c0 == 'U') {
605 if (c1 > 'Z') {
606 return true; // An Umpire, but a UTF8String, a U.
607 }
608 } else if (c0 == 'A' || c0 == 'E' || c0 == 'I' || c0 == 'O') {
609 return true; // An Ape, an ABCBook.
610 } else if ((c1 == 0 || (c1 >= 'A' && c1 <= 'Z')) &&
611 (c0 == 'F' || c0 == 'H' || c0 == 'M' || c0 == 'N' || c0 == 'R' ||
612 c0 == 'S' || c0 == 'X')) {
613 return true; // An MP3File, an M.
614 }
615 return false;
616}
617
618
John Reck59135872010-11-02 12:39:01 -0700619MaybeObject* String::SlowTryFlatten(PretenureFlag pretenure) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000620#ifdef DEBUG
621 // Do not attempt to flatten in debug mode when allocation is not
622 // allowed. This is to avoid an assertion failure when allocating.
623 // Flattening strings is the only case where we always allow
624 // allocation because no GC is performed if the allocation fails.
625 if (!Heap::IsAllocationAllowed()) return this;
626#endif
627
628 switch (StringShape(this).representation_tag()) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000629 case kConsStringTag: {
630 ConsString* cs = ConsString::cast(this);
631 if (cs->second()->length() == 0) {
Leon Clarkef7060e22010-06-03 12:02:55 +0100632 return cs->first();
Steve Blocka7e24c12009-10-30 11:49:00 +0000633 }
634 // There's little point in putting the flat string in new space if the
635 // cons string is in old space. It can never get GCed until there is
636 // an old space GC.
Steve Block6ded16b2010-05-10 14:33:55 +0100637 PretenureFlag tenure = Heap::InNewSpace(this) ? pretenure : TENURED;
Steve Blocka7e24c12009-10-30 11:49:00 +0000638 int len = length();
639 Object* object;
640 String* result;
641 if (IsAsciiRepresentation()) {
John Reck59135872010-11-02 12:39:01 -0700642 { MaybeObject* maybe_object = Heap::AllocateRawAsciiString(len, tenure);
643 if (!maybe_object->ToObject(&object)) return maybe_object;
644 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000645 result = String::cast(object);
646 String* first = cs->first();
647 int first_length = first->length();
648 char* dest = SeqAsciiString::cast(result)->GetChars();
649 WriteToFlat(first, dest, 0, first_length);
650 String* second = cs->second();
651 WriteToFlat(second,
652 dest + first_length,
653 0,
654 len - first_length);
655 } else {
John Reck59135872010-11-02 12:39:01 -0700656 { MaybeObject* maybe_object =
657 Heap::AllocateRawTwoByteString(len, tenure);
658 if (!maybe_object->ToObject(&object)) return maybe_object;
659 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000660 result = String::cast(object);
661 uc16* dest = SeqTwoByteString::cast(result)->GetChars();
662 String* first = cs->first();
663 int first_length = first->length();
664 WriteToFlat(first, dest, 0, first_length);
665 String* second = cs->second();
666 WriteToFlat(second,
667 dest + first_length,
668 0,
669 len - first_length);
670 }
671 cs->set_first(result);
672 cs->set_second(Heap::empty_string());
Leon Clarkef7060e22010-06-03 12:02:55 +0100673 return result;
Steve Blocka7e24c12009-10-30 11:49:00 +0000674 }
675 default:
676 return this;
677 }
678}
679
680
681bool String::MakeExternal(v8::String::ExternalStringResource* resource) {
Steve Block8defd9f2010-07-08 12:39:36 +0100682 // Externalizing twice leaks the external resource, so it's
Kristian Monsen9dcf7e22010-06-28 14:14:28 +0100683 // prohibited by the API.
684 ASSERT(!this->IsExternalString());
Steve Blocka7e24c12009-10-30 11:49:00 +0000685#ifdef DEBUG
Steve Block3ce2e202009-11-05 08:53:23 +0000686 if (FLAG_enable_slow_asserts) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000687 // Assert that the resource and the string are equivalent.
688 ASSERT(static_cast<size_t>(this->length()) == resource->length());
Kristian Monsen25f61362010-05-21 11:50:48 +0100689 ScopedVector<uc16> smart_chars(this->length());
690 String::WriteToFlat(this, smart_chars.start(), 0, this->length());
691 ASSERT(memcmp(smart_chars.start(),
Steve Blocka7e24c12009-10-30 11:49:00 +0000692 resource->data(),
Kristian Monsen25f61362010-05-21 11:50:48 +0100693 resource->length() * sizeof(smart_chars[0])) == 0);
Steve Blocka7e24c12009-10-30 11:49:00 +0000694 }
695#endif // DEBUG
696
697 int size = this->Size(); // Byte size of the original string.
698 if (size < ExternalString::kSize) {
699 // The string is too small to fit an external String in its place. This can
700 // only happen for zero length strings.
701 return false;
702 }
703 ASSERT(size >= ExternalString::kSize);
Kristian Monsen9dcf7e22010-06-28 14:14:28 +0100704 bool is_ascii = this->IsAsciiRepresentation();
Steve Blocka7e24c12009-10-30 11:49:00 +0000705 bool is_symbol = this->IsSymbol();
706 int length = this->length();
Steve Blockd0582a62009-12-15 09:54:21 +0000707 int hash_field = this->hash_field();
Steve Blocka7e24c12009-10-30 11:49:00 +0000708
709 // Morph the object to an external string by adjusting the map and
710 // reinitializing the fields.
Kristian Monsen9dcf7e22010-06-28 14:14:28 +0100711 this->set_map(is_ascii ?
712 Heap::external_string_with_ascii_data_map() :
713 Heap::external_string_map());
Steve Blocka7e24c12009-10-30 11:49:00 +0000714 ExternalTwoByteString* self = ExternalTwoByteString::cast(this);
715 self->set_length(length);
Steve Blockd0582a62009-12-15 09:54:21 +0000716 self->set_hash_field(hash_field);
Steve Blocka7e24c12009-10-30 11:49:00 +0000717 self->set_resource(resource);
718 // Additionally make the object into an external symbol if the original string
719 // was a symbol to start with.
720 if (is_symbol) {
721 self->Hash(); // Force regeneration of the hash value.
722 // Now morph this external string into a external symbol.
Kristian Monsen9dcf7e22010-06-28 14:14:28 +0100723 this->set_map(is_ascii ?
724 Heap::external_symbol_with_ascii_data_map() :
725 Heap::external_symbol_map());
Steve Blocka7e24c12009-10-30 11:49:00 +0000726 }
727
728 // Fill the remainder of the string with dead wood.
729 int new_size = this->Size(); // Byte size of the external String object.
730 Heap::CreateFillerObjectAt(this->address() + new_size, size - new_size);
731 return true;
732}
733
734
735bool String::MakeExternal(v8::String::ExternalAsciiStringResource* resource) {
736#ifdef DEBUG
Steve Block3ce2e202009-11-05 08:53:23 +0000737 if (FLAG_enable_slow_asserts) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000738 // Assert that the resource and the string are equivalent.
739 ASSERT(static_cast<size_t>(this->length()) == resource->length());
Kristian Monsen25f61362010-05-21 11:50:48 +0100740 ScopedVector<char> smart_chars(this->length());
741 String::WriteToFlat(this, smart_chars.start(), 0, this->length());
742 ASSERT(memcmp(smart_chars.start(),
Steve Blocka7e24c12009-10-30 11:49:00 +0000743 resource->data(),
Kristian Monsen25f61362010-05-21 11:50:48 +0100744 resource->length() * sizeof(smart_chars[0])) == 0);
Steve Blocka7e24c12009-10-30 11:49:00 +0000745 }
746#endif // DEBUG
747
748 int size = this->Size(); // Byte size of the original string.
749 if (size < ExternalString::kSize) {
750 // The string is too small to fit an external String in its place. This can
751 // only happen for zero length strings.
752 return false;
753 }
754 ASSERT(size >= ExternalString::kSize);
755 bool is_symbol = this->IsSymbol();
756 int length = this->length();
Steve Blockd0582a62009-12-15 09:54:21 +0000757 int hash_field = this->hash_field();
Steve Blocka7e24c12009-10-30 11:49:00 +0000758
759 // Morph the object to an external string by adjusting the map and
760 // reinitializing the fields.
Steve Blockd0582a62009-12-15 09:54:21 +0000761 this->set_map(Heap::external_ascii_string_map());
Steve Blocka7e24c12009-10-30 11:49:00 +0000762 ExternalAsciiString* self = ExternalAsciiString::cast(this);
763 self->set_length(length);
Steve Blockd0582a62009-12-15 09:54:21 +0000764 self->set_hash_field(hash_field);
Steve Blocka7e24c12009-10-30 11:49:00 +0000765 self->set_resource(resource);
766 // Additionally make the object into an external symbol if the original string
767 // was a symbol to start with.
768 if (is_symbol) {
769 self->Hash(); // Force regeneration of the hash value.
770 // Now morph this external string into a external symbol.
Steve Blockd0582a62009-12-15 09:54:21 +0000771 this->set_map(Heap::external_ascii_symbol_map());
Steve Blocka7e24c12009-10-30 11:49:00 +0000772 }
773
774 // Fill the remainder of the string with dead wood.
775 int new_size = this->Size(); // Byte size of the external String object.
776 Heap::CreateFillerObjectAt(this->address() + new_size, size - new_size);
777 return true;
778}
779
780
781void String::StringShortPrint(StringStream* accumulator) {
782 int len = length();
Steve Blockd0582a62009-12-15 09:54:21 +0000783 if (len > kMaxShortPrintLength) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000784 accumulator->Add("<Very long string[%u]>", len);
785 return;
786 }
787
788 if (!LooksValid()) {
789 accumulator->Add("<Invalid String>");
790 return;
791 }
792
793 StringInputBuffer buf(this);
794
795 bool truncated = false;
796 if (len > kMaxShortPrintLength) {
797 len = kMaxShortPrintLength;
798 truncated = true;
799 }
800 bool ascii = true;
801 for (int i = 0; i < len; i++) {
802 int c = buf.GetNext();
803
804 if (c < 32 || c >= 127) {
805 ascii = false;
806 }
807 }
808 buf.Reset(this);
809 if (ascii) {
810 accumulator->Add("<String[%u]: ", length());
811 for (int i = 0; i < len; i++) {
812 accumulator->Put(buf.GetNext());
813 }
814 accumulator->Put('>');
815 } else {
816 // Backslash indicates that the string contains control
817 // characters and that backslashes are therefore escaped.
818 accumulator->Add("<String[%u]\\: ", length());
819 for (int i = 0; i < len; i++) {
820 int c = buf.GetNext();
821 if (c == '\n') {
822 accumulator->Add("\\n");
823 } else if (c == '\r') {
824 accumulator->Add("\\r");
825 } else if (c == '\\') {
826 accumulator->Add("\\\\");
827 } else if (c < 32 || c > 126) {
828 accumulator->Add("\\x%02x", c);
829 } else {
830 accumulator->Put(c);
831 }
832 }
833 if (truncated) {
834 accumulator->Put('.');
835 accumulator->Put('.');
836 accumulator->Put('.');
837 }
838 accumulator->Put('>');
839 }
840 return;
841}
842
843
844void JSObject::JSObjectShortPrint(StringStream* accumulator) {
845 switch (map()->instance_type()) {
846 case JS_ARRAY_TYPE: {
847 double length = JSArray::cast(this)->length()->Number();
848 accumulator->Add("<JS array[%u]>", static_cast<uint32_t>(length));
849 break;
850 }
851 case JS_REGEXP_TYPE: {
852 accumulator->Add("<JS RegExp>");
853 break;
854 }
855 case JS_FUNCTION_TYPE: {
856 Object* fun_name = JSFunction::cast(this)->shared()->name();
857 bool printed = false;
858 if (fun_name->IsString()) {
859 String* str = String::cast(fun_name);
860 if (str->length() > 0) {
861 accumulator->Add("<JS Function ");
862 accumulator->Put(str);
863 accumulator->Put('>');
864 printed = true;
865 }
866 }
867 if (!printed) {
868 accumulator->Add("<JS Function>");
869 }
870 break;
871 }
872 // All other JSObjects are rather similar to each other (JSObject,
873 // JSGlobalProxy, JSGlobalObject, JSUndetectableObject, JSValue).
874 default: {
875 Object* constructor = map()->constructor();
876 bool printed = false;
877 if (constructor->IsHeapObject() &&
878 !Heap::Contains(HeapObject::cast(constructor))) {
879 accumulator->Add("!!!INVALID CONSTRUCTOR!!!");
880 } else {
881 bool global_object = IsJSGlobalProxy();
882 if (constructor->IsJSFunction()) {
883 if (!Heap::Contains(JSFunction::cast(constructor)->shared())) {
884 accumulator->Add("!!!INVALID SHARED ON CONSTRUCTOR!!!");
885 } else {
886 Object* constructor_name =
887 JSFunction::cast(constructor)->shared()->name();
888 if (constructor_name->IsString()) {
889 String* str = String::cast(constructor_name);
890 if (str->length() > 0) {
891 bool vowel = AnWord(str);
892 accumulator->Add("<%sa%s ",
893 global_object ? "Global Object: " : "",
894 vowel ? "n" : "");
895 accumulator->Put(str);
896 accumulator->Put('>');
897 printed = true;
898 }
899 }
900 }
901 }
902 if (!printed) {
903 accumulator->Add("<JS %sObject", global_object ? "Global " : "");
904 }
905 }
906 if (IsJSValue()) {
907 accumulator->Add(" value = ");
908 JSValue::cast(this)->value()->ShortPrint(accumulator);
909 }
910 accumulator->Put('>');
911 break;
912 }
913 }
914}
915
916
917void HeapObject::HeapObjectShortPrint(StringStream* accumulator) {
918 // if (!Heap::InNewSpace(this)) PrintF("*", this);
919 if (!Heap::Contains(this)) {
920 accumulator->Add("!!!INVALID POINTER!!!");
921 return;
922 }
923 if (!Heap::Contains(map())) {
924 accumulator->Add("!!!INVALID MAP!!!");
925 return;
926 }
927
928 accumulator->Add("%p ", this);
929
930 if (IsString()) {
931 String::cast(this)->StringShortPrint(accumulator);
932 return;
933 }
934 if (IsJSObject()) {
935 JSObject::cast(this)->JSObjectShortPrint(accumulator);
936 return;
937 }
938 switch (map()->instance_type()) {
939 case MAP_TYPE:
940 accumulator->Add("<Map>");
941 break;
942 case FIXED_ARRAY_TYPE:
943 accumulator->Add("<FixedArray[%u]>", FixedArray::cast(this)->length());
944 break;
945 case BYTE_ARRAY_TYPE:
946 accumulator->Add("<ByteArray[%u]>", ByteArray::cast(this)->length());
947 break;
948 case PIXEL_ARRAY_TYPE:
949 accumulator->Add("<PixelArray[%u]>", PixelArray::cast(this)->length());
950 break;
Steve Block3ce2e202009-11-05 08:53:23 +0000951 case EXTERNAL_BYTE_ARRAY_TYPE:
952 accumulator->Add("<ExternalByteArray[%u]>",
953 ExternalByteArray::cast(this)->length());
954 break;
955 case EXTERNAL_UNSIGNED_BYTE_ARRAY_TYPE:
956 accumulator->Add("<ExternalUnsignedByteArray[%u]>",
957 ExternalUnsignedByteArray::cast(this)->length());
958 break;
959 case EXTERNAL_SHORT_ARRAY_TYPE:
960 accumulator->Add("<ExternalShortArray[%u]>",
961 ExternalShortArray::cast(this)->length());
962 break;
963 case EXTERNAL_UNSIGNED_SHORT_ARRAY_TYPE:
964 accumulator->Add("<ExternalUnsignedShortArray[%u]>",
965 ExternalUnsignedShortArray::cast(this)->length());
966 break;
967 case EXTERNAL_INT_ARRAY_TYPE:
968 accumulator->Add("<ExternalIntArray[%u]>",
969 ExternalIntArray::cast(this)->length());
970 break;
971 case EXTERNAL_UNSIGNED_INT_ARRAY_TYPE:
972 accumulator->Add("<ExternalUnsignedIntArray[%u]>",
973 ExternalUnsignedIntArray::cast(this)->length());
974 break;
975 case EXTERNAL_FLOAT_ARRAY_TYPE:
976 accumulator->Add("<ExternalFloatArray[%u]>",
977 ExternalFloatArray::cast(this)->length());
978 break;
Steve Blocka7e24c12009-10-30 11:49:00 +0000979 case SHARED_FUNCTION_INFO_TYPE:
980 accumulator->Add("<SharedFunctionInfo>");
981 break;
Steve Block1e0659c2011-05-24 12:43:12 +0100982 case JS_MESSAGE_OBJECT_TYPE:
983 accumulator->Add("<JSMessageObject>");
984 break;
Steve Blocka7e24c12009-10-30 11:49:00 +0000985#define MAKE_STRUCT_CASE(NAME, Name, name) \
986 case NAME##_TYPE: \
987 accumulator->Put('<'); \
988 accumulator->Add(#Name); \
989 accumulator->Put('>'); \
990 break;
991 STRUCT_LIST(MAKE_STRUCT_CASE)
992#undef MAKE_STRUCT_CASE
993 case CODE_TYPE:
994 accumulator->Add("<Code>");
995 break;
996 case ODDBALL_TYPE: {
997 if (IsUndefined())
998 accumulator->Add("<undefined>");
999 else if (IsTheHole())
1000 accumulator->Add("<the hole>");
1001 else if (IsNull())
1002 accumulator->Add("<null>");
1003 else if (IsTrue())
1004 accumulator->Add("<true>");
1005 else if (IsFalse())
1006 accumulator->Add("<false>");
1007 else
1008 accumulator->Add("<Odd Oddball>");
1009 break;
1010 }
1011 case HEAP_NUMBER_TYPE:
1012 accumulator->Add("<Number: ");
1013 HeapNumber::cast(this)->HeapNumberPrint(accumulator);
1014 accumulator->Put('>');
1015 break;
1016 case PROXY_TYPE:
1017 accumulator->Add("<Proxy>");
1018 break;
1019 case JS_GLOBAL_PROPERTY_CELL_TYPE:
1020 accumulator->Add("Cell for ");
1021 JSGlobalPropertyCell::cast(this)->value()->ShortPrint(accumulator);
1022 break;
1023 default:
1024 accumulator->Add("<Other heap object (%d)>", map()->instance_type());
1025 break;
1026 }
1027}
1028
1029
Steve Blocka7e24c12009-10-30 11:49:00 +00001030void HeapObject::Iterate(ObjectVisitor* v) {
1031 // Handle header
1032 IteratePointer(v, kMapOffset);
1033 // Handle object body
1034 Map* m = map();
1035 IterateBody(m->instance_type(), SizeFromMap(m), v);
1036}
1037
1038
1039void HeapObject::IterateBody(InstanceType type, int object_size,
1040 ObjectVisitor* v) {
1041 // Avoiding <Type>::cast(this) because it accesses the map pointer field.
1042 // During GC, the map pointer field is encoded.
1043 if (type < FIRST_NONSTRING_TYPE) {
1044 switch (type & kStringRepresentationMask) {
1045 case kSeqStringTag:
1046 break;
1047 case kConsStringTag:
Iain Merrick75681382010-08-19 15:07:18 +01001048 ConsString::BodyDescriptor::IterateBody(this, v);
Steve Blocka7e24c12009-10-30 11:49:00 +00001049 break;
Steve Blockd0582a62009-12-15 09:54:21 +00001050 case kExternalStringTag:
1051 if ((type & kStringEncodingMask) == kAsciiStringTag) {
1052 reinterpret_cast<ExternalAsciiString*>(this)->
1053 ExternalAsciiStringIterateBody(v);
1054 } else {
1055 reinterpret_cast<ExternalTwoByteString*>(this)->
1056 ExternalTwoByteStringIterateBody(v);
1057 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001058 break;
1059 }
1060 return;
1061 }
1062
1063 switch (type) {
1064 case FIXED_ARRAY_TYPE:
Iain Merrick75681382010-08-19 15:07:18 +01001065 FixedArray::BodyDescriptor::IterateBody(this, object_size, v);
Steve Blocka7e24c12009-10-30 11:49:00 +00001066 break;
1067 case JS_OBJECT_TYPE:
1068 case JS_CONTEXT_EXTENSION_OBJECT_TYPE:
1069 case JS_VALUE_TYPE:
1070 case JS_ARRAY_TYPE:
1071 case JS_REGEXP_TYPE:
Steve Blocka7e24c12009-10-30 11:49:00 +00001072 case JS_GLOBAL_PROXY_TYPE:
1073 case JS_GLOBAL_OBJECT_TYPE:
1074 case JS_BUILTINS_OBJECT_TYPE:
Steve Block1e0659c2011-05-24 12:43:12 +01001075 case JS_MESSAGE_OBJECT_TYPE:
Iain Merrick75681382010-08-19 15:07:18 +01001076 JSObject::BodyDescriptor::IterateBody(this, object_size, v);
Steve Blocka7e24c12009-10-30 11:49:00 +00001077 break;
Steve Block791712a2010-08-27 10:21:07 +01001078 case JS_FUNCTION_TYPE:
1079 reinterpret_cast<JSFunction*>(this)
1080 ->JSFunctionIterateBody(object_size, v);
1081 break;
Steve Blocka7e24c12009-10-30 11:49:00 +00001082 case ODDBALL_TYPE:
Iain Merrick75681382010-08-19 15:07:18 +01001083 Oddball::BodyDescriptor::IterateBody(this, v);
Steve Blocka7e24c12009-10-30 11:49:00 +00001084 break;
1085 case PROXY_TYPE:
1086 reinterpret_cast<Proxy*>(this)->ProxyIterateBody(v);
1087 break;
1088 case MAP_TYPE:
Iain Merrick75681382010-08-19 15:07:18 +01001089 Map::BodyDescriptor::IterateBody(this, v);
Steve Blocka7e24c12009-10-30 11:49:00 +00001090 break;
1091 case CODE_TYPE:
1092 reinterpret_cast<Code*>(this)->CodeIterateBody(v);
1093 break;
1094 case JS_GLOBAL_PROPERTY_CELL_TYPE:
Iain Merrick75681382010-08-19 15:07:18 +01001095 JSGlobalPropertyCell::BodyDescriptor::IterateBody(this, v);
Steve Blocka7e24c12009-10-30 11:49:00 +00001096 break;
1097 case HEAP_NUMBER_TYPE:
1098 case FILLER_TYPE:
1099 case BYTE_ARRAY_TYPE:
1100 case PIXEL_ARRAY_TYPE:
Steve Block3ce2e202009-11-05 08:53:23 +00001101 case EXTERNAL_BYTE_ARRAY_TYPE:
1102 case EXTERNAL_UNSIGNED_BYTE_ARRAY_TYPE:
1103 case EXTERNAL_SHORT_ARRAY_TYPE:
1104 case EXTERNAL_UNSIGNED_SHORT_ARRAY_TYPE:
1105 case EXTERNAL_INT_ARRAY_TYPE:
1106 case EXTERNAL_UNSIGNED_INT_ARRAY_TYPE:
1107 case EXTERNAL_FLOAT_ARRAY_TYPE:
Steve Blocka7e24c12009-10-30 11:49:00 +00001108 break;
Iain Merrick75681382010-08-19 15:07:18 +01001109 case SHARED_FUNCTION_INFO_TYPE:
1110 SharedFunctionInfo::BodyDescriptor::IterateBody(this, v);
Steve Blocka7e24c12009-10-30 11:49:00 +00001111 break;
Iain Merrick75681382010-08-19 15:07:18 +01001112
Steve Blocka7e24c12009-10-30 11:49:00 +00001113#define MAKE_STRUCT_CASE(NAME, Name, name) \
1114 case NAME##_TYPE:
1115 STRUCT_LIST(MAKE_STRUCT_CASE)
1116#undef MAKE_STRUCT_CASE
Iain Merrick75681382010-08-19 15:07:18 +01001117 StructBodyDescriptor::IterateBody(this, object_size, v);
Steve Blocka7e24c12009-10-30 11:49:00 +00001118 break;
1119 default:
1120 PrintF("Unknown type: %d\n", type);
1121 UNREACHABLE();
1122 }
1123}
1124
1125
Steve Blocka7e24c12009-10-30 11:49:00 +00001126Object* HeapNumber::HeapNumberToBoolean() {
1127 // NaN, +0, and -0 should return the false object
Iain Merrick75681382010-08-19 15:07:18 +01001128#if __BYTE_ORDER == __LITTLE_ENDIAN
1129 union IeeeDoubleLittleEndianArchType u;
1130#elif __BYTE_ORDER == __BIG_ENDIAN
1131 union IeeeDoubleBigEndianArchType u;
1132#endif
1133 u.d = value();
1134 if (u.bits.exp == 2047) {
1135 // Detect NaN for IEEE double precision floating point.
1136 if ((u.bits.man_low | u.bits.man_high) != 0)
1137 return Heap::false_value();
Steve Blocka7e24c12009-10-30 11:49:00 +00001138 }
Iain Merrick75681382010-08-19 15:07:18 +01001139 if (u.bits.exp == 0) {
1140 // Detect +0, and -0 for IEEE double precision floating point.
1141 if ((u.bits.man_low | u.bits.man_high) == 0)
1142 return Heap::false_value();
1143 }
1144 return Heap::true_value();
Steve Blocka7e24c12009-10-30 11:49:00 +00001145}
1146
1147
Ben Murdochb0fe1622011-05-05 13:52:32 +01001148void HeapNumber::HeapNumberPrint(FILE* out) {
1149 PrintF(out, "%.16g", Number());
Steve Blocka7e24c12009-10-30 11:49:00 +00001150}
1151
1152
1153void HeapNumber::HeapNumberPrint(StringStream* accumulator) {
1154 // The Windows version of vsnprintf can allocate when printing a %g string
1155 // into a buffer that may not be big enough. We don't want random memory
1156 // allocation when producing post-crash stack traces, so we print into a
1157 // buffer that is plenty big enough for any floating point number, then
1158 // print that using vsnprintf (which may truncate but never allocate if
1159 // there is no more space in the buffer).
1160 EmbeddedVector<char, 100> buffer;
1161 OS::SNPrintF(buffer, "%.16g", Number());
1162 accumulator->Add("%s", buffer.start());
1163}
1164
1165
1166String* JSObject::class_name() {
1167 if (IsJSFunction()) {
1168 return Heap::function_class_symbol();
1169 }
1170 if (map()->constructor()->IsJSFunction()) {
1171 JSFunction* constructor = JSFunction::cast(map()->constructor());
1172 return String::cast(constructor->shared()->instance_class_name());
1173 }
1174 // If the constructor is not present, return "Object".
1175 return Heap::Object_symbol();
1176}
1177
1178
1179String* JSObject::constructor_name() {
Steve Blocka7e24c12009-10-30 11:49:00 +00001180 if (map()->constructor()->IsJSFunction()) {
1181 JSFunction* constructor = JSFunction::cast(map()->constructor());
1182 String* name = String::cast(constructor->shared()->name());
Ben Murdochf87a2032010-10-22 12:50:53 +01001183 if (name->length() > 0) return name;
1184 String* inferred_name = constructor->shared()->inferred_name();
1185 if (inferred_name->length() > 0) return inferred_name;
1186 Object* proto = GetPrototype();
1187 if (proto->IsJSObject()) return JSObject::cast(proto)->constructor_name();
Steve Blocka7e24c12009-10-30 11:49:00 +00001188 }
1189 // If the constructor is not present, return "Object".
1190 return Heap::Object_symbol();
1191}
1192
1193
John Reck59135872010-11-02 12:39:01 -07001194MaybeObject* JSObject::AddFastPropertyUsingMap(Map* new_map,
1195 String* name,
1196 Object* value) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001197 int index = new_map->PropertyIndexFor(name);
1198 if (map()->unused_property_fields() == 0) {
1199 ASSERT(map()->unused_property_fields() == 0);
1200 int new_unused = new_map->unused_property_fields();
John Reck59135872010-11-02 12:39:01 -07001201 Object* values;
1202 { MaybeObject* maybe_values =
1203 properties()->CopySize(properties()->length() + new_unused + 1);
1204 if (!maybe_values->ToObject(&values)) return maybe_values;
1205 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001206 set_properties(FixedArray::cast(values));
1207 }
1208 set_map(new_map);
1209 return FastPropertyAtPut(index, value);
1210}
1211
1212
John Reck59135872010-11-02 12:39:01 -07001213MaybeObject* JSObject::AddFastProperty(String* name,
1214 Object* value,
1215 PropertyAttributes attributes) {
Steve Block1e0659c2011-05-24 12:43:12 +01001216 ASSERT(!IsJSGlobalProxy());
1217
Steve Blocka7e24c12009-10-30 11:49:00 +00001218 // Normalize the object if the name is an actual string (not the
1219 // hidden symbols) and is not a real identifier.
1220 StringInputBuffer buffer(name);
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -08001221 if (!ScannerConstants::IsIdentifier(&buffer)
1222 && name != Heap::hidden_symbol()) {
John Reck59135872010-11-02 12:39:01 -07001223 Object* obj;
1224 { MaybeObject* maybe_obj =
1225 NormalizeProperties(CLEAR_INOBJECT_PROPERTIES, 0);
1226 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
1227 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001228 return AddSlowProperty(name, value, attributes);
1229 }
1230
1231 DescriptorArray* old_descriptors = map()->instance_descriptors();
1232 // Compute the new index for new field.
1233 int index = map()->NextFreePropertyIndex();
1234
1235 // Allocate new instance descriptors with (name, index) added
1236 FieldDescriptor new_field(name, index, attributes);
John Reck59135872010-11-02 12:39:01 -07001237 Object* new_descriptors;
1238 { MaybeObject* maybe_new_descriptors =
1239 old_descriptors->CopyInsert(&new_field, REMOVE_TRANSITIONS);
1240 if (!maybe_new_descriptors->ToObject(&new_descriptors)) {
1241 return maybe_new_descriptors;
1242 }
1243 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001244
1245 // Only allow map transition if the object's map is NOT equal to the
1246 // global object_function's map and there is not a transition for name.
1247 bool allow_map_transition =
1248 !old_descriptors->Contains(name) &&
1249 (Top::context()->global_context()->object_function()->map() != map());
1250
1251 ASSERT(index < map()->inobject_properties() ||
1252 (index - map()->inobject_properties()) < properties()->length() ||
1253 map()->unused_property_fields() == 0);
1254 // Allocate a new map for the object.
John Reck59135872010-11-02 12:39:01 -07001255 Object* r;
1256 { MaybeObject* maybe_r = map()->CopyDropDescriptors();
1257 if (!maybe_r->ToObject(&r)) return maybe_r;
1258 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001259 Map* new_map = Map::cast(r);
1260 if (allow_map_transition) {
1261 // Allocate new instance descriptors for the old map with map transition.
1262 MapTransitionDescriptor d(name, Map::cast(new_map), attributes);
John Reck59135872010-11-02 12:39:01 -07001263 Object* r;
1264 { MaybeObject* maybe_r = old_descriptors->CopyInsert(&d, KEEP_TRANSITIONS);
1265 if (!maybe_r->ToObject(&r)) return maybe_r;
1266 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001267 old_descriptors = DescriptorArray::cast(r);
1268 }
1269
1270 if (map()->unused_property_fields() == 0) {
Steve Block8defd9f2010-07-08 12:39:36 +01001271 if (properties()->length() > MaxFastProperties()) {
John Reck59135872010-11-02 12:39:01 -07001272 Object* obj;
1273 { MaybeObject* maybe_obj =
1274 NormalizeProperties(CLEAR_INOBJECT_PROPERTIES, 0);
1275 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
1276 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001277 return AddSlowProperty(name, value, attributes);
1278 }
1279 // Make room for the new value
John Reck59135872010-11-02 12:39:01 -07001280 Object* values;
1281 { MaybeObject* maybe_values =
1282 properties()->CopySize(properties()->length() + kFieldsAdded);
1283 if (!maybe_values->ToObject(&values)) return maybe_values;
1284 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001285 set_properties(FixedArray::cast(values));
1286 new_map->set_unused_property_fields(kFieldsAdded - 1);
1287 } else {
1288 new_map->set_unused_property_fields(map()->unused_property_fields() - 1);
1289 }
1290 // We have now allocated all the necessary objects.
1291 // All the changes can be applied at once, so they are atomic.
1292 map()->set_instance_descriptors(old_descriptors);
1293 new_map->set_instance_descriptors(DescriptorArray::cast(new_descriptors));
1294 set_map(new_map);
1295 return FastPropertyAtPut(index, value);
1296}
1297
1298
John Reck59135872010-11-02 12:39:01 -07001299MaybeObject* JSObject::AddConstantFunctionProperty(
1300 String* name,
1301 JSFunction* function,
1302 PropertyAttributes attributes) {
Leon Clarkee46be812010-01-19 14:06:41 +00001303 ASSERT(!Heap::InNewSpace(function));
1304
Steve Blocka7e24c12009-10-30 11:49:00 +00001305 // Allocate new instance descriptors with (name, function) added
1306 ConstantFunctionDescriptor d(name, function, attributes);
John Reck59135872010-11-02 12:39:01 -07001307 Object* new_descriptors;
1308 { MaybeObject* maybe_new_descriptors =
1309 map()->instance_descriptors()->CopyInsert(&d, REMOVE_TRANSITIONS);
1310 if (!maybe_new_descriptors->ToObject(&new_descriptors)) {
1311 return maybe_new_descriptors;
1312 }
1313 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001314
1315 // Allocate a new map for the object.
John Reck59135872010-11-02 12:39:01 -07001316 Object* new_map;
1317 { MaybeObject* maybe_new_map = map()->CopyDropDescriptors();
1318 if (!maybe_new_map->ToObject(&new_map)) return maybe_new_map;
1319 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001320
1321 DescriptorArray* descriptors = DescriptorArray::cast(new_descriptors);
1322 Map::cast(new_map)->set_instance_descriptors(descriptors);
1323 Map* old_map = map();
1324 set_map(Map::cast(new_map));
1325
1326 // If the old map is the global object map (from new Object()),
1327 // then transitions are not added to it, so we are done.
1328 if (old_map == Top::context()->global_context()->object_function()->map()) {
1329 return function;
1330 }
1331
1332 // Do not add CONSTANT_TRANSITIONS to global objects
1333 if (IsGlobalObject()) {
1334 return function;
1335 }
1336
1337 // Add a CONSTANT_TRANSITION descriptor to the old map,
1338 // so future assignments to this property on other objects
1339 // of the same type will create a normal field, not a constant function.
1340 // Don't do this for special properties, with non-trival attributes.
1341 if (attributes != NONE) {
1342 return function;
1343 }
Iain Merrick75681382010-08-19 15:07:18 +01001344 ConstTransitionDescriptor mark(name, Map::cast(new_map));
John Reck59135872010-11-02 12:39:01 -07001345 { MaybeObject* maybe_new_descriptors =
1346 old_map->instance_descriptors()->CopyInsert(&mark, KEEP_TRANSITIONS);
1347 if (!maybe_new_descriptors->ToObject(&new_descriptors)) {
1348 // We have accomplished the main goal, so return success.
1349 return function;
1350 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001351 }
1352 old_map->set_instance_descriptors(DescriptorArray::cast(new_descriptors));
1353
1354 return function;
1355}
1356
1357
1358// Add property in slow mode
John Reck59135872010-11-02 12:39:01 -07001359MaybeObject* JSObject::AddSlowProperty(String* name,
1360 Object* value,
1361 PropertyAttributes attributes) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001362 ASSERT(!HasFastProperties());
1363 StringDictionary* dict = property_dictionary();
1364 Object* store_value = value;
1365 if (IsGlobalObject()) {
1366 // In case name is an orphaned property reuse the cell.
1367 int entry = dict->FindEntry(name);
1368 if (entry != StringDictionary::kNotFound) {
1369 store_value = dict->ValueAt(entry);
1370 JSGlobalPropertyCell::cast(store_value)->set_value(value);
1371 // Assign an enumeration index to the property and update
1372 // SetNextEnumerationIndex.
1373 int index = dict->NextEnumerationIndex();
1374 PropertyDetails details = PropertyDetails(attributes, NORMAL, index);
1375 dict->SetNextEnumerationIndex(index + 1);
1376 dict->SetEntry(entry, name, store_value, details);
1377 return value;
1378 }
John Reck59135872010-11-02 12:39:01 -07001379 { MaybeObject* maybe_store_value =
1380 Heap::AllocateJSGlobalPropertyCell(value);
1381 if (!maybe_store_value->ToObject(&store_value)) return maybe_store_value;
1382 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001383 JSGlobalPropertyCell::cast(store_value)->set_value(value);
1384 }
1385 PropertyDetails details = PropertyDetails(attributes, NORMAL);
John Reck59135872010-11-02 12:39:01 -07001386 Object* result;
1387 { MaybeObject* maybe_result = dict->Add(name, store_value, details);
1388 if (!maybe_result->ToObject(&result)) return maybe_result;
1389 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001390 if (dict != result) set_properties(StringDictionary::cast(result));
1391 return value;
1392}
1393
1394
John Reck59135872010-11-02 12:39:01 -07001395MaybeObject* JSObject::AddProperty(String* name,
1396 Object* value,
1397 PropertyAttributes attributes) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001398 ASSERT(!IsJSGlobalProxy());
Steve Block8defd9f2010-07-08 12:39:36 +01001399 if (!map()->is_extensible()) {
1400 Handle<Object> args[1] = {Handle<String>(name)};
1401 return Top::Throw(*Factory::NewTypeError("object_not_extensible",
1402 HandleVector(args, 1)));
1403 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001404 if (HasFastProperties()) {
1405 // Ensure the descriptor array does not get too big.
1406 if (map()->instance_descriptors()->number_of_descriptors() <
1407 DescriptorArray::kMaxNumberOfDescriptors) {
Leon Clarkee46be812010-01-19 14:06:41 +00001408 if (value->IsJSFunction() && !Heap::InNewSpace(value)) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001409 return AddConstantFunctionProperty(name,
1410 JSFunction::cast(value),
1411 attributes);
1412 } else {
1413 return AddFastProperty(name, value, attributes);
1414 }
1415 } else {
1416 // Normalize the object to prevent very large instance descriptors.
1417 // This eliminates unwanted N^2 allocation and lookup behavior.
John Reck59135872010-11-02 12:39:01 -07001418 Object* obj;
1419 { MaybeObject* maybe_obj =
1420 NormalizeProperties(CLEAR_INOBJECT_PROPERTIES, 0);
1421 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
1422 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001423 }
1424 }
1425 return AddSlowProperty(name, value, attributes);
1426}
1427
1428
John Reck59135872010-11-02 12:39:01 -07001429MaybeObject* JSObject::SetPropertyPostInterceptor(
1430 String* name,
1431 Object* value,
1432 PropertyAttributes attributes) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001433 // Check local property, ignore interceptor.
1434 LookupResult result;
1435 LocalLookupRealNamedProperty(name, &result);
Andrei Popescu402d9372010-02-26 13:31:12 +00001436 if (result.IsFound()) {
1437 // An existing property, a map transition or a null descriptor was
1438 // found. Use set property to handle all these cases.
1439 return SetProperty(&result, name, value, attributes);
1440 }
1441 // Add a new real property.
Steve Blocka7e24c12009-10-30 11:49:00 +00001442 return AddProperty(name, value, attributes);
1443}
1444
1445
John Reck59135872010-11-02 12:39:01 -07001446MaybeObject* JSObject::ReplaceSlowProperty(String* name,
1447 Object* value,
1448 PropertyAttributes attributes) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001449 StringDictionary* dictionary = property_dictionary();
1450 int old_index = dictionary->FindEntry(name);
1451 int new_enumeration_index = 0; // 0 means "Use the next available index."
1452 if (old_index != -1) {
1453 // All calls to ReplaceSlowProperty have had all transitions removed.
1454 ASSERT(!dictionary->DetailsAt(old_index).IsTransition());
1455 new_enumeration_index = dictionary->DetailsAt(old_index).index();
1456 }
1457
1458 PropertyDetails new_details(attributes, NORMAL, new_enumeration_index);
1459 return SetNormalizedProperty(name, value, new_details);
1460}
1461
Steve Blockd0582a62009-12-15 09:54:21 +00001462
John Reck59135872010-11-02 12:39:01 -07001463MaybeObject* JSObject::ConvertDescriptorToFieldAndMapTransition(
Steve Blocka7e24c12009-10-30 11:49:00 +00001464 String* name,
1465 Object* new_value,
1466 PropertyAttributes attributes) {
1467 Map* old_map = map();
John Reck59135872010-11-02 12:39:01 -07001468 Object* result;
1469 { MaybeObject* maybe_result =
1470 ConvertDescriptorToField(name, new_value, attributes);
1471 if (!maybe_result->ToObject(&result)) return maybe_result;
1472 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001473 // If we get to this point we have succeeded - do not return failure
1474 // after this point. Later stuff is optional.
1475 if (!HasFastProperties()) {
1476 return result;
1477 }
1478 // Do not add transitions to the map of "new Object()".
1479 if (map() == Top::context()->global_context()->object_function()->map()) {
1480 return result;
1481 }
1482
1483 MapTransitionDescriptor transition(name,
1484 map(),
1485 attributes);
John Reck59135872010-11-02 12:39:01 -07001486 Object* new_descriptors;
1487 { MaybeObject* maybe_new_descriptors = old_map->instance_descriptors()->
1488 CopyInsert(&transition, KEEP_TRANSITIONS);
1489 if (!maybe_new_descriptors->ToObject(&new_descriptors)) {
1490 return result; // Yes, return _result_.
1491 }
1492 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001493 old_map->set_instance_descriptors(DescriptorArray::cast(new_descriptors));
1494 return result;
1495}
1496
1497
John Reck59135872010-11-02 12:39:01 -07001498MaybeObject* JSObject::ConvertDescriptorToField(String* name,
1499 Object* new_value,
1500 PropertyAttributes attributes) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001501 if (map()->unused_property_fields() == 0 &&
Steve Block8defd9f2010-07-08 12:39:36 +01001502 properties()->length() > MaxFastProperties()) {
John Reck59135872010-11-02 12:39:01 -07001503 Object* obj;
1504 { MaybeObject* maybe_obj =
1505 NormalizeProperties(CLEAR_INOBJECT_PROPERTIES, 0);
1506 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
1507 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001508 return ReplaceSlowProperty(name, new_value, attributes);
1509 }
1510
1511 int index = map()->NextFreePropertyIndex();
1512 FieldDescriptor new_field(name, index, attributes);
1513 // Make a new DescriptorArray replacing an entry with FieldDescriptor.
John Reck59135872010-11-02 12:39:01 -07001514 Object* descriptors_unchecked;
1515 { MaybeObject* maybe_descriptors_unchecked = map()->instance_descriptors()->
1516 CopyInsert(&new_field, REMOVE_TRANSITIONS);
1517 if (!maybe_descriptors_unchecked->ToObject(&descriptors_unchecked)) {
1518 return maybe_descriptors_unchecked;
1519 }
1520 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001521 DescriptorArray* new_descriptors =
1522 DescriptorArray::cast(descriptors_unchecked);
1523
1524 // Make a new map for the object.
John Reck59135872010-11-02 12:39:01 -07001525 Object* new_map_unchecked;
1526 { MaybeObject* maybe_new_map_unchecked = map()->CopyDropDescriptors();
1527 if (!maybe_new_map_unchecked->ToObject(&new_map_unchecked)) {
1528 return maybe_new_map_unchecked;
1529 }
1530 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001531 Map* new_map = Map::cast(new_map_unchecked);
1532 new_map->set_instance_descriptors(new_descriptors);
1533
1534 // Make new properties array if necessary.
1535 FixedArray* new_properties = 0; // Will always be NULL or a valid pointer.
1536 int new_unused_property_fields = map()->unused_property_fields() - 1;
1537 if (map()->unused_property_fields() == 0) {
Kristian Monsen0d5e1162010-09-30 15:31:59 +01001538 new_unused_property_fields = kFieldsAdded - 1;
John Reck59135872010-11-02 12:39:01 -07001539 Object* new_properties_object;
1540 { MaybeObject* maybe_new_properties_object =
1541 properties()->CopySize(properties()->length() + kFieldsAdded);
1542 if (!maybe_new_properties_object->ToObject(&new_properties_object)) {
1543 return maybe_new_properties_object;
1544 }
1545 }
1546 new_properties = FixedArray::cast(new_properties_object);
Steve Blocka7e24c12009-10-30 11:49:00 +00001547 }
1548
1549 // Update pointers to commit changes.
1550 // Object points to the new map.
1551 new_map->set_unused_property_fields(new_unused_property_fields);
1552 set_map(new_map);
1553 if (new_properties) {
1554 set_properties(FixedArray::cast(new_properties));
1555 }
1556 return FastPropertyAtPut(index, new_value);
1557}
1558
1559
1560
John Reck59135872010-11-02 12:39:01 -07001561MaybeObject* JSObject::SetPropertyWithInterceptor(
1562 String* name,
1563 Object* value,
1564 PropertyAttributes attributes) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001565 HandleScope scope;
1566 Handle<JSObject> this_handle(this);
1567 Handle<String> name_handle(name);
1568 Handle<Object> value_handle(value);
1569 Handle<InterceptorInfo> interceptor(GetNamedInterceptor());
1570 if (!interceptor->setter()->IsUndefined()) {
1571 LOG(ApiNamedPropertyAccess("interceptor-named-set", this, name));
1572 CustomArguments args(interceptor->data(), this, this);
1573 v8::AccessorInfo info(args.end());
1574 v8::NamedPropertySetter setter =
1575 v8::ToCData<v8::NamedPropertySetter>(interceptor->setter());
1576 v8::Handle<v8::Value> result;
1577 {
1578 // Leaving JavaScript.
1579 VMState state(EXTERNAL);
1580 Handle<Object> value_unhole(value->IsTheHole() ?
1581 Heap::undefined_value() :
1582 value);
1583 result = setter(v8::Utils::ToLocal(name_handle),
1584 v8::Utils::ToLocal(value_unhole),
1585 info);
1586 }
1587 RETURN_IF_SCHEDULED_EXCEPTION();
1588 if (!result.IsEmpty()) return *value_handle;
1589 }
John Reck59135872010-11-02 12:39:01 -07001590 MaybeObject* raw_result =
1591 this_handle->SetPropertyPostInterceptor(*name_handle,
1592 *value_handle,
1593 attributes);
Steve Blocka7e24c12009-10-30 11:49:00 +00001594 RETURN_IF_SCHEDULED_EXCEPTION();
1595 return raw_result;
1596}
1597
1598
John Reck59135872010-11-02 12:39:01 -07001599MaybeObject* JSObject::SetProperty(String* name,
1600 Object* value,
1601 PropertyAttributes attributes) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001602 LookupResult result;
1603 LocalLookup(name, &result);
1604 return SetProperty(&result, name, value, attributes);
1605}
1606
1607
John Reck59135872010-11-02 12:39:01 -07001608MaybeObject* JSObject::SetPropertyWithCallback(Object* structure,
1609 String* name,
1610 Object* value,
1611 JSObject* holder) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001612 HandleScope scope;
1613
1614 // We should never get here to initialize a const with the hole
1615 // value since a const declaration would conflict with the setter.
1616 ASSERT(!value->IsTheHole());
1617 Handle<Object> value_handle(value);
1618
1619 // To accommodate both the old and the new api we switch on the
1620 // data structure used to store the callbacks. Eventually proxy
1621 // callbacks should be phased out.
1622 if (structure->IsProxy()) {
1623 AccessorDescriptor* callback =
1624 reinterpret_cast<AccessorDescriptor*>(Proxy::cast(structure)->proxy());
John Reck59135872010-11-02 12:39:01 -07001625 MaybeObject* obj = (callback->setter)(this, value, callback->data);
Steve Blocka7e24c12009-10-30 11:49:00 +00001626 RETURN_IF_SCHEDULED_EXCEPTION();
1627 if (obj->IsFailure()) return obj;
1628 return *value_handle;
1629 }
1630
1631 if (structure->IsAccessorInfo()) {
1632 // api style callbacks
1633 AccessorInfo* data = AccessorInfo::cast(structure);
1634 Object* call_obj = data->setter();
1635 v8::AccessorSetter call_fun = v8::ToCData<v8::AccessorSetter>(call_obj);
1636 if (call_fun == NULL) return value;
1637 Handle<String> key(name);
1638 LOG(ApiNamedPropertyAccess("store", this, name));
1639 CustomArguments args(data->data(), this, JSObject::cast(holder));
1640 v8::AccessorInfo info(args.end());
1641 {
1642 // Leaving JavaScript.
1643 VMState state(EXTERNAL);
1644 call_fun(v8::Utils::ToLocal(key),
1645 v8::Utils::ToLocal(value_handle),
1646 info);
1647 }
1648 RETURN_IF_SCHEDULED_EXCEPTION();
1649 return *value_handle;
1650 }
1651
1652 if (structure->IsFixedArray()) {
1653 Object* setter = FixedArray::cast(structure)->get(kSetterIndex);
1654 if (setter->IsJSFunction()) {
1655 return SetPropertyWithDefinedSetter(JSFunction::cast(setter), value);
1656 } else {
1657 Handle<String> key(name);
1658 Handle<Object> holder_handle(holder);
1659 Handle<Object> args[2] = { key, holder_handle };
1660 return Top::Throw(*Factory::NewTypeError("no_setter_in_callback",
1661 HandleVector(args, 2)));
1662 }
1663 }
1664
1665 UNREACHABLE();
Leon Clarkef7060e22010-06-03 12:02:55 +01001666 return NULL;
Steve Blocka7e24c12009-10-30 11:49:00 +00001667}
1668
1669
John Reck59135872010-11-02 12:39:01 -07001670MaybeObject* JSObject::SetPropertyWithDefinedSetter(JSFunction* setter,
1671 Object* value) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001672 Handle<Object> value_handle(value);
1673 Handle<JSFunction> fun(JSFunction::cast(setter));
1674 Handle<JSObject> self(this);
1675#ifdef ENABLE_DEBUGGER_SUPPORT
1676 // Handle stepping into a setter if step into is active.
1677 if (Debug::StepInActive()) {
1678 Debug::HandleStepIn(fun, Handle<Object>::null(), 0, false);
1679 }
1680#endif
1681 bool has_pending_exception;
1682 Object** argv[] = { value_handle.location() };
1683 Execution::Call(fun, self, 1, argv, &has_pending_exception);
1684 // Check for pending exception and return the result.
1685 if (has_pending_exception) return Failure::Exception();
1686 return *value_handle;
1687}
1688
1689
1690void JSObject::LookupCallbackSetterInPrototypes(String* name,
1691 LookupResult* result) {
1692 for (Object* pt = GetPrototype();
1693 pt != Heap::null_value();
1694 pt = pt->GetPrototype()) {
1695 JSObject::cast(pt)->LocalLookupRealNamedProperty(name, result);
Andrei Popescu402d9372010-02-26 13:31:12 +00001696 if (result->IsProperty()) {
1697 if (result->IsReadOnly()) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001698 result->NotFound();
1699 return;
1700 }
1701 if (result->type() == CALLBACKS) {
1702 return;
1703 }
1704 }
1705 }
1706 result->NotFound();
1707}
1708
1709
Steve Block1e0659c2011-05-24 12:43:12 +01001710MaybeObject* JSObject::SetElementWithCallbackSetterInPrototypes(uint32_t index,
1711 Object* value,
1712 bool* found) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001713 for (Object* pt = GetPrototype();
1714 pt != Heap::null_value();
1715 pt = pt->GetPrototype()) {
1716 if (!JSObject::cast(pt)->HasDictionaryElements()) {
1717 continue;
1718 }
1719 NumberDictionary* dictionary = JSObject::cast(pt)->element_dictionary();
1720 int entry = dictionary->FindEntry(index);
1721 if (entry != NumberDictionary::kNotFound) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001722 PropertyDetails details = dictionary->DetailsAt(entry);
1723 if (details.type() == CALLBACKS) {
Steve Block1e0659c2011-05-24 12:43:12 +01001724 *found = true;
1725 return SetElementWithCallback(
1726 dictionary->ValueAt(entry), index, value, JSObject::cast(pt));
Steve Blocka7e24c12009-10-30 11:49:00 +00001727 }
1728 }
1729 }
Steve Block1e0659c2011-05-24 12:43:12 +01001730 *found = false;
1731 return Heap::the_hole_value();
Steve Blocka7e24c12009-10-30 11:49:00 +00001732}
1733
1734
1735void JSObject::LookupInDescriptor(String* name, LookupResult* result) {
1736 DescriptorArray* descriptors = map()->instance_descriptors();
Iain Merrick75681382010-08-19 15:07:18 +01001737 int number = descriptors->SearchWithCache(name);
Steve Blocka7e24c12009-10-30 11:49:00 +00001738 if (number != DescriptorArray::kNotFound) {
1739 result->DescriptorResult(this, descriptors->GetDetails(number), number);
1740 } else {
1741 result->NotFound();
1742 }
1743}
1744
1745
Ben Murdochb0fe1622011-05-05 13:52:32 +01001746void Map::LookupInDescriptors(JSObject* holder,
1747 String* name,
1748 LookupResult* result) {
1749 DescriptorArray* descriptors = instance_descriptors();
1750 int number = DescriptorLookupCache::Lookup(descriptors, name);
1751 if (number == DescriptorLookupCache::kAbsent) {
1752 number = descriptors->Search(name);
1753 DescriptorLookupCache::Update(descriptors, name, number);
1754 }
1755 if (number != DescriptorArray::kNotFound) {
1756 result->DescriptorResult(holder, descriptors->GetDetails(number), number);
1757 } else {
1758 result->NotFound();
1759 }
1760}
1761
1762
Steve Blocka7e24c12009-10-30 11:49:00 +00001763void JSObject::LocalLookupRealNamedProperty(String* name,
1764 LookupResult* result) {
1765 if (IsJSGlobalProxy()) {
1766 Object* proto = GetPrototype();
1767 if (proto->IsNull()) return result->NotFound();
1768 ASSERT(proto->IsJSGlobalObject());
1769 return JSObject::cast(proto)->LocalLookupRealNamedProperty(name, result);
1770 }
1771
1772 if (HasFastProperties()) {
1773 LookupInDescriptor(name, result);
Andrei Popescu402d9372010-02-26 13:31:12 +00001774 if (result->IsFound()) {
1775 // A property, a map transition or a null descriptor was found.
1776 // We return all of these result types because
1777 // LocalLookupRealNamedProperty is used when setting properties
1778 // where map transitions and null descriptors are handled.
Steve Blocka7e24c12009-10-30 11:49:00 +00001779 ASSERT(result->holder() == this && result->type() != NORMAL);
1780 // Disallow caching for uninitialized constants. These can only
1781 // occur as fields.
1782 if (result->IsReadOnly() && result->type() == FIELD &&
1783 FastPropertyAt(result->GetFieldIndex())->IsTheHole()) {
1784 result->DisallowCaching();
1785 }
1786 return;
1787 }
1788 } else {
1789 int entry = property_dictionary()->FindEntry(name);
1790 if (entry != StringDictionary::kNotFound) {
1791 Object* value = property_dictionary()->ValueAt(entry);
1792 if (IsGlobalObject()) {
1793 PropertyDetails d = property_dictionary()->DetailsAt(entry);
1794 if (d.IsDeleted()) {
1795 result->NotFound();
1796 return;
1797 }
1798 value = JSGlobalPropertyCell::cast(value)->value();
Steve Blocka7e24c12009-10-30 11:49:00 +00001799 }
1800 // Make sure to disallow caching for uninitialized constants
1801 // found in the dictionary-mode objects.
1802 if (value->IsTheHole()) result->DisallowCaching();
1803 result->DictionaryResult(this, entry);
1804 return;
1805 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001806 }
1807 result->NotFound();
1808}
1809
1810
1811void JSObject::LookupRealNamedProperty(String* name, LookupResult* result) {
1812 LocalLookupRealNamedProperty(name, result);
1813 if (result->IsProperty()) return;
1814
1815 LookupRealNamedPropertyInPrototypes(name, result);
1816}
1817
1818
1819void JSObject::LookupRealNamedPropertyInPrototypes(String* name,
1820 LookupResult* result) {
1821 for (Object* pt = GetPrototype();
1822 pt != Heap::null_value();
1823 pt = JSObject::cast(pt)->GetPrototype()) {
1824 JSObject::cast(pt)->LocalLookupRealNamedProperty(name, result);
Andrei Popescu402d9372010-02-26 13:31:12 +00001825 if (result->IsProperty() && (result->type() != INTERCEPTOR)) return;
Steve Blocka7e24c12009-10-30 11:49:00 +00001826 }
1827 result->NotFound();
1828}
1829
1830
1831// We only need to deal with CALLBACKS and INTERCEPTORS
John Reck59135872010-11-02 12:39:01 -07001832MaybeObject* JSObject::SetPropertyWithFailedAccessCheck(LookupResult* result,
1833 String* name,
Ben Murdoch086aeea2011-05-13 15:57:08 +01001834 Object* value,
1835 bool check_prototype) {
1836 if (check_prototype && !result->IsProperty()) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001837 LookupCallbackSetterInPrototypes(name, result);
1838 }
1839
1840 if (result->IsProperty()) {
1841 if (!result->IsReadOnly()) {
1842 switch (result->type()) {
1843 case CALLBACKS: {
1844 Object* obj = result->GetCallbackObject();
1845 if (obj->IsAccessorInfo()) {
1846 AccessorInfo* info = AccessorInfo::cast(obj);
1847 if (info->all_can_write()) {
1848 return SetPropertyWithCallback(result->GetCallbackObject(),
1849 name,
1850 value,
1851 result->holder());
1852 }
1853 }
1854 break;
1855 }
1856 case INTERCEPTOR: {
1857 // Try lookup real named properties. Note that only property can be
1858 // set is callbacks marked as ALL_CAN_WRITE on the prototype chain.
1859 LookupResult r;
1860 LookupRealNamedProperty(name, &r);
1861 if (r.IsProperty()) {
Ben Murdoch086aeea2011-05-13 15:57:08 +01001862 return SetPropertyWithFailedAccessCheck(&r, name, value,
1863 check_prototype);
Steve Blocka7e24c12009-10-30 11:49:00 +00001864 }
1865 break;
1866 }
1867 default: {
1868 break;
1869 }
1870 }
1871 }
1872 }
1873
Iain Merrick75681382010-08-19 15:07:18 +01001874 HandleScope scope;
1875 Handle<Object> value_handle(value);
Steve Blocka7e24c12009-10-30 11:49:00 +00001876 Top::ReportFailedAccessCheck(this, v8::ACCESS_SET);
Iain Merrick75681382010-08-19 15:07:18 +01001877 return *value_handle;
Steve Blocka7e24c12009-10-30 11:49:00 +00001878}
1879
1880
John Reck59135872010-11-02 12:39:01 -07001881MaybeObject* JSObject::SetProperty(LookupResult* result,
1882 String* name,
1883 Object* value,
1884 PropertyAttributes attributes) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001885 // Make sure that the top context does not change when doing callbacks or
1886 // interceptor calls.
1887 AssertNoContextChange ncc;
1888
Steve Blockd0582a62009-12-15 09:54:21 +00001889 // Optimization for 2-byte strings often used as keys in a decompression
1890 // dictionary. We make these short keys into symbols to avoid constantly
1891 // reallocating them.
1892 if (!name->IsSymbol() && name->length() <= 2) {
John Reck59135872010-11-02 12:39:01 -07001893 Object* symbol_version;
1894 { MaybeObject* maybe_symbol_version = Heap::LookupSymbol(name);
1895 if (maybe_symbol_version->ToObject(&symbol_version)) {
1896 name = String::cast(symbol_version);
1897 }
1898 }
Steve Blockd0582a62009-12-15 09:54:21 +00001899 }
1900
Steve Blocka7e24c12009-10-30 11:49:00 +00001901 // Check access rights if needed.
1902 if (IsAccessCheckNeeded()
1903 && !Top::MayNamedAccess(this, name, v8::ACCESS_SET)) {
Ben Murdoch086aeea2011-05-13 15:57:08 +01001904 return SetPropertyWithFailedAccessCheck(result, name, value, true);
Steve Blocka7e24c12009-10-30 11:49:00 +00001905 }
1906
1907 if (IsJSGlobalProxy()) {
1908 Object* proto = GetPrototype();
1909 if (proto->IsNull()) return value;
1910 ASSERT(proto->IsJSGlobalObject());
1911 return JSObject::cast(proto)->SetProperty(result, name, value, attributes);
1912 }
1913
1914 if (!result->IsProperty() && !IsJSContextExtensionObject()) {
1915 // We could not find a local property so let's check whether there is an
1916 // accessor that wants to handle the property.
1917 LookupResult accessor_result;
1918 LookupCallbackSetterInPrototypes(name, &accessor_result);
Andrei Popescu402d9372010-02-26 13:31:12 +00001919 if (accessor_result.IsProperty()) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001920 return SetPropertyWithCallback(accessor_result.GetCallbackObject(),
1921 name,
1922 value,
1923 accessor_result.holder());
1924 }
1925 }
Andrei Popescu402d9372010-02-26 13:31:12 +00001926 if (!result->IsFound()) {
1927 // Neither properties nor transitions found.
Steve Blocka7e24c12009-10-30 11:49:00 +00001928 return AddProperty(name, value, attributes);
1929 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001930 if (result->IsReadOnly() && result->IsProperty()) return value;
1931 // This is a real property that is not read-only, or it is a
1932 // transition or null descriptor and there are no setters in the prototypes.
1933 switch (result->type()) {
1934 case NORMAL:
1935 return SetNormalizedProperty(result, value);
1936 case FIELD:
1937 return FastPropertyAtPut(result->GetFieldIndex(), value);
1938 case MAP_TRANSITION:
1939 if (attributes == result->GetAttributes()) {
1940 // Only use map transition if the attributes match.
1941 return AddFastPropertyUsingMap(result->GetTransitionMap(),
1942 name,
1943 value);
1944 }
1945 return ConvertDescriptorToField(name, value, attributes);
1946 case CONSTANT_FUNCTION:
1947 // Only replace the function if necessary.
1948 if (value == result->GetConstantFunction()) return value;
1949 // Preserve the attributes of this existing property.
1950 attributes = result->GetAttributes();
1951 return ConvertDescriptorToField(name, value, attributes);
1952 case CALLBACKS:
1953 return SetPropertyWithCallback(result->GetCallbackObject(),
1954 name,
1955 value,
1956 result->holder());
1957 case INTERCEPTOR:
1958 return SetPropertyWithInterceptor(name, value, attributes);
Iain Merrick75681382010-08-19 15:07:18 +01001959 case CONSTANT_TRANSITION: {
1960 // If the same constant function is being added we can simply
1961 // transition to the target map.
1962 Map* target_map = result->GetTransitionMap();
1963 DescriptorArray* target_descriptors = target_map->instance_descriptors();
1964 int number = target_descriptors->SearchWithCache(name);
1965 ASSERT(number != DescriptorArray::kNotFound);
1966 ASSERT(target_descriptors->GetType(number) == CONSTANT_FUNCTION);
1967 JSFunction* function =
1968 JSFunction::cast(target_descriptors->GetValue(number));
1969 ASSERT(!Heap::InNewSpace(function));
1970 if (value == function) {
1971 set_map(target_map);
1972 return value;
1973 }
1974 // Otherwise, replace with a MAP_TRANSITION to a new map with a
1975 // FIELD, even if the value is a constant function.
Steve Blocka7e24c12009-10-30 11:49:00 +00001976 return ConvertDescriptorToFieldAndMapTransition(name, value, attributes);
Iain Merrick75681382010-08-19 15:07:18 +01001977 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001978 case NULL_DESCRIPTOR:
1979 return ConvertDescriptorToFieldAndMapTransition(name, value, attributes);
1980 default:
1981 UNREACHABLE();
1982 }
1983 UNREACHABLE();
1984 return value;
1985}
1986
1987
1988// Set a real local property, even if it is READ_ONLY. If the property is not
1989// present, add it with attributes NONE. This code is an exact clone of
1990// SetProperty, with the check for IsReadOnly and the check for a
1991// callback setter removed. The two lines looking up the LookupResult
1992// result are also added. If one of the functions is changed, the other
1993// should be.
Ben Murdoch086aeea2011-05-13 15:57:08 +01001994MaybeObject* JSObject::SetLocalPropertyIgnoreAttributes(
Steve Blocka7e24c12009-10-30 11:49:00 +00001995 String* name,
1996 Object* value,
1997 PropertyAttributes attributes) {
1998 // Make sure that the top context does not change when doing callbacks or
1999 // interceptor calls.
2000 AssertNoContextChange ncc;
Andrei Popescu402d9372010-02-26 13:31:12 +00002001 LookupResult result;
2002 LocalLookup(name, &result);
Steve Blocka7e24c12009-10-30 11:49:00 +00002003 // Check access rights if needed.
2004 if (IsAccessCheckNeeded()
Andrei Popescu402d9372010-02-26 13:31:12 +00002005 && !Top::MayNamedAccess(this, name, v8::ACCESS_SET)) {
Ben Murdoch086aeea2011-05-13 15:57:08 +01002006 return SetPropertyWithFailedAccessCheck(&result, name, value, false);
Steve Blocka7e24c12009-10-30 11:49:00 +00002007 }
2008
2009 if (IsJSGlobalProxy()) {
2010 Object* proto = GetPrototype();
2011 if (proto->IsNull()) return value;
2012 ASSERT(proto->IsJSGlobalObject());
Ben Murdoch086aeea2011-05-13 15:57:08 +01002013 return JSObject::cast(proto)->SetLocalPropertyIgnoreAttributes(
Steve Blocka7e24c12009-10-30 11:49:00 +00002014 name,
2015 value,
2016 attributes);
2017 }
2018
2019 // Check for accessor in prototype chain removed here in clone.
Andrei Popescu402d9372010-02-26 13:31:12 +00002020 if (!result.IsFound()) {
2021 // Neither properties nor transitions found.
Steve Blocka7e24c12009-10-30 11:49:00 +00002022 return AddProperty(name, value, attributes);
2023 }
Steve Block6ded16b2010-05-10 14:33:55 +01002024
Andrei Popescu402d9372010-02-26 13:31:12 +00002025 PropertyDetails details = PropertyDetails(attributes, NORMAL);
2026
Steve Blocka7e24c12009-10-30 11:49:00 +00002027 // Check of IsReadOnly removed from here in clone.
Andrei Popescu402d9372010-02-26 13:31:12 +00002028 switch (result.type()) {
Steve Blocka7e24c12009-10-30 11:49:00 +00002029 case NORMAL:
Andrei Popescu402d9372010-02-26 13:31:12 +00002030 return SetNormalizedProperty(name, value, details);
Steve Blocka7e24c12009-10-30 11:49:00 +00002031 case FIELD:
Andrei Popescu402d9372010-02-26 13:31:12 +00002032 return FastPropertyAtPut(result.GetFieldIndex(), value);
Steve Blocka7e24c12009-10-30 11:49:00 +00002033 case MAP_TRANSITION:
Andrei Popescu402d9372010-02-26 13:31:12 +00002034 if (attributes == result.GetAttributes()) {
Steve Blocka7e24c12009-10-30 11:49:00 +00002035 // Only use map transition if the attributes match.
Andrei Popescu402d9372010-02-26 13:31:12 +00002036 return AddFastPropertyUsingMap(result.GetTransitionMap(),
Steve Blocka7e24c12009-10-30 11:49:00 +00002037 name,
2038 value);
2039 }
2040 return ConvertDescriptorToField(name, value, attributes);
2041 case CONSTANT_FUNCTION:
2042 // Only replace the function if necessary.
Andrei Popescu402d9372010-02-26 13:31:12 +00002043 if (value == result.GetConstantFunction()) return value;
Steve Blocka7e24c12009-10-30 11:49:00 +00002044 // Preserve the attributes of this existing property.
Andrei Popescu402d9372010-02-26 13:31:12 +00002045 attributes = result.GetAttributes();
Steve Blocka7e24c12009-10-30 11:49:00 +00002046 return ConvertDescriptorToField(name, value, attributes);
2047 case CALLBACKS:
2048 case INTERCEPTOR:
2049 // Override callback in clone
2050 return ConvertDescriptorToField(name, value, attributes);
2051 case CONSTANT_TRANSITION:
2052 // Replace with a MAP_TRANSITION to a new map with a FIELD, even
2053 // if the value is a function.
2054 return ConvertDescriptorToFieldAndMapTransition(name, value, attributes);
2055 case NULL_DESCRIPTOR:
2056 return ConvertDescriptorToFieldAndMapTransition(name, value, attributes);
2057 default:
2058 UNREACHABLE();
2059 }
2060 UNREACHABLE();
2061 return value;
2062}
2063
2064
2065PropertyAttributes JSObject::GetPropertyAttributePostInterceptor(
2066 JSObject* receiver,
2067 String* name,
2068 bool continue_search) {
2069 // Check local property, ignore interceptor.
2070 LookupResult result;
2071 LocalLookupRealNamedProperty(name, &result);
2072 if (result.IsProperty()) return result.GetAttributes();
2073
2074 if (continue_search) {
2075 // Continue searching via the prototype chain.
2076 Object* pt = GetPrototype();
2077 if (pt != Heap::null_value()) {
2078 return JSObject::cast(pt)->
2079 GetPropertyAttributeWithReceiver(receiver, name);
2080 }
2081 }
2082 return ABSENT;
2083}
2084
2085
2086PropertyAttributes JSObject::GetPropertyAttributeWithInterceptor(
2087 JSObject* receiver,
2088 String* name,
2089 bool continue_search) {
2090 // Make sure that the top context does not change when doing
2091 // callbacks or interceptor calls.
2092 AssertNoContextChange ncc;
2093
2094 HandleScope scope;
2095 Handle<InterceptorInfo> interceptor(GetNamedInterceptor());
2096 Handle<JSObject> receiver_handle(receiver);
2097 Handle<JSObject> holder_handle(this);
2098 Handle<String> name_handle(name);
2099 CustomArguments args(interceptor->data(), receiver, this);
2100 v8::AccessorInfo info(args.end());
2101 if (!interceptor->query()->IsUndefined()) {
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01002102 v8::NamedPropertyQuery query =
2103 v8::ToCData<v8::NamedPropertyQuery>(interceptor->query());
Steve Blocka7e24c12009-10-30 11:49:00 +00002104 LOG(ApiNamedPropertyAccess("interceptor-named-has", *holder_handle, name));
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01002105 v8::Handle<v8::Integer> result;
Steve Blocka7e24c12009-10-30 11:49:00 +00002106 {
2107 // Leaving JavaScript.
2108 VMState state(EXTERNAL);
2109 result = query(v8::Utils::ToLocal(name_handle), info);
2110 }
2111 if (!result.IsEmpty()) {
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01002112 ASSERT(result->IsInt32());
2113 return static_cast<PropertyAttributes>(result->Int32Value());
Steve Blocka7e24c12009-10-30 11:49:00 +00002114 }
2115 } else if (!interceptor->getter()->IsUndefined()) {
2116 v8::NamedPropertyGetter getter =
2117 v8::ToCData<v8::NamedPropertyGetter>(interceptor->getter());
2118 LOG(ApiNamedPropertyAccess("interceptor-named-get-has", this, name));
2119 v8::Handle<v8::Value> result;
2120 {
2121 // Leaving JavaScript.
2122 VMState state(EXTERNAL);
2123 result = getter(v8::Utils::ToLocal(name_handle), info);
2124 }
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01002125 if (!result.IsEmpty()) return DONT_ENUM;
Steve Blocka7e24c12009-10-30 11:49:00 +00002126 }
2127 return holder_handle->GetPropertyAttributePostInterceptor(*receiver_handle,
2128 *name_handle,
2129 continue_search);
2130}
2131
2132
2133PropertyAttributes JSObject::GetPropertyAttributeWithReceiver(
2134 JSObject* receiver,
2135 String* key) {
2136 uint32_t index = 0;
2137 if (key->AsArrayIndex(&index)) {
2138 if (HasElementWithReceiver(receiver, index)) return NONE;
2139 return ABSENT;
2140 }
2141 // Named property.
2142 LookupResult result;
2143 Lookup(key, &result);
2144 return GetPropertyAttribute(receiver, &result, key, true);
2145}
2146
2147
2148PropertyAttributes JSObject::GetPropertyAttribute(JSObject* receiver,
2149 LookupResult* result,
2150 String* name,
2151 bool continue_search) {
2152 // Check access rights if needed.
2153 if (IsAccessCheckNeeded() &&
2154 !Top::MayNamedAccess(this, name, v8::ACCESS_HAS)) {
2155 return GetPropertyAttributeWithFailedAccessCheck(receiver,
2156 result,
2157 name,
2158 continue_search);
2159 }
Andrei Popescu402d9372010-02-26 13:31:12 +00002160 if (result->IsProperty()) {
Steve Blocka7e24c12009-10-30 11:49:00 +00002161 switch (result->type()) {
2162 case NORMAL: // fall through
2163 case FIELD:
2164 case CONSTANT_FUNCTION:
2165 case CALLBACKS:
2166 return result->GetAttributes();
2167 case INTERCEPTOR:
2168 return result->holder()->
2169 GetPropertyAttributeWithInterceptor(receiver, name, continue_search);
Steve Blocka7e24c12009-10-30 11:49:00 +00002170 default:
2171 UNREACHABLE();
Steve Blocka7e24c12009-10-30 11:49:00 +00002172 }
2173 }
2174 return ABSENT;
2175}
2176
2177
2178PropertyAttributes JSObject::GetLocalPropertyAttribute(String* name) {
2179 // Check whether the name is an array index.
2180 uint32_t index = 0;
2181 if (name->AsArrayIndex(&index)) {
2182 if (HasLocalElement(index)) return NONE;
2183 return ABSENT;
2184 }
2185 // Named property.
2186 LookupResult result;
2187 LocalLookup(name, &result);
2188 return GetPropertyAttribute(this, &result, name, false);
2189}
2190
2191
John Reck59135872010-11-02 12:39:01 -07002192MaybeObject* NormalizedMapCache::Get(JSObject* obj,
2193 PropertyNormalizationMode mode) {
Kristian Monsen80d68ea2010-09-08 11:05:35 +01002194 Map* fast = obj->map();
Kristian Monsen0d5e1162010-09-30 15:31:59 +01002195 int index = Hash(fast) % kEntries;
2196 Object* result = get(index);
2197 if (result->IsMap() && CheckHit(Map::cast(result), fast, mode)) {
Kristian Monsen80d68ea2010-09-08 11:05:35 +01002198#ifdef DEBUG
Kristian Monsen0d5e1162010-09-30 15:31:59 +01002199 if (FLAG_enable_slow_asserts) {
2200 // The cached map should match newly created normalized map bit-by-bit.
John Reck59135872010-11-02 12:39:01 -07002201 Object* fresh;
2202 { MaybeObject* maybe_fresh =
2203 fast->CopyNormalized(mode, SHARED_NORMALIZED_MAP);
2204 if (maybe_fresh->ToObject(&fresh)) {
2205 ASSERT(memcmp(Map::cast(fresh)->address(),
2206 Map::cast(result)->address(),
2207 Map::kSize) == 0);
2208 }
Kristian Monsen80d68ea2010-09-08 11:05:35 +01002209 }
Kristian Monsen80d68ea2010-09-08 11:05:35 +01002210 }
Kristian Monsen0d5e1162010-09-30 15:31:59 +01002211#endif
2212 return result;
Kristian Monsen80d68ea2010-09-08 11:05:35 +01002213 }
Kristian Monsen0d5e1162010-09-30 15:31:59 +01002214
John Reck59135872010-11-02 12:39:01 -07002215 { MaybeObject* maybe_result =
2216 fast->CopyNormalized(mode, SHARED_NORMALIZED_MAP);
2217 if (!maybe_result->ToObject(&result)) return maybe_result;
2218 }
Kristian Monsen0d5e1162010-09-30 15:31:59 +01002219 set(index, result);
Kristian Monsen80d68ea2010-09-08 11:05:35 +01002220 Counters::normalized_maps.Increment();
2221
2222 return result;
2223}
2224
2225
Kristian Monsen80d68ea2010-09-08 11:05:35 +01002226void NormalizedMapCache::Clear() {
2227 int entries = length();
2228 for (int i = 0; i != entries; i++) {
2229 set_undefined(i);
2230 }
2231}
2232
2233
2234int NormalizedMapCache::Hash(Map* fast) {
2235 // For performance reasons we only hash the 3 most variable fields of a map:
2236 // constructor, prototype and bit_field2.
2237
2238 // Shift away the tag.
2239 int hash = (static_cast<uint32_t>(
2240 reinterpret_cast<uintptr_t>(fast->constructor())) >> 2);
2241
2242 // XOR-ing the prototype and constructor directly yields too many zero bits
2243 // when the two pointers are close (which is fairly common).
2244 // To avoid this we shift the prototype 4 bits relatively to the constructor.
2245 hash ^= (static_cast<uint32_t>(
2246 reinterpret_cast<uintptr_t>(fast->prototype())) << 2);
2247
2248 return hash ^ (hash >> 16) ^ fast->bit_field2();
2249}
2250
2251
2252bool NormalizedMapCache::CheckHit(Map* slow,
2253 Map* fast,
2254 PropertyNormalizationMode mode) {
2255#ifdef DEBUG
Kristian Monsen0d5e1162010-09-30 15:31:59 +01002256 slow->SharedMapVerify();
Kristian Monsen80d68ea2010-09-08 11:05:35 +01002257#endif
2258 return
2259 slow->constructor() == fast->constructor() &&
2260 slow->prototype() == fast->prototype() &&
2261 slow->inobject_properties() == ((mode == CLEAR_INOBJECT_PROPERTIES) ?
2262 0 :
2263 fast->inobject_properties()) &&
2264 slow->instance_type() == fast->instance_type() &&
2265 slow->bit_field() == fast->bit_field() &&
Kristian Monsen0d5e1162010-09-30 15:31:59 +01002266 (slow->bit_field2() & ~(1<<Map::kIsShared)) == fast->bit_field2();
Kristian Monsen80d68ea2010-09-08 11:05:35 +01002267}
2268
2269
John Reck59135872010-11-02 12:39:01 -07002270MaybeObject* JSObject::UpdateMapCodeCache(String* name, Code* code) {
Kristian Monsen0d5e1162010-09-30 15:31:59 +01002271 if (map()->is_shared()) {
2272 // Fast case maps are never marked as shared.
2273 ASSERT(!HasFastProperties());
2274 // Replace the map with an identical copy that can be safely modified.
John Reck59135872010-11-02 12:39:01 -07002275 Object* obj;
2276 { MaybeObject* maybe_obj = map()->CopyNormalized(KEEP_INOBJECT_PROPERTIES,
2277 UNIQUE_NORMALIZED_MAP);
2278 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
2279 }
Kristian Monsen80d68ea2010-09-08 11:05:35 +01002280 Counters::normalized_maps.Increment();
2281
2282 set_map(Map::cast(obj));
2283 }
2284 return map()->UpdateCodeCache(name, code);
2285}
2286
2287
John Reck59135872010-11-02 12:39:01 -07002288MaybeObject* JSObject::NormalizeProperties(PropertyNormalizationMode mode,
2289 int expected_additional_properties) {
Steve Blocka7e24c12009-10-30 11:49:00 +00002290 if (!HasFastProperties()) return this;
2291
2292 // The global object is always normalized.
2293 ASSERT(!IsGlobalObject());
2294
Steve Block1e0659c2011-05-24 12:43:12 +01002295 // JSGlobalProxy must never be normalized
2296 ASSERT(!IsJSGlobalProxy());
2297
Steve Blocka7e24c12009-10-30 11:49:00 +00002298 // Allocate new content.
2299 int property_count = map()->NumberOfDescribedProperties();
2300 if (expected_additional_properties > 0) {
2301 property_count += expected_additional_properties;
2302 } else {
2303 property_count += 2; // Make space for two more properties.
2304 }
John Reck59135872010-11-02 12:39:01 -07002305 Object* obj;
2306 { MaybeObject* maybe_obj =
2307 StringDictionary::Allocate(property_count);
2308 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
2309 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002310 StringDictionary* dictionary = StringDictionary::cast(obj);
2311
2312 DescriptorArray* descs = map()->instance_descriptors();
2313 for (int i = 0; i < descs->number_of_descriptors(); i++) {
2314 PropertyDetails details = descs->GetDetails(i);
2315 switch (details.type()) {
2316 case CONSTANT_FUNCTION: {
2317 PropertyDetails d =
2318 PropertyDetails(details.attributes(), NORMAL, details.index());
2319 Object* value = descs->GetConstantFunction(i);
John Reck59135872010-11-02 12:39:01 -07002320 Object* result;
2321 { MaybeObject* maybe_result =
2322 dictionary->Add(descs->GetKey(i), value, d);
2323 if (!maybe_result->ToObject(&result)) return maybe_result;
2324 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002325 dictionary = StringDictionary::cast(result);
2326 break;
2327 }
2328 case FIELD: {
2329 PropertyDetails d =
2330 PropertyDetails(details.attributes(), NORMAL, details.index());
2331 Object* value = FastPropertyAt(descs->GetFieldIndex(i));
John Reck59135872010-11-02 12:39:01 -07002332 Object* result;
2333 { MaybeObject* maybe_result =
2334 dictionary->Add(descs->GetKey(i), value, d);
2335 if (!maybe_result->ToObject(&result)) return maybe_result;
2336 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002337 dictionary = StringDictionary::cast(result);
2338 break;
2339 }
2340 case CALLBACKS: {
2341 PropertyDetails d =
2342 PropertyDetails(details.attributes(), CALLBACKS, details.index());
2343 Object* value = descs->GetCallbacksObject(i);
John Reck59135872010-11-02 12:39:01 -07002344 Object* result;
2345 { MaybeObject* maybe_result =
2346 dictionary->Add(descs->GetKey(i), value, d);
2347 if (!maybe_result->ToObject(&result)) return maybe_result;
2348 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002349 dictionary = StringDictionary::cast(result);
2350 break;
2351 }
2352 case MAP_TRANSITION:
2353 case CONSTANT_TRANSITION:
2354 case NULL_DESCRIPTOR:
2355 case INTERCEPTOR:
2356 break;
2357 default:
2358 UNREACHABLE();
2359 }
2360 }
2361
2362 // Copy the next enumeration index from instance descriptor.
2363 int index = map()->instance_descriptors()->NextEnumerationIndex();
2364 dictionary->SetNextEnumerationIndex(index);
2365
John Reck59135872010-11-02 12:39:01 -07002366 { MaybeObject* maybe_obj = Top::context()->global_context()->
2367 normalized_map_cache()->Get(this, mode);
2368 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
2369 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002370 Map* new_map = Map::cast(obj);
2371
Steve Blocka7e24c12009-10-30 11:49:00 +00002372 // We have now successfully allocated all the necessary objects.
2373 // Changes can now be made with the guarantee that all of them take effect.
Kristian Monsen80d68ea2010-09-08 11:05:35 +01002374
2375 // Resize the object in the heap if necessary.
2376 int new_instance_size = new_map->instance_size();
2377 int instance_size_delta = map()->instance_size() - new_instance_size;
2378 ASSERT(instance_size_delta >= 0);
2379 Heap::CreateFillerObjectAt(this->address() + new_instance_size,
2380 instance_size_delta);
2381
Steve Blocka7e24c12009-10-30 11:49:00 +00002382 set_map(new_map);
Steve Blocka7e24c12009-10-30 11:49:00 +00002383
2384 set_properties(dictionary);
2385
2386 Counters::props_to_dictionary.Increment();
2387
2388#ifdef DEBUG
2389 if (FLAG_trace_normalization) {
2390 PrintF("Object properties have been normalized:\n");
2391 Print();
2392 }
2393#endif
2394 return this;
2395}
2396
2397
John Reck59135872010-11-02 12:39:01 -07002398MaybeObject* JSObject::TransformToFastProperties(int unused_property_fields) {
Steve Blocka7e24c12009-10-30 11:49:00 +00002399 if (HasFastProperties()) return this;
2400 ASSERT(!IsGlobalObject());
2401 return property_dictionary()->
2402 TransformPropertiesToFastFor(this, unused_property_fields);
2403}
2404
2405
John Reck59135872010-11-02 12:39:01 -07002406MaybeObject* JSObject::NormalizeElements() {
Steve Block3ce2e202009-11-05 08:53:23 +00002407 ASSERT(!HasPixelElements() && !HasExternalArrayElements());
Steve Blocka7e24c12009-10-30 11:49:00 +00002408 if (HasDictionaryElements()) return this;
Steve Block8defd9f2010-07-08 12:39:36 +01002409 ASSERT(map()->has_fast_elements());
2410
John Reck59135872010-11-02 12:39:01 -07002411 Object* obj;
2412 { MaybeObject* maybe_obj = map()->GetSlowElementsMap();
2413 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
2414 }
Steve Block8defd9f2010-07-08 12:39:36 +01002415 Map* new_map = Map::cast(obj);
Steve Blocka7e24c12009-10-30 11:49:00 +00002416
2417 // Get number of entries.
2418 FixedArray* array = FixedArray::cast(elements());
2419
2420 // Compute the effective length.
2421 int length = IsJSArray() ?
2422 Smi::cast(JSArray::cast(this)->length())->value() :
2423 array->length();
John Reck59135872010-11-02 12:39:01 -07002424 { MaybeObject* maybe_obj = NumberDictionary::Allocate(length);
2425 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
2426 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002427 NumberDictionary* dictionary = NumberDictionary::cast(obj);
2428 // Copy entries.
2429 for (int i = 0; i < length; i++) {
2430 Object* value = array->get(i);
2431 if (!value->IsTheHole()) {
2432 PropertyDetails details = PropertyDetails(NONE, NORMAL);
John Reck59135872010-11-02 12:39:01 -07002433 Object* result;
2434 { MaybeObject* maybe_result =
2435 dictionary->AddNumberEntry(i, array->get(i), details);
2436 if (!maybe_result->ToObject(&result)) return maybe_result;
2437 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002438 dictionary = NumberDictionary::cast(result);
2439 }
2440 }
Steve Block8defd9f2010-07-08 12:39:36 +01002441 // Switch to using the dictionary as the backing storage for
2442 // elements. Set the new map first to satify the elements type
2443 // assert in set_elements().
2444 set_map(new_map);
Steve Blocka7e24c12009-10-30 11:49:00 +00002445 set_elements(dictionary);
2446
2447 Counters::elements_to_dictionary.Increment();
2448
2449#ifdef DEBUG
2450 if (FLAG_trace_normalization) {
2451 PrintF("Object elements have been normalized:\n");
2452 Print();
2453 }
2454#endif
2455
2456 return this;
2457}
2458
2459
John Reck59135872010-11-02 12:39:01 -07002460MaybeObject* JSObject::DeletePropertyPostInterceptor(String* name,
2461 DeleteMode mode) {
Steve Blocka7e24c12009-10-30 11:49:00 +00002462 // Check local property, ignore interceptor.
2463 LookupResult result;
2464 LocalLookupRealNamedProperty(name, &result);
Andrei Popescu402d9372010-02-26 13:31:12 +00002465 if (!result.IsProperty()) return Heap::true_value();
Steve Blocka7e24c12009-10-30 11:49:00 +00002466
2467 // Normalize object if needed.
John Reck59135872010-11-02 12:39:01 -07002468 Object* obj;
2469 { MaybeObject* maybe_obj = NormalizeProperties(CLEAR_INOBJECT_PROPERTIES, 0);
2470 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
2471 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002472
2473 return DeleteNormalizedProperty(name, mode);
2474}
2475
2476
John Reck59135872010-11-02 12:39:01 -07002477MaybeObject* JSObject::DeletePropertyWithInterceptor(String* name) {
Steve Blocka7e24c12009-10-30 11:49:00 +00002478 HandleScope scope;
2479 Handle<InterceptorInfo> interceptor(GetNamedInterceptor());
2480 Handle<String> name_handle(name);
2481 Handle<JSObject> this_handle(this);
2482 if (!interceptor->deleter()->IsUndefined()) {
2483 v8::NamedPropertyDeleter deleter =
2484 v8::ToCData<v8::NamedPropertyDeleter>(interceptor->deleter());
2485 LOG(ApiNamedPropertyAccess("interceptor-named-delete", *this_handle, name));
2486 CustomArguments args(interceptor->data(), this, this);
2487 v8::AccessorInfo info(args.end());
2488 v8::Handle<v8::Boolean> result;
2489 {
2490 // Leaving JavaScript.
2491 VMState state(EXTERNAL);
2492 result = deleter(v8::Utils::ToLocal(name_handle), info);
2493 }
2494 RETURN_IF_SCHEDULED_EXCEPTION();
2495 if (!result.IsEmpty()) {
2496 ASSERT(result->IsBoolean());
2497 return *v8::Utils::OpenHandle(*result);
2498 }
2499 }
John Reck59135872010-11-02 12:39:01 -07002500 MaybeObject* raw_result =
Steve Blocka7e24c12009-10-30 11:49:00 +00002501 this_handle->DeletePropertyPostInterceptor(*name_handle, NORMAL_DELETION);
2502 RETURN_IF_SCHEDULED_EXCEPTION();
2503 return raw_result;
2504}
2505
2506
John Reck59135872010-11-02 12:39:01 -07002507MaybeObject* JSObject::DeleteElementPostInterceptor(uint32_t index,
2508 DeleteMode mode) {
Steve Block3ce2e202009-11-05 08:53:23 +00002509 ASSERT(!HasPixelElements() && !HasExternalArrayElements());
Steve Blocka7e24c12009-10-30 11:49:00 +00002510 switch (GetElementsKind()) {
2511 case FAST_ELEMENTS: {
John Reck59135872010-11-02 12:39:01 -07002512 Object* obj;
2513 { MaybeObject* maybe_obj = EnsureWritableFastElements();
2514 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
2515 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002516 uint32_t length = IsJSArray() ?
2517 static_cast<uint32_t>(Smi::cast(JSArray::cast(this)->length())->value()) :
2518 static_cast<uint32_t>(FixedArray::cast(elements())->length());
2519 if (index < length) {
2520 FixedArray::cast(elements())->set_the_hole(index);
2521 }
2522 break;
2523 }
2524 case DICTIONARY_ELEMENTS: {
2525 NumberDictionary* dictionary = element_dictionary();
2526 int entry = dictionary->FindEntry(index);
2527 if (entry != NumberDictionary::kNotFound) {
2528 return dictionary->DeleteProperty(entry, mode);
2529 }
2530 break;
2531 }
2532 default:
2533 UNREACHABLE();
2534 break;
2535 }
2536 return Heap::true_value();
2537}
2538
2539
John Reck59135872010-11-02 12:39:01 -07002540MaybeObject* JSObject::DeleteElementWithInterceptor(uint32_t index) {
Steve Blocka7e24c12009-10-30 11:49:00 +00002541 // Make sure that the top context does not change when doing
2542 // callbacks or interceptor calls.
2543 AssertNoContextChange ncc;
2544 HandleScope scope;
2545 Handle<InterceptorInfo> interceptor(GetIndexedInterceptor());
2546 if (interceptor->deleter()->IsUndefined()) return Heap::false_value();
2547 v8::IndexedPropertyDeleter deleter =
2548 v8::ToCData<v8::IndexedPropertyDeleter>(interceptor->deleter());
2549 Handle<JSObject> this_handle(this);
2550 LOG(ApiIndexedPropertyAccess("interceptor-indexed-delete", this, index));
2551 CustomArguments args(interceptor->data(), this, this);
2552 v8::AccessorInfo info(args.end());
2553 v8::Handle<v8::Boolean> result;
2554 {
2555 // Leaving JavaScript.
2556 VMState state(EXTERNAL);
2557 result = deleter(index, info);
2558 }
2559 RETURN_IF_SCHEDULED_EXCEPTION();
2560 if (!result.IsEmpty()) {
2561 ASSERT(result->IsBoolean());
2562 return *v8::Utils::OpenHandle(*result);
2563 }
John Reck59135872010-11-02 12:39:01 -07002564 MaybeObject* raw_result =
Steve Blocka7e24c12009-10-30 11:49:00 +00002565 this_handle->DeleteElementPostInterceptor(index, NORMAL_DELETION);
2566 RETURN_IF_SCHEDULED_EXCEPTION();
2567 return raw_result;
2568}
2569
2570
John Reck59135872010-11-02 12:39:01 -07002571MaybeObject* JSObject::DeleteElement(uint32_t index, DeleteMode mode) {
Steve Blocka7e24c12009-10-30 11:49:00 +00002572 // Check access rights if needed.
2573 if (IsAccessCheckNeeded() &&
2574 !Top::MayIndexedAccess(this, index, v8::ACCESS_DELETE)) {
2575 Top::ReportFailedAccessCheck(this, v8::ACCESS_DELETE);
2576 return Heap::false_value();
2577 }
2578
2579 if (IsJSGlobalProxy()) {
2580 Object* proto = GetPrototype();
2581 if (proto->IsNull()) return Heap::false_value();
2582 ASSERT(proto->IsJSGlobalObject());
2583 return JSGlobalObject::cast(proto)->DeleteElement(index, mode);
2584 }
2585
2586 if (HasIndexedInterceptor()) {
2587 // Skip interceptor if forcing deletion.
2588 if (mode == FORCE_DELETION) {
2589 return DeleteElementPostInterceptor(index, mode);
2590 }
2591 return DeleteElementWithInterceptor(index);
2592 }
2593
2594 switch (GetElementsKind()) {
2595 case FAST_ELEMENTS: {
John Reck59135872010-11-02 12:39:01 -07002596 Object* obj;
2597 { MaybeObject* maybe_obj = EnsureWritableFastElements();
2598 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
2599 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002600 uint32_t length = IsJSArray() ?
2601 static_cast<uint32_t>(Smi::cast(JSArray::cast(this)->length())->value()) :
2602 static_cast<uint32_t>(FixedArray::cast(elements())->length());
2603 if (index < length) {
2604 FixedArray::cast(elements())->set_the_hole(index);
2605 }
2606 break;
2607 }
Steve Block3ce2e202009-11-05 08:53:23 +00002608 case PIXEL_ELEMENTS:
2609 case EXTERNAL_BYTE_ELEMENTS:
2610 case EXTERNAL_UNSIGNED_BYTE_ELEMENTS:
2611 case EXTERNAL_SHORT_ELEMENTS:
2612 case EXTERNAL_UNSIGNED_SHORT_ELEMENTS:
2613 case EXTERNAL_INT_ELEMENTS:
2614 case EXTERNAL_UNSIGNED_INT_ELEMENTS:
2615 case EXTERNAL_FLOAT_ELEMENTS:
2616 // Pixel and external array elements cannot be deleted. Just
2617 // silently ignore here.
Steve Blocka7e24c12009-10-30 11:49:00 +00002618 break;
Steve Blocka7e24c12009-10-30 11:49:00 +00002619 case DICTIONARY_ELEMENTS: {
2620 NumberDictionary* dictionary = element_dictionary();
2621 int entry = dictionary->FindEntry(index);
2622 if (entry != NumberDictionary::kNotFound) {
2623 return dictionary->DeleteProperty(entry, mode);
2624 }
2625 break;
2626 }
2627 default:
2628 UNREACHABLE();
2629 break;
2630 }
2631 return Heap::true_value();
2632}
2633
2634
John Reck59135872010-11-02 12:39:01 -07002635MaybeObject* JSObject::DeleteProperty(String* name, DeleteMode mode) {
Steve Blocka7e24c12009-10-30 11:49:00 +00002636 // ECMA-262, 3rd, 8.6.2.5
2637 ASSERT(name->IsString());
2638
2639 // Check access rights if needed.
2640 if (IsAccessCheckNeeded() &&
2641 !Top::MayNamedAccess(this, name, v8::ACCESS_DELETE)) {
2642 Top::ReportFailedAccessCheck(this, v8::ACCESS_DELETE);
2643 return Heap::false_value();
2644 }
2645
2646 if (IsJSGlobalProxy()) {
2647 Object* proto = GetPrototype();
2648 if (proto->IsNull()) return Heap::false_value();
2649 ASSERT(proto->IsJSGlobalObject());
2650 return JSGlobalObject::cast(proto)->DeleteProperty(name, mode);
2651 }
2652
2653 uint32_t index = 0;
2654 if (name->AsArrayIndex(&index)) {
2655 return DeleteElement(index, mode);
2656 } else {
2657 LookupResult result;
2658 LocalLookup(name, &result);
Andrei Popescu402d9372010-02-26 13:31:12 +00002659 if (!result.IsProperty()) return Heap::true_value();
Steve Blocka7e24c12009-10-30 11:49:00 +00002660 // Ignore attributes if forcing a deletion.
2661 if (result.IsDontDelete() && mode != FORCE_DELETION) {
2662 return Heap::false_value();
2663 }
2664 // Check for interceptor.
2665 if (result.type() == INTERCEPTOR) {
2666 // Skip interceptor if forcing a deletion.
2667 if (mode == FORCE_DELETION) {
2668 return DeletePropertyPostInterceptor(name, mode);
2669 }
2670 return DeletePropertyWithInterceptor(name);
2671 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002672 // Normalize object if needed.
John Reck59135872010-11-02 12:39:01 -07002673 Object* obj;
2674 { MaybeObject* maybe_obj =
2675 NormalizeProperties(CLEAR_INOBJECT_PROPERTIES, 0);
2676 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
2677 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002678 // Make sure the properties are normalized before removing the entry.
2679 return DeleteNormalizedProperty(name, mode);
2680 }
2681}
2682
2683
2684// Check whether this object references another object.
2685bool JSObject::ReferencesObject(Object* obj) {
2686 AssertNoAllocation no_alloc;
2687
2688 // Is the object the constructor for this object?
2689 if (map()->constructor() == obj) {
2690 return true;
2691 }
2692
2693 // Is the object the prototype for this object?
2694 if (map()->prototype() == obj) {
2695 return true;
2696 }
2697
2698 // Check if the object is among the named properties.
2699 Object* key = SlowReverseLookup(obj);
2700 if (key != Heap::undefined_value()) {
2701 return true;
2702 }
2703
2704 // Check if the object is among the indexed properties.
2705 switch (GetElementsKind()) {
2706 case PIXEL_ELEMENTS:
Steve Block3ce2e202009-11-05 08:53:23 +00002707 case EXTERNAL_BYTE_ELEMENTS:
2708 case EXTERNAL_UNSIGNED_BYTE_ELEMENTS:
2709 case EXTERNAL_SHORT_ELEMENTS:
2710 case EXTERNAL_UNSIGNED_SHORT_ELEMENTS:
2711 case EXTERNAL_INT_ELEMENTS:
2712 case EXTERNAL_UNSIGNED_INT_ELEMENTS:
2713 case EXTERNAL_FLOAT_ELEMENTS:
2714 // Raw pixels and external arrays do not reference other
2715 // objects.
Steve Blocka7e24c12009-10-30 11:49:00 +00002716 break;
2717 case FAST_ELEMENTS: {
2718 int length = IsJSArray() ?
2719 Smi::cast(JSArray::cast(this)->length())->value() :
2720 FixedArray::cast(elements())->length();
2721 for (int i = 0; i < length; i++) {
2722 Object* element = FixedArray::cast(elements())->get(i);
2723 if (!element->IsTheHole() && element == obj) {
2724 return true;
2725 }
2726 }
2727 break;
2728 }
2729 case DICTIONARY_ELEMENTS: {
2730 key = element_dictionary()->SlowReverseLookup(obj);
2731 if (key != Heap::undefined_value()) {
2732 return true;
2733 }
2734 break;
2735 }
2736 default:
2737 UNREACHABLE();
2738 break;
2739 }
2740
Steve Block6ded16b2010-05-10 14:33:55 +01002741 // For functions check the context.
2742 if (IsJSFunction()) {
Steve Blocka7e24c12009-10-30 11:49:00 +00002743 // Get the constructor function for arguments array.
2744 JSObject* arguments_boilerplate =
2745 Top::context()->global_context()->arguments_boilerplate();
2746 JSFunction* arguments_function =
2747 JSFunction::cast(arguments_boilerplate->map()->constructor());
2748
2749 // Get the context and don't check if it is the global context.
2750 JSFunction* f = JSFunction::cast(this);
2751 Context* context = f->context();
2752 if (context->IsGlobalContext()) {
2753 return false;
2754 }
2755
2756 // Check the non-special context slots.
2757 for (int i = Context::MIN_CONTEXT_SLOTS; i < context->length(); i++) {
2758 // Only check JS objects.
2759 if (context->get(i)->IsJSObject()) {
2760 JSObject* ctxobj = JSObject::cast(context->get(i));
2761 // If it is an arguments array check the content.
2762 if (ctxobj->map()->constructor() == arguments_function) {
2763 if (ctxobj->ReferencesObject(obj)) {
2764 return true;
2765 }
2766 } else if (ctxobj == obj) {
2767 return true;
2768 }
2769 }
2770 }
2771
2772 // Check the context extension if any.
2773 if (context->has_extension()) {
2774 return context->extension()->ReferencesObject(obj);
2775 }
2776 }
2777
2778 // No references to object.
2779 return false;
2780}
2781
2782
John Reck59135872010-11-02 12:39:01 -07002783MaybeObject* JSObject::PreventExtensions() {
Steve Block1e0659c2011-05-24 12:43:12 +01002784 if (IsJSGlobalProxy()) {
2785 Object* proto = GetPrototype();
2786 if (proto->IsNull()) return this;
2787 ASSERT(proto->IsJSGlobalObject());
2788 return JSObject::cast(proto)->PreventExtensions();
2789 }
2790
Steve Block8defd9f2010-07-08 12:39:36 +01002791 // If there are fast elements we normalize.
2792 if (HasFastElements()) {
John Reck59135872010-11-02 12:39:01 -07002793 Object* ok;
2794 { MaybeObject* maybe_ok = NormalizeElements();
2795 if (!maybe_ok->ToObject(&ok)) return maybe_ok;
2796 }
Steve Block8defd9f2010-07-08 12:39:36 +01002797 }
2798 // Make sure that we never go back to fast case.
2799 element_dictionary()->set_requires_slow_elements();
2800
2801 // Do a map transition, other objects with this map may still
2802 // be extensible.
John Reck59135872010-11-02 12:39:01 -07002803 Object* new_map;
2804 { MaybeObject* maybe_new_map = map()->CopyDropTransitions();
2805 if (!maybe_new_map->ToObject(&new_map)) return maybe_new_map;
2806 }
Steve Block8defd9f2010-07-08 12:39:36 +01002807 Map::cast(new_map)->set_is_extensible(false);
2808 set_map(Map::cast(new_map));
2809 ASSERT(!map()->is_extensible());
2810 return new_map;
2811}
2812
2813
Steve Blocka7e24c12009-10-30 11:49:00 +00002814// Tests for the fast common case for property enumeration:
Steve Blockd0582a62009-12-15 09:54:21 +00002815// - This object and all prototypes has an enum cache (which means that it has
2816// no interceptors and needs no access checks).
2817// - This object has no elements.
2818// - No prototype has enumerable properties/elements.
Steve Blocka7e24c12009-10-30 11:49:00 +00002819bool JSObject::IsSimpleEnum() {
Steve Blocka7e24c12009-10-30 11:49:00 +00002820 for (Object* o = this;
2821 o != Heap::null_value();
2822 o = JSObject::cast(o)->GetPrototype()) {
2823 JSObject* curr = JSObject::cast(o);
Steve Blocka7e24c12009-10-30 11:49:00 +00002824 if (!curr->map()->instance_descriptors()->HasEnumCache()) return false;
Steve Blockd0582a62009-12-15 09:54:21 +00002825 ASSERT(!curr->HasNamedInterceptor());
2826 ASSERT(!curr->HasIndexedInterceptor());
2827 ASSERT(!curr->IsAccessCheckNeeded());
Steve Blocka7e24c12009-10-30 11:49:00 +00002828 if (curr->NumberOfEnumElements() > 0) return false;
Steve Blocka7e24c12009-10-30 11:49:00 +00002829 if (curr != this) {
2830 FixedArray* curr_fixed_array =
2831 FixedArray::cast(curr->map()->instance_descriptors()->GetEnumCache());
Steve Blockd0582a62009-12-15 09:54:21 +00002832 if (curr_fixed_array->length() > 0) return false;
Steve Blocka7e24c12009-10-30 11:49:00 +00002833 }
2834 }
2835 return true;
2836}
2837
2838
2839int Map::NumberOfDescribedProperties() {
2840 int result = 0;
2841 DescriptorArray* descs = instance_descriptors();
2842 for (int i = 0; i < descs->number_of_descriptors(); i++) {
2843 if (descs->IsProperty(i)) result++;
2844 }
2845 return result;
2846}
2847
2848
2849int Map::PropertyIndexFor(String* name) {
2850 DescriptorArray* descs = instance_descriptors();
2851 for (int i = 0; i < descs->number_of_descriptors(); i++) {
2852 if (name->Equals(descs->GetKey(i)) && !descs->IsNullDescriptor(i)) {
2853 return descs->GetFieldIndex(i);
2854 }
2855 }
2856 return -1;
2857}
2858
2859
2860int Map::NextFreePropertyIndex() {
2861 int max_index = -1;
2862 DescriptorArray* descs = instance_descriptors();
2863 for (int i = 0; i < descs->number_of_descriptors(); i++) {
2864 if (descs->GetType(i) == FIELD) {
2865 int current_index = descs->GetFieldIndex(i);
2866 if (current_index > max_index) max_index = current_index;
2867 }
2868 }
2869 return max_index + 1;
2870}
2871
2872
2873AccessorDescriptor* Map::FindAccessor(String* name) {
2874 DescriptorArray* descs = instance_descriptors();
2875 for (int i = 0; i < descs->number_of_descriptors(); i++) {
2876 if (name->Equals(descs->GetKey(i)) && descs->GetType(i) == CALLBACKS) {
2877 return descs->GetCallbacks(i);
2878 }
2879 }
2880 return NULL;
2881}
2882
2883
2884void JSObject::LocalLookup(String* name, LookupResult* result) {
2885 ASSERT(name->IsString());
2886
2887 if (IsJSGlobalProxy()) {
2888 Object* proto = GetPrototype();
2889 if (proto->IsNull()) return result->NotFound();
2890 ASSERT(proto->IsJSGlobalObject());
2891 return JSObject::cast(proto)->LocalLookup(name, result);
2892 }
2893
2894 // Do not use inline caching if the object is a non-global object
2895 // that requires access checks.
2896 if (!IsJSGlobalProxy() && IsAccessCheckNeeded()) {
2897 result->DisallowCaching();
2898 }
2899
2900 // Check __proto__ before interceptor.
2901 if (name->Equals(Heap::Proto_symbol()) && !IsJSContextExtensionObject()) {
2902 result->ConstantResult(this);
2903 return;
2904 }
2905
2906 // Check for lookup interceptor except when bootstrapping.
2907 if (HasNamedInterceptor() && !Bootstrapper::IsActive()) {
2908 result->InterceptorResult(this);
2909 return;
2910 }
2911
2912 LocalLookupRealNamedProperty(name, result);
2913}
2914
2915
2916void JSObject::Lookup(String* name, LookupResult* result) {
2917 // Ecma-262 3rd 8.6.2.4
2918 for (Object* current = this;
2919 current != Heap::null_value();
2920 current = JSObject::cast(current)->GetPrototype()) {
2921 JSObject::cast(current)->LocalLookup(name, result);
Andrei Popescu402d9372010-02-26 13:31:12 +00002922 if (result->IsProperty()) return;
Steve Blocka7e24c12009-10-30 11:49:00 +00002923 }
2924 result->NotFound();
2925}
2926
2927
2928// Search object and it's prototype chain for callback properties.
2929void JSObject::LookupCallback(String* name, LookupResult* result) {
2930 for (Object* current = this;
2931 current != Heap::null_value();
2932 current = JSObject::cast(current)->GetPrototype()) {
2933 JSObject::cast(current)->LocalLookupRealNamedProperty(name, result);
Andrei Popescu402d9372010-02-26 13:31:12 +00002934 if (result->IsProperty() && result->type() == CALLBACKS) return;
Steve Blocka7e24c12009-10-30 11:49:00 +00002935 }
2936 result->NotFound();
2937}
2938
2939
John Reck59135872010-11-02 12:39:01 -07002940MaybeObject* JSObject::DefineGetterSetter(String* name,
2941 PropertyAttributes attributes) {
Steve Blocka7e24c12009-10-30 11:49:00 +00002942 // Make sure that the top context does not change when doing callbacks or
2943 // interceptor calls.
2944 AssertNoContextChange ncc;
2945
Steve Blocka7e24c12009-10-30 11:49:00 +00002946 // Try to flatten before operating on the string.
Steve Block6ded16b2010-05-10 14:33:55 +01002947 name->TryFlatten();
Steve Blocka7e24c12009-10-30 11:49:00 +00002948
Leon Clarkef7060e22010-06-03 12:02:55 +01002949 if (!CanSetCallback(name)) {
2950 return Heap::undefined_value();
Steve Blocka7e24c12009-10-30 11:49:00 +00002951 }
2952
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01002953 uint32_t index = 0;
Steve Blocka7e24c12009-10-30 11:49:00 +00002954 bool is_element = name->AsArrayIndex(&index);
Steve Blocka7e24c12009-10-30 11:49:00 +00002955
2956 if (is_element) {
2957 switch (GetElementsKind()) {
2958 case FAST_ELEMENTS:
2959 break;
2960 case PIXEL_ELEMENTS:
Steve Block3ce2e202009-11-05 08:53:23 +00002961 case EXTERNAL_BYTE_ELEMENTS:
2962 case EXTERNAL_UNSIGNED_BYTE_ELEMENTS:
2963 case EXTERNAL_SHORT_ELEMENTS:
2964 case EXTERNAL_UNSIGNED_SHORT_ELEMENTS:
2965 case EXTERNAL_INT_ELEMENTS:
2966 case EXTERNAL_UNSIGNED_INT_ELEMENTS:
2967 case EXTERNAL_FLOAT_ELEMENTS:
2968 // Ignore getters and setters on pixel and external array
2969 // elements.
Steve Blocka7e24c12009-10-30 11:49:00 +00002970 return Heap::undefined_value();
2971 case DICTIONARY_ELEMENTS: {
2972 // Lookup the index.
2973 NumberDictionary* dictionary = element_dictionary();
2974 int entry = dictionary->FindEntry(index);
2975 if (entry != NumberDictionary::kNotFound) {
2976 Object* result = dictionary->ValueAt(entry);
2977 PropertyDetails details = dictionary->DetailsAt(entry);
2978 if (details.IsReadOnly()) return Heap::undefined_value();
2979 if (details.type() == CALLBACKS) {
Leon Clarkef7060e22010-06-03 12:02:55 +01002980 if (result->IsFixedArray()) {
2981 return result;
2982 }
2983 // Otherwise allow to override it.
Steve Blocka7e24c12009-10-30 11:49:00 +00002984 }
2985 }
2986 break;
2987 }
2988 default:
2989 UNREACHABLE();
2990 break;
2991 }
2992 } else {
2993 // Lookup the name.
2994 LookupResult result;
2995 LocalLookup(name, &result);
Andrei Popescu402d9372010-02-26 13:31:12 +00002996 if (result.IsProperty()) {
Steve Blocka7e24c12009-10-30 11:49:00 +00002997 if (result.IsReadOnly()) return Heap::undefined_value();
2998 if (result.type() == CALLBACKS) {
2999 Object* obj = result.GetCallbackObject();
Leon Clarkef7060e22010-06-03 12:02:55 +01003000 // Need to preserve old getters/setters.
Leon Clarked91b9f72010-01-27 17:25:45 +00003001 if (obj->IsFixedArray()) {
Leon Clarkef7060e22010-06-03 12:02:55 +01003002 // Use set to update attributes.
3003 return SetPropertyCallback(name, obj, attributes);
Leon Clarked91b9f72010-01-27 17:25:45 +00003004 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003005 }
3006 }
3007 }
3008
3009 // Allocate the fixed array to hold getter and setter.
John Reck59135872010-11-02 12:39:01 -07003010 Object* structure;
3011 { MaybeObject* maybe_structure = Heap::AllocateFixedArray(2, TENURED);
3012 if (!maybe_structure->ToObject(&structure)) return maybe_structure;
3013 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003014
3015 if (is_element) {
Leon Clarkef7060e22010-06-03 12:02:55 +01003016 return SetElementCallback(index, structure, attributes);
Steve Blocka7e24c12009-10-30 11:49:00 +00003017 } else {
Leon Clarkef7060e22010-06-03 12:02:55 +01003018 return SetPropertyCallback(name, structure, attributes);
Steve Blocka7e24c12009-10-30 11:49:00 +00003019 }
Leon Clarkef7060e22010-06-03 12:02:55 +01003020}
3021
3022
3023bool JSObject::CanSetCallback(String* name) {
3024 ASSERT(!IsAccessCheckNeeded()
3025 || Top::MayNamedAccess(this, name, v8::ACCESS_SET));
3026
3027 // Check if there is an API defined callback object which prohibits
3028 // callback overwriting in this object or it's prototype chain.
3029 // This mechanism is needed for instance in a browser setting, where
3030 // certain accessors such as window.location should not be allowed
3031 // to be overwritten because allowing overwriting could potentially
3032 // cause security problems.
3033 LookupResult callback_result;
3034 LookupCallback(name, &callback_result);
3035 if (callback_result.IsProperty()) {
3036 Object* obj = callback_result.GetCallbackObject();
3037 if (obj->IsAccessorInfo() &&
3038 AccessorInfo::cast(obj)->prohibits_overwriting()) {
3039 return false;
3040 }
3041 }
3042
3043 return true;
3044}
3045
3046
John Reck59135872010-11-02 12:39:01 -07003047MaybeObject* JSObject::SetElementCallback(uint32_t index,
3048 Object* structure,
3049 PropertyAttributes attributes) {
Leon Clarkef7060e22010-06-03 12:02:55 +01003050 PropertyDetails details = PropertyDetails(attributes, CALLBACKS);
3051
3052 // Normalize elements to make this operation simple.
John Reck59135872010-11-02 12:39:01 -07003053 Object* ok;
3054 { MaybeObject* maybe_ok = NormalizeElements();
3055 if (!maybe_ok->ToObject(&ok)) return maybe_ok;
3056 }
Leon Clarkef7060e22010-06-03 12:02:55 +01003057
3058 // Update the dictionary with the new CALLBACKS property.
John Reck59135872010-11-02 12:39:01 -07003059 Object* dict;
3060 { MaybeObject* maybe_dict =
3061 element_dictionary()->Set(index, structure, details);
3062 if (!maybe_dict->ToObject(&dict)) return maybe_dict;
3063 }
Leon Clarkef7060e22010-06-03 12:02:55 +01003064
3065 NumberDictionary* elements = NumberDictionary::cast(dict);
3066 elements->set_requires_slow_elements();
3067 // Set the potential new dictionary on the object.
3068 set_elements(elements);
Steve Blocka7e24c12009-10-30 11:49:00 +00003069
3070 return structure;
3071}
3072
3073
John Reck59135872010-11-02 12:39:01 -07003074MaybeObject* JSObject::SetPropertyCallback(String* name,
3075 Object* structure,
3076 PropertyAttributes attributes) {
Leon Clarkef7060e22010-06-03 12:02:55 +01003077 PropertyDetails details = PropertyDetails(attributes, CALLBACKS);
3078
3079 bool convert_back_to_fast = HasFastProperties() &&
3080 (map()->instance_descriptors()->number_of_descriptors()
3081 < DescriptorArray::kMaxNumberOfDescriptors);
3082
3083 // Normalize object to make this operation simple.
John Reck59135872010-11-02 12:39:01 -07003084 Object* ok;
3085 { MaybeObject* maybe_ok = NormalizeProperties(CLEAR_INOBJECT_PROPERTIES, 0);
3086 if (!maybe_ok->ToObject(&ok)) return maybe_ok;
3087 }
Leon Clarkef7060e22010-06-03 12:02:55 +01003088
3089 // For the global object allocate a new map to invalidate the global inline
3090 // caches which have a global property cell reference directly in the code.
3091 if (IsGlobalObject()) {
John Reck59135872010-11-02 12:39:01 -07003092 Object* new_map;
3093 { MaybeObject* maybe_new_map = map()->CopyDropDescriptors();
3094 if (!maybe_new_map->ToObject(&new_map)) return maybe_new_map;
3095 }
Leon Clarkef7060e22010-06-03 12:02:55 +01003096 set_map(Map::cast(new_map));
Ben Murdochb0fe1622011-05-05 13:52:32 +01003097 // When running crankshaft, changing the map is not enough. We
3098 // need to deoptimize all functions that rely on this global
3099 // object.
3100 Deoptimizer::DeoptimizeGlobalObject(this);
Leon Clarkef7060e22010-06-03 12:02:55 +01003101 }
3102
3103 // Update the dictionary with the new CALLBACKS property.
John Reck59135872010-11-02 12:39:01 -07003104 Object* result;
3105 { MaybeObject* maybe_result = SetNormalizedProperty(name, structure, details);
3106 if (!maybe_result->ToObject(&result)) return maybe_result;
3107 }
Leon Clarkef7060e22010-06-03 12:02:55 +01003108
3109 if (convert_back_to_fast) {
John Reck59135872010-11-02 12:39:01 -07003110 { MaybeObject* maybe_ok = TransformToFastProperties(0);
3111 if (!maybe_ok->ToObject(&ok)) return maybe_ok;
3112 }
Leon Clarkef7060e22010-06-03 12:02:55 +01003113 }
3114 return result;
3115}
3116
John Reck59135872010-11-02 12:39:01 -07003117MaybeObject* JSObject::DefineAccessor(String* name,
3118 bool is_getter,
Ben Murdochb0fe1622011-05-05 13:52:32 +01003119 Object* fun,
John Reck59135872010-11-02 12:39:01 -07003120 PropertyAttributes attributes) {
Ben Murdochb0fe1622011-05-05 13:52:32 +01003121 ASSERT(fun->IsJSFunction() || fun->IsUndefined());
Steve Blocka7e24c12009-10-30 11:49:00 +00003122 // Check access rights if needed.
3123 if (IsAccessCheckNeeded() &&
Leon Clarkef7060e22010-06-03 12:02:55 +01003124 !Top::MayNamedAccess(this, name, v8::ACCESS_SET)) {
3125 Top::ReportFailedAccessCheck(this, v8::ACCESS_SET);
Steve Blocka7e24c12009-10-30 11:49:00 +00003126 return Heap::undefined_value();
3127 }
3128
3129 if (IsJSGlobalProxy()) {
3130 Object* proto = GetPrototype();
3131 if (proto->IsNull()) return this;
3132 ASSERT(proto->IsJSGlobalObject());
3133 return JSObject::cast(proto)->DefineAccessor(name, is_getter,
3134 fun, attributes);
3135 }
3136
John Reck59135872010-11-02 12:39:01 -07003137 Object* array;
3138 { MaybeObject* maybe_array = DefineGetterSetter(name, attributes);
3139 if (!maybe_array->ToObject(&array)) return maybe_array;
3140 }
3141 if (array->IsUndefined()) return array;
Steve Blocka7e24c12009-10-30 11:49:00 +00003142 FixedArray::cast(array)->set(is_getter ? 0 : 1, fun);
3143 return this;
3144}
3145
3146
John Reck59135872010-11-02 12:39:01 -07003147MaybeObject* JSObject::DefineAccessor(AccessorInfo* info) {
Leon Clarkef7060e22010-06-03 12:02:55 +01003148 String* name = String::cast(info->name());
3149 // Check access rights if needed.
3150 if (IsAccessCheckNeeded() &&
3151 !Top::MayNamedAccess(this, name, v8::ACCESS_SET)) {
3152 Top::ReportFailedAccessCheck(this, v8::ACCESS_SET);
3153 return Heap::undefined_value();
3154 }
3155
3156 if (IsJSGlobalProxy()) {
3157 Object* proto = GetPrototype();
3158 if (proto->IsNull()) return this;
3159 ASSERT(proto->IsJSGlobalObject());
3160 return JSObject::cast(proto)->DefineAccessor(info);
3161 }
3162
3163 // Make sure that the top context does not change when doing callbacks or
3164 // interceptor calls.
3165 AssertNoContextChange ncc;
3166
3167 // Try to flatten before operating on the string.
3168 name->TryFlatten();
3169
3170 if (!CanSetCallback(name)) {
3171 return Heap::undefined_value();
3172 }
3173
3174 uint32_t index = 0;
3175 bool is_element = name->AsArrayIndex(&index);
3176
3177 if (is_element) {
3178 if (IsJSArray()) return Heap::undefined_value();
3179
3180 // Accessors overwrite previous callbacks (cf. with getters/setters).
3181 switch (GetElementsKind()) {
3182 case FAST_ELEMENTS:
3183 break;
3184 case PIXEL_ELEMENTS:
3185 case EXTERNAL_BYTE_ELEMENTS:
3186 case EXTERNAL_UNSIGNED_BYTE_ELEMENTS:
3187 case EXTERNAL_SHORT_ELEMENTS:
3188 case EXTERNAL_UNSIGNED_SHORT_ELEMENTS:
3189 case EXTERNAL_INT_ELEMENTS:
3190 case EXTERNAL_UNSIGNED_INT_ELEMENTS:
3191 case EXTERNAL_FLOAT_ELEMENTS:
3192 // Ignore getters and setters on pixel and external array
3193 // elements.
3194 return Heap::undefined_value();
3195 case DICTIONARY_ELEMENTS:
3196 break;
3197 default:
3198 UNREACHABLE();
3199 break;
3200 }
3201
John Reck59135872010-11-02 12:39:01 -07003202 Object* ok;
3203 { MaybeObject* maybe_ok =
3204 SetElementCallback(index, info, info->property_attributes());
3205 if (!maybe_ok->ToObject(&ok)) return maybe_ok;
3206 }
Leon Clarkef7060e22010-06-03 12:02:55 +01003207 } else {
3208 // Lookup the name.
3209 LookupResult result;
3210 LocalLookup(name, &result);
3211 // ES5 forbids turning a property into an accessor if it's not
3212 // configurable (that is IsDontDelete in ES3 and v8), see 8.6.1 (Table 5).
3213 if (result.IsProperty() && (result.IsReadOnly() || result.IsDontDelete())) {
3214 return Heap::undefined_value();
3215 }
John Reck59135872010-11-02 12:39:01 -07003216 Object* ok;
3217 { MaybeObject* maybe_ok =
3218 SetPropertyCallback(name, info, info->property_attributes());
3219 if (!maybe_ok->ToObject(&ok)) return maybe_ok;
3220 }
Leon Clarkef7060e22010-06-03 12:02:55 +01003221 }
3222
3223 return this;
3224}
3225
3226
Steve Blocka7e24c12009-10-30 11:49:00 +00003227Object* JSObject::LookupAccessor(String* name, bool is_getter) {
3228 // Make sure that the top context does not change when doing callbacks or
3229 // interceptor calls.
3230 AssertNoContextChange ncc;
3231
3232 // Check access rights if needed.
3233 if (IsAccessCheckNeeded() &&
3234 !Top::MayNamedAccess(this, name, v8::ACCESS_HAS)) {
3235 Top::ReportFailedAccessCheck(this, v8::ACCESS_HAS);
3236 return Heap::undefined_value();
3237 }
3238
3239 // Make the lookup and include prototypes.
3240 int accessor_index = is_getter ? kGetterIndex : kSetterIndex;
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01003241 uint32_t index = 0;
Steve Blocka7e24c12009-10-30 11:49:00 +00003242 if (name->AsArrayIndex(&index)) {
3243 for (Object* obj = this;
3244 obj != Heap::null_value();
3245 obj = JSObject::cast(obj)->GetPrototype()) {
3246 JSObject* js_object = JSObject::cast(obj);
3247 if (js_object->HasDictionaryElements()) {
3248 NumberDictionary* dictionary = js_object->element_dictionary();
3249 int entry = dictionary->FindEntry(index);
3250 if (entry != NumberDictionary::kNotFound) {
3251 Object* element = dictionary->ValueAt(entry);
3252 PropertyDetails details = dictionary->DetailsAt(entry);
3253 if (details.type() == CALLBACKS) {
Leon Clarkef7060e22010-06-03 12:02:55 +01003254 if (element->IsFixedArray()) {
3255 return FixedArray::cast(element)->get(accessor_index);
3256 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003257 }
3258 }
3259 }
3260 }
3261 } else {
3262 for (Object* obj = this;
3263 obj != Heap::null_value();
3264 obj = JSObject::cast(obj)->GetPrototype()) {
3265 LookupResult result;
3266 JSObject::cast(obj)->LocalLookup(name, &result);
Andrei Popescu402d9372010-02-26 13:31:12 +00003267 if (result.IsProperty()) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003268 if (result.IsReadOnly()) return Heap::undefined_value();
3269 if (result.type() == CALLBACKS) {
3270 Object* obj = result.GetCallbackObject();
3271 if (obj->IsFixedArray()) {
3272 return FixedArray::cast(obj)->get(accessor_index);
3273 }
3274 }
3275 }
3276 }
3277 }
3278 return Heap::undefined_value();
3279}
3280
3281
3282Object* JSObject::SlowReverseLookup(Object* value) {
3283 if (HasFastProperties()) {
3284 DescriptorArray* descs = map()->instance_descriptors();
3285 for (int i = 0; i < descs->number_of_descriptors(); i++) {
3286 if (descs->GetType(i) == FIELD) {
3287 if (FastPropertyAt(descs->GetFieldIndex(i)) == value) {
3288 return descs->GetKey(i);
3289 }
3290 } else if (descs->GetType(i) == CONSTANT_FUNCTION) {
3291 if (descs->GetConstantFunction(i) == value) {
3292 return descs->GetKey(i);
3293 }
3294 }
3295 }
3296 return Heap::undefined_value();
3297 } else {
3298 return property_dictionary()->SlowReverseLookup(value);
3299 }
3300}
3301
3302
John Reck59135872010-11-02 12:39:01 -07003303MaybeObject* Map::CopyDropDescriptors() {
3304 Object* result;
3305 { MaybeObject* maybe_result =
3306 Heap::AllocateMap(instance_type(), instance_size());
3307 if (!maybe_result->ToObject(&result)) return maybe_result;
3308 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003309 Map::cast(result)->set_prototype(prototype());
3310 Map::cast(result)->set_constructor(constructor());
3311 // Don't copy descriptors, so map transitions always remain a forest.
3312 // If we retained the same descriptors we would have two maps
3313 // pointing to the same transition which is bad because the garbage
3314 // collector relies on being able to reverse pointers from transitions
3315 // to maps. If properties need to be retained use CopyDropTransitions.
3316 Map::cast(result)->set_instance_descriptors(Heap::empty_descriptor_array());
3317 // Please note instance_type and instance_size are set when allocated.
3318 Map::cast(result)->set_inobject_properties(inobject_properties());
3319 Map::cast(result)->set_unused_property_fields(unused_property_fields());
3320
3321 // If the map has pre-allocated properties always start out with a descriptor
3322 // array describing these properties.
3323 if (pre_allocated_property_fields() > 0) {
3324 ASSERT(constructor()->IsJSFunction());
3325 JSFunction* ctor = JSFunction::cast(constructor());
John Reck59135872010-11-02 12:39:01 -07003326 Object* descriptors;
3327 { MaybeObject* maybe_descriptors =
3328 ctor->initial_map()->instance_descriptors()->RemoveTransitions();
3329 if (!maybe_descriptors->ToObject(&descriptors)) return maybe_descriptors;
3330 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003331 Map::cast(result)->set_instance_descriptors(
3332 DescriptorArray::cast(descriptors));
3333 Map::cast(result)->set_pre_allocated_property_fields(
3334 pre_allocated_property_fields());
3335 }
3336 Map::cast(result)->set_bit_field(bit_field());
3337 Map::cast(result)->set_bit_field2(bit_field2());
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003338 Map::cast(result)->set_is_shared(false);
Steve Blocka7e24c12009-10-30 11:49:00 +00003339 Map::cast(result)->ClearCodeCache();
3340 return result;
3341}
3342
3343
John Reck59135872010-11-02 12:39:01 -07003344MaybeObject* Map::CopyNormalized(PropertyNormalizationMode mode,
3345 NormalizedMapSharingMode sharing) {
Kristian Monsen80d68ea2010-09-08 11:05:35 +01003346 int new_instance_size = instance_size();
3347 if (mode == CLEAR_INOBJECT_PROPERTIES) {
3348 new_instance_size -= inobject_properties() * kPointerSize;
3349 }
3350
John Reck59135872010-11-02 12:39:01 -07003351 Object* result;
3352 { MaybeObject* maybe_result =
3353 Heap::AllocateMap(instance_type(), new_instance_size);
3354 if (!maybe_result->ToObject(&result)) return maybe_result;
3355 }
Kristian Monsen80d68ea2010-09-08 11:05:35 +01003356
3357 if (mode != CLEAR_INOBJECT_PROPERTIES) {
3358 Map::cast(result)->set_inobject_properties(inobject_properties());
3359 }
3360
3361 Map::cast(result)->set_prototype(prototype());
3362 Map::cast(result)->set_constructor(constructor());
3363
3364 Map::cast(result)->set_bit_field(bit_field());
3365 Map::cast(result)->set_bit_field2(bit_field2());
3366
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003367 Map::cast(result)->set_is_shared(sharing == SHARED_NORMALIZED_MAP);
3368
Kristian Monsen80d68ea2010-09-08 11:05:35 +01003369#ifdef DEBUG
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003370 if (Map::cast(result)->is_shared()) {
3371 Map::cast(result)->SharedMapVerify();
3372 }
Kristian Monsen80d68ea2010-09-08 11:05:35 +01003373#endif
3374
3375 return result;
3376}
3377
3378
John Reck59135872010-11-02 12:39:01 -07003379MaybeObject* Map::CopyDropTransitions() {
3380 Object* new_map;
3381 { MaybeObject* maybe_new_map = CopyDropDescriptors();
3382 if (!maybe_new_map->ToObject(&new_map)) return maybe_new_map;
3383 }
3384 Object* descriptors;
3385 { MaybeObject* maybe_descriptors =
3386 instance_descriptors()->RemoveTransitions();
3387 if (!maybe_descriptors->ToObject(&descriptors)) return maybe_descriptors;
3388 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003389 cast(new_map)->set_instance_descriptors(DescriptorArray::cast(descriptors));
Steve Block8defd9f2010-07-08 12:39:36 +01003390 return new_map;
Steve Blocka7e24c12009-10-30 11:49:00 +00003391}
3392
3393
John Reck59135872010-11-02 12:39:01 -07003394MaybeObject* Map::UpdateCodeCache(String* name, Code* code) {
Steve Block6ded16b2010-05-10 14:33:55 +01003395 // Allocate the code cache if not present.
3396 if (code_cache()->IsFixedArray()) {
John Reck59135872010-11-02 12:39:01 -07003397 Object* result;
3398 { MaybeObject* maybe_result = Heap::AllocateCodeCache();
3399 if (!maybe_result->ToObject(&result)) return maybe_result;
3400 }
Steve Block6ded16b2010-05-10 14:33:55 +01003401 set_code_cache(result);
3402 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003403
Steve Block6ded16b2010-05-10 14:33:55 +01003404 // Update the code cache.
3405 return CodeCache::cast(code_cache())->Update(name, code);
3406}
3407
3408
3409Object* Map::FindInCodeCache(String* name, Code::Flags flags) {
3410 // Do a lookup if a code cache exists.
3411 if (!code_cache()->IsFixedArray()) {
3412 return CodeCache::cast(code_cache())->Lookup(name, flags);
3413 } else {
3414 return Heap::undefined_value();
3415 }
3416}
3417
3418
3419int Map::IndexInCodeCache(Object* name, Code* code) {
3420 // Get the internal index if a code cache exists.
3421 if (!code_cache()->IsFixedArray()) {
3422 return CodeCache::cast(code_cache())->GetIndex(name, code);
3423 }
3424 return -1;
3425}
3426
3427
3428void Map::RemoveFromCodeCache(String* name, Code* code, int index) {
3429 // No GC is supposed to happen between a call to IndexInCodeCache and
3430 // RemoveFromCodeCache so the code cache must be there.
3431 ASSERT(!code_cache()->IsFixedArray());
3432 CodeCache::cast(code_cache())->RemoveByIndex(name, code, index);
3433}
3434
3435
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003436void Map::TraverseTransitionTree(TraverseCallback callback, void* data) {
3437 Map* current = this;
3438 while (current != Heap::meta_map()) {
3439 DescriptorArray* d = reinterpret_cast<DescriptorArray*>(
3440 *RawField(current, Map::kInstanceDescriptorsOffset));
3441 if (d == Heap::empty_descriptor_array()) {
3442 Map* prev = current->map();
3443 current->set_map(Heap::meta_map());
3444 callback(current, data);
3445 current = prev;
3446 continue;
3447 }
3448
3449 FixedArray* contents = reinterpret_cast<FixedArray*>(
3450 d->get(DescriptorArray::kContentArrayIndex));
3451 Object** map_or_index_field = RawField(contents, HeapObject::kMapOffset);
3452 Object* map_or_index = *map_or_index_field;
3453 bool map_done = true;
3454 for (int i = map_or_index->IsSmi() ? Smi::cast(map_or_index)->value() : 0;
3455 i < contents->length();
3456 i += 2) {
3457 PropertyDetails details(Smi::cast(contents->get(i + 1)));
3458 if (details.IsTransition()) {
3459 Map* next = reinterpret_cast<Map*>(contents->get(i));
3460 next->set_map(current);
3461 *map_or_index_field = Smi::FromInt(i + 2);
3462 current = next;
3463 map_done = false;
3464 break;
3465 }
3466 }
3467 if (!map_done) continue;
3468 *map_or_index_field = Heap::fixed_array_map();
3469 Map* prev = current->map();
3470 current->set_map(Heap::meta_map());
3471 callback(current, data);
3472 current = prev;
3473 }
3474}
3475
3476
John Reck59135872010-11-02 12:39:01 -07003477MaybeObject* CodeCache::Update(String* name, Code* code) {
Steve Block6ded16b2010-05-10 14:33:55 +01003478 ASSERT(code->ic_state() == MONOMORPHIC);
3479
3480 // The number of monomorphic stubs for normal load/store/call IC's can grow to
3481 // a large number and therefore they need to go into a hash table. They are
3482 // used to load global properties from cells.
3483 if (code->type() == NORMAL) {
3484 // Make sure that a hash table is allocated for the normal load code cache.
3485 if (normal_type_cache()->IsUndefined()) {
John Reck59135872010-11-02 12:39:01 -07003486 Object* result;
3487 { MaybeObject* maybe_result =
3488 CodeCacheHashTable::Allocate(CodeCacheHashTable::kInitialSize);
3489 if (!maybe_result->ToObject(&result)) return maybe_result;
3490 }
Steve Block6ded16b2010-05-10 14:33:55 +01003491 set_normal_type_cache(result);
3492 }
3493 return UpdateNormalTypeCache(name, code);
3494 } else {
3495 ASSERT(default_cache()->IsFixedArray());
3496 return UpdateDefaultCache(name, code);
3497 }
3498}
3499
3500
John Reck59135872010-11-02 12:39:01 -07003501MaybeObject* CodeCache::UpdateDefaultCache(String* name, Code* code) {
Steve Block6ded16b2010-05-10 14:33:55 +01003502 // When updating the default code cache we disregard the type encoded in the
Steve Blocka7e24c12009-10-30 11:49:00 +00003503 // flags. This allows call constant stubs to overwrite call field
3504 // stubs, etc.
3505 Code::Flags flags = Code::RemoveTypeFromFlags(code->flags());
3506
3507 // First check whether we can update existing code cache without
3508 // extending it.
Steve Block6ded16b2010-05-10 14:33:55 +01003509 FixedArray* cache = default_cache();
Steve Blocka7e24c12009-10-30 11:49:00 +00003510 int length = cache->length();
3511 int deleted_index = -1;
Steve Block6ded16b2010-05-10 14:33:55 +01003512 for (int i = 0; i < length; i += kCodeCacheEntrySize) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003513 Object* key = cache->get(i);
3514 if (key->IsNull()) {
3515 if (deleted_index < 0) deleted_index = i;
3516 continue;
3517 }
3518 if (key->IsUndefined()) {
3519 if (deleted_index >= 0) i = deleted_index;
Steve Block6ded16b2010-05-10 14:33:55 +01003520 cache->set(i + kCodeCacheEntryNameOffset, name);
3521 cache->set(i + kCodeCacheEntryCodeOffset, code);
Steve Blocka7e24c12009-10-30 11:49:00 +00003522 return this;
3523 }
3524 if (name->Equals(String::cast(key))) {
Steve Block6ded16b2010-05-10 14:33:55 +01003525 Code::Flags found =
3526 Code::cast(cache->get(i + kCodeCacheEntryCodeOffset))->flags();
Steve Blocka7e24c12009-10-30 11:49:00 +00003527 if (Code::RemoveTypeFromFlags(found) == flags) {
Steve Block6ded16b2010-05-10 14:33:55 +01003528 cache->set(i + kCodeCacheEntryCodeOffset, code);
Steve Blocka7e24c12009-10-30 11:49:00 +00003529 return this;
3530 }
3531 }
3532 }
3533
3534 // Reached the end of the code cache. If there were deleted
3535 // elements, reuse the space for the first of them.
3536 if (deleted_index >= 0) {
Steve Block6ded16b2010-05-10 14:33:55 +01003537 cache->set(deleted_index + kCodeCacheEntryNameOffset, name);
3538 cache->set(deleted_index + kCodeCacheEntryCodeOffset, code);
Steve Blocka7e24c12009-10-30 11:49:00 +00003539 return this;
3540 }
3541
Steve Block6ded16b2010-05-10 14:33:55 +01003542 // Extend the code cache with some new entries (at least one). Must be a
3543 // multiple of the entry size.
3544 int new_length = length + ((length >> 1)) + kCodeCacheEntrySize;
3545 new_length = new_length - new_length % kCodeCacheEntrySize;
3546 ASSERT((new_length % kCodeCacheEntrySize) == 0);
John Reck59135872010-11-02 12:39:01 -07003547 Object* result;
3548 { MaybeObject* maybe_result = cache->CopySize(new_length);
3549 if (!maybe_result->ToObject(&result)) return maybe_result;
3550 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003551
3552 // Add the (name, code) pair to the new cache.
3553 cache = FixedArray::cast(result);
Steve Block6ded16b2010-05-10 14:33:55 +01003554 cache->set(length + kCodeCacheEntryNameOffset, name);
3555 cache->set(length + kCodeCacheEntryCodeOffset, code);
3556 set_default_cache(cache);
Steve Blocka7e24c12009-10-30 11:49:00 +00003557 return this;
3558}
3559
3560
John Reck59135872010-11-02 12:39:01 -07003561MaybeObject* CodeCache::UpdateNormalTypeCache(String* name, Code* code) {
Steve Block6ded16b2010-05-10 14:33:55 +01003562 // Adding a new entry can cause a new cache to be allocated.
3563 CodeCacheHashTable* cache = CodeCacheHashTable::cast(normal_type_cache());
John Reck59135872010-11-02 12:39:01 -07003564 Object* new_cache;
3565 { MaybeObject* maybe_new_cache = cache->Put(name, code);
3566 if (!maybe_new_cache->ToObject(&new_cache)) return maybe_new_cache;
3567 }
Steve Block6ded16b2010-05-10 14:33:55 +01003568 set_normal_type_cache(new_cache);
3569 return this;
3570}
3571
3572
3573Object* CodeCache::Lookup(String* name, Code::Flags flags) {
3574 if (Code::ExtractTypeFromFlags(flags) == NORMAL) {
3575 return LookupNormalTypeCache(name, flags);
3576 } else {
3577 return LookupDefaultCache(name, flags);
3578 }
3579}
3580
3581
3582Object* CodeCache::LookupDefaultCache(String* name, Code::Flags flags) {
3583 FixedArray* cache = default_cache();
Steve Blocka7e24c12009-10-30 11:49:00 +00003584 int length = cache->length();
Steve Block6ded16b2010-05-10 14:33:55 +01003585 for (int i = 0; i < length; i += kCodeCacheEntrySize) {
3586 Object* key = cache->get(i + kCodeCacheEntryNameOffset);
Steve Blocka7e24c12009-10-30 11:49:00 +00003587 // Skip deleted elements.
3588 if (key->IsNull()) continue;
3589 if (key->IsUndefined()) return key;
3590 if (name->Equals(String::cast(key))) {
Steve Block6ded16b2010-05-10 14:33:55 +01003591 Code* code = Code::cast(cache->get(i + kCodeCacheEntryCodeOffset));
3592 if (code->flags() == flags) {
3593 return code;
3594 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003595 }
3596 }
3597 return Heap::undefined_value();
3598}
3599
3600
Steve Block6ded16b2010-05-10 14:33:55 +01003601Object* CodeCache::LookupNormalTypeCache(String* name, Code::Flags flags) {
3602 if (!normal_type_cache()->IsUndefined()) {
3603 CodeCacheHashTable* cache = CodeCacheHashTable::cast(normal_type_cache());
3604 return cache->Lookup(name, flags);
3605 } else {
3606 return Heap::undefined_value();
3607 }
3608}
3609
3610
3611int CodeCache::GetIndex(Object* name, Code* code) {
3612 if (code->type() == NORMAL) {
3613 if (normal_type_cache()->IsUndefined()) return -1;
3614 CodeCacheHashTable* cache = CodeCacheHashTable::cast(normal_type_cache());
3615 return cache->GetIndex(String::cast(name), code->flags());
3616 }
3617
3618 FixedArray* array = default_cache();
Steve Blocka7e24c12009-10-30 11:49:00 +00003619 int len = array->length();
Steve Block6ded16b2010-05-10 14:33:55 +01003620 for (int i = 0; i < len; i += kCodeCacheEntrySize) {
3621 if (array->get(i + kCodeCacheEntryCodeOffset) == code) return i + 1;
Steve Blocka7e24c12009-10-30 11:49:00 +00003622 }
3623 return -1;
3624}
3625
3626
Steve Block6ded16b2010-05-10 14:33:55 +01003627void CodeCache::RemoveByIndex(Object* name, Code* code, int index) {
3628 if (code->type() == NORMAL) {
3629 ASSERT(!normal_type_cache()->IsUndefined());
3630 CodeCacheHashTable* cache = CodeCacheHashTable::cast(normal_type_cache());
3631 ASSERT(cache->GetIndex(String::cast(name), code->flags()) == index);
3632 cache->RemoveByIndex(index);
3633 } else {
3634 FixedArray* array = default_cache();
3635 ASSERT(array->length() >= index && array->get(index)->IsCode());
3636 // Use null instead of undefined for deleted elements to distinguish
3637 // deleted elements from unused elements. This distinction is used
3638 // when looking up in the cache and when updating the cache.
3639 ASSERT_EQ(1, kCodeCacheEntryCodeOffset - kCodeCacheEntryNameOffset);
3640 array->set_null(index - 1); // Name.
3641 array->set_null(index); // Code.
3642 }
3643}
3644
3645
3646// The key in the code cache hash table consists of the property name and the
3647// code object. The actual match is on the name and the code flags. If a key
3648// is created using the flags and not a code object it can only be used for
3649// lookup not to create a new entry.
3650class CodeCacheHashTableKey : public HashTableKey {
3651 public:
3652 CodeCacheHashTableKey(String* name, Code::Flags flags)
3653 : name_(name), flags_(flags), code_(NULL) { }
3654
3655 CodeCacheHashTableKey(String* name, Code* code)
3656 : name_(name),
3657 flags_(code->flags()),
3658 code_(code) { }
3659
3660
3661 bool IsMatch(Object* other) {
3662 if (!other->IsFixedArray()) return false;
3663 FixedArray* pair = FixedArray::cast(other);
3664 String* name = String::cast(pair->get(0));
3665 Code::Flags flags = Code::cast(pair->get(1))->flags();
3666 if (flags != flags_) {
3667 return false;
3668 }
3669 return name_->Equals(name);
3670 }
3671
3672 static uint32_t NameFlagsHashHelper(String* name, Code::Flags flags) {
3673 return name->Hash() ^ flags;
3674 }
3675
3676 uint32_t Hash() { return NameFlagsHashHelper(name_, flags_); }
3677
3678 uint32_t HashForObject(Object* obj) {
3679 FixedArray* pair = FixedArray::cast(obj);
3680 String* name = String::cast(pair->get(0));
3681 Code* code = Code::cast(pair->get(1));
3682 return NameFlagsHashHelper(name, code->flags());
3683 }
3684
John Reck59135872010-11-02 12:39:01 -07003685 MUST_USE_RESULT MaybeObject* AsObject() {
Steve Block6ded16b2010-05-10 14:33:55 +01003686 ASSERT(code_ != NULL);
John Reck59135872010-11-02 12:39:01 -07003687 Object* obj;
3688 { MaybeObject* maybe_obj = Heap::AllocateFixedArray(2);
3689 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
3690 }
Steve Block6ded16b2010-05-10 14:33:55 +01003691 FixedArray* pair = FixedArray::cast(obj);
3692 pair->set(0, name_);
3693 pair->set(1, code_);
3694 return pair;
3695 }
3696
3697 private:
3698 String* name_;
3699 Code::Flags flags_;
3700 Code* code_;
3701};
3702
3703
3704Object* CodeCacheHashTable::Lookup(String* name, Code::Flags flags) {
3705 CodeCacheHashTableKey key(name, flags);
3706 int entry = FindEntry(&key);
3707 if (entry == kNotFound) return Heap::undefined_value();
3708 return get(EntryToIndex(entry) + 1);
3709}
3710
3711
John Reck59135872010-11-02 12:39:01 -07003712MaybeObject* CodeCacheHashTable::Put(String* name, Code* code) {
Steve Block6ded16b2010-05-10 14:33:55 +01003713 CodeCacheHashTableKey key(name, code);
John Reck59135872010-11-02 12:39:01 -07003714 Object* obj;
3715 { MaybeObject* maybe_obj = EnsureCapacity(1, &key);
3716 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
3717 }
Steve Block6ded16b2010-05-10 14:33:55 +01003718
3719 // Don't use this, as the table might have grown.
3720 CodeCacheHashTable* cache = reinterpret_cast<CodeCacheHashTable*>(obj);
3721
3722 int entry = cache->FindInsertionEntry(key.Hash());
John Reck59135872010-11-02 12:39:01 -07003723 Object* k;
3724 { MaybeObject* maybe_k = key.AsObject();
3725 if (!maybe_k->ToObject(&k)) return maybe_k;
3726 }
Steve Block6ded16b2010-05-10 14:33:55 +01003727
3728 cache->set(EntryToIndex(entry), k);
3729 cache->set(EntryToIndex(entry) + 1, code);
3730 cache->ElementAdded();
3731 return cache;
3732}
3733
3734
3735int CodeCacheHashTable::GetIndex(String* name, Code::Flags flags) {
3736 CodeCacheHashTableKey key(name, flags);
3737 int entry = FindEntry(&key);
3738 return (entry == kNotFound) ? -1 : entry;
3739}
3740
3741
3742void CodeCacheHashTable::RemoveByIndex(int index) {
3743 ASSERT(index >= 0);
3744 set(EntryToIndex(index), Heap::null_value());
3745 set(EntryToIndex(index) + 1, Heap::null_value());
3746 ElementRemoved();
Steve Blocka7e24c12009-10-30 11:49:00 +00003747}
3748
3749
Steve Blocka7e24c12009-10-30 11:49:00 +00003750static bool HasKey(FixedArray* array, Object* key) {
3751 int len0 = array->length();
3752 for (int i = 0; i < len0; i++) {
3753 Object* element = array->get(i);
3754 if (element->IsSmi() && key->IsSmi() && (element == key)) return true;
3755 if (element->IsString() &&
3756 key->IsString() && String::cast(element)->Equals(String::cast(key))) {
3757 return true;
3758 }
3759 }
3760 return false;
3761}
3762
3763
John Reck59135872010-11-02 12:39:01 -07003764MaybeObject* FixedArray::AddKeysFromJSArray(JSArray* array) {
Steve Block3ce2e202009-11-05 08:53:23 +00003765 ASSERT(!array->HasPixelElements() && !array->HasExternalArrayElements());
Steve Blocka7e24c12009-10-30 11:49:00 +00003766 switch (array->GetElementsKind()) {
3767 case JSObject::FAST_ELEMENTS:
3768 return UnionOfKeys(FixedArray::cast(array->elements()));
3769 case JSObject::DICTIONARY_ELEMENTS: {
3770 NumberDictionary* dict = array->element_dictionary();
3771 int size = dict->NumberOfElements();
3772
3773 // Allocate a temporary fixed array.
John Reck59135872010-11-02 12:39:01 -07003774 Object* object;
3775 { MaybeObject* maybe_object = Heap::AllocateFixedArray(size);
3776 if (!maybe_object->ToObject(&object)) return maybe_object;
3777 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003778 FixedArray* key_array = FixedArray::cast(object);
3779
3780 int capacity = dict->Capacity();
3781 int pos = 0;
3782 // Copy the elements from the JSArray to the temporary fixed array.
3783 for (int i = 0; i < capacity; i++) {
3784 if (dict->IsKey(dict->KeyAt(i))) {
3785 key_array->set(pos++, dict->ValueAt(i));
3786 }
3787 }
3788 // Compute the union of this and the temporary fixed array.
3789 return UnionOfKeys(key_array);
3790 }
3791 default:
3792 UNREACHABLE();
3793 }
3794 UNREACHABLE();
3795 return Heap::null_value(); // Failure case needs to "return" a value.
3796}
3797
3798
John Reck59135872010-11-02 12:39:01 -07003799MaybeObject* FixedArray::UnionOfKeys(FixedArray* other) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003800 int len0 = length();
Ben Murdochf87a2032010-10-22 12:50:53 +01003801#ifdef DEBUG
3802 if (FLAG_enable_slow_asserts) {
3803 for (int i = 0; i < len0; i++) {
3804 ASSERT(get(i)->IsString() || get(i)->IsNumber());
3805 }
3806 }
3807#endif
Steve Blocka7e24c12009-10-30 11:49:00 +00003808 int len1 = other->length();
Ben Murdochf87a2032010-10-22 12:50:53 +01003809 // Optimize if 'other' is empty.
3810 // We cannot optimize if 'this' is empty, as other may have holes
3811 // or non keys.
Steve Blocka7e24c12009-10-30 11:49:00 +00003812 if (len1 == 0) return this;
3813
3814 // Compute how many elements are not in this.
3815 int extra = 0;
3816 for (int y = 0; y < len1; y++) {
3817 Object* value = other->get(y);
3818 if (!value->IsTheHole() && !HasKey(this, value)) extra++;
3819 }
3820
3821 if (extra == 0) return this;
3822
3823 // Allocate the result
John Reck59135872010-11-02 12:39:01 -07003824 Object* obj;
3825 { MaybeObject* maybe_obj = Heap::AllocateFixedArray(len0 + extra);
3826 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
3827 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003828 // Fill in the content
Leon Clarke4515c472010-02-03 11:58:03 +00003829 AssertNoAllocation no_gc;
Steve Blocka7e24c12009-10-30 11:49:00 +00003830 FixedArray* result = FixedArray::cast(obj);
Leon Clarke4515c472010-02-03 11:58:03 +00003831 WriteBarrierMode mode = result->GetWriteBarrierMode(no_gc);
Steve Blocka7e24c12009-10-30 11:49:00 +00003832 for (int i = 0; i < len0; i++) {
Ben Murdochf87a2032010-10-22 12:50:53 +01003833 Object* e = get(i);
3834 ASSERT(e->IsString() || e->IsNumber());
3835 result->set(i, e, mode);
Steve Blocka7e24c12009-10-30 11:49:00 +00003836 }
3837 // Fill in the extra keys.
3838 int index = 0;
3839 for (int y = 0; y < len1; y++) {
3840 Object* value = other->get(y);
3841 if (!value->IsTheHole() && !HasKey(this, value)) {
Ben Murdochf87a2032010-10-22 12:50:53 +01003842 Object* e = other->get(y);
3843 ASSERT(e->IsString() || e->IsNumber());
3844 result->set(len0 + index, e, mode);
Steve Blocka7e24c12009-10-30 11:49:00 +00003845 index++;
3846 }
3847 }
3848 ASSERT(extra == index);
3849 return result;
3850}
3851
3852
John Reck59135872010-11-02 12:39:01 -07003853MaybeObject* FixedArray::CopySize(int new_length) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003854 if (new_length == 0) return Heap::empty_fixed_array();
John Reck59135872010-11-02 12:39:01 -07003855 Object* obj;
3856 { MaybeObject* maybe_obj = Heap::AllocateFixedArray(new_length);
3857 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
3858 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003859 FixedArray* result = FixedArray::cast(obj);
3860 // Copy the content
Leon Clarke4515c472010-02-03 11:58:03 +00003861 AssertNoAllocation no_gc;
Steve Blocka7e24c12009-10-30 11:49:00 +00003862 int len = length();
3863 if (new_length < len) len = new_length;
3864 result->set_map(map());
Leon Clarke4515c472010-02-03 11:58:03 +00003865 WriteBarrierMode mode = result->GetWriteBarrierMode(no_gc);
Steve Blocka7e24c12009-10-30 11:49:00 +00003866 for (int i = 0; i < len; i++) {
3867 result->set(i, get(i), mode);
3868 }
3869 return result;
3870}
3871
3872
3873void FixedArray::CopyTo(int pos, FixedArray* dest, int dest_pos, int len) {
Leon Clarke4515c472010-02-03 11:58:03 +00003874 AssertNoAllocation no_gc;
3875 WriteBarrierMode mode = dest->GetWriteBarrierMode(no_gc);
Steve Blocka7e24c12009-10-30 11:49:00 +00003876 for (int index = 0; index < len; index++) {
3877 dest->set(dest_pos+index, get(pos+index), mode);
3878 }
3879}
3880
3881
3882#ifdef DEBUG
3883bool FixedArray::IsEqualTo(FixedArray* other) {
3884 if (length() != other->length()) return false;
3885 for (int i = 0 ; i < length(); ++i) {
3886 if (get(i) != other->get(i)) return false;
3887 }
3888 return true;
3889}
3890#endif
3891
3892
John Reck59135872010-11-02 12:39:01 -07003893MaybeObject* DescriptorArray::Allocate(int number_of_descriptors) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003894 if (number_of_descriptors == 0) {
3895 return Heap::empty_descriptor_array();
3896 }
3897 // Allocate the array of keys.
John Reck59135872010-11-02 12:39:01 -07003898 Object* array;
3899 { MaybeObject* maybe_array =
3900 Heap::AllocateFixedArray(ToKeyIndex(number_of_descriptors));
3901 if (!maybe_array->ToObject(&array)) return maybe_array;
3902 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003903 // Do not use DescriptorArray::cast on incomplete object.
3904 FixedArray* result = FixedArray::cast(array);
3905
3906 // Allocate the content array and set it in the descriptor array.
John Reck59135872010-11-02 12:39:01 -07003907 { MaybeObject* maybe_array =
3908 Heap::AllocateFixedArray(number_of_descriptors << 1);
3909 if (!maybe_array->ToObject(&array)) return maybe_array;
3910 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003911 result->set(kContentArrayIndex, array);
3912 result->set(kEnumerationIndexIndex,
Leon Clarke4515c472010-02-03 11:58:03 +00003913 Smi::FromInt(PropertyDetails::kInitialIndex));
Steve Blocka7e24c12009-10-30 11:49:00 +00003914 return result;
3915}
3916
3917
3918void DescriptorArray::SetEnumCache(FixedArray* bridge_storage,
3919 FixedArray* new_cache) {
3920 ASSERT(bridge_storage->length() >= kEnumCacheBridgeLength);
3921 if (HasEnumCache()) {
3922 FixedArray::cast(get(kEnumerationIndexIndex))->
3923 set(kEnumCacheBridgeCacheIndex, new_cache);
3924 } else {
3925 if (IsEmpty()) return; // Do nothing for empty descriptor array.
3926 FixedArray::cast(bridge_storage)->
3927 set(kEnumCacheBridgeCacheIndex, new_cache);
3928 fast_set(FixedArray::cast(bridge_storage),
3929 kEnumCacheBridgeEnumIndex,
3930 get(kEnumerationIndexIndex));
3931 set(kEnumerationIndexIndex, bridge_storage);
3932 }
3933}
3934
3935
John Reck59135872010-11-02 12:39:01 -07003936MaybeObject* DescriptorArray::CopyInsert(Descriptor* descriptor,
3937 TransitionFlag transition_flag) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003938 // Transitions are only kept when inserting another transition.
3939 // This precondition is not required by this function's implementation, but
3940 // is currently required by the semantics of maps, so we check it.
3941 // Conversely, we filter after replacing, so replacing a transition and
3942 // removing all other transitions is not supported.
3943 bool remove_transitions = transition_flag == REMOVE_TRANSITIONS;
3944 ASSERT(remove_transitions == !descriptor->GetDetails().IsTransition());
3945 ASSERT(descriptor->GetDetails().type() != NULL_DESCRIPTOR);
3946
3947 // Ensure the key is a symbol.
John Reck59135872010-11-02 12:39:01 -07003948 Object* result;
3949 { MaybeObject* maybe_result = descriptor->KeyToSymbol();
3950 if (!maybe_result->ToObject(&result)) return maybe_result;
3951 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003952
3953 int transitions = 0;
3954 int null_descriptors = 0;
3955 if (remove_transitions) {
3956 for (int i = 0; i < number_of_descriptors(); i++) {
3957 if (IsTransition(i)) transitions++;
3958 if (IsNullDescriptor(i)) null_descriptors++;
3959 }
3960 } else {
3961 for (int i = 0; i < number_of_descriptors(); i++) {
3962 if (IsNullDescriptor(i)) null_descriptors++;
3963 }
3964 }
3965 int new_size = number_of_descriptors() - transitions - null_descriptors;
3966
3967 // If key is in descriptor, we replace it in-place when filtering.
3968 // Count a null descriptor for key as inserted, not replaced.
3969 int index = Search(descriptor->GetKey());
3970 const bool inserting = (index == kNotFound);
3971 const bool replacing = !inserting;
3972 bool keep_enumeration_index = false;
3973 if (inserting) {
3974 ++new_size;
3975 }
3976 if (replacing) {
3977 // We are replacing an existing descriptor. We keep the enumeration
3978 // index of a visible property.
3979 PropertyType t = PropertyDetails(GetDetails(index)).type();
3980 if (t == CONSTANT_FUNCTION ||
3981 t == FIELD ||
3982 t == CALLBACKS ||
3983 t == INTERCEPTOR) {
3984 keep_enumeration_index = true;
3985 } else if (remove_transitions) {
3986 // Replaced descriptor has been counted as removed if it is
3987 // a transition that will be replaced. Adjust count in this case.
3988 ++new_size;
3989 }
3990 }
John Reck59135872010-11-02 12:39:01 -07003991 { MaybeObject* maybe_result = Allocate(new_size);
3992 if (!maybe_result->ToObject(&result)) return maybe_result;
3993 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003994 DescriptorArray* new_descriptors = DescriptorArray::cast(result);
3995 // Set the enumeration index in the descriptors and set the enumeration index
3996 // in the result.
3997 int enumeration_index = NextEnumerationIndex();
3998 if (!descriptor->GetDetails().IsTransition()) {
3999 if (keep_enumeration_index) {
4000 descriptor->SetEnumerationIndex(
4001 PropertyDetails(GetDetails(index)).index());
4002 } else {
4003 descriptor->SetEnumerationIndex(enumeration_index);
4004 ++enumeration_index;
4005 }
4006 }
4007 new_descriptors->SetNextEnumerationIndex(enumeration_index);
4008
4009 // Copy the descriptors, filtering out transitions and null descriptors,
4010 // and inserting or replacing a descriptor.
4011 uint32_t descriptor_hash = descriptor->GetKey()->Hash();
4012 int from_index = 0;
4013 int to_index = 0;
4014
4015 for (; from_index < number_of_descriptors(); from_index++) {
4016 String* key = GetKey(from_index);
4017 if (key->Hash() > descriptor_hash || key == descriptor->GetKey()) {
4018 break;
4019 }
4020 if (IsNullDescriptor(from_index)) continue;
4021 if (remove_transitions && IsTransition(from_index)) continue;
4022 new_descriptors->CopyFrom(to_index++, this, from_index);
4023 }
4024
4025 new_descriptors->Set(to_index++, descriptor);
4026 if (replacing) from_index++;
4027
4028 for (; from_index < number_of_descriptors(); from_index++) {
4029 if (IsNullDescriptor(from_index)) continue;
4030 if (remove_transitions && IsTransition(from_index)) continue;
4031 new_descriptors->CopyFrom(to_index++, this, from_index);
4032 }
4033
4034 ASSERT(to_index == new_descriptors->number_of_descriptors());
4035 SLOW_ASSERT(new_descriptors->IsSortedNoDuplicates());
4036
4037 return new_descriptors;
4038}
4039
4040
John Reck59135872010-11-02 12:39:01 -07004041MaybeObject* DescriptorArray::RemoveTransitions() {
Steve Blocka7e24c12009-10-30 11:49:00 +00004042 // Remove all transitions and null descriptors. Return a copy of the array
4043 // with all transitions removed, or a Failure object if the new array could
4044 // not be allocated.
4045
4046 // Compute the size of the map transition entries to be removed.
4047 int num_removed = 0;
4048 for (int i = 0; i < number_of_descriptors(); i++) {
4049 if (!IsProperty(i)) num_removed++;
4050 }
4051
4052 // Allocate the new descriptor array.
John Reck59135872010-11-02 12:39:01 -07004053 Object* result;
4054 { MaybeObject* maybe_result = Allocate(number_of_descriptors() - num_removed);
4055 if (!maybe_result->ToObject(&result)) return maybe_result;
4056 }
Steve Blocka7e24c12009-10-30 11:49:00 +00004057 DescriptorArray* new_descriptors = DescriptorArray::cast(result);
4058
4059 // Copy the content.
4060 int next_descriptor = 0;
4061 for (int i = 0; i < number_of_descriptors(); i++) {
4062 if (IsProperty(i)) new_descriptors->CopyFrom(next_descriptor++, this, i);
4063 }
4064 ASSERT(next_descriptor == new_descriptors->number_of_descriptors());
4065
4066 return new_descriptors;
4067}
4068
4069
Kristian Monsen0d5e1162010-09-30 15:31:59 +01004070void DescriptorArray::SortUnchecked() {
Steve Blocka7e24c12009-10-30 11:49:00 +00004071 // In-place heap sort.
4072 int len = number_of_descriptors();
4073
4074 // Bottom-up max-heap construction.
Steve Block6ded16b2010-05-10 14:33:55 +01004075 // Index of the last node with children
4076 const int max_parent_index = (len / 2) - 1;
4077 for (int i = max_parent_index; i >= 0; --i) {
4078 int parent_index = i;
4079 const uint32_t parent_hash = GetKey(i)->Hash();
4080 while (parent_index <= max_parent_index) {
4081 int child_index = 2 * parent_index + 1;
Steve Blocka7e24c12009-10-30 11:49:00 +00004082 uint32_t child_hash = GetKey(child_index)->Hash();
Steve Block6ded16b2010-05-10 14:33:55 +01004083 if (child_index + 1 < len) {
4084 uint32_t right_child_hash = GetKey(child_index + 1)->Hash();
4085 if (right_child_hash > child_hash) {
4086 child_index++;
4087 child_hash = right_child_hash;
4088 }
Steve Blocka7e24c12009-10-30 11:49:00 +00004089 }
Steve Block6ded16b2010-05-10 14:33:55 +01004090 if (child_hash <= parent_hash) break;
4091 Swap(parent_index, child_index);
4092 // Now element at child_index could be < its children.
4093 parent_index = child_index; // parent_hash remains correct.
Steve Blocka7e24c12009-10-30 11:49:00 +00004094 }
4095 }
4096
4097 // Extract elements and create sorted array.
4098 for (int i = len - 1; i > 0; --i) {
4099 // Put max element at the back of the array.
4100 Swap(0, i);
4101 // Sift down the new top element.
4102 int parent_index = 0;
Steve Block6ded16b2010-05-10 14:33:55 +01004103 const uint32_t parent_hash = GetKey(parent_index)->Hash();
4104 const int max_parent_index = (i / 2) - 1;
4105 while (parent_index <= max_parent_index) {
4106 int child_index = parent_index * 2 + 1;
4107 uint32_t child_hash = GetKey(child_index)->Hash();
4108 if (child_index + 1 < i) {
4109 uint32_t right_child_hash = GetKey(child_index + 1)->Hash();
4110 if (right_child_hash > child_hash) {
4111 child_index++;
4112 child_hash = right_child_hash;
4113 }
Steve Blocka7e24c12009-10-30 11:49:00 +00004114 }
Steve Block6ded16b2010-05-10 14:33:55 +01004115 if (child_hash <= parent_hash) break;
4116 Swap(parent_index, child_index);
4117 parent_index = child_index;
Steve Blocka7e24c12009-10-30 11:49:00 +00004118 }
4119 }
Kristian Monsen0d5e1162010-09-30 15:31:59 +01004120}
Steve Blocka7e24c12009-10-30 11:49:00 +00004121
Kristian Monsen0d5e1162010-09-30 15:31:59 +01004122
4123void DescriptorArray::Sort() {
4124 SortUnchecked();
Steve Blocka7e24c12009-10-30 11:49:00 +00004125 SLOW_ASSERT(IsSortedNoDuplicates());
4126}
4127
4128
4129int DescriptorArray::BinarySearch(String* name, int low, int high) {
4130 uint32_t hash = name->Hash();
4131
4132 while (low <= high) {
4133 int mid = (low + high) / 2;
4134 String* mid_name = GetKey(mid);
4135 uint32_t mid_hash = mid_name->Hash();
4136
4137 if (mid_hash > hash) {
4138 high = mid - 1;
4139 continue;
4140 }
4141 if (mid_hash < hash) {
4142 low = mid + 1;
4143 continue;
4144 }
4145 // Found an element with the same hash-code.
4146 ASSERT(hash == mid_hash);
4147 // There might be more, so we find the first one and
4148 // check them all to see if we have a match.
4149 if (name == mid_name && !is_null_descriptor(mid)) return mid;
4150 while ((mid > low) && (GetKey(mid - 1)->Hash() == hash)) mid--;
4151 for (; (mid <= high) && (GetKey(mid)->Hash() == hash); mid++) {
4152 if (GetKey(mid)->Equals(name) && !is_null_descriptor(mid)) return mid;
4153 }
4154 break;
4155 }
4156 return kNotFound;
4157}
4158
4159
4160int DescriptorArray::LinearSearch(String* name, int len) {
4161 uint32_t hash = name->Hash();
4162 for (int number = 0; number < len; number++) {
4163 String* entry = GetKey(number);
4164 if ((entry->Hash() == hash) &&
4165 name->Equals(entry) &&
4166 !is_null_descriptor(number)) {
4167 return number;
4168 }
4169 }
4170 return kNotFound;
4171}
4172
4173
Ben Murdochb0fe1622011-05-05 13:52:32 +01004174MaybeObject* DeoptimizationInputData::Allocate(int deopt_entry_count,
4175 PretenureFlag pretenure) {
4176 ASSERT(deopt_entry_count > 0);
4177 return Heap::AllocateFixedArray(LengthFor(deopt_entry_count),
4178 pretenure);
4179}
4180
4181
4182MaybeObject* DeoptimizationOutputData::Allocate(int number_of_deopt_points,
4183 PretenureFlag pretenure) {
4184 if (number_of_deopt_points == 0) return Heap::empty_fixed_array();
4185 return Heap::AllocateFixedArray(LengthOfFixedArray(number_of_deopt_points),
4186 pretenure);
4187}
4188
4189
Steve Blocka7e24c12009-10-30 11:49:00 +00004190#ifdef DEBUG
4191bool DescriptorArray::IsEqualTo(DescriptorArray* other) {
4192 if (IsEmpty()) return other->IsEmpty();
4193 if (other->IsEmpty()) return false;
4194 if (length() != other->length()) return false;
4195 for (int i = 0; i < length(); ++i) {
4196 if (get(i) != other->get(i) && i != kContentArrayIndex) return false;
4197 }
4198 return GetContentArray()->IsEqualTo(other->GetContentArray());
4199}
4200#endif
4201
4202
4203static StaticResource<StringInputBuffer> string_input_buffer;
4204
4205
4206bool String::LooksValid() {
4207 if (!Heap::Contains(this)) return false;
4208 return true;
4209}
4210
4211
4212int String::Utf8Length() {
4213 if (IsAsciiRepresentation()) return length();
4214 // Attempt to flatten before accessing the string. It probably
4215 // doesn't make Utf8Length faster, but it is very likely that
4216 // the string will be accessed later (for example by WriteUtf8)
4217 // so it's still a good idea.
Steve Block6ded16b2010-05-10 14:33:55 +01004218 TryFlatten();
Steve Blocka7e24c12009-10-30 11:49:00 +00004219 Access<StringInputBuffer> buffer(&string_input_buffer);
4220 buffer->Reset(0, this);
4221 int result = 0;
4222 while (buffer->has_more())
4223 result += unibrow::Utf8::Length(buffer->GetNext());
4224 return result;
4225}
4226
4227
4228Vector<const char> String::ToAsciiVector() {
4229 ASSERT(IsAsciiRepresentation());
4230 ASSERT(IsFlat());
4231
4232 int offset = 0;
4233 int length = this->length();
4234 StringRepresentationTag string_tag = StringShape(this).representation_tag();
4235 String* string = this;
Steve Blockd0582a62009-12-15 09:54:21 +00004236 if (string_tag == kConsStringTag) {
Steve Blocka7e24c12009-10-30 11:49:00 +00004237 ConsString* cons = ConsString::cast(string);
4238 ASSERT(cons->second()->length() == 0);
4239 string = cons->first();
4240 string_tag = StringShape(string).representation_tag();
4241 }
4242 if (string_tag == kSeqStringTag) {
4243 SeqAsciiString* seq = SeqAsciiString::cast(string);
4244 char* start = seq->GetChars();
4245 return Vector<const char>(start + offset, length);
4246 }
4247 ASSERT(string_tag == kExternalStringTag);
4248 ExternalAsciiString* ext = ExternalAsciiString::cast(string);
4249 const char* start = ext->resource()->data();
4250 return Vector<const char>(start + offset, length);
4251}
4252
4253
4254Vector<const uc16> String::ToUC16Vector() {
4255 ASSERT(IsTwoByteRepresentation());
4256 ASSERT(IsFlat());
4257
4258 int offset = 0;
4259 int length = this->length();
4260 StringRepresentationTag string_tag = StringShape(this).representation_tag();
4261 String* string = this;
Steve Blockd0582a62009-12-15 09:54:21 +00004262 if (string_tag == kConsStringTag) {
Steve Blocka7e24c12009-10-30 11:49:00 +00004263 ConsString* cons = ConsString::cast(string);
4264 ASSERT(cons->second()->length() == 0);
4265 string = cons->first();
4266 string_tag = StringShape(string).representation_tag();
4267 }
4268 if (string_tag == kSeqStringTag) {
4269 SeqTwoByteString* seq = SeqTwoByteString::cast(string);
4270 return Vector<const uc16>(seq->GetChars() + offset, length);
4271 }
4272 ASSERT(string_tag == kExternalStringTag);
4273 ExternalTwoByteString* ext = ExternalTwoByteString::cast(string);
4274 const uc16* start =
4275 reinterpret_cast<const uc16*>(ext->resource()->data());
4276 return Vector<const uc16>(start + offset, length);
4277}
4278
4279
4280SmartPointer<char> String::ToCString(AllowNullsFlag allow_nulls,
4281 RobustnessFlag robust_flag,
4282 int offset,
4283 int length,
4284 int* length_return) {
4285 ASSERT(NativeAllocationChecker::allocation_allowed());
4286 if (robust_flag == ROBUST_STRING_TRAVERSAL && !LooksValid()) {
4287 return SmartPointer<char>(NULL);
4288 }
4289
4290 // Negative length means the to the end of the string.
4291 if (length < 0) length = kMaxInt - offset;
4292
4293 // Compute the size of the UTF-8 string. Start at the specified offset.
4294 Access<StringInputBuffer> buffer(&string_input_buffer);
4295 buffer->Reset(offset, this);
4296 int character_position = offset;
4297 int utf8_bytes = 0;
4298 while (buffer->has_more()) {
4299 uint16_t character = buffer->GetNext();
4300 if (character_position < offset + length) {
4301 utf8_bytes += unibrow::Utf8::Length(character);
4302 }
4303 character_position++;
4304 }
4305
4306 if (length_return) {
4307 *length_return = utf8_bytes;
4308 }
4309
4310 char* result = NewArray<char>(utf8_bytes + 1);
4311
4312 // Convert the UTF-16 string to a UTF-8 buffer. Start at the specified offset.
4313 buffer->Rewind();
4314 buffer->Seek(offset);
4315 character_position = offset;
4316 int utf8_byte_position = 0;
4317 while (buffer->has_more()) {
4318 uint16_t character = buffer->GetNext();
4319 if (character_position < offset + length) {
4320 if (allow_nulls == DISALLOW_NULLS && character == 0) {
4321 character = ' ';
4322 }
4323 utf8_byte_position +=
4324 unibrow::Utf8::Encode(result + utf8_byte_position, character);
4325 }
4326 character_position++;
4327 }
4328 result[utf8_byte_position] = 0;
4329 return SmartPointer<char>(result);
4330}
4331
4332
4333SmartPointer<char> String::ToCString(AllowNullsFlag allow_nulls,
4334 RobustnessFlag robust_flag,
4335 int* length_return) {
4336 return ToCString(allow_nulls, robust_flag, 0, -1, length_return);
4337}
4338
4339
4340const uc16* String::GetTwoByteData() {
4341 return GetTwoByteData(0);
4342}
4343
4344
4345const uc16* String::GetTwoByteData(unsigned start) {
4346 ASSERT(!IsAsciiRepresentation());
4347 switch (StringShape(this).representation_tag()) {
4348 case kSeqStringTag:
4349 return SeqTwoByteString::cast(this)->SeqTwoByteStringGetData(start);
4350 case kExternalStringTag:
4351 return ExternalTwoByteString::cast(this)->
4352 ExternalTwoByteStringGetData(start);
Steve Blocka7e24c12009-10-30 11:49:00 +00004353 case kConsStringTag:
4354 UNREACHABLE();
4355 return NULL;
4356 }
4357 UNREACHABLE();
4358 return NULL;
4359}
4360
4361
4362SmartPointer<uc16> String::ToWideCString(RobustnessFlag robust_flag) {
4363 ASSERT(NativeAllocationChecker::allocation_allowed());
4364
4365 if (robust_flag == ROBUST_STRING_TRAVERSAL && !LooksValid()) {
4366 return SmartPointer<uc16>();
4367 }
4368
4369 Access<StringInputBuffer> buffer(&string_input_buffer);
4370 buffer->Reset(this);
4371
4372 uc16* result = NewArray<uc16>(length() + 1);
4373
4374 int i = 0;
4375 while (buffer->has_more()) {
4376 uint16_t character = buffer->GetNext();
4377 result[i++] = character;
4378 }
4379 result[i] = 0;
4380 return SmartPointer<uc16>(result);
4381}
4382
4383
4384const uc16* SeqTwoByteString::SeqTwoByteStringGetData(unsigned start) {
4385 return reinterpret_cast<uc16*>(
4386 reinterpret_cast<char*>(this) - kHeapObjectTag + kHeaderSize) + start;
4387}
4388
4389
4390void SeqTwoByteString::SeqTwoByteStringReadBlockIntoBuffer(ReadBlockBuffer* rbb,
4391 unsigned* offset_ptr,
4392 unsigned max_chars) {
4393 unsigned chars_read = 0;
4394 unsigned offset = *offset_ptr;
4395 while (chars_read < max_chars) {
4396 uint16_t c = *reinterpret_cast<uint16_t*>(
4397 reinterpret_cast<char*>(this) -
4398 kHeapObjectTag + kHeaderSize + offset * kShortSize);
4399 if (c <= kMaxAsciiCharCode) {
4400 // Fast case for ASCII characters. Cursor is an input output argument.
4401 if (!unibrow::CharacterStream::EncodeAsciiCharacter(c,
4402 rbb->util_buffer,
4403 rbb->capacity,
4404 rbb->cursor)) {
4405 break;
4406 }
4407 } else {
4408 if (!unibrow::CharacterStream::EncodeNonAsciiCharacter(c,
4409 rbb->util_buffer,
4410 rbb->capacity,
4411 rbb->cursor)) {
4412 break;
4413 }
4414 }
4415 offset++;
4416 chars_read++;
4417 }
4418 *offset_ptr = offset;
4419 rbb->remaining += chars_read;
4420}
4421
4422
4423const unibrow::byte* SeqAsciiString::SeqAsciiStringReadBlock(
4424 unsigned* remaining,
4425 unsigned* offset_ptr,
4426 unsigned max_chars) {
4427 const unibrow::byte* b = reinterpret_cast<unibrow::byte*>(this) -
4428 kHeapObjectTag + kHeaderSize + *offset_ptr * kCharSize;
4429 *remaining = max_chars;
4430 *offset_ptr += max_chars;
4431 return b;
4432}
4433
4434
4435// This will iterate unless the block of string data spans two 'halves' of
4436// a ConsString, in which case it will recurse. Since the block of string
4437// data to be read has a maximum size this limits the maximum recursion
4438// depth to something sane. Since C++ does not have tail call recursion
4439// elimination, the iteration must be explicit. Since this is not an
4440// -IntoBuffer method it can delegate to one of the efficient
4441// *AsciiStringReadBlock routines.
4442const unibrow::byte* ConsString::ConsStringReadBlock(ReadBlockBuffer* rbb,
4443 unsigned* offset_ptr,
4444 unsigned max_chars) {
4445 ConsString* current = this;
4446 unsigned offset = *offset_ptr;
4447 int offset_correction = 0;
4448
4449 while (true) {
4450 String* left = current->first();
4451 unsigned left_length = (unsigned)left->length();
4452 if (left_length > offset &&
4453 (max_chars <= left_length - offset ||
4454 (rbb->capacity <= left_length - offset &&
4455 (max_chars = left_length - offset, true)))) { // comma operator!
4456 // Left hand side only - iterate unless we have reached the bottom of
4457 // the cons tree. The assignment on the left of the comma operator is
4458 // in order to make use of the fact that the -IntoBuffer routines can
4459 // produce at most 'capacity' characters. This enables us to postpone
4460 // the point where we switch to the -IntoBuffer routines (below) in order
4461 // to maximize the chances of delegating a big chunk of work to the
4462 // efficient *AsciiStringReadBlock routines.
4463 if (StringShape(left).IsCons()) {
4464 current = ConsString::cast(left);
4465 continue;
4466 } else {
4467 const unibrow::byte* answer =
4468 String::ReadBlock(left, rbb, &offset, max_chars);
4469 *offset_ptr = offset + offset_correction;
4470 return answer;
4471 }
4472 } else if (left_length <= offset) {
4473 // Right hand side only - iterate unless we have reached the bottom of
4474 // the cons tree.
4475 String* right = current->second();
4476 offset -= left_length;
4477 offset_correction += left_length;
4478 if (StringShape(right).IsCons()) {
4479 current = ConsString::cast(right);
4480 continue;
4481 } else {
4482 const unibrow::byte* answer =
4483 String::ReadBlock(right, rbb, &offset, max_chars);
4484 *offset_ptr = offset + offset_correction;
4485 return answer;
4486 }
4487 } else {
4488 // The block to be read spans two sides of the ConsString, so we call the
4489 // -IntoBuffer version, which will recurse. The -IntoBuffer methods
4490 // are able to assemble data from several part strings because they use
4491 // the util_buffer to store their data and never return direct pointers
4492 // to their storage. We don't try to read more than the buffer capacity
4493 // here or we can get too much recursion.
4494 ASSERT(rbb->remaining == 0);
4495 ASSERT(rbb->cursor == 0);
4496 current->ConsStringReadBlockIntoBuffer(
4497 rbb,
4498 &offset,
4499 max_chars > rbb->capacity ? rbb->capacity : max_chars);
4500 *offset_ptr = offset + offset_correction;
4501 return rbb->util_buffer;
4502 }
4503 }
4504}
4505
4506
Steve Blocka7e24c12009-10-30 11:49:00 +00004507uint16_t ExternalAsciiString::ExternalAsciiStringGet(int index) {
4508 ASSERT(index >= 0 && index < length());
4509 return resource()->data()[index];
4510}
4511
4512
4513const unibrow::byte* ExternalAsciiString::ExternalAsciiStringReadBlock(
4514 unsigned* remaining,
4515 unsigned* offset_ptr,
4516 unsigned max_chars) {
4517 // Cast const char* to unibrow::byte* (signedness difference).
4518 const unibrow::byte* b =
4519 reinterpret_cast<const unibrow::byte*>(resource()->data()) + *offset_ptr;
4520 *remaining = max_chars;
4521 *offset_ptr += max_chars;
4522 return b;
4523}
4524
4525
4526const uc16* ExternalTwoByteString::ExternalTwoByteStringGetData(
4527 unsigned start) {
4528 return resource()->data() + start;
4529}
4530
4531
4532uint16_t ExternalTwoByteString::ExternalTwoByteStringGet(int index) {
4533 ASSERT(index >= 0 && index < length());
4534 return resource()->data()[index];
4535}
4536
4537
4538void ExternalTwoByteString::ExternalTwoByteStringReadBlockIntoBuffer(
4539 ReadBlockBuffer* rbb,
4540 unsigned* offset_ptr,
4541 unsigned max_chars) {
4542 unsigned chars_read = 0;
4543 unsigned offset = *offset_ptr;
4544 const uint16_t* data = resource()->data();
4545 while (chars_read < max_chars) {
4546 uint16_t c = data[offset];
4547 if (c <= kMaxAsciiCharCode) {
4548 // Fast case for ASCII characters. Cursor is an input output argument.
4549 if (!unibrow::CharacterStream::EncodeAsciiCharacter(c,
4550 rbb->util_buffer,
4551 rbb->capacity,
4552 rbb->cursor))
4553 break;
4554 } else {
4555 if (!unibrow::CharacterStream::EncodeNonAsciiCharacter(c,
4556 rbb->util_buffer,
4557 rbb->capacity,
4558 rbb->cursor))
4559 break;
4560 }
4561 offset++;
4562 chars_read++;
4563 }
4564 *offset_ptr = offset;
4565 rbb->remaining += chars_read;
4566}
4567
4568
4569void SeqAsciiString::SeqAsciiStringReadBlockIntoBuffer(ReadBlockBuffer* rbb,
4570 unsigned* offset_ptr,
4571 unsigned max_chars) {
4572 unsigned capacity = rbb->capacity - rbb->cursor;
4573 if (max_chars > capacity) max_chars = capacity;
4574 memcpy(rbb->util_buffer + rbb->cursor,
4575 reinterpret_cast<char*>(this) - kHeapObjectTag + kHeaderSize +
4576 *offset_ptr * kCharSize,
4577 max_chars);
4578 rbb->remaining += max_chars;
4579 *offset_ptr += max_chars;
4580 rbb->cursor += max_chars;
4581}
4582
4583
4584void ExternalAsciiString::ExternalAsciiStringReadBlockIntoBuffer(
4585 ReadBlockBuffer* rbb,
4586 unsigned* offset_ptr,
4587 unsigned max_chars) {
4588 unsigned capacity = rbb->capacity - rbb->cursor;
4589 if (max_chars > capacity) max_chars = capacity;
4590 memcpy(rbb->util_buffer + rbb->cursor,
4591 resource()->data() + *offset_ptr,
4592 max_chars);
4593 rbb->remaining += max_chars;
4594 *offset_ptr += max_chars;
4595 rbb->cursor += max_chars;
4596}
4597
4598
4599// This method determines the type of string involved and then copies
4600// a whole chunk of characters into a buffer, or returns a pointer to a buffer
4601// where they can be found. The pointer is not necessarily valid across a GC
4602// (see AsciiStringReadBlock).
4603const unibrow::byte* String::ReadBlock(String* input,
4604 ReadBlockBuffer* rbb,
4605 unsigned* offset_ptr,
4606 unsigned max_chars) {
4607 ASSERT(*offset_ptr <= static_cast<unsigned>(input->length()));
4608 if (max_chars == 0) {
4609 rbb->remaining = 0;
4610 return NULL;
4611 }
4612 switch (StringShape(input).representation_tag()) {
4613 case kSeqStringTag:
4614 if (input->IsAsciiRepresentation()) {
4615 SeqAsciiString* str = SeqAsciiString::cast(input);
4616 return str->SeqAsciiStringReadBlock(&rbb->remaining,
4617 offset_ptr,
4618 max_chars);
4619 } else {
4620 SeqTwoByteString* str = SeqTwoByteString::cast(input);
4621 str->SeqTwoByteStringReadBlockIntoBuffer(rbb,
4622 offset_ptr,
4623 max_chars);
4624 return rbb->util_buffer;
4625 }
4626 case kConsStringTag:
4627 return ConsString::cast(input)->ConsStringReadBlock(rbb,
4628 offset_ptr,
4629 max_chars);
Steve Blocka7e24c12009-10-30 11:49:00 +00004630 case kExternalStringTag:
4631 if (input->IsAsciiRepresentation()) {
4632 return ExternalAsciiString::cast(input)->ExternalAsciiStringReadBlock(
4633 &rbb->remaining,
4634 offset_ptr,
4635 max_chars);
4636 } else {
4637 ExternalTwoByteString::cast(input)->
4638 ExternalTwoByteStringReadBlockIntoBuffer(rbb,
4639 offset_ptr,
4640 max_chars);
4641 return rbb->util_buffer;
4642 }
4643 default:
4644 break;
4645 }
4646
4647 UNREACHABLE();
4648 return 0;
4649}
4650
4651
4652Relocatable* Relocatable::top_ = NULL;
4653
4654
4655void Relocatable::PostGarbageCollectionProcessing() {
4656 Relocatable* current = top_;
4657 while (current != NULL) {
4658 current->PostGarbageCollection();
4659 current = current->prev_;
4660 }
4661}
4662
4663
4664// Reserve space for statics needing saving and restoring.
4665int Relocatable::ArchiveSpacePerThread() {
4666 return sizeof(top_);
4667}
4668
4669
4670// Archive statics that are thread local.
4671char* Relocatable::ArchiveState(char* to) {
4672 *reinterpret_cast<Relocatable**>(to) = top_;
4673 top_ = NULL;
4674 return to + ArchiveSpacePerThread();
4675}
4676
4677
4678// Restore statics that are thread local.
4679char* Relocatable::RestoreState(char* from) {
4680 top_ = *reinterpret_cast<Relocatable**>(from);
4681 return from + ArchiveSpacePerThread();
4682}
4683
4684
4685char* Relocatable::Iterate(ObjectVisitor* v, char* thread_storage) {
4686 Relocatable* top = *reinterpret_cast<Relocatable**>(thread_storage);
4687 Iterate(v, top);
4688 return thread_storage + ArchiveSpacePerThread();
4689}
4690
4691
4692void Relocatable::Iterate(ObjectVisitor* v) {
4693 Iterate(v, top_);
4694}
4695
4696
4697void Relocatable::Iterate(ObjectVisitor* v, Relocatable* top) {
4698 Relocatable* current = top;
4699 while (current != NULL) {
4700 current->IterateInstance(v);
4701 current = current->prev_;
4702 }
4703}
4704
4705
4706FlatStringReader::FlatStringReader(Handle<String> str)
4707 : str_(str.location()),
4708 length_(str->length()) {
4709 PostGarbageCollection();
4710}
4711
4712
4713FlatStringReader::FlatStringReader(Vector<const char> input)
4714 : str_(0),
4715 is_ascii_(true),
4716 length_(input.length()),
4717 start_(input.start()) { }
4718
4719
4720void FlatStringReader::PostGarbageCollection() {
4721 if (str_ == NULL) return;
4722 Handle<String> str(str_);
4723 ASSERT(str->IsFlat());
4724 is_ascii_ = str->IsAsciiRepresentation();
4725 if (is_ascii_) {
4726 start_ = str->ToAsciiVector().start();
4727 } else {
4728 start_ = str->ToUC16Vector().start();
4729 }
4730}
4731
4732
4733void StringInputBuffer::Seek(unsigned pos) {
4734 Reset(pos, input_);
4735}
4736
4737
4738void SafeStringInputBuffer::Seek(unsigned pos) {
4739 Reset(pos, input_);
4740}
4741
4742
4743// This method determines the type of string involved and then copies
4744// a whole chunk of characters into a buffer. It can be used with strings
4745// that have been glued together to form a ConsString and which must cooperate
4746// to fill up a buffer.
4747void String::ReadBlockIntoBuffer(String* input,
4748 ReadBlockBuffer* rbb,
4749 unsigned* offset_ptr,
4750 unsigned max_chars) {
4751 ASSERT(*offset_ptr <= (unsigned)input->length());
4752 if (max_chars == 0) return;
4753
4754 switch (StringShape(input).representation_tag()) {
4755 case kSeqStringTag:
4756 if (input->IsAsciiRepresentation()) {
4757 SeqAsciiString::cast(input)->SeqAsciiStringReadBlockIntoBuffer(rbb,
4758 offset_ptr,
4759 max_chars);
4760 return;
4761 } else {
4762 SeqTwoByteString::cast(input)->SeqTwoByteStringReadBlockIntoBuffer(rbb,
4763 offset_ptr,
4764 max_chars);
4765 return;
4766 }
4767 case kConsStringTag:
4768 ConsString::cast(input)->ConsStringReadBlockIntoBuffer(rbb,
4769 offset_ptr,
4770 max_chars);
4771 return;
Steve Blocka7e24c12009-10-30 11:49:00 +00004772 case kExternalStringTag:
4773 if (input->IsAsciiRepresentation()) {
Steve Blockd0582a62009-12-15 09:54:21 +00004774 ExternalAsciiString::cast(input)->
4775 ExternalAsciiStringReadBlockIntoBuffer(rbb, offset_ptr, max_chars);
4776 } else {
4777 ExternalTwoByteString::cast(input)->
4778 ExternalTwoByteStringReadBlockIntoBuffer(rbb,
4779 offset_ptr,
4780 max_chars);
Steve Blocka7e24c12009-10-30 11:49:00 +00004781 }
4782 return;
4783 default:
4784 break;
4785 }
4786
4787 UNREACHABLE();
4788 return;
4789}
4790
4791
4792const unibrow::byte* String::ReadBlock(String* input,
4793 unibrow::byte* util_buffer,
4794 unsigned capacity,
4795 unsigned* remaining,
4796 unsigned* offset_ptr) {
4797 ASSERT(*offset_ptr <= (unsigned)input->length());
4798 unsigned chars = input->length() - *offset_ptr;
4799 ReadBlockBuffer rbb(util_buffer, 0, capacity, 0);
4800 const unibrow::byte* answer = ReadBlock(input, &rbb, offset_ptr, chars);
4801 ASSERT(rbb.remaining <= static_cast<unsigned>(input->length()));
4802 *remaining = rbb.remaining;
4803 return answer;
4804}
4805
4806
4807const unibrow::byte* String::ReadBlock(String** raw_input,
4808 unibrow::byte* util_buffer,
4809 unsigned capacity,
4810 unsigned* remaining,
4811 unsigned* offset_ptr) {
4812 Handle<String> input(raw_input);
4813 ASSERT(*offset_ptr <= (unsigned)input->length());
4814 unsigned chars = input->length() - *offset_ptr;
4815 if (chars > capacity) chars = capacity;
4816 ReadBlockBuffer rbb(util_buffer, 0, capacity, 0);
4817 ReadBlockIntoBuffer(*input, &rbb, offset_ptr, chars);
4818 ASSERT(rbb.remaining <= static_cast<unsigned>(input->length()));
4819 *remaining = rbb.remaining;
4820 return rbb.util_buffer;
4821}
4822
4823
4824// This will iterate unless the block of string data spans two 'halves' of
4825// a ConsString, in which case it will recurse. Since the block of string
4826// data to be read has a maximum size this limits the maximum recursion
4827// depth to something sane. Since C++ does not have tail call recursion
4828// elimination, the iteration must be explicit.
4829void ConsString::ConsStringReadBlockIntoBuffer(ReadBlockBuffer* rbb,
4830 unsigned* offset_ptr,
4831 unsigned max_chars) {
4832 ConsString* current = this;
4833 unsigned offset = *offset_ptr;
4834 int offset_correction = 0;
4835
4836 while (true) {
4837 String* left = current->first();
4838 unsigned left_length = (unsigned)left->length();
4839 if (left_length > offset &&
4840 max_chars <= left_length - offset) {
4841 // Left hand side only - iterate unless we have reached the bottom of
4842 // the cons tree.
4843 if (StringShape(left).IsCons()) {
4844 current = ConsString::cast(left);
4845 continue;
4846 } else {
4847 String::ReadBlockIntoBuffer(left, rbb, &offset, max_chars);
4848 *offset_ptr = offset + offset_correction;
4849 return;
4850 }
4851 } else if (left_length <= offset) {
4852 // Right hand side only - iterate unless we have reached the bottom of
4853 // the cons tree.
4854 offset -= left_length;
4855 offset_correction += left_length;
4856 String* right = current->second();
4857 if (StringShape(right).IsCons()) {
4858 current = ConsString::cast(right);
4859 continue;
4860 } else {
4861 String::ReadBlockIntoBuffer(right, rbb, &offset, max_chars);
4862 *offset_ptr = offset + offset_correction;
4863 return;
4864 }
4865 } else {
4866 // The block to be read spans two sides of the ConsString, so we recurse.
4867 // First recurse on the left.
4868 max_chars -= left_length - offset;
4869 String::ReadBlockIntoBuffer(left, rbb, &offset, left_length - offset);
4870 // We may have reached the max or there may not have been enough space
4871 // in the buffer for the characters in the left hand side.
4872 if (offset == left_length) {
4873 // Recurse on the right.
4874 String* right = String::cast(current->second());
4875 offset -= left_length;
4876 offset_correction += left_length;
4877 String::ReadBlockIntoBuffer(right, rbb, &offset, max_chars);
4878 }
4879 *offset_ptr = offset + offset_correction;
4880 return;
4881 }
4882 }
4883}
4884
4885
Steve Blocka7e24c12009-10-30 11:49:00 +00004886uint16_t ConsString::ConsStringGet(int index) {
4887 ASSERT(index >= 0 && index < this->length());
4888
4889 // Check for a flattened cons string
4890 if (second()->length() == 0) {
4891 String* left = first();
4892 return left->Get(index);
4893 }
4894
4895 String* string = String::cast(this);
4896
4897 while (true) {
4898 if (StringShape(string).IsCons()) {
4899 ConsString* cons_string = ConsString::cast(string);
4900 String* left = cons_string->first();
4901 if (left->length() > index) {
4902 string = left;
4903 } else {
4904 index -= left->length();
4905 string = cons_string->second();
4906 }
4907 } else {
4908 return string->Get(index);
4909 }
4910 }
4911
4912 UNREACHABLE();
4913 return 0;
4914}
4915
4916
4917template <typename sinkchar>
4918void String::WriteToFlat(String* src,
4919 sinkchar* sink,
4920 int f,
4921 int t) {
4922 String* source = src;
4923 int from = f;
4924 int to = t;
4925 while (true) {
4926 ASSERT(0 <= from && from <= to && to <= source->length());
4927 switch (StringShape(source).full_representation_tag()) {
4928 case kAsciiStringTag | kExternalStringTag: {
4929 CopyChars(sink,
4930 ExternalAsciiString::cast(source)->resource()->data() + from,
4931 to - from);
4932 return;
4933 }
4934 case kTwoByteStringTag | kExternalStringTag: {
4935 const uc16* data =
4936 ExternalTwoByteString::cast(source)->resource()->data();
4937 CopyChars(sink,
4938 data + from,
4939 to - from);
4940 return;
4941 }
4942 case kAsciiStringTag | kSeqStringTag: {
4943 CopyChars(sink,
4944 SeqAsciiString::cast(source)->GetChars() + from,
4945 to - from);
4946 return;
4947 }
4948 case kTwoByteStringTag | kSeqStringTag: {
4949 CopyChars(sink,
4950 SeqTwoByteString::cast(source)->GetChars() + from,
4951 to - from);
4952 return;
4953 }
Steve Blocka7e24c12009-10-30 11:49:00 +00004954 case kAsciiStringTag | kConsStringTag:
4955 case kTwoByteStringTag | kConsStringTag: {
4956 ConsString* cons_string = ConsString::cast(source);
4957 String* first = cons_string->first();
4958 int boundary = first->length();
4959 if (to - boundary >= boundary - from) {
4960 // Right hand side is longer. Recurse over left.
4961 if (from < boundary) {
4962 WriteToFlat(first, sink, from, boundary);
4963 sink += boundary - from;
4964 from = 0;
4965 } else {
4966 from -= boundary;
4967 }
4968 to -= boundary;
4969 source = cons_string->second();
4970 } else {
4971 // Left hand side is longer. Recurse over right.
4972 if (to > boundary) {
4973 String* second = cons_string->second();
4974 WriteToFlat(second,
4975 sink + boundary - from,
4976 0,
4977 to - boundary);
4978 to = boundary;
4979 }
4980 source = first;
4981 }
4982 break;
4983 }
4984 }
4985 }
4986}
4987
4988
Steve Blocka7e24c12009-10-30 11:49:00 +00004989template <typename IteratorA, typename IteratorB>
4990static inline bool CompareStringContents(IteratorA* ia, IteratorB* ib) {
4991 // General slow case check. We know that the ia and ib iterators
4992 // have the same length.
4993 while (ia->has_more()) {
4994 uc32 ca = ia->GetNext();
4995 uc32 cb = ib->GetNext();
4996 if (ca != cb)
4997 return false;
4998 }
4999 return true;
5000}
5001
5002
5003// Compares the contents of two strings by reading and comparing
5004// int-sized blocks of characters.
5005template <typename Char>
5006static inline bool CompareRawStringContents(Vector<Char> a, Vector<Char> b) {
5007 int length = a.length();
5008 ASSERT_EQ(length, b.length());
5009 const Char* pa = a.start();
5010 const Char* pb = b.start();
5011 int i = 0;
5012#ifndef V8_HOST_CAN_READ_UNALIGNED
5013 // If this architecture isn't comfortable reading unaligned ints
5014 // then we have to check that the strings are aligned before
5015 // comparing them blockwise.
5016 const int kAlignmentMask = sizeof(uint32_t) - 1; // NOLINT
5017 uint32_t pa_addr = reinterpret_cast<uint32_t>(pa);
5018 uint32_t pb_addr = reinterpret_cast<uint32_t>(pb);
5019 if (((pa_addr & kAlignmentMask) | (pb_addr & kAlignmentMask)) == 0) {
5020#endif
5021 const int kStepSize = sizeof(int) / sizeof(Char); // NOLINT
5022 int endpoint = length - kStepSize;
5023 // Compare blocks until we reach near the end of the string.
5024 for (; i <= endpoint; i += kStepSize) {
5025 uint32_t wa = *reinterpret_cast<const uint32_t*>(pa + i);
5026 uint32_t wb = *reinterpret_cast<const uint32_t*>(pb + i);
5027 if (wa != wb) {
5028 return false;
5029 }
5030 }
5031#ifndef V8_HOST_CAN_READ_UNALIGNED
5032 }
5033#endif
5034 // Compare the remaining characters that didn't fit into a block.
5035 for (; i < length; i++) {
5036 if (a[i] != b[i]) {
5037 return false;
5038 }
5039 }
5040 return true;
5041}
5042
5043
5044static StringInputBuffer string_compare_buffer_b;
5045
5046
5047template <typename IteratorA>
5048static inline bool CompareStringContentsPartial(IteratorA* ia, String* b) {
5049 if (b->IsFlat()) {
5050 if (b->IsAsciiRepresentation()) {
5051 VectorIterator<char> ib(b->ToAsciiVector());
5052 return CompareStringContents(ia, &ib);
5053 } else {
5054 VectorIterator<uc16> ib(b->ToUC16Vector());
5055 return CompareStringContents(ia, &ib);
5056 }
5057 } else {
5058 string_compare_buffer_b.Reset(0, b);
5059 return CompareStringContents(ia, &string_compare_buffer_b);
5060 }
5061}
5062
5063
5064static StringInputBuffer string_compare_buffer_a;
5065
5066
5067bool String::SlowEquals(String* other) {
5068 // Fast check: negative check with lengths.
5069 int len = length();
5070 if (len != other->length()) return false;
5071 if (len == 0) return true;
5072
5073 // Fast check: if hash code is computed for both strings
5074 // a fast negative check can be performed.
5075 if (HasHashCode() && other->HasHashCode()) {
5076 if (Hash() != other->Hash()) return false;
5077 }
5078
Leon Clarkef7060e22010-06-03 12:02:55 +01005079 // We know the strings are both non-empty. Compare the first chars
5080 // before we try to flatten the strings.
5081 if (this->Get(0) != other->Get(0)) return false;
5082
5083 String* lhs = this->TryFlattenGetString();
5084 String* rhs = other->TryFlattenGetString();
5085
5086 if (StringShape(lhs).IsSequentialAscii() &&
5087 StringShape(rhs).IsSequentialAscii()) {
5088 const char* str1 = SeqAsciiString::cast(lhs)->GetChars();
5089 const char* str2 = SeqAsciiString::cast(rhs)->GetChars();
Steve Blocka7e24c12009-10-30 11:49:00 +00005090 return CompareRawStringContents(Vector<const char>(str1, len),
5091 Vector<const char>(str2, len));
5092 }
5093
Leon Clarkef7060e22010-06-03 12:02:55 +01005094 if (lhs->IsFlat()) {
Ben Murdochbb769b22010-08-11 14:56:33 +01005095 if (lhs->IsAsciiRepresentation()) {
Leon Clarkef7060e22010-06-03 12:02:55 +01005096 Vector<const char> vec1 = lhs->ToAsciiVector();
5097 if (rhs->IsFlat()) {
5098 if (rhs->IsAsciiRepresentation()) {
5099 Vector<const char> vec2 = rhs->ToAsciiVector();
Steve Blocka7e24c12009-10-30 11:49:00 +00005100 return CompareRawStringContents(vec1, vec2);
5101 } else {
5102 VectorIterator<char> buf1(vec1);
Leon Clarkef7060e22010-06-03 12:02:55 +01005103 VectorIterator<uc16> ib(rhs->ToUC16Vector());
Steve Blocka7e24c12009-10-30 11:49:00 +00005104 return CompareStringContents(&buf1, &ib);
5105 }
5106 } else {
5107 VectorIterator<char> buf1(vec1);
Leon Clarkef7060e22010-06-03 12:02:55 +01005108 string_compare_buffer_b.Reset(0, rhs);
Steve Blocka7e24c12009-10-30 11:49:00 +00005109 return CompareStringContents(&buf1, &string_compare_buffer_b);
5110 }
5111 } else {
Leon Clarkef7060e22010-06-03 12:02:55 +01005112 Vector<const uc16> vec1 = lhs->ToUC16Vector();
5113 if (rhs->IsFlat()) {
5114 if (rhs->IsAsciiRepresentation()) {
Steve Blocka7e24c12009-10-30 11:49:00 +00005115 VectorIterator<uc16> buf1(vec1);
Leon Clarkef7060e22010-06-03 12:02:55 +01005116 VectorIterator<char> ib(rhs->ToAsciiVector());
Steve Blocka7e24c12009-10-30 11:49:00 +00005117 return CompareStringContents(&buf1, &ib);
5118 } else {
Leon Clarkef7060e22010-06-03 12:02:55 +01005119 Vector<const uc16> vec2(rhs->ToUC16Vector());
Steve Blocka7e24c12009-10-30 11:49:00 +00005120 return CompareRawStringContents(vec1, vec2);
5121 }
5122 } else {
5123 VectorIterator<uc16> buf1(vec1);
Leon Clarkef7060e22010-06-03 12:02:55 +01005124 string_compare_buffer_b.Reset(0, rhs);
Steve Blocka7e24c12009-10-30 11:49:00 +00005125 return CompareStringContents(&buf1, &string_compare_buffer_b);
5126 }
5127 }
5128 } else {
Leon Clarkef7060e22010-06-03 12:02:55 +01005129 string_compare_buffer_a.Reset(0, lhs);
5130 return CompareStringContentsPartial(&string_compare_buffer_a, rhs);
Steve Blocka7e24c12009-10-30 11:49:00 +00005131 }
5132}
5133
5134
5135bool String::MarkAsUndetectable() {
5136 if (StringShape(this).IsSymbol()) return false;
5137
5138 Map* map = this->map();
Steve Blockd0582a62009-12-15 09:54:21 +00005139 if (map == Heap::string_map()) {
5140 this->set_map(Heap::undetectable_string_map());
Steve Blocka7e24c12009-10-30 11:49:00 +00005141 return true;
Steve Blockd0582a62009-12-15 09:54:21 +00005142 } else if (map == Heap::ascii_string_map()) {
5143 this->set_map(Heap::undetectable_ascii_string_map());
Steve Blocka7e24c12009-10-30 11:49:00 +00005144 return true;
5145 }
5146 // Rest cannot be marked as undetectable
5147 return false;
5148}
5149
5150
5151bool String::IsEqualTo(Vector<const char> str) {
5152 int slen = length();
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -08005153 Access<ScannerConstants::Utf8Decoder>
5154 decoder(ScannerConstants::utf8_decoder());
Steve Blocka7e24c12009-10-30 11:49:00 +00005155 decoder->Reset(str.start(), str.length());
5156 int i;
5157 for (i = 0; i < slen && decoder->has_more(); i++) {
5158 uc32 r = decoder->GetNext();
5159 if (Get(i) != r) return false;
5160 }
5161 return i == slen && !decoder->has_more();
5162}
5163
5164
Steve Block9fac8402011-05-12 15:51:54 +01005165bool String::IsAsciiEqualTo(Vector<const char> str) {
5166 int slen = length();
5167 if (str.length() != slen) return false;
5168 for (int i = 0; i < slen; i++) {
5169 if (Get(i) != static_cast<uint16_t>(str[i])) return false;
5170 }
5171 return true;
5172}
5173
5174
5175bool String::IsTwoByteEqualTo(Vector<const uc16> str) {
5176 int slen = length();
5177 if (str.length() != slen) return false;
5178 for (int i = 0; i < slen; i++) {
5179 if (Get(i) != str[i]) return false;
5180 }
5181 return true;
5182}
5183
5184
Steve Block6ded16b2010-05-10 14:33:55 +01005185template <typename schar>
5186static inline uint32_t HashSequentialString(const schar* chars, int length) {
5187 StringHasher hasher(length);
5188 if (!hasher.has_trivial_hash()) {
5189 int i;
5190 for (i = 0; hasher.is_array_index() && (i < length); i++) {
5191 hasher.AddCharacter(chars[i]);
5192 }
5193 for (; i < length; i++) {
5194 hasher.AddCharacterNoIndex(chars[i]);
5195 }
5196 }
5197 return hasher.GetHashField();
5198}
5199
5200
Steve Blocka7e24c12009-10-30 11:49:00 +00005201uint32_t String::ComputeAndSetHash() {
5202 // Should only be called if hash code has not yet been computed.
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01005203 ASSERT(!HasHashCode());
Steve Blocka7e24c12009-10-30 11:49:00 +00005204
Steve Block6ded16b2010-05-10 14:33:55 +01005205 const int len = length();
5206
Steve Blocka7e24c12009-10-30 11:49:00 +00005207 // Compute the hash code.
Steve Block6ded16b2010-05-10 14:33:55 +01005208 uint32_t field = 0;
5209 if (StringShape(this).IsSequentialAscii()) {
5210 field = HashSequentialString(SeqAsciiString::cast(this)->GetChars(), len);
5211 } else if (StringShape(this).IsSequentialTwoByte()) {
5212 field = HashSequentialString(SeqTwoByteString::cast(this)->GetChars(), len);
5213 } else {
5214 StringInputBuffer buffer(this);
5215 field = ComputeHashField(&buffer, len);
5216 }
Steve Blocka7e24c12009-10-30 11:49:00 +00005217
5218 // Store the hash code in the object.
Steve Blockd0582a62009-12-15 09:54:21 +00005219 set_hash_field(field);
Steve Blocka7e24c12009-10-30 11:49:00 +00005220
5221 // Check the hash code is there.
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01005222 ASSERT(HasHashCode());
Steve Blocka7e24c12009-10-30 11:49:00 +00005223 uint32_t result = field >> kHashShift;
5224 ASSERT(result != 0); // Ensure that the hash value of 0 is never computed.
5225 return result;
5226}
5227
5228
5229bool String::ComputeArrayIndex(unibrow::CharacterStream* buffer,
5230 uint32_t* index,
5231 int length) {
5232 if (length == 0 || length > kMaxArrayIndexSize) return false;
5233 uc32 ch = buffer->GetNext();
5234
5235 // If the string begins with a '0' character, it must only consist
5236 // of it to be a legal array index.
5237 if (ch == '0') {
5238 *index = 0;
5239 return length == 1;
5240 }
5241
5242 // Convert string to uint32 array index; character by character.
5243 int d = ch - '0';
5244 if (d < 0 || d > 9) return false;
5245 uint32_t result = d;
5246 while (buffer->has_more()) {
5247 d = buffer->GetNext() - '0';
5248 if (d < 0 || d > 9) return false;
5249 // Check that the new result is below the 32 bit limit.
5250 if (result > 429496729U - ((d > 5) ? 1 : 0)) return false;
5251 result = (result * 10) + d;
5252 }
5253
5254 *index = result;
5255 return true;
5256}
5257
5258
5259bool String::SlowAsArrayIndex(uint32_t* index) {
5260 if (length() <= kMaxCachedArrayIndexLength) {
5261 Hash(); // force computation of hash code
Steve Blockd0582a62009-12-15 09:54:21 +00005262 uint32_t field = hash_field();
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01005263 if ((field & kIsNotArrayIndexMask) != 0) return false;
Steve Blockd0582a62009-12-15 09:54:21 +00005264 // Isolate the array index form the full hash field.
5265 *index = (kArrayIndexHashMask & field) >> kHashShift;
Steve Blocka7e24c12009-10-30 11:49:00 +00005266 return true;
5267 } else {
5268 StringInputBuffer buffer(this);
5269 return ComputeArrayIndex(&buffer, index, length());
5270 }
5271}
5272
5273
Iain Merrick9ac36c92010-09-13 15:29:50 +01005274uint32_t StringHasher::MakeArrayIndexHash(uint32_t value, int length) {
Kristian Monsen80d68ea2010-09-08 11:05:35 +01005275 // For array indexes mix the length into the hash as an array index could
5276 // be zero.
5277 ASSERT(length > 0);
5278 ASSERT(length <= String::kMaxArrayIndexSize);
5279 ASSERT(TenToThe(String::kMaxCachedArrayIndexLength) <
5280 (1 << String::kArrayIndexValueBits));
Iain Merrick9ac36c92010-09-13 15:29:50 +01005281
5282 value <<= String::kHashShift;
Kristian Monsen80d68ea2010-09-08 11:05:35 +01005283 value |= length << String::kArrayIndexHashLengthShift;
Iain Merrick9ac36c92010-09-13 15:29:50 +01005284
5285 ASSERT((value & String::kIsNotArrayIndexMask) == 0);
5286 ASSERT((length > String::kMaxCachedArrayIndexLength) ||
5287 (value & String::kContainsCachedArrayIndexMask) == 0);
Kristian Monsen80d68ea2010-09-08 11:05:35 +01005288 return value;
Steve Blocka7e24c12009-10-30 11:49:00 +00005289}
5290
5291
5292uint32_t StringHasher::GetHashField() {
5293 ASSERT(is_valid());
Steve Blockd0582a62009-12-15 09:54:21 +00005294 if (length_ <= String::kMaxHashCalcLength) {
Steve Blocka7e24c12009-10-30 11:49:00 +00005295 if (is_array_index()) {
Iain Merrick9ac36c92010-09-13 15:29:50 +01005296 return MakeArrayIndexHash(array_index(), length_);
Steve Blocka7e24c12009-10-30 11:49:00 +00005297 }
Kristian Monsen80d68ea2010-09-08 11:05:35 +01005298 return (GetHash() << String::kHashShift) | String::kIsNotArrayIndexMask;
Steve Blocka7e24c12009-10-30 11:49:00 +00005299 } else {
Kristian Monsen80d68ea2010-09-08 11:05:35 +01005300 return (length_ << String::kHashShift) | String::kIsNotArrayIndexMask;
Steve Blocka7e24c12009-10-30 11:49:00 +00005301 }
5302}
5303
5304
Steve Blockd0582a62009-12-15 09:54:21 +00005305uint32_t String::ComputeHashField(unibrow::CharacterStream* buffer,
5306 int length) {
Steve Blocka7e24c12009-10-30 11:49:00 +00005307 StringHasher hasher(length);
5308
5309 // Very long strings have a trivial hash that doesn't inspect the
5310 // string contents.
5311 if (hasher.has_trivial_hash()) {
5312 return hasher.GetHashField();
5313 }
5314
5315 // Do the iterative array index computation as long as there is a
5316 // chance this is an array index.
5317 while (buffer->has_more() && hasher.is_array_index()) {
5318 hasher.AddCharacter(buffer->GetNext());
5319 }
5320
5321 // Process the remaining characters without updating the array
5322 // index.
5323 while (buffer->has_more()) {
5324 hasher.AddCharacterNoIndex(buffer->GetNext());
5325 }
5326
5327 return hasher.GetHashField();
5328}
5329
5330
John Reck59135872010-11-02 12:39:01 -07005331MaybeObject* String::SubString(int start, int end, PretenureFlag pretenure) {
Steve Blocka7e24c12009-10-30 11:49:00 +00005332 if (start == 0 && end == length()) return this;
John Reck59135872010-11-02 12:39:01 -07005333 MaybeObject* result = Heap::AllocateSubString(this, start, end, pretenure);
Steve Blockd0582a62009-12-15 09:54:21 +00005334 return result;
Steve Blocka7e24c12009-10-30 11:49:00 +00005335}
5336
5337
5338void String::PrintOn(FILE* file) {
5339 int length = this->length();
5340 for (int i = 0; i < length; i++) {
5341 fprintf(file, "%c", Get(i));
5342 }
5343}
5344
5345
5346void Map::CreateBackPointers() {
5347 DescriptorArray* descriptors = instance_descriptors();
5348 for (int i = 0; i < descriptors->number_of_descriptors(); i++) {
Iain Merrick75681382010-08-19 15:07:18 +01005349 if (descriptors->GetType(i) == MAP_TRANSITION ||
5350 descriptors->GetType(i) == CONSTANT_TRANSITION) {
Steve Blocka7e24c12009-10-30 11:49:00 +00005351 // Get target.
5352 Map* target = Map::cast(descriptors->GetValue(i));
5353#ifdef DEBUG
5354 // Verify target.
5355 Object* source_prototype = prototype();
5356 Object* target_prototype = target->prototype();
5357 ASSERT(source_prototype->IsJSObject() ||
5358 source_prototype->IsMap() ||
5359 source_prototype->IsNull());
5360 ASSERT(target_prototype->IsJSObject() ||
5361 target_prototype->IsNull());
5362 ASSERT(source_prototype->IsMap() ||
5363 source_prototype == target_prototype);
5364#endif
5365 // Point target back to source. set_prototype() will not let us set
5366 // the prototype to a map, as we do here.
5367 *RawField(target, kPrototypeOffset) = this;
5368 }
5369 }
5370}
5371
5372
5373void Map::ClearNonLiveTransitions(Object* real_prototype) {
5374 // Live DescriptorArray objects will be marked, so we must use
5375 // low-level accessors to get and modify their data.
5376 DescriptorArray* d = reinterpret_cast<DescriptorArray*>(
5377 *RawField(this, Map::kInstanceDescriptorsOffset));
5378 if (d == Heap::raw_unchecked_empty_descriptor_array()) return;
5379 Smi* NullDescriptorDetails =
5380 PropertyDetails(NONE, NULL_DESCRIPTOR).AsSmi();
5381 FixedArray* contents = reinterpret_cast<FixedArray*>(
5382 d->get(DescriptorArray::kContentArrayIndex));
5383 ASSERT(contents->length() >= 2);
5384 for (int i = 0; i < contents->length(); i += 2) {
5385 // If the pair (value, details) is a map transition,
5386 // check if the target is live. If not, null the descriptor.
5387 // Also drop the back pointer for that map transition, so that this
5388 // map is not reached again by following a back pointer from a
5389 // non-live object.
5390 PropertyDetails details(Smi::cast(contents->get(i + 1)));
Iain Merrick75681382010-08-19 15:07:18 +01005391 if (details.type() == MAP_TRANSITION ||
5392 details.type() == CONSTANT_TRANSITION) {
Steve Blocka7e24c12009-10-30 11:49:00 +00005393 Map* target = reinterpret_cast<Map*>(contents->get(i));
5394 ASSERT(target->IsHeapObject());
5395 if (!target->IsMarked()) {
5396 ASSERT(target->IsMap());
Iain Merrick75681382010-08-19 15:07:18 +01005397 contents->set_unchecked(i + 1, NullDescriptorDetails);
5398 contents->set_null_unchecked(i);
Steve Blocka7e24c12009-10-30 11:49:00 +00005399 ASSERT(target->prototype() == this ||
5400 target->prototype() == real_prototype);
5401 // Getter prototype() is read-only, set_prototype() has side effects.
5402 *RawField(target, Map::kPrototypeOffset) = real_prototype;
5403 }
5404 }
5405 }
5406}
5407
5408
Steve Block791712a2010-08-27 10:21:07 +01005409void JSFunction::JSFunctionIterateBody(int object_size, ObjectVisitor* v) {
5410 // Iterate over all fields in the body but take care in dealing with
5411 // the code entry.
5412 IteratePointers(v, kPropertiesOffset, kCodeEntryOffset);
5413 v->VisitCodeEntry(this->address() + kCodeEntryOffset);
5414 IteratePointers(v, kCodeEntryOffset + kPointerSize, object_size);
5415}
5416
5417
Ben Murdochb0fe1622011-05-05 13:52:32 +01005418void JSFunction::MarkForLazyRecompilation() {
5419 ASSERT(is_compiled() && !IsOptimized());
Ben Murdochb8e0da22011-05-16 14:20:40 +01005420 ASSERT(shared()->allows_lazy_compilation() ||
5421 code()->optimizable());
Ben Murdochb0fe1622011-05-05 13:52:32 +01005422 ReplaceCode(Builtins::builtin(Builtins::LazyRecompile));
5423}
5424
5425
5426uint32_t JSFunction::SourceHash() {
5427 uint32_t hash = 0;
5428 Object* script = shared()->script();
5429 if (!script->IsUndefined()) {
5430 Object* source = Script::cast(script)->source();
5431 if (source->IsUndefined()) hash = String::cast(source)->Hash();
5432 }
5433 hash ^= ComputeIntegerHash(shared()->start_position_and_type());
5434 hash += ComputeIntegerHash(shared()->end_position());
5435 return hash;
5436}
5437
5438
5439bool JSFunction::IsInlineable() {
5440 if (IsBuiltin()) return false;
5441 // Check that the function has a script associated with it.
5442 if (!shared()->script()->IsScript()) return false;
5443 Code* code = shared()->code();
5444 if (code->kind() == Code::OPTIMIZED_FUNCTION) return true;
5445 // If we never ran this (unlikely) then lets try to optimize it.
5446 if (code->kind() != Code::FUNCTION) return true;
5447 return code->optimizable();
5448}
5449
5450
Steve Blocka7e24c12009-10-30 11:49:00 +00005451Object* JSFunction::SetInstancePrototype(Object* value) {
5452 ASSERT(value->IsJSObject());
5453
5454 if (has_initial_map()) {
5455 initial_map()->set_prototype(value);
5456 } else {
5457 // Put the value in the initial map field until an initial map is
5458 // needed. At that point, a new initial map is created and the
5459 // prototype is put into the initial map where it belongs.
5460 set_prototype_or_initial_map(value);
5461 }
Kristian Monsen25f61362010-05-21 11:50:48 +01005462 Heap::ClearInstanceofCache();
Steve Blocka7e24c12009-10-30 11:49:00 +00005463 return value;
5464}
5465
5466
John Reck59135872010-11-02 12:39:01 -07005467MaybeObject* JSFunction::SetPrototype(Object* value) {
Steve Block6ded16b2010-05-10 14:33:55 +01005468 ASSERT(should_have_prototype());
Steve Blocka7e24c12009-10-30 11:49:00 +00005469 Object* construct_prototype = value;
5470
5471 // If the value is not a JSObject, store the value in the map's
5472 // constructor field so it can be accessed. Also, set the prototype
5473 // used for constructing objects to the original object prototype.
5474 // See ECMA-262 13.2.2.
5475 if (!value->IsJSObject()) {
5476 // Copy the map so this does not affect unrelated functions.
5477 // Remove map transitions because they point to maps with a
5478 // different prototype.
John Reck59135872010-11-02 12:39:01 -07005479 Object* new_map;
5480 { MaybeObject* maybe_new_map = map()->CopyDropTransitions();
5481 if (!maybe_new_map->ToObject(&new_map)) return maybe_new_map;
5482 }
Steve Blocka7e24c12009-10-30 11:49:00 +00005483 set_map(Map::cast(new_map));
5484 map()->set_constructor(value);
5485 map()->set_non_instance_prototype(true);
5486 construct_prototype =
5487 Top::context()->global_context()->initial_object_prototype();
5488 } else {
5489 map()->set_non_instance_prototype(false);
5490 }
5491
5492 return SetInstancePrototype(construct_prototype);
5493}
5494
5495
Steve Block6ded16b2010-05-10 14:33:55 +01005496Object* JSFunction::RemovePrototype() {
5497 ASSERT(map() == context()->global_context()->function_map());
5498 set_map(context()->global_context()->function_without_prototype_map());
5499 set_prototype_or_initial_map(Heap::the_hole_value());
5500 return this;
5501}
5502
5503
Steve Blocka7e24c12009-10-30 11:49:00 +00005504Object* JSFunction::SetInstanceClassName(String* name) {
5505 shared()->set_instance_class_name(name);
5506 return this;
5507}
5508
5509
Ben Murdochb0fe1622011-05-05 13:52:32 +01005510void JSFunction::PrintName(FILE* out) {
5511 SmartPointer<char> name = shared()->DebugName()->ToCString();
5512 PrintF(out, "%s", *name);
5513}
5514
5515
Steve Blocka7e24c12009-10-30 11:49:00 +00005516Context* JSFunction::GlobalContextFromLiterals(FixedArray* literals) {
5517 return Context::cast(literals->get(JSFunction::kLiteralGlobalContextIndex));
5518}
5519
5520
John Reck59135872010-11-02 12:39:01 -07005521MaybeObject* Oddball::Initialize(const char* to_string, Object* to_number) {
5522 Object* symbol;
5523 { MaybeObject* maybe_symbol = Heap::LookupAsciiSymbol(to_string);
5524 if (!maybe_symbol->ToObject(&symbol)) return maybe_symbol;
5525 }
Steve Blocka7e24c12009-10-30 11:49:00 +00005526 set_to_string(String::cast(symbol));
5527 set_to_number(to_number);
5528 return this;
5529}
5530
5531
Ben Murdochf87a2032010-10-22 12:50:53 +01005532String* SharedFunctionInfo::DebugName() {
5533 Object* n = name();
5534 if (!n->IsString() || String::cast(n)->length() == 0) return inferred_name();
5535 return String::cast(n);
5536}
5537
5538
Steve Blocka7e24c12009-10-30 11:49:00 +00005539bool SharedFunctionInfo::HasSourceCode() {
5540 return !script()->IsUndefined() &&
Iain Merrick75681382010-08-19 15:07:18 +01005541 !reinterpret_cast<Script*>(script())->source()->IsUndefined();
Steve Blocka7e24c12009-10-30 11:49:00 +00005542}
5543
5544
5545Object* SharedFunctionInfo::GetSourceCode() {
Ben Murdochb0fe1622011-05-05 13:52:32 +01005546 if (!HasSourceCode()) return Heap::undefined_value();
Steve Blocka7e24c12009-10-30 11:49:00 +00005547 HandleScope scope;
Steve Blocka7e24c12009-10-30 11:49:00 +00005548 Object* source = Script::cast(script())->source();
Steve Blocka7e24c12009-10-30 11:49:00 +00005549 return *SubString(Handle<String>(String::cast(source)),
5550 start_position(), end_position());
5551}
5552
5553
Ben Murdochb0fe1622011-05-05 13:52:32 +01005554int SharedFunctionInfo::SourceSize() {
5555 return end_position() - start_position();
5556}
5557
5558
Steve Blocka7e24c12009-10-30 11:49:00 +00005559int SharedFunctionInfo::CalculateInstanceSize() {
5560 int instance_size =
5561 JSObject::kHeaderSize +
5562 expected_nof_properties() * kPointerSize;
5563 if (instance_size > JSObject::kMaxInstanceSize) {
5564 instance_size = JSObject::kMaxInstanceSize;
5565 }
5566 return instance_size;
5567}
5568
5569
5570int SharedFunctionInfo::CalculateInObjectProperties() {
5571 return (CalculateInstanceSize() - JSObject::kHeaderSize) / kPointerSize;
5572}
5573
5574
Andrei Popescu402d9372010-02-26 13:31:12 +00005575bool SharedFunctionInfo::CanGenerateInlineConstructor(Object* prototype) {
5576 // Check the basic conditions for generating inline constructor code.
5577 if (!FLAG_inline_new
5578 || !has_only_simple_this_property_assignments()
5579 || this_property_assignments_count() == 0) {
5580 return false;
5581 }
5582
5583 // If the prototype is null inline constructors cause no problems.
5584 if (!prototype->IsJSObject()) {
5585 ASSERT(prototype->IsNull());
5586 return true;
5587 }
5588
5589 // Traverse the proposed prototype chain looking for setters for properties of
5590 // the same names as are set by the inline constructor.
5591 for (Object* obj = prototype;
5592 obj != Heap::null_value();
5593 obj = obj->GetPrototype()) {
5594 JSObject* js_object = JSObject::cast(obj);
5595 for (int i = 0; i < this_property_assignments_count(); i++) {
5596 LookupResult result;
5597 String* name = GetThisPropertyAssignmentName(i);
5598 js_object->LocalLookupRealNamedProperty(name, &result);
5599 if (result.IsProperty() && result.type() == CALLBACKS) {
5600 return false;
5601 }
5602 }
5603 }
5604
5605 return true;
5606}
5607
5608
Kristian Monsen0d5e1162010-09-30 15:31:59 +01005609void SharedFunctionInfo::ForbidInlineConstructor() {
5610 set_compiler_hints(BooleanBit::set(compiler_hints(),
5611 kHasOnlySimpleThisPropertyAssignments,
5612 false));
5613}
5614
5615
Steve Blocka7e24c12009-10-30 11:49:00 +00005616void SharedFunctionInfo::SetThisPropertyAssignmentsInfo(
Steve Blocka7e24c12009-10-30 11:49:00 +00005617 bool only_simple_this_property_assignments,
5618 FixedArray* assignments) {
5619 set_compiler_hints(BooleanBit::set(compiler_hints(),
Steve Blocka7e24c12009-10-30 11:49:00 +00005620 kHasOnlySimpleThisPropertyAssignments,
5621 only_simple_this_property_assignments));
5622 set_this_property_assignments(assignments);
5623 set_this_property_assignments_count(assignments->length() / 3);
5624}
5625
5626
5627void SharedFunctionInfo::ClearThisPropertyAssignmentsInfo() {
5628 set_compiler_hints(BooleanBit::set(compiler_hints(),
Steve Blocka7e24c12009-10-30 11:49:00 +00005629 kHasOnlySimpleThisPropertyAssignments,
5630 false));
5631 set_this_property_assignments(Heap::undefined_value());
5632 set_this_property_assignments_count(0);
5633}
5634
5635
5636String* SharedFunctionInfo::GetThisPropertyAssignmentName(int index) {
5637 Object* obj = this_property_assignments();
5638 ASSERT(obj->IsFixedArray());
5639 ASSERT(index < this_property_assignments_count());
5640 obj = FixedArray::cast(obj)->get(index * 3);
5641 ASSERT(obj->IsString());
5642 return String::cast(obj);
5643}
5644
5645
5646bool SharedFunctionInfo::IsThisPropertyAssignmentArgument(int index) {
5647 Object* obj = this_property_assignments();
5648 ASSERT(obj->IsFixedArray());
5649 ASSERT(index < this_property_assignments_count());
5650 obj = FixedArray::cast(obj)->get(index * 3 + 1);
5651 return Smi::cast(obj)->value() != -1;
5652}
5653
5654
5655int SharedFunctionInfo::GetThisPropertyAssignmentArgument(int index) {
5656 ASSERT(IsThisPropertyAssignmentArgument(index));
5657 Object* obj =
5658 FixedArray::cast(this_property_assignments())->get(index * 3 + 1);
5659 return Smi::cast(obj)->value();
5660}
5661
5662
5663Object* SharedFunctionInfo::GetThisPropertyAssignmentConstant(int index) {
5664 ASSERT(!IsThisPropertyAssignmentArgument(index));
5665 Object* obj =
5666 FixedArray::cast(this_property_assignments())->get(index * 3 + 2);
5667 return obj;
5668}
5669
5670
Steve Blocka7e24c12009-10-30 11:49:00 +00005671// Support function for printing the source code to a StringStream
5672// without any allocation in the heap.
5673void SharedFunctionInfo::SourceCodePrint(StringStream* accumulator,
5674 int max_length) {
5675 // For some native functions there is no source.
Ben Murdochb0fe1622011-05-05 13:52:32 +01005676 if (!HasSourceCode()) {
Steve Blocka7e24c12009-10-30 11:49:00 +00005677 accumulator->Add("<No Source>");
5678 return;
5679 }
5680
Steve Blockd0582a62009-12-15 09:54:21 +00005681 // Get the source for the script which this function came from.
Steve Blocka7e24c12009-10-30 11:49:00 +00005682 // Don't use String::cast because we don't want more assertion errors while
5683 // we are already creating a stack dump.
5684 String* script_source =
5685 reinterpret_cast<String*>(Script::cast(script())->source());
5686
5687 if (!script_source->LooksValid()) {
5688 accumulator->Add("<Invalid Source>");
5689 return;
5690 }
5691
5692 if (!is_toplevel()) {
5693 accumulator->Add("function ");
5694 Object* name = this->name();
5695 if (name->IsString() && String::cast(name)->length() > 0) {
5696 accumulator->PrintName(name);
5697 }
5698 }
5699
5700 int len = end_position() - start_position();
Ben Murdochb0fe1622011-05-05 13:52:32 +01005701 if (len <= max_length || max_length < 0) {
5702 accumulator->Put(script_source, start_position(), end_position());
5703 } else {
Steve Blocka7e24c12009-10-30 11:49:00 +00005704 accumulator->Put(script_source,
5705 start_position(),
5706 start_position() + max_length);
5707 accumulator->Add("...\n");
Steve Blocka7e24c12009-10-30 11:49:00 +00005708 }
5709}
5710
5711
Ben Murdochb0fe1622011-05-05 13:52:32 +01005712static bool IsCodeEquivalent(Code* code, Code* recompiled) {
5713 if (code->instruction_size() != recompiled->instruction_size()) return false;
5714 ByteArray* code_relocation = code->relocation_info();
5715 ByteArray* recompiled_relocation = recompiled->relocation_info();
5716 int length = code_relocation->length();
5717 if (length != recompiled_relocation->length()) return false;
5718 int compare = memcmp(code_relocation->GetDataStartAddress(),
5719 recompiled_relocation->GetDataStartAddress(),
5720 length);
5721 return compare == 0;
5722}
5723
5724
5725void SharedFunctionInfo::EnableDeoptimizationSupport(Code* recompiled) {
5726 ASSERT(!has_deoptimization_support());
5727 AssertNoAllocation no_allocation;
5728 Code* code = this->code();
5729 if (IsCodeEquivalent(code, recompiled)) {
5730 // Copy the deoptimization data from the recompiled code.
5731 code->set_deoptimization_data(recompiled->deoptimization_data());
5732 code->set_has_deoptimization_support(true);
5733 } else {
5734 // TODO(3025757): In case the recompiled isn't equivalent to the
5735 // old code, we have to replace it. We should try to avoid this
5736 // altogether because it flushes valuable type feedback by
5737 // effectively resetting all IC state.
5738 set_code(recompiled);
5739 }
5740 ASSERT(has_deoptimization_support());
5741}
5742
5743
5744bool SharedFunctionInfo::VerifyBailoutId(int id) {
5745 // TODO(srdjan): debugging ARM crashes in hydrogen. OK to disable while
5746 // we are always bailing out on ARM.
5747
5748 ASSERT(id != AstNode::kNoNumber);
5749 Code* unoptimized = code();
5750 DeoptimizationOutputData* data =
5751 DeoptimizationOutputData::cast(unoptimized->deoptimization_data());
5752 unsigned ignore = Deoptimizer::GetOutputInfo(data, id, this);
5753 USE(ignore);
5754 return true; // Return true if there was no ASSERT.
5755}
5756
5757
Kristian Monsen0d5e1162010-09-30 15:31:59 +01005758void SharedFunctionInfo::StartInobjectSlackTracking(Map* map) {
5759 ASSERT(!IsInobjectSlackTrackingInProgress());
5760
5761 // Only initiate the tracking the first time.
5762 if (live_objects_may_exist()) return;
5763 set_live_objects_may_exist(true);
5764
5765 // No tracking during the snapshot construction phase.
5766 if (Serializer::enabled()) return;
5767
5768 if (map->unused_property_fields() == 0) return;
5769
5770 // Nonzero counter is a leftover from the previous attempt interrupted
5771 // by GC, keep it.
5772 if (construction_count() == 0) {
5773 set_construction_count(kGenerousAllocationCount);
5774 }
5775 set_initial_map(map);
5776 ASSERT_EQ(Builtins::builtin(Builtins::JSConstructStubGeneric),
5777 construct_stub());
5778 set_construct_stub(Builtins::builtin(Builtins::JSConstructStubCountdown));
5779}
5780
5781
5782// Called from GC, hence reinterpret_cast and unchecked accessors.
5783void SharedFunctionInfo::DetachInitialMap() {
5784 Map* map = reinterpret_cast<Map*>(initial_map());
5785
5786 // Make the map remember to restore the link if it survives the GC.
5787 map->set_bit_field2(
5788 map->bit_field2() | (1 << Map::kAttachedToSharedFunctionInfo));
5789
5790 // Undo state changes made by StartInobjectTracking (except the
5791 // construction_count). This way if the initial map does not survive the GC
5792 // then StartInobjectTracking will be called again the next time the
5793 // constructor is called. The countdown will continue and (possibly after
5794 // several more GCs) CompleteInobjectSlackTracking will eventually be called.
5795 set_initial_map(Heap::raw_unchecked_undefined_value());
5796 ASSERT_EQ(Builtins::builtin(Builtins::JSConstructStubCountdown),
5797 *RawField(this, kConstructStubOffset));
5798 set_construct_stub(Builtins::builtin(Builtins::JSConstructStubGeneric));
5799 // It is safe to clear the flag: it will be set again if the map is live.
5800 set_live_objects_may_exist(false);
5801}
5802
5803
5804// Called from GC, hence reinterpret_cast and unchecked accessors.
5805void SharedFunctionInfo::AttachInitialMap(Map* map) {
5806 map->set_bit_field2(
5807 map->bit_field2() & ~(1 << Map::kAttachedToSharedFunctionInfo));
5808
5809 // Resume inobject slack tracking.
5810 set_initial_map(map);
5811 ASSERT_EQ(Builtins::builtin(Builtins::JSConstructStubGeneric),
5812 *RawField(this, kConstructStubOffset));
5813 set_construct_stub(Builtins::builtin(Builtins::JSConstructStubCountdown));
5814 // The map survived the gc, so there may be objects referencing it.
5815 set_live_objects_may_exist(true);
5816}
5817
5818
5819static void GetMinInobjectSlack(Map* map, void* data) {
5820 int slack = map->unused_property_fields();
5821 if (*reinterpret_cast<int*>(data) > slack) {
5822 *reinterpret_cast<int*>(data) = slack;
5823 }
5824}
5825
5826
5827static void ShrinkInstanceSize(Map* map, void* data) {
5828 int slack = *reinterpret_cast<int*>(data);
5829 map->set_inobject_properties(map->inobject_properties() - slack);
5830 map->set_unused_property_fields(map->unused_property_fields() - slack);
5831 map->set_instance_size(map->instance_size() - slack * kPointerSize);
5832
5833 // Visitor id might depend on the instance size, recalculate it.
5834 map->set_visitor_id(StaticVisitorBase::GetVisitorId(map));
5835}
5836
5837
5838void SharedFunctionInfo::CompleteInobjectSlackTracking() {
5839 ASSERT(live_objects_may_exist() && IsInobjectSlackTrackingInProgress());
5840 Map* map = Map::cast(initial_map());
5841
5842 set_initial_map(Heap::undefined_value());
5843 ASSERT_EQ(Builtins::builtin(Builtins::JSConstructStubCountdown),
5844 construct_stub());
5845 set_construct_stub(Builtins::builtin(Builtins::JSConstructStubGeneric));
5846
5847 int slack = map->unused_property_fields();
5848 map->TraverseTransitionTree(&GetMinInobjectSlack, &slack);
5849 if (slack != 0) {
5850 // Resize the initial map and all maps in its transition tree.
5851 map->TraverseTransitionTree(&ShrinkInstanceSize, &slack);
5852 // Give the correct expected_nof_properties to initial maps created later.
5853 ASSERT(expected_nof_properties() >= slack);
5854 set_expected_nof_properties(expected_nof_properties() - slack);
5855 }
5856}
5857
5858
Steve Blocka7e24c12009-10-30 11:49:00 +00005859void ObjectVisitor::VisitCodeTarget(RelocInfo* rinfo) {
5860 ASSERT(RelocInfo::IsCodeTarget(rinfo->rmode()));
5861 Object* target = Code::GetCodeFromTargetAddress(rinfo->target_address());
5862 Object* old_target = target;
5863 VisitPointer(&target);
5864 CHECK_EQ(target, old_target); // VisitPointer doesn't change Code* *target.
5865}
5866
5867
Steve Block791712a2010-08-27 10:21:07 +01005868void ObjectVisitor::VisitCodeEntry(Address entry_address) {
5869 Object* code = Code::GetObjectFromEntryAddress(entry_address);
5870 Object* old_code = code;
5871 VisitPointer(&code);
5872 if (code != old_code) {
5873 Memory::Address_at(entry_address) = reinterpret_cast<Code*>(code)->entry();
5874 }
5875}
5876
5877
Ben Murdochb0fe1622011-05-05 13:52:32 +01005878void ObjectVisitor::VisitGlobalPropertyCell(RelocInfo* rinfo) {
5879 ASSERT(rinfo->rmode() == RelocInfo::GLOBAL_PROPERTY_CELL);
5880 Object* cell = rinfo->target_cell();
5881 Object* old_cell = cell;
5882 VisitPointer(&cell);
5883 if (cell != old_cell) {
5884 rinfo->set_target_cell(reinterpret_cast<JSGlobalPropertyCell*>(cell));
5885 }
5886}
5887
5888
Steve Blocka7e24c12009-10-30 11:49:00 +00005889void ObjectVisitor::VisitDebugTarget(RelocInfo* rinfo) {
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01005890 ASSERT((RelocInfo::IsJSReturn(rinfo->rmode()) &&
5891 rinfo->IsPatchedReturnSequence()) ||
5892 (RelocInfo::IsDebugBreakSlot(rinfo->rmode()) &&
5893 rinfo->IsPatchedDebugBreakSlotSequence()));
Steve Blocka7e24c12009-10-30 11:49:00 +00005894 Object* target = Code::GetCodeFromTargetAddress(rinfo->call_address());
5895 Object* old_target = target;
5896 VisitPointer(&target);
5897 CHECK_EQ(target, old_target); // VisitPointer doesn't change Code* *target.
5898}
5899
5900
Ben Murdochb0fe1622011-05-05 13:52:32 +01005901void Code::InvalidateRelocation() {
5902 HandleScope scope;
5903 set_relocation_info(Heap::empty_byte_array());
5904}
5905
5906
Steve Blockd0582a62009-12-15 09:54:21 +00005907void Code::Relocate(intptr_t delta) {
Steve Blocka7e24c12009-10-30 11:49:00 +00005908 for (RelocIterator it(this, RelocInfo::kApplyMask); !it.done(); it.next()) {
5909 it.rinfo()->apply(delta);
5910 }
5911 CPU::FlushICache(instruction_start(), instruction_size());
5912}
5913
5914
5915void Code::CopyFrom(const CodeDesc& desc) {
5916 // copy code
5917 memmove(instruction_start(), desc.buffer, desc.instr_size);
5918
Steve Blocka7e24c12009-10-30 11:49:00 +00005919 // copy reloc info
5920 memmove(relocation_start(),
5921 desc.buffer + desc.buffer_size - desc.reloc_size,
5922 desc.reloc_size);
5923
5924 // unbox handles and relocate
Steve Block3ce2e202009-11-05 08:53:23 +00005925 intptr_t delta = instruction_start() - desc.buffer;
Steve Blocka7e24c12009-10-30 11:49:00 +00005926 int mode_mask = RelocInfo::kCodeTargetMask |
5927 RelocInfo::ModeMask(RelocInfo::EMBEDDED_OBJECT) |
Ben Murdochb0fe1622011-05-05 13:52:32 +01005928 RelocInfo::ModeMask(RelocInfo::GLOBAL_PROPERTY_CELL) |
Steve Blocka7e24c12009-10-30 11:49:00 +00005929 RelocInfo::kApplyMask;
Steve Block3ce2e202009-11-05 08:53:23 +00005930 Assembler* origin = desc.origin; // Needed to find target_object on X64.
Steve Blocka7e24c12009-10-30 11:49:00 +00005931 for (RelocIterator it(this, mode_mask); !it.done(); it.next()) {
5932 RelocInfo::Mode mode = it.rinfo()->rmode();
5933 if (mode == RelocInfo::EMBEDDED_OBJECT) {
Steve Block3ce2e202009-11-05 08:53:23 +00005934 Handle<Object> p = it.rinfo()->target_object_handle(origin);
Steve Blocka7e24c12009-10-30 11:49:00 +00005935 it.rinfo()->set_target_object(*p);
Ben Murdochb0fe1622011-05-05 13:52:32 +01005936 } else if (mode == RelocInfo::GLOBAL_PROPERTY_CELL) {
Steve Block1e0659c2011-05-24 12:43:12 +01005937 Handle<JSGlobalPropertyCell> cell = it.rinfo()->target_cell_handle();
Ben Murdochb0fe1622011-05-05 13:52:32 +01005938 it.rinfo()->set_target_cell(*cell);
Steve Blocka7e24c12009-10-30 11:49:00 +00005939 } else if (RelocInfo::IsCodeTarget(mode)) {
5940 // rewrite code handles in inline cache targets to direct
5941 // pointers to the first instruction in the code object
Steve Block3ce2e202009-11-05 08:53:23 +00005942 Handle<Object> p = it.rinfo()->target_object_handle(origin);
Steve Blocka7e24c12009-10-30 11:49:00 +00005943 Code* code = Code::cast(*p);
5944 it.rinfo()->set_target_address(code->instruction_start());
5945 } else {
5946 it.rinfo()->apply(delta);
5947 }
5948 }
5949 CPU::FlushICache(instruction_start(), instruction_size());
5950}
5951
5952
5953// Locate the source position which is closest to the address in the code. This
5954// is using the source position information embedded in the relocation info.
5955// The position returned is relative to the beginning of the script where the
5956// source for this function is found.
5957int Code::SourcePosition(Address pc) {
5958 int distance = kMaxInt;
5959 int position = RelocInfo::kNoPosition; // Initially no position found.
5960 // Run through all the relocation info to find the best matching source
5961 // position. All the code needs to be considered as the sequence of the
5962 // instructions in the code does not necessarily follow the same order as the
5963 // source.
5964 RelocIterator it(this, RelocInfo::kPositionMask);
5965 while (!it.done()) {
5966 // Only look at positions after the current pc.
5967 if (it.rinfo()->pc() < pc) {
5968 // Get position and distance.
Steve Blockd0582a62009-12-15 09:54:21 +00005969
5970 int dist = static_cast<int>(pc - it.rinfo()->pc());
5971 int pos = static_cast<int>(it.rinfo()->data());
Steve Blocka7e24c12009-10-30 11:49:00 +00005972 // If this position is closer than the current candidate or if it has the
5973 // same distance as the current candidate and the position is higher then
5974 // this position is the new candidate.
5975 if ((dist < distance) ||
5976 (dist == distance && pos > position)) {
5977 position = pos;
5978 distance = dist;
5979 }
5980 }
5981 it.next();
5982 }
5983 return position;
5984}
5985
5986
5987// Same as Code::SourcePosition above except it only looks for statement
5988// positions.
5989int Code::SourceStatementPosition(Address pc) {
5990 // First find the position as close as possible using all position
5991 // information.
5992 int position = SourcePosition(pc);
5993 // Now find the closest statement position before the position.
5994 int statement_position = 0;
5995 RelocIterator it(this, RelocInfo::kPositionMask);
5996 while (!it.done()) {
5997 if (RelocInfo::IsStatementPosition(it.rinfo()->rmode())) {
Steve Blockd0582a62009-12-15 09:54:21 +00005998 int p = static_cast<int>(it.rinfo()->data());
Steve Blocka7e24c12009-10-30 11:49:00 +00005999 if (statement_position < p && p <= position) {
6000 statement_position = p;
6001 }
6002 }
6003 it.next();
6004 }
6005 return statement_position;
6006}
6007
6008
Ben Murdochb8e0da22011-05-16 14:20:40 +01006009SafepointEntry Code::GetSafepointEntry(Address pc) {
Ben Murdochb0fe1622011-05-05 13:52:32 +01006010 SafepointTable table(this);
Ben Murdochb8e0da22011-05-16 14:20:40 +01006011 return table.FindEntry(pc);
Ben Murdochb0fe1622011-05-05 13:52:32 +01006012}
6013
6014
6015void Code::SetNoStackCheckTable() {
6016 // Indicate the absence of a stack-check table by a table start after the
6017 // end of the instructions. Table start must be aligned, so round up.
Steve Block1e0659c2011-05-24 12:43:12 +01006018 set_stack_check_table_offset(RoundUp(instruction_size(), kIntSize));
Ben Murdochb0fe1622011-05-05 13:52:32 +01006019}
6020
6021
6022Map* Code::FindFirstMap() {
6023 ASSERT(is_inline_cache_stub());
6024 AssertNoAllocation no_allocation;
6025 int mask = RelocInfo::ModeMask(RelocInfo::EMBEDDED_OBJECT);
6026 for (RelocIterator it(this, mask); !it.done(); it.next()) {
6027 RelocInfo* info = it.rinfo();
6028 Object* object = info->target_object();
6029 if (object->IsMap()) return Map::cast(object);
6030 }
6031 return NULL;
6032}
6033
6034
Steve Blocka7e24c12009-10-30 11:49:00 +00006035#ifdef ENABLE_DISASSEMBLER
Ben Murdochb0fe1622011-05-05 13:52:32 +01006036
6037#ifdef OBJECT_PRINT
6038
6039void DeoptimizationInputData::DeoptimizationInputDataPrint(FILE* out) {
6040 disasm::NameConverter converter;
6041 int deopt_count = DeoptCount();
6042 PrintF(out, "Deoptimization Input Data (deopt points = %d)\n", deopt_count);
6043 if (0 == deopt_count) return;
6044
6045 PrintF(out, "%6s %6s %6s %12s\n", "index", "ast id", "argc", "commands");
6046 for (int i = 0; i < deopt_count; i++) {
6047 int command_count = 0;
6048 PrintF(out, "%6d %6d %6d",
6049 i, AstId(i)->value(), ArgumentsStackHeight(i)->value());
6050 int translation_index = TranslationIndex(i)->value();
6051 TranslationIterator iterator(TranslationByteArray(), translation_index);
6052 Translation::Opcode opcode =
6053 static_cast<Translation::Opcode>(iterator.Next());
6054 ASSERT(Translation::BEGIN == opcode);
6055 int frame_count = iterator.Next();
6056 if (FLAG_print_code_verbose) {
6057 PrintF(out, " %s {count=%d}\n", Translation::StringFor(opcode),
6058 frame_count);
6059 }
6060
6061 for (int i = 0; i < frame_count; ++i) {
6062 opcode = static_cast<Translation::Opcode>(iterator.Next());
6063 ASSERT(Translation::FRAME == opcode);
6064 int ast_id = iterator.Next();
6065 int function_id = iterator.Next();
6066 JSFunction* function =
6067 JSFunction::cast(LiteralArray()->get(function_id));
6068 unsigned height = iterator.Next();
6069 if (FLAG_print_code_verbose) {
6070 PrintF(out, "%24s %s {ast_id=%d, function=",
6071 "", Translation::StringFor(opcode), ast_id);
6072 function->PrintName(out);
6073 PrintF(out, ", height=%u}\n", height);
6074 }
6075
6076 // Size of translation is height plus all incoming arguments including
6077 // receiver.
6078 int size = height + function->shared()->formal_parameter_count() + 1;
6079 command_count += size;
6080 for (int j = 0; j < size; ++j) {
6081 opcode = static_cast<Translation::Opcode>(iterator.Next());
6082 if (FLAG_print_code_verbose) {
6083 PrintF(out, "%24s %s ", "", Translation::StringFor(opcode));
6084 }
6085
6086 if (opcode == Translation::DUPLICATE) {
6087 opcode = static_cast<Translation::Opcode>(iterator.Next());
6088 if (FLAG_print_code_verbose) {
6089 PrintF(out, "%s ", Translation::StringFor(opcode));
6090 }
6091 --j; // Two commands share the same frame index.
6092 }
6093
6094 switch (opcode) {
6095 case Translation::BEGIN:
6096 case Translation::FRAME:
6097 case Translation::DUPLICATE:
6098 UNREACHABLE();
6099 break;
6100
6101 case Translation::REGISTER: {
6102 int reg_code = iterator.Next();
6103 if (FLAG_print_code_verbose) {
6104 PrintF(out, "{input=%s}", converter.NameOfCPURegister(reg_code));
6105 }
6106 break;
6107 }
6108
6109 case Translation::INT32_REGISTER: {
6110 int reg_code = iterator.Next();
6111 if (FLAG_print_code_verbose) {
6112 PrintF(out, "{input=%s}", converter.NameOfCPURegister(reg_code));
6113 }
6114 break;
6115 }
6116
6117 case Translation::DOUBLE_REGISTER: {
6118 int reg_code = iterator.Next();
6119 if (FLAG_print_code_verbose) {
6120 PrintF(out, "{input=%s}",
6121 DoubleRegister::AllocationIndexToString(reg_code));
6122 }
6123 break;
6124 }
6125
6126 case Translation::STACK_SLOT: {
6127 int input_slot_index = iterator.Next();
6128 if (FLAG_print_code_verbose) {
6129 PrintF(out, "{input=%d}", input_slot_index);
6130 }
6131 break;
6132 }
6133
6134 case Translation::INT32_STACK_SLOT: {
6135 int input_slot_index = iterator.Next();
6136 if (FLAG_print_code_verbose) {
6137 PrintF(out, "{input=%d}", input_slot_index);
6138 }
6139 break;
6140 }
6141
6142 case Translation::DOUBLE_STACK_SLOT: {
6143 int input_slot_index = iterator.Next();
6144 if (FLAG_print_code_verbose) {
6145 PrintF(out, "{input=%d}", input_slot_index);
6146 }
6147 break;
6148 }
6149
6150 case Translation::LITERAL: {
6151 unsigned literal_index = iterator.Next();
6152 if (FLAG_print_code_verbose) {
6153 PrintF(out, "{literal_id=%u}", literal_index);
6154 }
6155 break;
6156 }
6157
6158 case Translation::ARGUMENTS_OBJECT:
6159 break;
6160 }
6161 if (FLAG_print_code_verbose) PrintF(out, "\n");
6162 }
6163 }
6164 if (!FLAG_print_code_verbose) PrintF(out, " %12d\n", command_count);
6165 }
6166}
6167
6168
6169void DeoptimizationOutputData::DeoptimizationOutputDataPrint(FILE* out) {
6170 PrintF(out, "Deoptimization Output Data (deopt points = %d)\n",
6171 this->DeoptPoints());
6172 if (this->DeoptPoints() == 0) return;
6173
6174 PrintF("%6s %8s %s\n", "ast id", "pc", "state");
6175 for (int i = 0; i < this->DeoptPoints(); i++) {
6176 int pc_and_state = this->PcAndState(i)->value();
6177 PrintF("%6d %8d %s\n",
6178 this->AstId(i)->value(),
6179 FullCodeGenerator::PcField::decode(pc_and_state),
6180 FullCodeGenerator::State2String(
6181 FullCodeGenerator::StateField::decode(pc_and_state)));
6182 }
6183}
6184
6185#endif
6186
6187
Steve Blocka7e24c12009-10-30 11:49:00 +00006188// Identify kind of code.
6189const char* Code::Kind2String(Kind kind) {
6190 switch (kind) {
6191 case FUNCTION: return "FUNCTION";
Ben Murdochb0fe1622011-05-05 13:52:32 +01006192 case OPTIMIZED_FUNCTION: return "OPTIMIZED_FUNCTION";
Steve Blocka7e24c12009-10-30 11:49:00 +00006193 case STUB: return "STUB";
6194 case BUILTIN: return "BUILTIN";
6195 case LOAD_IC: return "LOAD_IC";
6196 case KEYED_LOAD_IC: return "KEYED_LOAD_IC";
6197 case STORE_IC: return "STORE_IC";
6198 case KEYED_STORE_IC: return "KEYED_STORE_IC";
6199 case CALL_IC: return "CALL_IC";
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01006200 case KEYED_CALL_IC: return "KEYED_CALL_IC";
Steve Block6ded16b2010-05-10 14:33:55 +01006201 case BINARY_OP_IC: return "BINARY_OP_IC";
Ben Murdochb0fe1622011-05-05 13:52:32 +01006202 case TYPE_RECORDING_BINARY_OP_IC: return "TYPE_RECORDING_BINARY_OP_IC";
6203 case COMPARE_IC: return "COMPARE_IC";
Steve Blocka7e24c12009-10-30 11:49:00 +00006204 }
6205 UNREACHABLE();
6206 return NULL;
6207}
6208
6209
6210const char* Code::ICState2String(InlineCacheState state) {
6211 switch (state) {
6212 case UNINITIALIZED: return "UNINITIALIZED";
6213 case PREMONOMORPHIC: return "PREMONOMORPHIC";
6214 case MONOMORPHIC: return "MONOMORPHIC";
6215 case MONOMORPHIC_PROTOTYPE_FAILURE: return "MONOMORPHIC_PROTOTYPE_FAILURE";
6216 case MEGAMORPHIC: return "MEGAMORPHIC";
6217 case DEBUG_BREAK: return "DEBUG_BREAK";
6218 case DEBUG_PREPARE_STEP_IN: return "DEBUG_PREPARE_STEP_IN";
6219 }
6220 UNREACHABLE();
6221 return NULL;
6222}
6223
6224
6225const char* Code::PropertyType2String(PropertyType type) {
6226 switch (type) {
6227 case NORMAL: return "NORMAL";
6228 case FIELD: return "FIELD";
6229 case CONSTANT_FUNCTION: return "CONSTANT_FUNCTION";
6230 case CALLBACKS: return "CALLBACKS";
6231 case INTERCEPTOR: return "INTERCEPTOR";
6232 case MAP_TRANSITION: return "MAP_TRANSITION";
6233 case CONSTANT_TRANSITION: return "CONSTANT_TRANSITION";
6234 case NULL_DESCRIPTOR: return "NULL_DESCRIPTOR";
6235 }
6236 UNREACHABLE();
6237 return NULL;
6238}
6239
Ben Murdochb0fe1622011-05-05 13:52:32 +01006240
Steve Block1e0659c2011-05-24 12:43:12 +01006241void Code::PrintExtraICState(FILE* out, Kind kind, ExtraICState extra) {
6242 const char* name = NULL;
6243 switch (kind) {
6244 case CALL_IC:
6245 if (extra == STRING_INDEX_OUT_OF_BOUNDS) {
6246 name = "STRING_INDEX_OUT_OF_BOUNDS";
6247 }
6248 break;
6249 case STORE_IC:
6250 if (extra == StoreIC::kStoreICStrict) {
6251 name = "STRICT";
6252 }
6253 break;
6254 default:
6255 break;
6256 }
6257 if (name != NULL) {
6258 PrintF(out, "extra_ic_state = %s\n", name);
6259 } else {
6260 PrintF(out, "etra_ic_state = %d\n", extra);
6261 }
6262}
6263
6264
Ben Murdochb0fe1622011-05-05 13:52:32 +01006265void Code::Disassemble(const char* name, FILE* out) {
6266 PrintF(out, "kind = %s\n", Kind2String(kind()));
Steve Blocka7e24c12009-10-30 11:49:00 +00006267 if (is_inline_cache_stub()) {
Ben Murdochb0fe1622011-05-05 13:52:32 +01006268 PrintF(out, "ic_state = %s\n", ICState2String(ic_state()));
Steve Block1e0659c2011-05-24 12:43:12 +01006269 PrintExtraICState(out, kind(), extra_ic_state());
Ben Murdochb0fe1622011-05-05 13:52:32 +01006270 PrintF(out, "ic_in_loop = %d\n", ic_in_loop() == IN_LOOP);
Steve Blocka7e24c12009-10-30 11:49:00 +00006271 if (ic_state() == MONOMORPHIC) {
Ben Murdochb0fe1622011-05-05 13:52:32 +01006272 PrintF(out, "type = %s\n", PropertyType2String(type()));
Steve Blocka7e24c12009-10-30 11:49:00 +00006273 }
6274 }
6275 if ((name != NULL) && (name[0] != '\0')) {
Ben Murdochb0fe1622011-05-05 13:52:32 +01006276 PrintF(out, "name = %s\n", name);
6277 }
6278 if (kind() == OPTIMIZED_FUNCTION) {
6279 PrintF(out, "stack_slots = %d\n", stack_slots());
Steve Blocka7e24c12009-10-30 11:49:00 +00006280 }
6281
Ben Murdochb0fe1622011-05-05 13:52:32 +01006282 PrintF(out, "Instructions (size = %d)\n", instruction_size());
6283 Disassembler::Decode(out, this);
6284 PrintF(out, "\n");
6285
6286#ifdef DEBUG
6287 if (kind() == FUNCTION) {
6288 DeoptimizationOutputData* data =
6289 DeoptimizationOutputData::cast(this->deoptimization_data());
6290 data->DeoptimizationOutputDataPrint(out);
6291 } else if (kind() == OPTIMIZED_FUNCTION) {
6292 DeoptimizationInputData* data =
6293 DeoptimizationInputData::cast(this->deoptimization_data());
6294 data->DeoptimizationInputDataPrint(out);
6295 }
Steve Blocka7e24c12009-10-30 11:49:00 +00006296 PrintF("\n");
Ben Murdochb0fe1622011-05-05 13:52:32 +01006297#endif
6298
6299 if (kind() == OPTIMIZED_FUNCTION) {
6300 SafepointTable table(this);
6301 PrintF(out, "Safepoints (size = %u)\n", table.size());
6302 for (unsigned i = 0; i < table.length(); i++) {
6303 unsigned pc_offset = table.GetPcOffset(i);
6304 PrintF(out, "%p %4d ", (instruction_start() + pc_offset), pc_offset);
6305 table.PrintEntry(i);
6306 PrintF(out, " (sp -> fp)");
Ben Murdochb8e0da22011-05-16 14:20:40 +01006307 SafepointEntry entry = table.GetEntry(i);
6308 if (entry.deoptimization_index() != Safepoint::kNoDeoptimizationIndex) {
6309 PrintF(out, " %6d", entry.deoptimization_index());
Ben Murdochb0fe1622011-05-05 13:52:32 +01006310 } else {
6311 PrintF(out, " <none>");
6312 }
Ben Murdochb8e0da22011-05-16 14:20:40 +01006313 if (entry.argument_count() > 0) {
6314 PrintF(out, " argc: %d", entry.argument_count());
6315 }
Ben Murdochb0fe1622011-05-05 13:52:32 +01006316 PrintF(out, "\n");
6317 }
6318 PrintF(out, "\n");
6319 } else if (kind() == FUNCTION) {
Steve Block1e0659c2011-05-24 12:43:12 +01006320 unsigned offset = stack_check_table_offset();
Ben Murdochb0fe1622011-05-05 13:52:32 +01006321 // If there is no stack check table, the "table start" will at or after
6322 // (due to alignment) the end of the instruction stream.
6323 if (static_cast<int>(offset) < instruction_size()) {
6324 unsigned* address =
6325 reinterpret_cast<unsigned*>(instruction_start() + offset);
6326 unsigned length = address[0];
6327 PrintF(out, "Stack checks (size = %u)\n", length);
6328 PrintF(out, "ast_id pc_offset\n");
6329 for (unsigned i = 0; i < length; ++i) {
6330 unsigned index = (2 * i) + 1;
6331 PrintF(out, "%6u %9u\n", address[index], address[index + 1]);
6332 }
6333 PrintF(out, "\n");
6334 }
6335 }
Steve Blocka7e24c12009-10-30 11:49:00 +00006336
6337 PrintF("RelocInfo (size = %d)\n", relocation_size());
Ben Murdochb0fe1622011-05-05 13:52:32 +01006338 for (RelocIterator it(this); !it.done(); it.next()) it.rinfo()->Print(out);
6339 PrintF(out, "\n");
Steve Blocka7e24c12009-10-30 11:49:00 +00006340}
6341#endif // ENABLE_DISASSEMBLER
6342
6343
John Reck59135872010-11-02 12:39:01 -07006344MaybeObject* JSObject::SetFastElementsCapacityAndLength(int capacity,
6345 int length) {
Steve Block3ce2e202009-11-05 08:53:23 +00006346 // We should never end in here with a pixel or external array.
6347 ASSERT(!HasPixelElements() && !HasExternalArrayElements());
Steve Block8defd9f2010-07-08 12:39:36 +01006348
John Reck59135872010-11-02 12:39:01 -07006349 Object* obj;
6350 { MaybeObject* maybe_obj = Heap::AllocateFixedArrayWithHoles(capacity);
6351 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
6352 }
Steve Block8defd9f2010-07-08 12:39:36 +01006353 FixedArray* elems = FixedArray::cast(obj);
6354
John Reck59135872010-11-02 12:39:01 -07006355 { MaybeObject* maybe_obj = map()->GetFastElementsMap();
6356 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
6357 }
Steve Block8defd9f2010-07-08 12:39:36 +01006358 Map* new_map = Map::cast(obj);
6359
Leon Clarke4515c472010-02-03 11:58:03 +00006360 AssertNoAllocation no_gc;
6361 WriteBarrierMode mode = elems->GetWriteBarrierMode(no_gc);
Steve Blocka7e24c12009-10-30 11:49:00 +00006362 switch (GetElementsKind()) {
6363 case FAST_ELEMENTS: {
6364 FixedArray* old_elements = FixedArray::cast(elements());
6365 uint32_t old_length = static_cast<uint32_t>(old_elements->length());
6366 // Fill out the new array with this content and array holes.
6367 for (uint32_t i = 0; i < old_length; i++) {
6368 elems->set(i, old_elements->get(i), mode);
6369 }
6370 break;
6371 }
6372 case DICTIONARY_ELEMENTS: {
6373 NumberDictionary* dictionary = NumberDictionary::cast(elements());
6374 for (int i = 0; i < dictionary->Capacity(); i++) {
6375 Object* key = dictionary->KeyAt(i);
6376 if (key->IsNumber()) {
6377 uint32_t entry = static_cast<uint32_t>(key->Number());
6378 elems->set(entry, dictionary->ValueAt(i), mode);
6379 }
6380 }
6381 break;
6382 }
6383 default:
6384 UNREACHABLE();
6385 break;
6386 }
Steve Block8defd9f2010-07-08 12:39:36 +01006387
6388 set_map(new_map);
Steve Blocka7e24c12009-10-30 11:49:00 +00006389 set_elements(elems);
Steve Block8defd9f2010-07-08 12:39:36 +01006390
6391 if (IsJSArray()) {
6392 JSArray::cast(this)->set_length(Smi::FromInt(length));
6393 }
6394
6395 return this;
Steve Blocka7e24c12009-10-30 11:49:00 +00006396}
6397
6398
John Reck59135872010-11-02 12:39:01 -07006399MaybeObject* JSObject::SetSlowElements(Object* len) {
Steve Block3ce2e202009-11-05 08:53:23 +00006400 // We should never end in here with a pixel or external array.
6401 ASSERT(!HasPixelElements() && !HasExternalArrayElements());
Steve Blocka7e24c12009-10-30 11:49:00 +00006402
6403 uint32_t new_length = static_cast<uint32_t>(len->Number());
6404
6405 switch (GetElementsKind()) {
6406 case FAST_ELEMENTS: {
6407 // Make sure we never try to shrink dense arrays into sparse arrays.
6408 ASSERT(static_cast<uint32_t>(FixedArray::cast(elements())->length()) <=
6409 new_length);
John Reck59135872010-11-02 12:39:01 -07006410 Object* obj;
6411 { MaybeObject* maybe_obj = NormalizeElements();
6412 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
6413 }
Steve Blocka7e24c12009-10-30 11:49:00 +00006414
6415 // Update length for JSArrays.
6416 if (IsJSArray()) JSArray::cast(this)->set_length(len);
6417 break;
6418 }
6419 case DICTIONARY_ELEMENTS: {
6420 if (IsJSArray()) {
6421 uint32_t old_length =
Steve Block6ded16b2010-05-10 14:33:55 +01006422 static_cast<uint32_t>(JSArray::cast(this)->length()->Number());
Steve Blocka7e24c12009-10-30 11:49:00 +00006423 element_dictionary()->RemoveNumberEntries(new_length, old_length),
6424 JSArray::cast(this)->set_length(len);
6425 }
6426 break;
6427 }
6428 default:
6429 UNREACHABLE();
6430 break;
6431 }
6432 return this;
6433}
6434
6435
John Reck59135872010-11-02 12:39:01 -07006436MaybeObject* JSArray::Initialize(int capacity) {
Steve Blocka7e24c12009-10-30 11:49:00 +00006437 ASSERT(capacity >= 0);
Leon Clarke4515c472010-02-03 11:58:03 +00006438 set_length(Smi::FromInt(0));
Steve Blocka7e24c12009-10-30 11:49:00 +00006439 FixedArray* new_elements;
6440 if (capacity == 0) {
6441 new_elements = Heap::empty_fixed_array();
6442 } else {
John Reck59135872010-11-02 12:39:01 -07006443 Object* obj;
6444 { MaybeObject* maybe_obj = Heap::AllocateFixedArrayWithHoles(capacity);
6445 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
6446 }
Steve Blocka7e24c12009-10-30 11:49:00 +00006447 new_elements = FixedArray::cast(obj);
6448 }
6449 set_elements(new_elements);
6450 return this;
6451}
6452
6453
6454void JSArray::Expand(int required_size) {
6455 Handle<JSArray> self(this);
6456 Handle<FixedArray> old_backing(FixedArray::cast(elements()));
6457 int old_size = old_backing->length();
Steve Blockd0582a62009-12-15 09:54:21 +00006458 int new_size = required_size > old_size ? required_size : old_size;
Steve Blocka7e24c12009-10-30 11:49:00 +00006459 Handle<FixedArray> new_backing = Factory::NewFixedArray(new_size);
6460 // Can't use this any more now because we may have had a GC!
6461 for (int i = 0; i < old_size; i++) new_backing->set(i, old_backing->get(i));
6462 self->SetContent(*new_backing);
6463}
6464
6465
6466// Computes the new capacity when expanding the elements of a JSObject.
6467static int NewElementsCapacity(int old_capacity) {
6468 // (old_capacity + 50%) + 16
6469 return old_capacity + (old_capacity >> 1) + 16;
6470}
6471
6472
John Reck59135872010-11-02 12:39:01 -07006473static Failure* ArrayLengthRangeError() {
Steve Blocka7e24c12009-10-30 11:49:00 +00006474 HandleScope scope;
6475 return Top::Throw(*Factory::NewRangeError("invalid_array_length",
6476 HandleVector<Object>(NULL, 0)));
6477}
6478
6479
John Reck59135872010-11-02 12:39:01 -07006480MaybeObject* JSObject::SetElementsLength(Object* len) {
Steve Block3ce2e202009-11-05 08:53:23 +00006481 // We should never end in here with a pixel or external array.
Steve Block6ded16b2010-05-10 14:33:55 +01006482 ASSERT(AllowsSetElementsLength());
Steve Blocka7e24c12009-10-30 11:49:00 +00006483
John Reck59135872010-11-02 12:39:01 -07006484 MaybeObject* maybe_smi_length = len->ToSmi();
6485 Object* smi_length = Smi::FromInt(0);
6486 if (maybe_smi_length->ToObject(&smi_length) && smi_length->IsSmi()) {
Steve Block8defd9f2010-07-08 12:39:36 +01006487 const int value = Smi::cast(smi_length)->value();
Steve Blocka7e24c12009-10-30 11:49:00 +00006488 if (value < 0) return ArrayLengthRangeError();
6489 switch (GetElementsKind()) {
6490 case FAST_ELEMENTS: {
6491 int old_capacity = FixedArray::cast(elements())->length();
6492 if (value <= old_capacity) {
6493 if (IsJSArray()) {
John Reck59135872010-11-02 12:39:01 -07006494 Object* obj;
6495 { MaybeObject* maybe_obj = EnsureWritableFastElements();
6496 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
6497 }
Steve Blocka7e24c12009-10-30 11:49:00 +00006498 int old_length = FastD2I(JSArray::cast(this)->length()->Number());
6499 // NOTE: We may be able to optimize this by removing the
6500 // last part of the elements backing storage array and
6501 // setting the capacity to the new size.
6502 for (int i = value; i < old_length; i++) {
6503 FixedArray::cast(elements())->set_the_hole(i);
6504 }
Leon Clarke4515c472010-02-03 11:58:03 +00006505 JSArray::cast(this)->set_length(Smi::cast(smi_length));
Steve Blocka7e24c12009-10-30 11:49:00 +00006506 }
6507 return this;
6508 }
6509 int min = NewElementsCapacity(old_capacity);
6510 int new_capacity = value > min ? value : min;
6511 if (new_capacity <= kMaxFastElementsLength ||
6512 !ShouldConvertToSlowElements(new_capacity)) {
John Reck59135872010-11-02 12:39:01 -07006513 Object* obj;
6514 { MaybeObject* maybe_obj =
6515 SetFastElementsCapacityAndLength(new_capacity, value);
6516 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
6517 }
Steve Blocka7e24c12009-10-30 11:49:00 +00006518 return this;
6519 }
6520 break;
6521 }
6522 case DICTIONARY_ELEMENTS: {
6523 if (IsJSArray()) {
6524 if (value == 0) {
6525 // If the length of a slow array is reset to zero, we clear
6526 // the array and flush backing storage. This has the added
6527 // benefit that the array returns to fast mode.
John Reck59135872010-11-02 12:39:01 -07006528 Object* obj;
6529 { MaybeObject* maybe_obj = ResetElements();
6530 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
6531 }
Steve Blocka7e24c12009-10-30 11:49:00 +00006532 } else {
6533 // Remove deleted elements.
6534 uint32_t old_length =
6535 static_cast<uint32_t>(JSArray::cast(this)->length()->Number());
6536 element_dictionary()->RemoveNumberEntries(value, old_length);
6537 }
Leon Clarke4515c472010-02-03 11:58:03 +00006538 JSArray::cast(this)->set_length(Smi::cast(smi_length));
Steve Blocka7e24c12009-10-30 11:49:00 +00006539 }
6540 return this;
6541 }
6542 default:
6543 UNREACHABLE();
6544 break;
6545 }
6546 }
6547
6548 // General slow case.
6549 if (len->IsNumber()) {
6550 uint32_t length;
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01006551 if (len->ToArrayIndex(&length)) {
Steve Blocka7e24c12009-10-30 11:49:00 +00006552 return SetSlowElements(len);
6553 } else {
6554 return ArrayLengthRangeError();
6555 }
6556 }
6557
6558 // len is not a number so make the array size one and
6559 // set only element to len.
John Reck59135872010-11-02 12:39:01 -07006560 Object* obj;
6561 { MaybeObject* maybe_obj = Heap::AllocateFixedArray(1);
6562 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
6563 }
Steve Blocka7e24c12009-10-30 11:49:00 +00006564 FixedArray::cast(obj)->set(0, len);
Leon Clarke4515c472010-02-03 11:58:03 +00006565 if (IsJSArray()) JSArray::cast(this)->set_length(Smi::FromInt(1));
Steve Blocka7e24c12009-10-30 11:49:00 +00006566 set_elements(FixedArray::cast(obj));
6567 return this;
6568}
6569
6570
John Reck59135872010-11-02 12:39:01 -07006571MaybeObject* JSObject::SetPrototype(Object* value,
6572 bool skip_hidden_prototypes) {
Andrei Popescu402d9372010-02-26 13:31:12 +00006573 // Silently ignore the change if value is not a JSObject or null.
6574 // SpiderMonkey behaves this way.
6575 if (!value->IsJSObject() && !value->IsNull()) return value;
6576
6577 // Before we can set the prototype we need to be sure
6578 // prototype cycles are prevented.
6579 // It is sufficient to validate that the receiver is not in the new prototype
6580 // chain.
6581 for (Object* pt = value; pt != Heap::null_value(); pt = pt->GetPrototype()) {
6582 if (JSObject::cast(pt) == this) {
6583 // Cycle detected.
6584 HandleScope scope;
6585 return Top::Throw(*Factory::NewError("cyclic_proto",
6586 HandleVector<Object>(NULL, 0)));
6587 }
6588 }
6589
6590 JSObject* real_receiver = this;
6591
6592 if (skip_hidden_prototypes) {
6593 // Find the first object in the chain whose prototype object is not
6594 // hidden and set the new prototype on that object.
6595 Object* current_proto = real_receiver->GetPrototype();
6596 while (current_proto->IsJSObject() &&
6597 JSObject::cast(current_proto)->map()->is_hidden_prototype()) {
6598 real_receiver = JSObject::cast(current_proto);
6599 current_proto = current_proto->GetPrototype();
6600 }
6601 }
6602
6603 // Set the new prototype of the object.
John Reck59135872010-11-02 12:39:01 -07006604 Object* new_map;
6605 { MaybeObject* maybe_new_map = real_receiver->map()->CopyDropTransitions();
6606 if (!maybe_new_map->ToObject(&new_map)) return maybe_new_map;
6607 }
Andrei Popescu402d9372010-02-26 13:31:12 +00006608 Map::cast(new_map)->set_prototype(value);
6609 real_receiver->set_map(Map::cast(new_map));
6610
Kristian Monsen25f61362010-05-21 11:50:48 +01006611 Heap::ClearInstanceofCache();
6612
Andrei Popescu402d9372010-02-26 13:31:12 +00006613 return value;
6614}
6615
6616
Steve Blocka7e24c12009-10-30 11:49:00 +00006617bool JSObject::HasElementPostInterceptor(JSObject* receiver, uint32_t index) {
6618 switch (GetElementsKind()) {
6619 case FAST_ELEMENTS: {
6620 uint32_t length = IsJSArray() ?
6621 static_cast<uint32_t>
6622 (Smi::cast(JSArray::cast(this)->length())->value()) :
6623 static_cast<uint32_t>(FixedArray::cast(elements())->length());
6624 if ((index < length) &&
6625 !FixedArray::cast(elements())->get(index)->IsTheHole()) {
6626 return true;
6627 }
6628 break;
6629 }
6630 case PIXEL_ELEMENTS: {
6631 // TODO(iposva): Add testcase.
6632 PixelArray* pixels = PixelArray::cast(elements());
6633 if (index < static_cast<uint32_t>(pixels->length())) {
6634 return true;
6635 }
6636 break;
6637 }
Steve Block3ce2e202009-11-05 08:53:23 +00006638 case EXTERNAL_BYTE_ELEMENTS:
6639 case EXTERNAL_UNSIGNED_BYTE_ELEMENTS:
6640 case EXTERNAL_SHORT_ELEMENTS:
6641 case EXTERNAL_UNSIGNED_SHORT_ELEMENTS:
6642 case EXTERNAL_INT_ELEMENTS:
6643 case EXTERNAL_UNSIGNED_INT_ELEMENTS:
6644 case EXTERNAL_FLOAT_ELEMENTS: {
6645 // TODO(kbr): Add testcase.
6646 ExternalArray* array = ExternalArray::cast(elements());
6647 if (index < static_cast<uint32_t>(array->length())) {
6648 return true;
6649 }
6650 break;
6651 }
Steve Blocka7e24c12009-10-30 11:49:00 +00006652 case DICTIONARY_ELEMENTS: {
6653 if (element_dictionary()->FindEntry(index)
6654 != NumberDictionary::kNotFound) {
6655 return true;
6656 }
6657 break;
6658 }
6659 default:
6660 UNREACHABLE();
6661 break;
6662 }
6663
6664 // Handle [] on String objects.
6665 if (this->IsStringObjectWithCharacterAt(index)) return true;
6666
6667 Object* pt = GetPrototype();
6668 if (pt == Heap::null_value()) return false;
6669 return JSObject::cast(pt)->HasElementWithReceiver(receiver, index);
6670}
6671
6672
6673bool JSObject::HasElementWithInterceptor(JSObject* receiver, uint32_t index) {
6674 // Make sure that the top context does not change when doing
6675 // callbacks or interceptor calls.
6676 AssertNoContextChange ncc;
6677 HandleScope scope;
6678 Handle<InterceptorInfo> interceptor(GetIndexedInterceptor());
6679 Handle<JSObject> receiver_handle(receiver);
6680 Handle<JSObject> holder_handle(this);
6681 CustomArguments args(interceptor->data(), receiver, this);
6682 v8::AccessorInfo info(args.end());
6683 if (!interceptor->query()->IsUndefined()) {
6684 v8::IndexedPropertyQuery query =
6685 v8::ToCData<v8::IndexedPropertyQuery>(interceptor->query());
6686 LOG(ApiIndexedPropertyAccess("interceptor-indexed-has", this, index));
Iain Merrick75681382010-08-19 15:07:18 +01006687 v8::Handle<v8::Integer> result;
Steve Blocka7e24c12009-10-30 11:49:00 +00006688 {
6689 // Leaving JavaScript.
6690 VMState state(EXTERNAL);
6691 result = query(index, info);
6692 }
Iain Merrick75681382010-08-19 15:07:18 +01006693 if (!result.IsEmpty()) {
6694 ASSERT(result->IsInt32());
6695 return true; // absence of property is signaled by empty handle.
6696 }
Steve Blocka7e24c12009-10-30 11:49:00 +00006697 } else if (!interceptor->getter()->IsUndefined()) {
6698 v8::IndexedPropertyGetter getter =
6699 v8::ToCData<v8::IndexedPropertyGetter>(interceptor->getter());
6700 LOG(ApiIndexedPropertyAccess("interceptor-indexed-has-get", this, index));
6701 v8::Handle<v8::Value> result;
6702 {
6703 // Leaving JavaScript.
6704 VMState state(EXTERNAL);
6705 result = getter(index, info);
6706 }
6707 if (!result.IsEmpty()) return true;
6708 }
6709 return holder_handle->HasElementPostInterceptor(*receiver_handle, index);
6710}
6711
6712
Kristian Monsen0d5e1162010-09-30 15:31:59 +01006713JSObject::LocalElementType JSObject::HasLocalElement(uint32_t index) {
Steve Blocka7e24c12009-10-30 11:49:00 +00006714 // Check access rights if needed.
6715 if (IsAccessCheckNeeded() &&
6716 !Top::MayIndexedAccess(this, index, v8::ACCESS_HAS)) {
6717 Top::ReportFailedAccessCheck(this, v8::ACCESS_HAS);
Kristian Monsen0d5e1162010-09-30 15:31:59 +01006718 return UNDEFINED_ELEMENT;
Steve Blocka7e24c12009-10-30 11:49:00 +00006719 }
6720
Steve Block1e0659c2011-05-24 12:43:12 +01006721 if (IsJSGlobalProxy()) {
6722 Object* proto = GetPrototype();
6723 if (proto->IsNull()) return UNDEFINED_ELEMENT;
6724 ASSERT(proto->IsJSGlobalObject());
6725 return JSObject::cast(proto)->HasLocalElement(index);
6726 }
6727
Steve Blocka7e24c12009-10-30 11:49:00 +00006728 // Check for lookup interceptor
6729 if (HasIndexedInterceptor()) {
Kristian Monsen0d5e1162010-09-30 15:31:59 +01006730 return HasElementWithInterceptor(this, index) ? INTERCEPTED_ELEMENT
6731 : UNDEFINED_ELEMENT;
Steve Blocka7e24c12009-10-30 11:49:00 +00006732 }
6733
6734 // Handle [] on String objects.
Kristian Monsen0d5e1162010-09-30 15:31:59 +01006735 if (this->IsStringObjectWithCharacterAt(index)) {
6736 return STRING_CHARACTER_ELEMENT;
6737 }
Steve Blocka7e24c12009-10-30 11:49:00 +00006738
6739 switch (GetElementsKind()) {
6740 case FAST_ELEMENTS: {
6741 uint32_t length = IsJSArray() ?
6742 static_cast<uint32_t>
6743 (Smi::cast(JSArray::cast(this)->length())->value()) :
6744 static_cast<uint32_t>(FixedArray::cast(elements())->length());
Kristian Monsen0d5e1162010-09-30 15:31:59 +01006745 if ((index < length) &&
6746 !FixedArray::cast(elements())->get(index)->IsTheHole()) {
6747 return FAST_ELEMENT;
6748 }
6749 break;
Steve Blocka7e24c12009-10-30 11:49:00 +00006750 }
6751 case PIXEL_ELEMENTS: {
6752 PixelArray* pixels = PixelArray::cast(elements());
Kristian Monsen0d5e1162010-09-30 15:31:59 +01006753 if (index < static_cast<uint32_t>(pixels->length())) return FAST_ELEMENT;
6754 break;
Steve Blocka7e24c12009-10-30 11:49:00 +00006755 }
Steve Block3ce2e202009-11-05 08:53:23 +00006756 case EXTERNAL_BYTE_ELEMENTS:
6757 case EXTERNAL_UNSIGNED_BYTE_ELEMENTS:
6758 case EXTERNAL_SHORT_ELEMENTS:
6759 case EXTERNAL_UNSIGNED_SHORT_ELEMENTS:
6760 case EXTERNAL_INT_ELEMENTS:
6761 case EXTERNAL_UNSIGNED_INT_ELEMENTS:
6762 case EXTERNAL_FLOAT_ELEMENTS: {
6763 ExternalArray* array = ExternalArray::cast(elements());
Kristian Monsen0d5e1162010-09-30 15:31:59 +01006764 if (index < static_cast<uint32_t>(array->length())) return FAST_ELEMENT;
6765 break;
Steve Block3ce2e202009-11-05 08:53:23 +00006766 }
Steve Blocka7e24c12009-10-30 11:49:00 +00006767 case DICTIONARY_ELEMENTS: {
Kristian Monsen0d5e1162010-09-30 15:31:59 +01006768 if (element_dictionary()->FindEntry(index) !=
6769 NumberDictionary::kNotFound) {
6770 return DICTIONARY_ELEMENT;
6771 }
6772 break;
Steve Blocka7e24c12009-10-30 11:49:00 +00006773 }
6774 default:
6775 UNREACHABLE();
6776 break;
6777 }
Kristian Monsen0d5e1162010-09-30 15:31:59 +01006778
6779 return UNDEFINED_ELEMENT;
Steve Blocka7e24c12009-10-30 11:49:00 +00006780}
6781
6782
6783bool JSObject::HasElementWithReceiver(JSObject* receiver, uint32_t index) {
6784 // Check access rights if needed.
6785 if (IsAccessCheckNeeded() &&
6786 !Top::MayIndexedAccess(this, index, v8::ACCESS_HAS)) {
6787 Top::ReportFailedAccessCheck(this, v8::ACCESS_HAS);
6788 return false;
6789 }
6790
6791 // Check for lookup interceptor
6792 if (HasIndexedInterceptor()) {
6793 return HasElementWithInterceptor(receiver, index);
6794 }
6795
6796 switch (GetElementsKind()) {
6797 case FAST_ELEMENTS: {
6798 uint32_t length = IsJSArray() ?
6799 static_cast<uint32_t>
6800 (Smi::cast(JSArray::cast(this)->length())->value()) :
6801 static_cast<uint32_t>(FixedArray::cast(elements())->length());
6802 if ((index < length) &&
6803 !FixedArray::cast(elements())->get(index)->IsTheHole()) return true;
6804 break;
6805 }
6806 case PIXEL_ELEMENTS: {
6807 PixelArray* pixels = PixelArray::cast(elements());
6808 if (index < static_cast<uint32_t>(pixels->length())) {
6809 return true;
6810 }
6811 break;
6812 }
Steve Block3ce2e202009-11-05 08:53:23 +00006813 case EXTERNAL_BYTE_ELEMENTS:
6814 case EXTERNAL_UNSIGNED_BYTE_ELEMENTS:
6815 case EXTERNAL_SHORT_ELEMENTS:
6816 case EXTERNAL_UNSIGNED_SHORT_ELEMENTS:
6817 case EXTERNAL_INT_ELEMENTS:
6818 case EXTERNAL_UNSIGNED_INT_ELEMENTS:
6819 case EXTERNAL_FLOAT_ELEMENTS: {
6820 ExternalArray* array = ExternalArray::cast(elements());
6821 if (index < static_cast<uint32_t>(array->length())) {
6822 return true;
6823 }
6824 break;
6825 }
Steve Blocka7e24c12009-10-30 11:49:00 +00006826 case DICTIONARY_ELEMENTS: {
6827 if (element_dictionary()->FindEntry(index)
6828 != NumberDictionary::kNotFound) {
6829 return true;
6830 }
6831 break;
6832 }
6833 default:
6834 UNREACHABLE();
6835 break;
6836 }
6837
6838 // Handle [] on String objects.
6839 if (this->IsStringObjectWithCharacterAt(index)) return true;
6840
6841 Object* pt = GetPrototype();
6842 if (pt == Heap::null_value()) return false;
6843 return JSObject::cast(pt)->HasElementWithReceiver(receiver, index);
6844}
6845
6846
John Reck59135872010-11-02 12:39:01 -07006847MaybeObject* JSObject::SetElementWithInterceptor(uint32_t index,
Steve Block9fac8402011-05-12 15:51:54 +01006848 Object* value,
6849 bool check_prototype) {
Steve Blocka7e24c12009-10-30 11:49:00 +00006850 // Make sure that the top context does not change when doing
6851 // callbacks or interceptor calls.
6852 AssertNoContextChange ncc;
6853 HandleScope scope;
6854 Handle<InterceptorInfo> interceptor(GetIndexedInterceptor());
6855 Handle<JSObject> this_handle(this);
6856 Handle<Object> value_handle(value);
6857 if (!interceptor->setter()->IsUndefined()) {
6858 v8::IndexedPropertySetter setter =
6859 v8::ToCData<v8::IndexedPropertySetter>(interceptor->setter());
6860 LOG(ApiIndexedPropertyAccess("interceptor-indexed-set", this, index));
6861 CustomArguments args(interceptor->data(), this, this);
6862 v8::AccessorInfo info(args.end());
6863 v8::Handle<v8::Value> result;
6864 {
6865 // Leaving JavaScript.
6866 VMState state(EXTERNAL);
6867 result = setter(index, v8::Utils::ToLocal(value_handle), info);
6868 }
6869 RETURN_IF_SCHEDULED_EXCEPTION();
6870 if (!result.IsEmpty()) return *value_handle;
6871 }
John Reck59135872010-11-02 12:39:01 -07006872 MaybeObject* raw_result =
Steve Block9fac8402011-05-12 15:51:54 +01006873 this_handle->SetElementWithoutInterceptor(index,
6874 *value_handle,
6875 check_prototype);
Steve Blocka7e24c12009-10-30 11:49:00 +00006876 RETURN_IF_SCHEDULED_EXCEPTION();
6877 return raw_result;
6878}
6879
6880
John Reck59135872010-11-02 12:39:01 -07006881MaybeObject* JSObject::GetElementWithCallback(Object* receiver,
6882 Object* structure,
6883 uint32_t index,
6884 Object* holder) {
Leon Clarkef7060e22010-06-03 12:02:55 +01006885 ASSERT(!structure->IsProxy());
6886
6887 // api style callbacks.
6888 if (structure->IsAccessorInfo()) {
6889 AccessorInfo* data = AccessorInfo::cast(structure);
6890 Object* fun_obj = data->getter();
6891 v8::AccessorGetter call_fun = v8::ToCData<v8::AccessorGetter>(fun_obj);
6892 HandleScope scope;
6893 Handle<JSObject> self(JSObject::cast(receiver));
6894 Handle<JSObject> holder_handle(JSObject::cast(holder));
6895 Handle<Object> number = Factory::NewNumberFromUint(index);
6896 Handle<String> key(Factory::NumberToString(number));
6897 LOG(ApiNamedPropertyAccess("load", *self, *key));
6898 CustomArguments args(data->data(), *self, *holder_handle);
6899 v8::AccessorInfo info(args.end());
6900 v8::Handle<v8::Value> result;
6901 {
6902 // Leaving JavaScript.
6903 VMState state(EXTERNAL);
6904 result = call_fun(v8::Utils::ToLocal(key), info);
6905 }
6906 RETURN_IF_SCHEDULED_EXCEPTION();
6907 if (result.IsEmpty()) return Heap::undefined_value();
6908 return *v8::Utils::OpenHandle(*result);
6909 }
6910
6911 // __defineGetter__ callback
6912 if (structure->IsFixedArray()) {
6913 Object* getter = FixedArray::cast(structure)->get(kGetterIndex);
6914 if (getter->IsJSFunction()) {
6915 return Object::GetPropertyWithDefinedGetter(receiver,
6916 JSFunction::cast(getter));
6917 }
6918 // Getter is not a function.
6919 return Heap::undefined_value();
6920 }
6921
6922 UNREACHABLE();
6923 return NULL;
6924}
6925
6926
John Reck59135872010-11-02 12:39:01 -07006927MaybeObject* JSObject::SetElementWithCallback(Object* structure,
6928 uint32_t index,
6929 Object* value,
6930 JSObject* holder) {
Leon Clarkef7060e22010-06-03 12:02:55 +01006931 HandleScope scope;
6932
6933 // We should never get here to initialize a const with the hole
6934 // value since a const declaration would conflict with the setter.
6935 ASSERT(!value->IsTheHole());
6936 Handle<Object> value_handle(value);
6937
6938 // To accommodate both the old and the new api we switch on the
6939 // data structure used to store the callbacks. Eventually proxy
6940 // callbacks should be phased out.
6941 ASSERT(!structure->IsProxy());
6942
6943 if (structure->IsAccessorInfo()) {
6944 // api style callbacks
6945 AccessorInfo* data = AccessorInfo::cast(structure);
6946 Object* call_obj = data->setter();
6947 v8::AccessorSetter call_fun = v8::ToCData<v8::AccessorSetter>(call_obj);
6948 if (call_fun == NULL) return value;
6949 Handle<Object> number = Factory::NewNumberFromUint(index);
6950 Handle<String> key(Factory::NumberToString(number));
6951 LOG(ApiNamedPropertyAccess("store", this, *key));
6952 CustomArguments args(data->data(), this, JSObject::cast(holder));
6953 v8::AccessorInfo info(args.end());
6954 {
6955 // Leaving JavaScript.
6956 VMState state(EXTERNAL);
6957 call_fun(v8::Utils::ToLocal(key),
6958 v8::Utils::ToLocal(value_handle),
6959 info);
6960 }
6961 RETURN_IF_SCHEDULED_EXCEPTION();
6962 return *value_handle;
6963 }
6964
6965 if (structure->IsFixedArray()) {
6966 Object* setter = FixedArray::cast(structure)->get(kSetterIndex);
6967 if (setter->IsJSFunction()) {
6968 return SetPropertyWithDefinedSetter(JSFunction::cast(setter), value);
6969 } else {
6970 Handle<Object> holder_handle(holder);
6971 Handle<Object> key(Factory::NewNumberFromUint(index));
6972 Handle<Object> args[2] = { key, holder_handle };
6973 return Top::Throw(*Factory::NewTypeError("no_setter_in_callback",
6974 HandleVector(args, 2)));
6975 }
6976 }
6977
6978 UNREACHABLE();
6979 return NULL;
6980}
6981
6982
Steve Blocka7e24c12009-10-30 11:49:00 +00006983// Adding n elements in fast case is O(n*n).
6984// Note: revisit design to have dual undefined values to capture absent
6985// elements.
Steve Block9fac8402011-05-12 15:51:54 +01006986MaybeObject* JSObject::SetFastElement(uint32_t index,
6987 Object* value,
6988 bool check_prototype) {
Steve Blocka7e24c12009-10-30 11:49:00 +00006989 ASSERT(HasFastElements());
6990
John Reck59135872010-11-02 12:39:01 -07006991 Object* elms_obj;
6992 { MaybeObject* maybe_elms_obj = EnsureWritableFastElements();
6993 if (!maybe_elms_obj->ToObject(&elms_obj)) return maybe_elms_obj;
6994 }
Iain Merrick75681382010-08-19 15:07:18 +01006995 FixedArray* elms = FixedArray::cast(elms_obj);
Steve Blocka7e24c12009-10-30 11:49:00 +00006996 uint32_t elms_length = static_cast<uint32_t>(elms->length());
6997
Steve Block9fac8402011-05-12 15:51:54 +01006998 if (check_prototype &&
Steve Block1e0659c2011-05-24 12:43:12 +01006999 (index >= elms_length || elms->get(index)->IsTheHole())) {
7000 bool found;
7001 MaybeObject* result =
7002 SetElementWithCallbackSetterInPrototypes(index, value, &found);
7003 if (found) return result;
Steve Blocka7e24c12009-10-30 11:49:00 +00007004 }
7005
Steve Block9fac8402011-05-12 15:51:54 +01007006
Steve Blocka7e24c12009-10-30 11:49:00 +00007007 // Check whether there is extra space in fixed array..
7008 if (index < elms_length) {
7009 elms->set(index, value);
7010 if (IsJSArray()) {
7011 // Update the length of the array if needed.
7012 uint32_t array_length = 0;
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01007013 CHECK(JSArray::cast(this)->length()->ToArrayIndex(&array_length));
Steve Blocka7e24c12009-10-30 11:49:00 +00007014 if (index >= array_length) {
Leon Clarke4515c472010-02-03 11:58:03 +00007015 JSArray::cast(this)->set_length(Smi::FromInt(index + 1));
Steve Blocka7e24c12009-10-30 11:49:00 +00007016 }
7017 }
7018 return value;
7019 }
7020
7021 // Allow gap in fast case.
7022 if ((index - elms_length) < kMaxGap) {
7023 // Try allocating extra space.
7024 int new_capacity = NewElementsCapacity(index+1);
7025 if (new_capacity <= kMaxFastElementsLength ||
7026 !ShouldConvertToSlowElements(new_capacity)) {
7027 ASSERT(static_cast<uint32_t>(new_capacity) > index);
John Reck59135872010-11-02 12:39:01 -07007028 Object* obj;
7029 { MaybeObject* maybe_obj =
7030 SetFastElementsCapacityAndLength(new_capacity, index + 1);
7031 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
7032 }
Steve Blocka7e24c12009-10-30 11:49:00 +00007033 FixedArray::cast(elements())->set(index, value);
7034 return value;
7035 }
7036 }
7037
7038 // Otherwise default to slow case.
John Reck59135872010-11-02 12:39:01 -07007039 Object* obj;
7040 { MaybeObject* maybe_obj = NormalizeElements();
7041 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
7042 }
Steve Blocka7e24c12009-10-30 11:49:00 +00007043 ASSERT(HasDictionaryElements());
Steve Block9fac8402011-05-12 15:51:54 +01007044 return SetElement(index, value, check_prototype);
Steve Blocka7e24c12009-10-30 11:49:00 +00007045}
7046
Iain Merrick75681382010-08-19 15:07:18 +01007047
Steve Block9fac8402011-05-12 15:51:54 +01007048MaybeObject* JSObject::SetElement(uint32_t index,
7049 Object* value,
7050 bool check_prototype) {
Steve Blocka7e24c12009-10-30 11:49:00 +00007051 // Check access rights if needed.
7052 if (IsAccessCheckNeeded() &&
7053 !Top::MayIndexedAccess(this, index, v8::ACCESS_SET)) {
Iain Merrick75681382010-08-19 15:07:18 +01007054 HandleScope scope;
7055 Handle<Object> value_handle(value);
Steve Blocka7e24c12009-10-30 11:49:00 +00007056 Top::ReportFailedAccessCheck(this, v8::ACCESS_SET);
Iain Merrick75681382010-08-19 15:07:18 +01007057 return *value_handle;
Steve Blocka7e24c12009-10-30 11:49:00 +00007058 }
7059
7060 if (IsJSGlobalProxy()) {
7061 Object* proto = GetPrototype();
7062 if (proto->IsNull()) return value;
7063 ASSERT(proto->IsJSGlobalObject());
Steve Block9fac8402011-05-12 15:51:54 +01007064 return JSObject::cast(proto)->SetElement(index, value, check_prototype);
Steve Blocka7e24c12009-10-30 11:49:00 +00007065 }
7066
7067 // Check for lookup interceptor
7068 if (HasIndexedInterceptor()) {
Steve Block9fac8402011-05-12 15:51:54 +01007069 return SetElementWithInterceptor(index, value, check_prototype);
Steve Blocka7e24c12009-10-30 11:49:00 +00007070 }
7071
Steve Block9fac8402011-05-12 15:51:54 +01007072 return SetElementWithoutInterceptor(index, value, check_prototype);
Steve Blocka7e24c12009-10-30 11:49:00 +00007073}
7074
7075
John Reck59135872010-11-02 12:39:01 -07007076MaybeObject* JSObject::SetElementWithoutInterceptor(uint32_t index,
Steve Block9fac8402011-05-12 15:51:54 +01007077 Object* value,
7078 bool check_prototype) {
Steve Blocka7e24c12009-10-30 11:49:00 +00007079 switch (GetElementsKind()) {
7080 case FAST_ELEMENTS:
7081 // Fast case.
Steve Block9fac8402011-05-12 15:51:54 +01007082 return SetFastElement(index, value, check_prototype);
Steve Blocka7e24c12009-10-30 11:49:00 +00007083 case PIXEL_ELEMENTS: {
7084 PixelArray* pixels = PixelArray::cast(elements());
7085 return pixels->SetValue(index, value);
7086 }
Steve Block3ce2e202009-11-05 08:53:23 +00007087 case EXTERNAL_BYTE_ELEMENTS: {
7088 ExternalByteArray* array = ExternalByteArray::cast(elements());
7089 return array->SetValue(index, value);
7090 }
7091 case EXTERNAL_UNSIGNED_BYTE_ELEMENTS: {
7092 ExternalUnsignedByteArray* array =
7093 ExternalUnsignedByteArray::cast(elements());
7094 return array->SetValue(index, value);
7095 }
7096 case EXTERNAL_SHORT_ELEMENTS: {
7097 ExternalShortArray* array = ExternalShortArray::cast(elements());
7098 return array->SetValue(index, value);
7099 }
7100 case EXTERNAL_UNSIGNED_SHORT_ELEMENTS: {
7101 ExternalUnsignedShortArray* array =
7102 ExternalUnsignedShortArray::cast(elements());
7103 return array->SetValue(index, value);
7104 }
7105 case EXTERNAL_INT_ELEMENTS: {
7106 ExternalIntArray* array = ExternalIntArray::cast(elements());
7107 return array->SetValue(index, value);
7108 }
7109 case EXTERNAL_UNSIGNED_INT_ELEMENTS: {
7110 ExternalUnsignedIntArray* array =
7111 ExternalUnsignedIntArray::cast(elements());
7112 return array->SetValue(index, value);
7113 }
7114 case EXTERNAL_FLOAT_ELEMENTS: {
7115 ExternalFloatArray* array = ExternalFloatArray::cast(elements());
7116 return array->SetValue(index, value);
7117 }
Steve Blocka7e24c12009-10-30 11:49:00 +00007118 case DICTIONARY_ELEMENTS: {
7119 // Insert element in the dictionary.
7120 FixedArray* elms = FixedArray::cast(elements());
7121 NumberDictionary* dictionary = NumberDictionary::cast(elms);
7122
7123 int entry = dictionary->FindEntry(index);
7124 if (entry != NumberDictionary::kNotFound) {
7125 Object* element = dictionary->ValueAt(entry);
7126 PropertyDetails details = dictionary->DetailsAt(entry);
7127 if (details.type() == CALLBACKS) {
Leon Clarkef7060e22010-06-03 12:02:55 +01007128 return SetElementWithCallback(element, index, value, this);
Steve Blocka7e24c12009-10-30 11:49:00 +00007129 } else {
7130 dictionary->UpdateMaxNumberKey(index);
7131 dictionary->ValueAtPut(entry, value);
7132 }
7133 } else {
7134 // Index not already used. Look for an accessor in the prototype chain.
Steve Block1e0659c2011-05-24 12:43:12 +01007135 if (check_prototype) {
7136 bool found;
7137 MaybeObject* result =
7138 SetElementWithCallbackSetterInPrototypes(index, value, &found);
7139 if (found) return result;
Steve Blocka7e24c12009-10-30 11:49:00 +00007140 }
Steve Block8defd9f2010-07-08 12:39:36 +01007141 // When we set the is_extensible flag to false we always force
7142 // the element into dictionary mode (and force them to stay there).
7143 if (!map()->is_extensible()) {
Ben Murdochf87a2032010-10-22 12:50:53 +01007144 Handle<Object> number(Factory::NewNumberFromUint(index));
Steve Block8defd9f2010-07-08 12:39:36 +01007145 Handle<String> index_string(Factory::NumberToString(number));
7146 Handle<Object> args[1] = { index_string };
7147 return Top::Throw(*Factory::NewTypeError("object_not_extensible",
7148 HandleVector(args, 1)));
7149 }
John Reck59135872010-11-02 12:39:01 -07007150 Object* result;
7151 { MaybeObject* maybe_result = dictionary->AtNumberPut(index, value);
7152 if (!maybe_result->ToObject(&result)) return maybe_result;
7153 }
Steve Blocka7e24c12009-10-30 11:49:00 +00007154 if (elms != FixedArray::cast(result)) {
7155 set_elements(FixedArray::cast(result));
7156 }
7157 }
7158
7159 // Update the array length if this JSObject is an array.
7160 if (IsJSArray()) {
7161 JSArray* array = JSArray::cast(this);
John Reck59135872010-11-02 12:39:01 -07007162 Object* return_value;
7163 { MaybeObject* maybe_return_value =
7164 array->JSArrayUpdateLengthFromIndex(index, value);
7165 if (!maybe_return_value->ToObject(&return_value)) {
7166 return maybe_return_value;
7167 }
7168 }
Steve Blocka7e24c12009-10-30 11:49:00 +00007169 }
7170
7171 // Attempt to put this object back in fast case.
7172 if (ShouldConvertToFastElements()) {
7173 uint32_t new_length = 0;
7174 if (IsJSArray()) {
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01007175 CHECK(JSArray::cast(this)->length()->ToArrayIndex(&new_length));
Steve Blocka7e24c12009-10-30 11:49:00 +00007176 } else {
7177 new_length = NumberDictionary::cast(elements())->max_number_key() + 1;
7178 }
John Reck59135872010-11-02 12:39:01 -07007179 Object* obj;
7180 { MaybeObject* maybe_obj =
7181 SetFastElementsCapacityAndLength(new_length, new_length);
7182 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
7183 }
Steve Blocka7e24c12009-10-30 11:49:00 +00007184#ifdef DEBUG
7185 if (FLAG_trace_normalization) {
7186 PrintF("Object elements are fast case again:\n");
7187 Print();
7188 }
7189#endif
7190 }
7191
7192 return value;
7193 }
7194 default:
7195 UNREACHABLE();
7196 break;
7197 }
7198 // All possible cases have been handled above. Add a return to avoid the
7199 // complaints from the compiler.
7200 UNREACHABLE();
7201 return Heap::null_value();
7202}
7203
7204
John Reck59135872010-11-02 12:39:01 -07007205MaybeObject* JSArray::JSArrayUpdateLengthFromIndex(uint32_t index,
7206 Object* value) {
Steve Blocka7e24c12009-10-30 11:49:00 +00007207 uint32_t old_len = 0;
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01007208 CHECK(length()->ToArrayIndex(&old_len));
Steve Blocka7e24c12009-10-30 11:49:00 +00007209 // Check to see if we need to update the length. For now, we make
7210 // sure that the length stays within 32-bits (unsigned).
7211 if (index >= old_len && index != 0xffffffff) {
John Reck59135872010-11-02 12:39:01 -07007212 Object* len;
7213 { MaybeObject* maybe_len =
7214 Heap::NumberFromDouble(static_cast<double>(index) + 1);
7215 if (!maybe_len->ToObject(&len)) return maybe_len;
7216 }
Steve Blocka7e24c12009-10-30 11:49:00 +00007217 set_length(len);
7218 }
7219 return value;
7220}
7221
7222
John Reck59135872010-11-02 12:39:01 -07007223MaybeObject* JSObject::GetElementPostInterceptor(JSObject* receiver,
7224 uint32_t index) {
Steve Blocka7e24c12009-10-30 11:49:00 +00007225 // Get element works for both JSObject and JSArray since
7226 // JSArray::length cannot change.
7227 switch (GetElementsKind()) {
7228 case FAST_ELEMENTS: {
7229 FixedArray* elms = FixedArray::cast(elements());
7230 if (index < static_cast<uint32_t>(elms->length())) {
7231 Object* value = elms->get(index);
7232 if (!value->IsTheHole()) return value;
7233 }
7234 break;
7235 }
7236 case PIXEL_ELEMENTS: {
7237 // TODO(iposva): Add testcase and implement.
7238 UNIMPLEMENTED();
7239 break;
7240 }
Steve Block3ce2e202009-11-05 08:53:23 +00007241 case EXTERNAL_BYTE_ELEMENTS:
7242 case EXTERNAL_UNSIGNED_BYTE_ELEMENTS:
7243 case EXTERNAL_SHORT_ELEMENTS:
7244 case EXTERNAL_UNSIGNED_SHORT_ELEMENTS:
7245 case EXTERNAL_INT_ELEMENTS:
7246 case EXTERNAL_UNSIGNED_INT_ELEMENTS:
7247 case EXTERNAL_FLOAT_ELEMENTS: {
7248 // TODO(kbr): Add testcase and implement.
7249 UNIMPLEMENTED();
7250 break;
7251 }
Steve Blocka7e24c12009-10-30 11:49:00 +00007252 case DICTIONARY_ELEMENTS: {
7253 NumberDictionary* dictionary = element_dictionary();
7254 int entry = dictionary->FindEntry(index);
7255 if (entry != NumberDictionary::kNotFound) {
7256 Object* element = dictionary->ValueAt(entry);
7257 PropertyDetails details = dictionary->DetailsAt(entry);
7258 if (details.type() == CALLBACKS) {
Leon Clarkef7060e22010-06-03 12:02:55 +01007259 return GetElementWithCallback(receiver,
7260 element,
7261 index,
7262 this);
Steve Blocka7e24c12009-10-30 11:49:00 +00007263 }
7264 return element;
7265 }
7266 break;
7267 }
7268 default:
7269 UNREACHABLE();
7270 break;
7271 }
7272
7273 // Continue searching via the prototype chain.
7274 Object* pt = GetPrototype();
7275 if (pt == Heap::null_value()) return Heap::undefined_value();
7276 return pt->GetElementWithReceiver(receiver, index);
7277}
7278
7279
John Reck59135872010-11-02 12:39:01 -07007280MaybeObject* JSObject::GetElementWithInterceptor(JSObject* receiver,
7281 uint32_t index) {
Steve Blocka7e24c12009-10-30 11:49:00 +00007282 // Make sure that the top context does not change when doing
7283 // callbacks or interceptor calls.
7284 AssertNoContextChange ncc;
7285 HandleScope scope;
7286 Handle<InterceptorInfo> interceptor(GetIndexedInterceptor());
7287 Handle<JSObject> this_handle(receiver);
7288 Handle<JSObject> holder_handle(this);
7289
7290 if (!interceptor->getter()->IsUndefined()) {
7291 v8::IndexedPropertyGetter getter =
7292 v8::ToCData<v8::IndexedPropertyGetter>(interceptor->getter());
7293 LOG(ApiIndexedPropertyAccess("interceptor-indexed-get", this, index));
7294 CustomArguments args(interceptor->data(), receiver, this);
7295 v8::AccessorInfo info(args.end());
7296 v8::Handle<v8::Value> result;
7297 {
7298 // Leaving JavaScript.
7299 VMState state(EXTERNAL);
7300 result = getter(index, info);
7301 }
7302 RETURN_IF_SCHEDULED_EXCEPTION();
7303 if (!result.IsEmpty()) return *v8::Utils::OpenHandle(*result);
7304 }
7305
John Reck59135872010-11-02 12:39:01 -07007306 MaybeObject* raw_result =
Steve Blocka7e24c12009-10-30 11:49:00 +00007307 holder_handle->GetElementPostInterceptor(*this_handle, index);
7308 RETURN_IF_SCHEDULED_EXCEPTION();
7309 return raw_result;
7310}
7311
7312
John Reck59135872010-11-02 12:39:01 -07007313MaybeObject* JSObject::GetElementWithReceiver(JSObject* receiver,
7314 uint32_t index) {
Steve Blocka7e24c12009-10-30 11:49:00 +00007315 // Check access rights if needed.
7316 if (IsAccessCheckNeeded() &&
7317 !Top::MayIndexedAccess(this, index, v8::ACCESS_GET)) {
7318 Top::ReportFailedAccessCheck(this, v8::ACCESS_GET);
7319 return Heap::undefined_value();
7320 }
7321
7322 if (HasIndexedInterceptor()) {
7323 return GetElementWithInterceptor(receiver, index);
7324 }
7325
7326 // Get element works for both JSObject and JSArray since
7327 // JSArray::length cannot change.
7328 switch (GetElementsKind()) {
7329 case FAST_ELEMENTS: {
7330 FixedArray* elms = FixedArray::cast(elements());
7331 if (index < static_cast<uint32_t>(elms->length())) {
7332 Object* value = elms->get(index);
7333 if (!value->IsTheHole()) return value;
7334 }
7335 break;
7336 }
7337 case PIXEL_ELEMENTS: {
7338 PixelArray* pixels = PixelArray::cast(elements());
7339 if (index < static_cast<uint32_t>(pixels->length())) {
7340 uint8_t value = pixels->get(index);
7341 return Smi::FromInt(value);
7342 }
7343 break;
7344 }
Steve Block3ce2e202009-11-05 08:53:23 +00007345 case EXTERNAL_BYTE_ELEMENTS: {
7346 ExternalByteArray* array = ExternalByteArray::cast(elements());
7347 if (index < static_cast<uint32_t>(array->length())) {
7348 int8_t value = array->get(index);
7349 return Smi::FromInt(value);
7350 }
7351 break;
7352 }
7353 case EXTERNAL_UNSIGNED_BYTE_ELEMENTS: {
7354 ExternalUnsignedByteArray* array =
7355 ExternalUnsignedByteArray::cast(elements());
7356 if (index < static_cast<uint32_t>(array->length())) {
7357 uint8_t value = array->get(index);
7358 return Smi::FromInt(value);
7359 }
7360 break;
7361 }
7362 case EXTERNAL_SHORT_ELEMENTS: {
7363 ExternalShortArray* array = ExternalShortArray::cast(elements());
7364 if (index < static_cast<uint32_t>(array->length())) {
7365 int16_t value = array->get(index);
7366 return Smi::FromInt(value);
7367 }
7368 break;
7369 }
7370 case EXTERNAL_UNSIGNED_SHORT_ELEMENTS: {
7371 ExternalUnsignedShortArray* array =
7372 ExternalUnsignedShortArray::cast(elements());
7373 if (index < static_cast<uint32_t>(array->length())) {
7374 uint16_t value = array->get(index);
7375 return Smi::FromInt(value);
7376 }
7377 break;
7378 }
7379 case EXTERNAL_INT_ELEMENTS: {
7380 ExternalIntArray* array = ExternalIntArray::cast(elements());
7381 if (index < static_cast<uint32_t>(array->length())) {
7382 int32_t value = array->get(index);
7383 return Heap::NumberFromInt32(value);
7384 }
7385 break;
7386 }
7387 case EXTERNAL_UNSIGNED_INT_ELEMENTS: {
7388 ExternalUnsignedIntArray* array =
7389 ExternalUnsignedIntArray::cast(elements());
7390 if (index < static_cast<uint32_t>(array->length())) {
7391 uint32_t value = array->get(index);
7392 return Heap::NumberFromUint32(value);
7393 }
7394 break;
7395 }
7396 case EXTERNAL_FLOAT_ELEMENTS: {
7397 ExternalFloatArray* array = ExternalFloatArray::cast(elements());
7398 if (index < static_cast<uint32_t>(array->length())) {
7399 float value = array->get(index);
7400 return Heap::AllocateHeapNumber(value);
7401 }
7402 break;
7403 }
Steve Blocka7e24c12009-10-30 11:49:00 +00007404 case DICTIONARY_ELEMENTS: {
7405 NumberDictionary* dictionary = element_dictionary();
7406 int entry = dictionary->FindEntry(index);
7407 if (entry != NumberDictionary::kNotFound) {
7408 Object* element = dictionary->ValueAt(entry);
7409 PropertyDetails details = dictionary->DetailsAt(entry);
7410 if (details.type() == CALLBACKS) {
Leon Clarkef7060e22010-06-03 12:02:55 +01007411 return GetElementWithCallback(receiver,
7412 element,
7413 index,
7414 this);
Steve Blocka7e24c12009-10-30 11:49:00 +00007415 }
7416 return element;
7417 }
7418 break;
7419 }
7420 }
7421
7422 Object* pt = GetPrototype();
7423 if (pt == Heap::null_value()) return Heap::undefined_value();
7424 return pt->GetElementWithReceiver(receiver, index);
7425}
7426
7427
7428bool JSObject::HasDenseElements() {
7429 int capacity = 0;
7430 int number_of_elements = 0;
7431
7432 switch (GetElementsKind()) {
7433 case FAST_ELEMENTS: {
7434 FixedArray* elms = FixedArray::cast(elements());
7435 capacity = elms->length();
7436 for (int i = 0; i < capacity; i++) {
7437 if (!elms->get(i)->IsTheHole()) number_of_elements++;
7438 }
7439 break;
7440 }
Steve Block3ce2e202009-11-05 08:53:23 +00007441 case PIXEL_ELEMENTS:
7442 case EXTERNAL_BYTE_ELEMENTS:
7443 case EXTERNAL_UNSIGNED_BYTE_ELEMENTS:
7444 case EXTERNAL_SHORT_ELEMENTS:
7445 case EXTERNAL_UNSIGNED_SHORT_ELEMENTS:
7446 case EXTERNAL_INT_ELEMENTS:
7447 case EXTERNAL_UNSIGNED_INT_ELEMENTS:
7448 case EXTERNAL_FLOAT_ELEMENTS: {
Steve Blocka7e24c12009-10-30 11:49:00 +00007449 return true;
7450 }
7451 case DICTIONARY_ELEMENTS: {
7452 NumberDictionary* dictionary = NumberDictionary::cast(elements());
7453 capacity = dictionary->Capacity();
7454 number_of_elements = dictionary->NumberOfElements();
7455 break;
7456 }
7457 default:
7458 UNREACHABLE();
7459 break;
7460 }
7461
7462 if (capacity == 0) return true;
7463 return (number_of_elements > (capacity / 2));
7464}
7465
7466
7467bool JSObject::ShouldConvertToSlowElements(int new_capacity) {
7468 ASSERT(HasFastElements());
7469 // Keep the array in fast case if the current backing storage is
7470 // almost filled and if the new capacity is no more than twice the
7471 // old capacity.
7472 int elements_length = FixedArray::cast(elements())->length();
7473 return !HasDenseElements() || ((new_capacity / 2) > elements_length);
7474}
7475
7476
7477bool JSObject::ShouldConvertToFastElements() {
7478 ASSERT(HasDictionaryElements());
7479 NumberDictionary* dictionary = NumberDictionary::cast(elements());
7480 // If the elements are sparse, we should not go back to fast case.
7481 if (!HasDenseElements()) return false;
7482 // If an element has been added at a very high index in the elements
7483 // dictionary, we cannot go back to fast case.
7484 if (dictionary->requires_slow_elements()) return false;
7485 // An object requiring access checks is never allowed to have fast
7486 // elements. If it had fast elements we would skip security checks.
7487 if (IsAccessCheckNeeded()) return false;
7488 // If the dictionary backing storage takes up roughly half as much
7489 // space as a fast-case backing storage would the array should have
7490 // fast elements.
7491 uint32_t length = 0;
7492 if (IsJSArray()) {
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01007493 CHECK(JSArray::cast(this)->length()->ToArrayIndex(&length));
Steve Blocka7e24c12009-10-30 11:49:00 +00007494 } else {
7495 length = dictionary->max_number_key();
7496 }
7497 return static_cast<uint32_t>(dictionary->Capacity()) >=
7498 (length / (2 * NumberDictionary::kEntrySize));
7499}
7500
7501
7502// Certain compilers request function template instantiation when they
7503// see the definition of the other template functions in the
7504// class. This requires us to have the template functions put
7505// together, so even though this function belongs in objects-debug.cc,
7506// we keep it here instead to satisfy certain compilers.
Ben Murdochb0fe1622011-05-05 13:52:32 +01007507#ifdef OBJECT_PRINT
Steve Blocka7e24c12009-10-30 11:49:00 +00007508template<typename Shape, typename Key>
Ben Murdochb0fe1622011-05-05 13:52:32 +01007509void Dictionary<Shape, Key>::Print(FILE* out) {
Steve Blocka7e24c12009-10-30 11:49:00 +00007510 int capacity = HashTable<Shape, Key>::Capacity();
7511 for (int i = 0; i < capacity; i++) {
7512 Object* k = HashTable<Shape, Key>::KeyAt(i);
7513 if (HashTable<Shape, Key>::IsKey(k)) {
Ben Murdochb0fe1622011-05-05 13:52:32 +01007514 PrintF(out, " ");
Steve Blocka7e24c12009-10-30 11:49:00 +00007515 if (k->IsString()) {
Ben Murdochb0fe1622011-05-05 13:52:32 +01007516 String::cast(k)->StringPrint(out);
Steve Blocka7e24c12009-10-30 11:49:00 +00007517 } else {
Ben Murdochb0fe1622011-05-05 13:52:32 +01007518 k->ShortPrint(out);
Steve Blocka7e24c12009-10-30 11:49:00 +00007519 }
Ben Murdochb0fe1622011-05-05 13:52:32 +01007520 PrintF(out, ": ");
7521 ValueAt(i)->ShortPrint(out);
7522 PrintF(out, "\n");
Steve Blocka7e24c12009-10-30 11:49:00 +00007523 }
7524 }
7525}
7526#endif
7527
7528
7529template<typename Shape, typename Key>
7530void Dictionary<Shape, Key>::CopyValuesTo(FixedArray* elements) {
7531 int pos = 0;
7532 int capacity = HashTable<Shape, Key>::Capacity();
Leon Clarke4515c472010-02-03 11:58:03 +00007533 AssertNoAllocation no_gc;
7534 WriteBarrierMode mode = elements->GetWriteBarrierMode(no_gc);
Steve Blocka7e24c12009-10-30 11:49:00 +00007535 for (int i = 0; i < capacity; i++) {
7536 Object* k = Dictionary<Shape, Key>::KeyAt(i);
7537 if (Dictionary<Shape, Key>::IsKey(k)) {
7538 elements->set(pos++, ValueAt(i), mode);
7539 }
7540 }
7541 ASSERT(pos == elements->length());
7542}
7543
7544
7545InterceptorInfo* JSObject::GetNamedInterceptor() {
7546 ASSERT(map()->has_named_interceptor());
7547 JSFunction* constructor = JSFunction::cast(map()->constructor());
Steve Block6ded16b2010-05-10 14:33:55 +01007548 ASSERT(constructor->shared()->IsApiFunction());
Steve Blocka7e24c12009-10-30 11:49:00 +00007549 Object* result =
Steve Block6ded16b2010-05-10 14:33:55 +01007550 constructor->shared()->get_api_func_data()->named_property_handler();
Steve Blocka7e24c12009-10-30 11:49:00 +00007551 return InterceptorInfo::cast(result);
7552}
7553
7554
7555InterceptorInfo* JSObject::GetIndexedInterceptor() {
7556 ASSERT(map()->has_indexed_interceptor());
7557 JSFunction* constructor = JSFunction::cast(map()->constructor());
Steve Block6ded16b2010-05-10 14:33:55 +01007558 ASSERT(constructor->shared()->IsApiFunction());
Steve Blocka7e24c12009-10-30 11:49:00 +00007559 Object* result =
Steve Block6ded16b2010-05-10 14:33:55 +01007560 constructor->shared()->get_api_func_data()->indexed_property_handler();
Steve Blocka7e24c12009-10-30 11:49:00 +00007561 return InterceptorInfo::cast(result);
7562}
7563
7564
John Reck59135872010-11-02 12:39:01 -07007565MaybeObject* JSObject::GetPropertyPostInterceptor(
7566 JSObject* receiver,
7567 String* name,
7568 PropertyAttributes* attributes) {
Steve Blocka7e24c12009-10-30 11:49:00 +00007569 // Check local property in holder, ignore interceptor.
7570 LookupResult result;
7571 LocalLookupRealNamedProperty(name, &result);
Andrei Popescu402d9372010-02-26 13:31:12 +00007572 if (result.IsProperty()) {
7573 return GetProperty(receiver, &result, name, attributes);
7574 }
Steve Blocka7e24c12009-10-30 11:49:00 +00007575 // Continue searching via the prototype chain.
7576 Object* pt = GetPrototype();
7577 *attributes = ABSENT;
7578 if (pt == Heap::null_value()) return Heap::undefined_value();
7579 return pt->GetPropertyWithReceiver(receiver, name, attributes);
7580}
7581
7582
John Reck59135872010-11-02 12:39:01 -07007583MaybeObject* JSObject::GetLocalPropertyPostInterceptor(
Steve Blockd0582a62009-12-15 09:54:21 +00007584 JSObject* receiver,
7585 String* name,
7586 PropertyAttributes* attributes) {
7587 // Check local property in holder, ignore interceptor.
7588 LookupResult result;
7589 LocalLookupRealNamedProperty(name, &result);
Andrei Popescu402d9372010-02-26 13:31:12 +00007590 if (result.IsProperty()) {
7591 return GetProperty(receiver, &result, name, attributes);
7592 }
7593 return Heap::undefined_value();
Steve Blockd0582a62009-12-15 09:54:21 +00007594}
7595
7596
John Reck59135872010-11-02 12:39:01 -07007597MaybeObject* JSObject::GetPropertyWithInterceptor(
Steve Blocka7e24c12009-10-30 11:49:00 +00007598 JSObject* receiver,
7599 String* name,
7600 PropertyAttributes* attributes) {
7601 InterceptorInfo* interceptor = GetNamedInterceptor();
7602 HandleScope scope;
7603 Handle<JSObject> receiver_handle(receiver);
7604 Handle<JSObject> holder_handle(this);
7605 Handle<String> name_handle(name);
7606
7607 if (!interceptor->getter()->IsUndefined()) {
7608 v8::NamedPropertyGetter getter =
7609 v8::ToCData<v8::NamedPropertyGetter>(interceptor->getter());
7610 LOG(ApiNamedPropertyAccess("interceptor-named-get", *holder_handle, name));
7611 CustomArguments args(interceptor->data(), receiver, this);
7612 v8::AccessorInfo info(args.end());
7613 v8::Handle<v8::Value> result;
7614 {
7615 // Leaving JavaScript.
7616 VMState state(EXTERNAL);
7617 result = getter(v8::Utils::ToLocal(name_handle), info);
7618 }
7619 RETURN_IF_SCHEDULED_EXCEPTION();
7620 if (!result.IsEmpty()) {
7621 *attributes = NONE;
7622 return *v8::Utils::OpenHandle(*result);
7623 }
7624 }
7625
John Reck59135872010-11-02 12:39:01 -07007626 MaybeObject* result = holder_handle->GetPropertyPostInterceptor(
Steve Blocka7e24c12009-10-30 11:49:00 +00007627 *receiver_handle,
7628 *name_handle,
7629 attributes);
7630 RETURN_IF_SCHEDULED_EXCEPTION();
7631 return result;
7632}
7633
7634
7635bool JSObject::HasRealNamedProperty(String* key) {
7636 // Check access rights if needed.
7637 if (IsAccessCheckNeeded() &&
7638 !Top::MayNamedAccess(this, key, v8::ACCESS_HAS)) {
7639 Top::ReportFailedAccessCheck(this, v8::ACCESS_HAS);
7640 return false;
7641 }
7642
7643 LookupResult result;
7644 LocalLookupRealNamedProperty(key, &result);
Andrei Popescu402d9372010-02-26 13:31:12 +00007645 return result.IsProperty() && (result.type() != INTERCEPTOR);
Steve Blocka7e24c12009-10-30 11:49:00 +00007646}
7647
7648
7649bool JSObject::HasRealElementProperty(uint32_t index) {
7650 // Check access rights if needed.
7651 if (IsAccessCheckNeeded() &&
7652 !Top::MayIndexedAccess(this, index, v8::ACCESS_HAS)) {
7653 Top::ReportFailedAccessCheck(this, v8::ACCESS_HAS);
7654 return false;
7655 }
7656
7657 // Handle [] on String objects.
7658 if (this->IsStringObjectWithCharacterAt(index)) return true;
7659
7660 switch (GetElementsKind()) {
7661 case FAST_ELEMENTS: {
7662 uint32_t length = IsJSArray() ?
7663 static_cast<uint32_t>(
7664 Smi::cast(JSArray::cast(this)->length())->value()) :
7665 static_cast<uint32_t>(FixedArray::cast(elements())->length());
7666 return (index < length) &&
7667 !FixedArray::cast(elements())->get(index)->IsTheHole();
7668 }
7669 case PIXEL_ELEMENTS: {
7670 PixelArray* pixels = PixelArray::cast(elements());
7671 return index < static_cast<uint32_t>(pixels->length());
7672 }
Steve Block3ce2e202009-11-05 08:53:23 +00007673 case EXTERNAL_BYTE_ELEMENTS:
7674 case EXTERNAL_UNSIGNED_BYTE_ELEMENTS:
7675 case EXTERNAL_SHORT_ELEMENTS:
7676 case EXTERNAL_UNSIGNED_SHORT_ELEMENTS:
7677 case EXTERNAL_INT_ELEMENTS:
7678 case EXTERNAL_UNSIGNED_INT_ELEMENTS:
7679 case EXTERNAL_FLOAT_ELEMENTS: {
7680 ExternalArray* array = ExternalArray::cast(elements());
7681 return index < static_cast<uint32_t>(array->length());
7682 }
Steve Blocka7e24c12009-10-30 11:49:00 +00007683 case DICTIONARY_ELEMENTS: {
7684 return element_dictionary()->FindEntry(index)
7685 != NumberDictionary::kNotFound;
7686 }
7687 default:
7688 UNREACHABLE();
7689 break;
7690 }
7691 // All possibilities have been handled above already.
7692 UNREACHABLE();
7693 return Heap::null_value();
7694}
7695
7696
7697bool JSObject::HasRealNamedCallbackProperty(String* key) {
7698 // Check access rights if needed.
7699 if (IsAccessCheckNeeded() &&
7700 !Top::MayNamedAccess(this, key, v8::ACCESS_HAS)) {
7701 Top::ReportFailedAccessCheck(this, v8::ACCESS_HAS);
7702 return false;
7703 }
7704
7705 LookupResult result;
7706 LocalLookupRealNamedProperty(key, &result);
Andrei Popescu402d9372010-02-26 13:31:12 +00007707 return result.IsProperty() && (result.type() == CALLBACKS);
Steve Blocka7e24c12009-10-30 11:49:00 +00007708}
7709
7710
7711int JSObject::NumberOfLocalProperties(PropertyAttributes filter) {
7712 if (HasFastProperties()) {
7713 DescriptorArray* descs = map()->instance_descriptors();
7714 int result = 0;
7715 for (int i = 0; i < descs->number_of_descriptors(); i++) {
7716 PropertyDetails details = descs->GetDetails(i);
7717 if (details.IsProperty() && (details.attributes() & filter) == 0) {
7718 result++;
7719 }
7720 }
7721 return result;
7722 } else {
7723 return property_dictionary()->NumberOfElementsFilterAttributes(filter);
7724 }
7725}
7726
7727
7728int JSObject::NumberOfEnumProperties() {
7729 return NumberOfLocalProperties(static_cast<PropertyAttributes>(DONT_ENUM));
7730}
7731
7732
7733void FixedArray::SwapPairs(FixedArray* numbers, int i, int j) {
7734 Object* temp = get(i);
7735 set(i, get(j));
7736 set(j, temp);
7737 if (this != numbers) {
7738 temp = numbers->get(i);
7739 numbers->set(i, numbers->get(j));
7740 numbers->set(j, temp);
7741 }
7742}
7743
7744
7745static void InsertionSortPairs(FixedArray* content,
7746 FixedArray* numbers,
7747 int len) {
7748 for (int i = 1; i < len; i++) {
7749 int j = i;
7750 while (j > 0 &&
7751 (NumberToUint32(numbers->get(j - 1)) >
7752 NumberToUint32(numbers->get(j)))) {
7753 content->SwapPairs(numbers, j - 1, j);
7754 j--;
7755 }
7756 }
7757}
7758
7759
7760void HeapSortPairs(FixedArray* content, FixedArray* numbers, int len) {
7761 // In-place heap sort.
7762 ASSERT(content->length() == numbers->length());
7763
7764 // Bottom-up max-heap construction.
7765 for (int i = 1; i < len; ++i) {
7766 int child_index = i;
7767 while (child_index > 0) {
7768 int parent_index = ((child_index + 1) >> 1) - 1;
7769 uint32_t parent_value = NumberToUint32(numbers->get(parent_index));
7770 uint32_t child_value = NumberToUint32(numbers->get(child_index));
7771 if (parent_value < child_value) {
7772 content->SwapPairs(numbers, parent_index, child_index);
7773 } else {
7774 break;
7775 }
7776 child_index = parent_index;
7777 }
7778 }
7779
7780 // Extract elements and create sorted array.
7781 for (int i = len - 1; i > 0; --i) {
7782 // Put max element at the back of the array.
7783 content->SwapPairs(numbers, 0, i);
7784 // Sift down the new top element.
7785 int parent_index = 0;
7786 while (true) {
7787 int child_index = ((parent_index + 1) << 1) - 1;
7788 if (child_index >= i) break;
7789 uint32_t child1_value = NumberToUint32(numbers->get(child_index));
7790 uint32_t child2_value = NumberToUint32(numbers->get(child_index + 1));
7791 uint32_t parent_value = NumberToUint32(numbers->get(parent_index));
7792 if (child_index + 1 >= i || child1_value > child2_value) {
7793 if (parent_value > child1_value) break;
7794 content->SwapPairs(numbers, parent_index, child_index);
7795 parent_index = child_index;
7796 } else {
7797 if (parent_value > child2_value) break;
7798 content->SwapPairs(numbers, parent_index, child_index + 1);
7799 parent_index = child_index + 1;
7800 }
7801 }
7802 }
7803}
7804
7805
7806// Sort this array and the numbers as pairs wrt. the (distinct) numbers.
7807void FixedArray::SortPairs(FixedArray* numbers, uint32_t len) {
7808 ASSERT(this->length() == numbers->length());
7809 // For small arrays, simply use insertion sort.
7810 if (len <= 10) {
7811 InsertionSortPairs(this, numbers, len);
7812 return;
7813 }
7814 // Check the range of indices.
7815 uint32_t min_index = NumberToUint32(numbers->get(0));
7816 uint32_t max_index = min_index;
7817 uint32_t i;
7818 for (i = 1; i < len; i++) {
7819 if (NumberToUint32(numbers->get(i)) < min_index) {
7820 min_index = NumberToUint32(numbers->get(i));
7821 } else if (NumberToUint32(numbers->get(i)) > max_index) {
7822 max_index = NumberToUint32(numbers->get(i));
7823 }
7824 }
7825 if (max_index - min_index + 1 == len) {
7826 // Indices form a contiguous range, unless there are duplicates.
7827 // Do an in-place linear time sort assuming distinct numbers, but
7828 // avoid hanging in case they are not.
7829 for (i = 0; i < len; i++) {
7830 uint32_t p;
7831 uint32_t j = 0;
7832 // While the current element at i is not at its correct position p,
7833 // swap the elements at these two positions.
7834 while ((p = NumberToUint32(numbers->get(i)) - min_index) != i &&
7835 j++ < len) {
7836 SwapPairs(numbers, i, p);
7837 }
7838 }
7839 } else {
7840 HeapSortPairs(this, numbers, len);
7841 return;
7842 }
7843}
7844
7845
7846// Fill in the names of local properties into the supplied storage. The main
7847// purpose of this function is to provide reflection information for the object
7848// mirrors.
7849void JSObject::GetLocalPropertyNames(FixedArray* storage, int index) {
7850 ASSERT(storage->length() >= (NumberOfLocalProperties(NONE) - index));
7851 if (HasFastProperties()) {
7852 DescriptorArray* descs = map()->instance_descriptors();
7853 for (int i = 0; i < descs->number_of_descriptors(); i++) {
7854 if (descs->IsProperty(i)) storage->set(index++, descs->GetKey(i));
7855 }
7856 ASSERT(storage->length() >= index);
7857 } else {
7858 property_dictionary()->CopyKeysTo(storage);
7859 }
7860}
7861
7862
7863int JSObject::NumberOfLocalElements(PropertyAttributes filter) {
7864 return GetLocalElementKeys(NULL, filter);
7865}
7866
7867
7868int JSObject::NumberOfEnumElements() {
Steve Blockd0582a62009-12-15 09:54:21 +00007869 // Fast case for objects with no elements.
7870 if (!IsJSValue() && HasFastElements()) {
7871 uint32_t length = IsJSArray() ?
7872 static_cast<uint32_t>(
7873 Smi::cast(JSArray::cast(this)->length())->value()) :
7874 static_cast<uint32_t>(FixedArray::cast(elements())->length());
7875 if (length == 0) return 0;
7876 }
7877 // Compute the number of enumerable elements.
Steve Blocka7e24c12009-10-30 11:49:00 +00007878 return NumberOfLocalElements(static_cast<PropertyAttributes>(DONT_ENUM));
7879}
7880
7881
7882int JSObject::GetLocalElementKeys(FixedArray* storage,
7883 PropertyAttributes filter) {
7884 int counter = 0;
7885 switch (GetElementsKind()) {
7886 case FAST_ELEMENTS: {
7887 int length = IsJSArray() ?
7888 Smi::cast(JSArray::cast(this)->length())->value() :
7889 FixedArray::cast(elements())->length();
7890 for (int i = 0; i < length; i++) {
7891 if (!FixedArray::cast(elements())->get(i)->IsTheHole()) {
7892 if (storage != NULL) {
Leon Clarke4515c472010-02-03 11:58:03 +00007893 storage->set(counter, Smi::FromInt(i));
Steve Blocka7e24c12009-10-30 11:49:00 +00007894 }
7895 counter++;
7896 }
7897 }
7898 ASSERT(!storage || storage->length() >= counter);
7899 break;
7900 }
7901 case PIXEL_ELEMENTS: {
7902 int length = PixelArray::cast(elements())->length();
7903 while (counter < length) {
7904 if (storage != NULL) {
Leon Clarke4515c472010-02-03 11:58:03 +00007905 storage->set(counter, Smi::FromInt(counter));
Steve Blocka7e24c12009-10-30 11:49:00 +00007906 }
7907 counter++;
7908 }
7909 ASSERT(!storage || storage->length() >= counter);
7910 break;
7911 }
Steve Block3ce2e202009-11-05 08:53:23 +00007912 case EXTERNAL_BYTE_ELEMENTS:
7913 case EXTERNAL_UNSIGNED_BYTE_ELEMENTS:
7914 case EXTERNAL_SHORT_ELEMENTS:
7915 case EXTERNAL_UNSIGNED_SHORT_ELEMENTS:
7916 case EXTERNAL_INT_ELEMENTS:
7917 case EXTERNAL_UNSIGNED_INT_ELEMENTS:
7918 case EXTERNAL_FLOAT_ELEMENTS: {
7919 int length = ExternalArray::cast(elements())->length();
7920 while (counter < length) {
7921 if (storage != NULL) {
Leon Clarke4515c472010-02-03 11:58:03 +00007922 storage->set(counter, Smi::FromInt(counter));
Steve Block3ce2e202009-11-05 08:53:23 +00007923 }
7924 counter++;
7925 }
7926 ASSERT(!storage || storage->length() >= counter);
7927 break;
7928 }
Steve Blocka7e24c12009-10-30 11:49:00 +00007929 case DICTIONARY_ELEMENTS: {
7930 if (storage != NULL) {
7931 element_dictionary()->CopyKeysTo(storage, filter);
7932 }
7933 counter = element_dictionary()->NumberOfElementsFilterAttributes(filter);
7934 break;
7935 }
7936 default:
7937 UNREACHABLE();
7938 break;
7939 }
7940
7941 if (this->IsJSValue()) {
7942 Object* val = JSValue::cast(this)->value();
7943 if (val->IsString()) {
7944 String* str = String::cast(val);
7945 if (storage) {
7946 for (int i = 0; i < str->length(); i++) {
Leon Clarke4515c472010-02-03 11:58:03 +00007947 storage->set(counter + i, Smi::FromInt(i));
Steve Blocka7e24c12009-10-30 11:49:00 +00007948 }
7949 }
7950 counter += str->length();
7951 }
7952 }
7953 ASSERT(!storage || storage->length() == counter);
7954 return counter;
7955}
7956
7957
7958int JSObject::GetEnumElementKeys(FixedArray* storage) {
7959 return GetLocalElementKeys(storage,
7960 static_cast<PropertyAttributes>(DONT_ENUM));
7961}
7962
7963
7964bool NumberDictionaryShape::IsMatch(uint32_t key, Object* other) {
7965 ASSERT(other->IsNumber());
7966 return key == static_cast<uint32_t>(other->Number());
7967}
7968
7969
7970uint32_t NumberDictionaryShape::Hash(uint32_t key) {
7971 return ComputeIntegerHash(key);
7972}
7973
7974
7975uint32_t NumberDictionaryShape::HashForObject(uint32_t key, Object* other) {
7976 ASSERT(other->IsNumber());
7977 return ComputeIntegerHash(static_cast<uint32_t>(other->Number()));
7978}
7979
7980
John Reck59135872010-11-02 12:39:01 -07007981MaybeObject* NumberDictionaryShape::AsObject(uint32_t key) {
Steve Blocka7e24c12009-10-30 11:49:00 +00007982 return Heap::NumberFromUint32(key);
7983}
7984
7985
7986bool StringDictionaryShape::IsMatch(String* key, Object* other) {
7987 // We know that all entries in a hash table had their hash keys created.
7988 // Use that knowledge to have fast failure.
7989 if (key->Hash() != String::cast(other)->Hash()) return false;
7990 return key->Equals(String::cast(other));
7991}
7992
7993
7994uint32_t StringDictionaryShape::Hash(String* key) {
7995 return key->Hash();
7996}
7997
7998
7999uint32_t StringDictionaryShape::HashForObject(String* key, Object* other) {
8000 return String::cast(other)->Hash();
8001}
8002
8003
John Reck59135872010-11-02 12:39:01 -07008004MaybeObject* StringDictionaryShape::AsObject(String* key) {
Steve Blocka7e24c12009-10-30 11:49:00 +00008005 return key;
8006}
8007
8008
8009// StringKey simply carries a string object as key.
8010class StringKey : public HashTableKey {
8011 public:
8012 explicit StringKey(String* string) :
8013 string_(string),
8014 hash_(HashForObject(string)) { }
8015
8016 bool IsMatch(Object* string) {
8017 // We know that all entries in a hash table had their hash keys created.
8018 // Use that knowledge to have fast failure.
8019 if (hash_ != HashForObject(string)) {
8020 return false;
8021 }
8022 return string_->Equals(String::cast(string));
8023 }
8024
8025 uint32_t Hash() { return hash_; }
8026
8027 uint32_t HashForObject(Object* other) { return String::cast(other)->Hash(); }
8028
8029 Object* AsObject() { return string_; }
8030
8031 String* string_;
8032 uint32_t hash_;
8033};
8034
8035
8036// StringSharedKeys are used as keys in the eval cache.
8037class StringSharedKey : public HashTableKey {
8038 public:
Steve Block1e0659c2011-05-24 12:43:12 +01008039 StringSharedKey(String* source,
8040 SharedFunctionInfo* shared,
8041 StrictModeFlag strict_mode)
8042 : source_(source),
8043 shared_(shared),
8044 strict_mode_(strict_mode) { }
Steve Blocka7e24c12009-10-30 11:49:00 +00008045
8046 bool IsMatch(Object* other) {
8047 if (!other->IsFixedArray()) return false;
8048 FixedArray* pair = FixedArray::cast(other);
8049 SharedFunctionInfo* shared = SharedFunctionInfo::cast(pair->get(0));
8050 if (shared != shared_) return false;
Steve Block1e0659c2011-05-24 12:43:12 +01008051 StrictModeFlag strict_mode = static_cast<StrictModeFlag>(
8052 Smi::cast(pair->get(2))->value());
8053 if (strict_mode != strict_mode_) return false;
Steve Blocka7e24c12009-10-30 11:49:00 +00008054 String* source = String::cast(pair->get(1));
8055 return source->Equals(source_);
8056 }
8057
8058 static uint32_t StringSharedHashHelper(String* source,
Steve Block1e0659c2011-05-24 12:43:12 +01008059 SharedFunctionInfo* shared,
8060 StrictModeFlag strict_mode) {
Steve Blocka7e24c12009-10-30 11:49:00 +00008061 uint32_t hash = source->Hash();
8062 if (shared->HasSourceCode()) {
8063 // Instead of using the SharedFunctionInfo pointer in the hash
8064 // code computation, we use a combination of the hash of the
8065 // script source code and the start and end positions. We do
8066 // this to ensure that the cache entries can survive garbage
8067 // collection.
8068 Script* script = Script::cast(shared->script());
8069 hash ^= String::cast(script->source())->Hash();
Steve Block1e0659c2011-05-24 12:43:12 +01008070 if (strict_mode == kStrictMode) hash ^= 0x8000;
Steve Blocka7e24c12009-10-30 11:49:00 +00008071 hash += shared->start_position();
8072 }
8073 return hash;
8074 }
8075
8076 uint32_t Hash() {
Steve Block1e0659c2011-05-24 12:43:12 +01008077 return StringSharedHashHelper(source_, shared_, strict_mode_);
Steve Blocka7e24c12009-10-30 11:49:00 +00008078 }
8079
8080 uint32_t HashForObject(Object* obj) {
8081 FixedArray* pair = FixedArray::cast(obj);
8082 SharedFunctionInfo* shared = SharedFunctionInfo::cast(pair->get(0));
8083 String* source = String::cast(pair->get(1));
Steve Block1e0659c2011-05-24 12:43:12 +01008084 StrictModeFlag strict_mode = static_cast<StrictModeFlag>(
8085 Smi::cast(pair->get(2))->value());
8086 return StringSharedHashHelper(source, shared, strict_mode);
Steve Blocka7e24c12009-10-30 11:49:00 +00008087 }
8088
John Reck59135872010-11-02 12:39:01 -07008089 MUST_USE_RESULT MaybeObject* AsObject() {
8090 Object* obj;
Steve Block1e0659c2011-05-24 12:43:12 +01008091 { MaybeObject* maybe_obj = Heap::AllocateFixedArray(3);
John Reck59135872010-11-02 12:39:01 -07008092 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
8093 }
Steve Blocka7e24c12009-10-30 11:49:00 +00008094 FixedArray* pair = FixedArray::cast(obj);
8095 pair->set(0, shared_);
8096 pair->set(1, source_);
Steve Block1e0659c2011-05-24 12:43:12 +01008097 pair->set(2, Smi::FromInt(strict_mode_));
Steve Blocka7e24c12009-10-30 11:49:00 +00008098 return pair;
8099 }
8100
8101 private:
8102 String* source_;
8103 SharedFunctionInfo* shared_;
Steve Block1e0659c2011-05-24 12:43:12 +01008104 StrictModeFlag strict_mode_;
Steve Blocka7e24c12009-10-30 11:49:00 +00008105};
8106
8107
8108// RegExpKey carries the source and flags of a regular expression as key.
8109class RegExpKey : public HashTableKey {
8110 public:
8111 RegExpKey(String* string, JSRegExp::Flags flags)
8112 : string_(string),
8113 flags_(Smi::FromInt(flags.value())) { }
8114
Steve Block3ce2e202009-11-05 08:53:23 +00008115 // Rather than storing the key in the hash table, a pointer to the
8116 // stored value is stored where the key should be. IsMatch then
8117 // compares the search key to the found object, rather than comparing
8118 // a key to a key.
Steve Blocka7e24c12009-10-30 11:49:00 +00008119 bool IsMatch(Object* obj) {
8120 FixedArray* val = FixedArray::cast(obj);
8121 return string_->Equals(String::cast(val->get(JSRegExp::kSourceIndex)))
8122 && (flags_ == val->get(JSRegExp::kFlagsIndex));
8123 }
8124
8125 uint32_t Hash() { return RegExpHash(string_, flags_); }
8126
8127 Object* AsObject() {
8128 // Plain hash maps, which is where regexp keys are used, don't
8129 // use this function.
8130 UNREACHABLE();
8131 return NULL;
8132 }
8133
8134 uint32_t HashForObject(Object* obj) {
8135 FixedArray* val = FixedArray::cast(obj);
8136 return RegExpHash(String::cast(val->get(JSRegExp::kSourceIndex)),
8137 Smi::cast(val->get(JSRegExp::kFlagsIndex)));
8138 }
8139
8140 static uint32_t RegExpHash(String* string, Smi* flags) {
8141 return string->Hash() + flags->value();
8142 }
8143
8144 String* string_;
8145 Smi* flags_;
8146};
8147
8148// Utf8SymbolKey carries a vector of chars as key.
8149class Utf8SymbolKey : public HashTableKey {
8150 public:
8151 explicit Utf8SymbolKey(Vector<const char> string)
Steve Blockd0582a62009-12-15 09:54:21 +00008152 : string_(string), hash_field_(0) { }
Steve Blocka7e24c12009-10-30 11:49:00 +00008153
8154 bool IsMatch(Object* string) {
8155 return String::cast(string)->IsEqualTo(string_);
8156 }
8157
8158 uint32_t Hash() {
Steve Blockd0582a62009-12-15 09:54:21 +00008159 if (hash_field_ != 0) return hash_field_ >> String::kHashShift;
Steve Blocka7e24c12009-10-30 11:49:00 +00008160 unibrow::Utf8InputBuffer<> buffer(string_.start(),
8161 static_cast<unsigned>(string_.length()));
8162 chars_ = buffer.Length();
Steve Blockd0582a62009-12-15 09:54:21 +00008163 hash_field_ = String::ComputeHashField(&buffer, chars_);
8164 uint32_t result = hash_field_ >> String::kHashShift;
Steve Blocka7e24c12009-10-30 11:49:00 +00008165 ASSERT(result != 0); // Ensure that the hash value of 0 is never computed.
8166 return result;
8167 }
8168
8169 uint32_t HashForObject(Object* other) {
8170 return String::cast(other)->Hash();
8171 }
8172
John Reck59135872010-11-02 12:39:01 -07008173 MaybeObject* AsObject() {
Steve Blockd0582a62009-12-15 09:54:21 +00008174 if (hash_field_ == 0) Hash();
8175 return Heap::AllocateSymbol(string_, chars_, hash_field_);
Steve Blocka7e24c12009-10-30 11:49:00 +00008176 }
8177
8178 Vector<const char> string_;
Steve Blockd0582a62009-12-15 09:54:21 +00008179 uint32_t hash_field_;
Steve Blocka7e24c12009-10-30 11:49:00 +00008180 int chars_; // Caches the number of characters when computing the hash code.
8181};
8182
8183
Steve Block9fac8402011-05-12 15:51:54 +01008184template <typename Char>
8185class SequentialSymbolKey : public HashTableKey {
8186 public:
8187 explicit SequentialSymbolKey(Vector<const Char> string)
8188 : string_(string), hash_field_(0) { }
8189
8190 uint32_t Hash() {
8191 StringHasher hasher(string_.length());
8192
8193 // Very long strings have a trivial hash that doesn't inspect the
8194 // string contents.
8195 if (hasher.has_trivial_hash()) {
8196 hash_field_ = hasher.GetHashField();
8197 } else {
8198 int i = 0;
8199 // Do the iterative array index computation as long as there is a
8200 // chance this is an array index.
8201 while (i < string_.length() && hasher.is_array_index()) {
8202 hasher.AddCharacter(static_cast<uc32>(string_[i]));
8203 i++;
8204 }
8205
8206 // Process the remaining characters without updating the array
8207 // index.
8208 while (i < string_.length()) {
8209 hasher.AddCharacterNoIndex(static_cast<uc32>(string_[i]));
8210 i++;
8211 }
8212 hash_field_ = hasher.GetHashField();
8213 }
8214
8215 uint32_t result = hash_field_ >> String::kHashShift;
8216 ASSERT(result != 0); // Ensure that the hash value of 0 is never computed.
8217 return result;
8218 }
8219
8220
8221 uint32_t HashForObject(Object* other) {
8222 return String::cast(other)->Hash();
8223 }
8224
8225 Vector<const Char> string_;
8226 uint32_t hash_field_;
8227};
8228
8229
8230
8231class AsciiSymbolKey : public SequentialSymbolKey<char> {
8232 public:
8233 explicit AsciiSymbolKey(Vector<const char> str)
8234 : SequentialSymbolKey<char>(str) { }
8235
8236 bool IsMatch(Object* string) {
8237 return String::cast(string)->IsAsciiEqualTo(string_);
8238 }
8239
8240 MaybeObject* AsObject() {
8241 if (hash_field_ == 0) Hash();
8242 return Heap::AllocateAsciiSymbol(string_, hash_field_);
8243 }
8244};
8245
8246
8247class TwoByteSymbolKey : public SequentialSymbolKey<uc16> {
8248 public:
8249 explicit TwoByteSymbolKey(Vector<const uc16> str)
8250 : SequentialSymbolKey<uc16>(str) { }
8251
8252 bool IsMatch(Object* string) {
8253 return String::cast(string)->IsTwoByteEqualTo(string_);
8254 }
8255
8256 MaybeObject* AsObject() {
8257 if (hash_field_ == 0) Hash();
8258 return Heap::AllocateTwoByteSymbol(string_, hash_field_);
8259 }
8260};
8261
8262
Steve Blocka7e24c12009-10-30 11:49:00 +00008263// SymbolKey carries a string/symbol object as key.
8264class SymbolKey : public HashTableKey {
8265 public:
8266 explicit SymbolKey(String* string) : string_(string) { }
8267
8268 bool IsMatch(Object* string) {
8269 return String::cast(string)->Equals(string_);
8270 }
8271
8272 uint32_t Hash() { return string_->Hash(); }
8273
8274 uint32_t HashForObject(Object* other) {
8275 return String::cast(other)->Hash();
8276 }
8277
John Reck59135872010-11-02 12:39:01 -07008278 MaybeObject* AsObject() {
Leon Clarkef7060e22010-06-03 12:02:55 +01008279 // Attempt to flatten the string, so that symbols will most often
8280 // be flat strings.
8281 string_ = string_->TryFlattenGetString();
Steve Blocka7e24c12009-10-30 11:49:00 +00008282 // Transform string to symbol if possible.
8283 Map* map = Heap::SymbolMapForString(string_);
8284 if (map != NULL) {
8285 string_->set_map(map);
8286 ASSERT(string_->IsSymbol());
8287 return string_;
8288 }
8289 // Otherwise allocate a new symbol.
8290 StringInputBuffer buffer(string_);
8291 return Heap::AllocateInternalSymbol(&buffer,
8292 string_->length(),
Steve Blockd0582a62009-12-15 09:54:21 +00008293 string_->hash_field());
Steve Blocka7e24c12009-10-30 11:49:00 +00008294 }
8295
8296 static uint32_t StringHash(Object* obj) {
8297 return String::cast(obj)->Hash();
8298 }
8299
8300 String* string_;
8301};
8302
8303
8304template<typename Shape, typename Key>
8305void HashTable<Shape, Key>::IteratePrefix(ObjectVisitor* v) {
8306 IteratePointers(v, 0, kElementsStartOffset);
8307}
8308
8309
8310template<typename Shape, typename Key>
8311void HashTable<Shape, Key>::IterateElements(ObjectVisitor* v) {
8312 IteratePointers(v,
8313 kElementsStartOffset,
8314 kHeaderSize + length() * kPointerSize);
8315}
8316
8317
8318template<typename Shape, typename Key>
John Reck59135872010-11-02 12:39:01 -07008319MaybeObject* HashTable<Shape, Key>::Allocate(int at_least_space_for,
8320 PretenureFlag pretenure) {
Steve Block6ded16b2010-05-10 14:33:55 +01008321 const int kMinCapacity = 32;
8322 int capacity = RoundUpToPowerOf2(at_least_space_for * 2);
8323 if (capacity < kMinCapacity) {
8324 capacity = kMinCapacity; // Guarantee min capacity.
Leon Clarkee46be812010-01-19 14:06:41 +00008325 } else if (capacity > HashTable::kMaxCapacity) {
8326 return Failure::OutOfMemoryException();
8327 }
8328
John Reck59135872010-11-02 12:39:01 -07008329 Object* obj;
8330 { MaybeObject* maybe_obj =
8331 Heap::AllocateHashTable(EntryToIndex(capacity), pretenure);
8332 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
Steve Blocka7e24c12009-10-30 11:49:00 +00008333 }
John Reck59135872010-11-02 12:39:01 -07008334 HashTable::cast(obj)->SetNumberOfElements(0);
8335 HashTable::cast(obj)->SetNumberOfDeletedElements(0);
8336 HashTable::cast(obj)->SetCapacity(capacity);
Steve Blocka7e24c12009-10-30 11:49:00 +00008337 return obj;
8338}
8339
8340
Leon Clarkee46be812010-01-19 14:06:41 +00008341// Find entry for key otherwise return kNotFound.
Steve Blocka7e24c12009-10-30 11:49:00 +00008342template<typename Shape, typename Key>
8343int HashTable<Shape, Key>::FindEntry(Key key) {
Steve Blocka7e24c12009-10-30 11:49:00 +00008344 uint32_t capacity = Capacity();
Leon Clarkee46be812010-01-19 14:06:41 +00008345 uint32_t entry = FirstProbe(Shape::Hash(key), capacity);
8346 uint32_t count = 1;
8347 // EnsureCapacity will guarantee the hash table is never full.
8348 while (true) {
8349 Object* element = KeyAt(entry);
8350 if (element->IsUndefined()) break; // Empty entry.
8351 if (!element->IsNull() && Shape::IsMatch(key, element)) return entry;
8352 entry = NextProbe(entry, count++, capacity);
Steve Blocka7e24c12009-10-30 11:49:00 +00008353 }
8354 return kNotFound;
8355}
8356
8357
Ben Murdoch3bec4d22010-07-22 14:51:16 +01008358// Find entry for key otherwise return kNotFound.
8359int StringDictionary::FindEntry(String* key) {
8360 if (!key->IsSymbol()) {
8361 return HashTable<StringDictionaryShape, String*>::FindEntry(key);
8362 }
8363
8364 // Optimized for symbol key. Knowledge of the key type allows:
8365 // 1. Move the check if the key is a symbol out of the loop.
8366 // 2. Avoid comparing hash codes in symbol to symbol comparision.
8367 // 3. Detect a case when a dictionary key is not a symbol but the key is.
8368 // In case of positive result the dictionary key may be replaced by
8369 // the symbol with minimal performance penalty. It gives a chance to
8370 // perform further lookups in code stubs (and significant performance boost
8371 // a certain style of code).
8372
8373 // EnsureCapacity will guarantee the hash table is never full.
8374 uint32_t capacity = Capacity();
8375 uint32_t entry = FirstProbe(key->Hash(), capacity);
8376 uint32_t count = 1;
8377
8378 while (true) {
8379 int index = EntryToIndex(entry);
8380 Object* element = get(index);
8381 if (element->IsUndefined()) break; // Empty entry.
8382 if (key == element) return entry;
8383 if (!element->IsSymbol() &&
8384 !element->IsNull() &&
8385 String::cast(element)->Equals(key)) {
8386 // Replace a non-symbol key by the equivalent symbol for faster further
8387 // lookups.
8388 set(index, key);
8389 return entry;
8390 }
8391 ASSERT(element->IsNull() || !String::cast(element)->Equals(key));
8392 entry = NextProbe(entry, count++, capacity);
8393 }
8394 return kNotFound;
8395}
8396
8397
Steve Blocka7e24c12009-10-30 11:49:00 +00008398template<typename Shape, typename Key>
John Reck59135872010-11-02 12:39:01 -07008399MaybeObject* HashTable<Shape, Key>::EnsureCapacity(int n, Key key) {
Steve Blocka7e24c12009-10-30 11:49:00 +00008400 int capacity = Capacity();
8401 int nof = NumberOfElements() + n;
Leon Clarkee46be812010-01-19 14:06:41 +00008402 int nod = NumberOfDeletedElements();
8403 // Return if:
8404 // 50% is still free after adding n elements and
8405 // at most 50% of the free elements are deleted elements.
Steve Block6ded16b2010-05-10 14:33:55 +01008406 if (nod <= (capacity - nof) >> 1) {
8407 int needed_free = nof >> 1;
8408 if (nof + needed_free <= capacity) return this;
8409 }
Steve Blocka7e24c12009-10-30 11:49:00 +00008410
Steve Block6ded16b2010-05-10 14:33:55 +01008411 const int kMinCapacityForPretenure = 256;
8412 bool pretenure =
8413 (capacity > kMinCapacityForPretenure) && !Heap::InNewSpace(this);
John Reck59135872010-11-02 12:39:01 -07008414 Object* obj;
8415 { MaybeObject* maybe_obj =
8416 Allocate(nof * 2, pretenure ? TENURED : NOT_TENURED);
8417 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
8418 }
Leon Clarke4515c472010-02-03 11:58:03 +00008419
8420 AssertNoAllocation no_gc;
Steve Blocka7e24c12009-10-30 11:49:00 +00008421 HashTable* table = HashTable::cast(obj);
Leon Clarke4515c472010-02-03 11:58:03 +00008422 WriteBarrierMode mode = table->GetWriteBarrierMode(no_gc);
Steve Blocka7e24c12009-10-30 11:49:00 +00008423
8424 // Copy prefix to new array.
8425 for (int i = kPrefixStartIndex;
8426 i < kPrefixStartIndex + Shape::kPrefixSize;
8427 i++) {
8428 table->set(i, get(i), mode);
8429 }
8430 // Rehash the elements.
8431 for (int i = 0; i < capacity; i++) {
8432 uint32_t from_index = EntryToIndex(i);
8433 Object* k = get(from_index);
8434 if (IsKey(k)) {
8435 uint32_t hash = Shape::HashForObject(key, k);
8436 uint32_t insertion_index =
8437 EntryToIndex(table->FindInsertionEntry(hash));
8438 for (int j = 0; j < Shape::kEntrySize; j++) {
8439 table->set(insertion_index + j, get(from_index + j), mode);
8440 }
8441 }
8442 }
8443 table->SetNumberOfElements(NumberOfElements());
Leon Clarkee46be812010-01-19 14:06:41 +00008444 table->SetNumberOfDeletedElements(0);
Steve Blocka7e24c12009-10-30 11:49:00 +00008445 return table;
8446}
8447
8448
8449template<typename Shape, typename Key>
8450uint32_t HashTable<Shape, Key>::FindInsertionEntry(uint32_t hash) {
8451 uint32_t capacity = Capacity();
Leon Clarkee46be812010-01-19 14:06:41 +00008452 uint32_t entry = FirstProbe(hash, capacity);
8453 uint32_t count = 1;
8454 // EnsureCapacity will guarantee the hash table is never full.
8455 while (true) {
8456 Object* element = KeyAt(entry);
8457 if (element->IsUndefined() || element->IsNull()) break;
8458 entry = NextProbe(entry, count++, capacity);
Steve Blocka7e24c12009-10-30 11:49:00 +00008459 }
Steve Blocka7e24c12009-10-30 11:49:00 +00008460 return entry;
8461}
8462
8463// Force instantiation of template instances class.
8464// Please note this list is compiler dependent.
8465
8466template class HashTable<SymbolTableShape, HashTableKey*>;
8467
8468template class HashTable<CompilationCacheShape, HashTableKey*>;
8469
8470template class HashTable<MapCacheShape, HashTableKey*>;
8471
8472template class Dictionary<StringDictionaryShape, String*>;
8473
8474template class Dictionary<NumberDictionaryShape, uint32_t>;
8475
John Reck59135872010-11-02 12:39:01 -07008476template MaybeObject* Dictionary<NumberDictionaryShape, uint32_t>::Allocate(
Steve Blocka7e24c12009-10-30 11:49:00 +00008477 int);
8478
John Reck59135872010-11-02 12:39:01 -07008479template MaybeObject* Dictionary<StringDictionaryShape, String*>::Allocate(
Steve Blocka7e24c12009-10-30 11:49:00 +00008480 int);
8481
John Reck59135872010-11-02 12:39:01 -07008482template MaybeObject* Dictionary<NumberDictionaryShape, uint32_t>::AtPut(
Steve Blocka7e24c12009-10-30 11:49:00 +00008483 uint32_t, Object*);
8484
8485template Object* Dictionary<NumberDictionaryShape, uint32_t>::SlowReverseLookup(
8486 Object*);
8487
8488template Object* Dictionary<StringDictionaryShape, String*>::SlowReverseLookup(
8489 Object*);
8490
8491template void Dictionary<NumberDictionaryShape, uint32_t>::CopyKeysTo(
8492 FixedArray*, PropertyAttributes);
8493
8494template Object* Dictionary<StringDictionaryShape, String*>::DeleteProperty(
8495 int, JSObject::DeleteMode);
8496
8497template Object* Dictionary<NumberDictionaryShape, uint32_t>::DeleteProperty(
8498 int, JSObject::DeleteMode);
8499
8500template void Dictionary<StringDictionaryShape, String*>::CopyKeysTo(
8501 FixedArray*);
8502
8503template int
8504Dictionary<StringDictionaryShape, String*>::NumberOfElementsFilterAttributes(
8505 PropertyAttributes);
8506
John Reck59135872010-11-02 12:39:01 -07008507template MaybeObject* Dictionary<StringDictionaryShape, String*>::Add(
Steve Blocka7e24c12009-10-30 11:49:00 +00008508 String*, Object*, PropertyDetails);
8509
John Reck59135872010-11-02 12:39:01 -07008510template MaybeObject*
Steve Blocka7e24c12009-10-30 11:49:00 +00008511Dictionary<StringDictionaryShape, String*>::GenerateNewEnumerationIndices();
8512
8513template int
8514Dictionary<NumberDictionaryShape, uint32_t>::NumberOfElementsFilterAttributes(
8515 PropertyAttributes);
8516
John Reck59135872010-11-02 12:39:01 -07008517template MaybeObject* Dictionary<NumberDictionaryShape, uint32_t>::Add(
Steve Blocka7e24c12009-10-30 11:49:00 +00008518 uint32_t, Object*, PropertyDetails);
8519
John Reck59135872010-11-02 12:39:01 -07008520template MaybeObject* Dictionary<NumberDictionaryShape, uint32_t>::
8521 EnsureCapacity(int, uint32_t);
Steve Blocka7e24c12009-10-30 11:49:00 +00008522
John Reck59135872010-11-02 12:39:01 -07008523template MaybeObject* Dictionary<StringDictionaryShape, String*>::
8524 EnsureCapacity(int, String*);
Steve Blocka7e24c12009-10-30 11:49:00 +00008525
John Reck59135872010-11-02 12:39:01 -07008526template MaybeObject* Dictionary<NumberDictionaryShape, uint32_t>::AddEntry(
Steve Blocka7e24c12009-10-30 11:49:00 +00008527 uint32_t, Object*, PropertyDetails, uint32_t);
8528
John Reck59135872010-11-02 12:39:01 -07008529template MaybeObject* Dictionary<StringDictionaryShape, String*>::AddEntry(
Steve Blocka7e24c12009-10-30 11:49:00 +00008530 String*, Object*, PropertyDetails, uint32_t);
8531
8532template
8533int Dictionary<NumberDictionaryShape, uint32_t>::NumberOfEnumElements();
8534
8535template
8536int Dictionary<StringDictionaryShape, String*>::NumberOfEnumElements();
8537
Leon Clarkee46be812010-01-19 14:06:41 +00008538template
8539int HashTable<NumberDictionaryShape, uint32_t>::FindEntry(uint32_t);
8540
8541
Steve Blocka7e24c12009-10-30 11:49:00 +00008542// Collates undefined and unexisting elements below limit from position
8543// zero of the elements. The object stays in Dictionary mode.
John Reck59135872010-11-02 12:39:01 -07008544MaybeObject* JSObject::PrepareSlowElementsForSort(uint32_t limit) {
Steve Blocka7e24c12009-10-30 11:49:00 +00008545 ASSERT(HasDictionaryElements());
8546 // Must stay in dictionary mode, either because of requires_slow_elements,
8547 // or because we are not going to sort (and therefore compact) all of the
8548 // elements.
8549 NumberDictionary* dict = element_dictionary();
8550 HeapNumber* result_double = NULL;
8551 if (limit > static_cast<uint32_t>(Smi::kMaxValue)) {
8552 // Allocate space for result before we start mutating the object.
John Reck59135872010-11-02 12:39:01 -07008553 Object* new_double;
8554 { MaybeObject* maybe_new_double = Heap::AllocateHeapNumber(0.0);
8555 if (!maybe_new_double->ToObject(&new_double)) return maybe_new_double;
8556 }
Steve Blocka7e24c12009-10-30 11:49:00 +00008557 result_double = HeapNumber::cast(new_double);
8558 }
8559
John Reck59135872010-11-02 12:39:01 -07008560 Object* obj;
8561 { MaybeObject* maybe_obj =
8562 NumberDictionary::Allocate(dict->NumberOfElements());
8563 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
8564 }
Steve Blocka7e24c12009-10-30 11:49:00 +00008565 NumberDictionary* new_dict = NumberDictionary::cast(obj);
8566
8567 AssertNoAllocation no_alloc;
8568
8569 uint32_t pos = 0;
8570 uint32_t undefs = 0;
Steve Block6ded16b2010-05-10 14:33:55 +01008571 int capacity = dict->Capacity();
Steve Blocka7e24c12009-10-30 11:49:00 +00008572 for (int i = 0; i < capacity; i++) {
8573 Object* k = dict->KeyAt(i);
8574 if (dict->IsKey(k)) {
8575 ASSERT(k->IsNumber());
8576 ASSERT(!k->IsSmi() || Smi::cast(k)->value() >= 0);
8577 ASSERT(!k->IsHeapNumber() || HeapNumber::cast(k)->value() >= 0);
8578 ASSERT(!k->IsHeapNumber() || HeapNumber::cast(k)->value() <= kMaxUInt32);
8579 Object* value = dict->ValueAt(i);
8580 PropertyDetails details = dict->DetailsAt(i);
8581 if (details.type() == CALLBACKS) {
8582 // Bail out and do the sorting of undefineds and array holes in JS.
8583 return Smi::FromInt(-1);
8584 }
8585 uint32_t key = NumberToUint32(k);
John Reck59135872010-11-02 12:39:01 -07008586 // In the following we assert that adding the entry to the new dictionary
8587 // does not cause GC. This is the case because we made sure to allocate
8588 // the dictionary big enough above, so it need not grow.
Steve Blocka7e24c12009-10-30 11:49:00 +00008589 if (key < limit) {
8590 if (value->IsUndefined()) {
8591 undefs++;
8592 } else {
Steve Block1e0659c2011-05-24 12:43:12 +01008593 if (pos > static_cast<uint32_t>(Smi::kMaxValue)) {
8594 // Adding an entry with the key beyond smi-range requires
8595 // allocation. Bailout.
8596 return Smi::FromInt(-1);
8597 }
John Reck59135872010-11-02 12:39:01 -07008598 new_dict->AddNumberEntry(pos, value, details)->ToObjectUnchecked();
Steve Blocka7e24c12009-10-30 11:49:00 +00008599 pos++;
8600 }
8601 } else {
Steve Block1e0659c2011-05-24 12:43:12 +01008602 if (key > static_cast<uint32_t>(Smi::kMaxValue)) {
8603 // Adding an entry with the key beyond smi-range requires
8604 // allocation. Bailout.
8605 return Smi::FromInt(-1);
8606 }
John Reck59135872010-11-02 12:39:01 -07008607 new_dict->AddNumberEntry(key, value, details)->ToObjectUnchecked();
Steve Blocka7e24c12009-10-30 11:49:00 +00008608 }
8609 }
8610 }
8611
8612 uint32_t result = pos;
8613 PropertyDetails no_details = PropertyDetails(NONE, NORMAL);
8614 while (undefs > 0) {
Steve Block1e0659c2011-05-24 12:43:12 +01008615 if (pos > static_cast<uint32_t>(Smi::kMaxValue)) {
8616 // Adding an entry with the key beyond smi-range requires
8617 // allocation. Bailout.
8618 return Smi::FromInt(-1);
8619 }
John Reck59135872010-11-02 12:39:01 -07008620 new_dict->AddNumberEntry(pos, Heap::undefined_value(), no_details)->
8621 ToObjectUnchecked();
Steve Blocka7e24c12009-10-30 11:49:00 +00008622 pos++;
8623 undefs--;
8624 }
8625
8626 set_elements(new_dict);
8627
8628 if (result <= static_cast<uint32_t>(Smi::kMaxValue)) {
8629 return Smi::FromInt(static_cast<int>(result));
8630 }
8631
8632 ASSERT_NE(NULL, result_double);
8633 result_double->set_value(static_cast<double>(result));
8634 return result_double;
8635}
8636
8637
8638// Collects all defined (non-hole) and non-undefined (array) elements at
8639// the start of the elements array.
8640// If the object is in dictionary mode, it is converted to fast elements
8641// mode.
John Reck59135872010-11-02 12:39:01 -07008642MaybeObject* JSObject::PrepareElementsForSort(uint32_t limit) {
Steve Block3ce2e202009-11-05 08:53:23 +00008643 ASSERT(!HasPixelElements() && !HasExternalArrayElements());
Steve Blocka7e24c12009-10-30 11:49:00 +00008644
8645 if (HasDictionaryElements()) {
8646 // Convert to fast elements containing only the existing properties.
8647 // Ordering is irrelevant, since we are going to sort anyway.
8648 NumberDictionary* dict = element_dictionary();
8649 if (IsJSArray() || dict->requires_slow_elements() ||
8650 dict->max_number_key() >= limit) {
8651 return PrepareSlowElementsForSort(limit);
8652 }
8653 // Convert to fast elements.
8654
John Reck59135872010-11-02 12:39:01 -07008655 Object* obj;
8656 { MaybeObject* maybe_obj = map()->GetFastElementsMap();
8657 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
8658 }
Steve Block8defd9f2010-07-08 12:39:36 +01008659 Map* new_map = Map::cast(obj);
8660
Steve Blocka7e24c12009-10-30 11:49:00 +00008661 PretenureFlag tenure = Heap::InNewSpace(this) ? NOT_TENURED: TENURED;
John Reck59135872010-11-02 12:39:01 -07008662 Object* new_array;
8663 { MaybeObject* maybe_new_array =
8664 Heap::AllocateFixedArray(dict->NumberOfElements(), tenure);
8665 if (!maybe_new_array->ToObject(&new_array)) return maybe_new_array;
8666 }
Steve Blocka7e24c12009-10-30 11:49:00 +00008667 FixedArray* fast_elements = FixedArray::cast(new_array);
8668 dict->CopyValuesTo(fast_elements);
Steve Block8defd9f2010-07-08 12:39:36 +01008669
8670 set_map(new_map);
Steve Blocka7e24c12009-10-30 11:49:00 +00008671 set_elements(fast_elements);
Iain Merrick75681382010-08-19 15:07:18 +01008672 } else {
John Reck59135872010-11-02 12:39:01 -07008673 Object* obj;
8674 { MaybeObject* maybe_obj = EnsureWritableFastElements();
8675 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
8676 }
Steve Blocka7e24c12009-10-30 11:49:00 +00008677 }
8678 ASSERT(HasFastElements());
8679
8680 // Collect holes at the end, undefined before that and the rest at the
8681 // start, and return the number of non-hole, non-undefined values.
8682
8683 FixedArray* elements = FixedArray::cast(this->elements());
8684 uint32_t elements_length = static_cast<uint32_t>(elements->length());
8685 if (limit > elements_length) {
8686 limit = elements_length ;
8687 }
8688 if (limit == 0) {
8689 return Smi::FromInt(0);
8690 }
8691
8692 HeapNumber* result_double = NULL;
8693 if (limit > static_cast<uint32_t>(Smi::kMaxValue)) {
8694 // Pessimistically allocate space for return value before
8695 // we start mutating the array.
John Reck59135872010-11-02 12:39:01 -07008696 Object* new_double;
8697 { MaybeObject* maybe_new_double = Heap::AllocateHeapNumber(0.0);
8698 if (!maybe_new_double->ToObject(&new_double)) return maybe_new_double;
8699 }
Steve Blocka7e24c12009-10-30 11:49:00 +00008700 result_double = HeapNumber::cast(new_double);
8701 }
8702
8703 AssertNoAllocation no_alloc;
8704
8705 // Split elements into defined, undefined and the_hole, in that order.
8706 // Only count locations for undefined and the hole, and fill them afterwards.
Leon Clarke4515c472010-02-03 11:58:03 +00008707 WriteBarrierMode write_barrier = elements->GetWriteBarrierMode(no_alloc);
Steve Blocka7e24c12009-10-30 11:49:00 +00008708 unsigned int undefs = limit;
8709 unsigned int holes = limit;
8710 // Assume most arrays contain no holes and undefined values, so minimize the
8711 // number of stores of non-undefined, non-the-hole values.
8712 for (unsigned int i = 0; i < undefs; i++) {
8713 Object* current = elements->get(i);
8714 if (current->IsTheHole()) {
8715 holes--;
8716 undefs--;
8717 } else if (current->IsUndefined()) {
8718 undefs--;
8719 } else {
8720 continue;
8721 }
8722 // Position i needs to be filled.
8723 while (undefs > i) {
8724 current = elements->get(undefs);
8725 if (current->IsTheHole()) {
8726 holes--;
8727 undefs--;
8728 } else if (current->IsUndefined()) {
8729 undefs--;
8730 } else {
8731 elements->set(i, current, write_barrier);
8732 break;
8733 }
8734 }
8735 }
8736 uint32_t result = undefs;
8737 while (undefs < holes) {
8738 elements->set_undefined(undefs);
8739 undefs++;
8740 }
8741 while (holes < limit) {
8742 elements->set_the_hole(holes);
8743 holes++;
8744 }
8745
8746 if (result <= static_cast<uint32_t>(Smi::kMaxValue)) {
8747 return Smi::FromInt(static_cast<int>(result));
8748 }
8749 ASSERT_NE(NULL, result_double);
8750 result_double->set_value(static_cast<double>(result));
8751 return result_double;
8752}
8753
8754
8755Object* PixelArray::SetValue(uint32_t index, Object* value) {
8756 uint8_t clamped_value = 0;
8757 if (index < static_cast<uint32_t>(length())) {
8758 if (value->IsSmi()) {
8759 int int_value = Smi::cast(value)->value();
8760 if (int_value < 0) {
8761 clamped_value = 0;
8762 } else if (int_value > 255) {
8763 clamped_value = 255;
8764 } else {
8765 clamped_value = static_cast<uint8_t>(int_value);
8766 }
8767 } else if (value->IsHeapNumber()) {
8768 double double_value = HeapNumber::cast(value)->value();
8769 if (!(double_value > 0)) {
8770 // NaN and less than zero clamp to zero.
8771 clamped_value = 0;
8772 } else if (double_value > 255) {
8773 // Greater than 255 clamp to 255.
8774 clamped_value = 255;
8775 } else {
8776 // Other doubles are rounded to the nearest integer.
8777 clamped_value = static_cast<uint8_t>(double_value + 0.5);
8778 }
8779 } else {
8780 // Clamp undefined to zero (default). All other types have been
8781 // converted to a number type further up in the call chain.
8782 ASSERT(value->IsUndefined());
8783 }
8784 set(index, clamped_value);
8785 }
8786 return Smi::FromInt(clamped_value);
8787}
8788
8789
Steve Block3ce2e202009-11-05 08:53:23 +00008790template<typename ExternalArrayClass, typename ValueType>
John Reck59135872010-11-02 12:39:01 -07008791static MaybeObject* ExternalArrayIntSetter(ExternalArrayClass* receiver,
8792 uint32_t index,
8793 Object* value) {
Steve Block3ce2e202009-11-05 08:53:23 +00008794 ValueType cast_value = 0;
8795 if (index < static_cast<uint32_t>(receiver->length())) {
8796 if (value->IsSmi()) {
8797 int int_value = Smi::cast(value)->value();
8798 cast_value = static_cast<ValueType>(int_value);
8799 } else if (value->IsHeapNumber()) {
8800 double double_value = HeapNumber::cast(value)->value();
8801 cast_value = static_cast<ValueType>(DoubleToInt32(double_value));
8802 } else {
8803 // Clamp undefined to zero (default). All other types have been
8804 // converted to a number type further up in the call chain.
8805 ASSERT(value->IsUndefined());
8806 }
8807 receiver->set(index, cast_value);
8808 }
8809 return Heap::NumberFromInt32(cast_value);
8810}
8811
8812
John Reck59135872010-11-02 12:39:01 -07008813MaybeObject* ExternalByteArray::SetValue(uint32_t index, Object* value) {
Steve Block3ce2e202009-11-05 08:53:23 +00008814 return ExternalArrayIntSetter<ExternalByteArray, int8_t>
8815 (this, index, value);
8816}
8817
8818
John Reck59135872010-11-02 12:39:01 -07008819MaybeObject* ExternalUnsignedByteArray::SetValue(uint32_t index,
8820 Object* value) {
Steve Block3ce2e202009-11-05 08:53:23 +00008821 return ExternalArrayIntSetter<ExternalUnsignedByteArray, uint8_t>
8822 (this, index, value);
8823}
8824
8825
John Reck59135872010-11-02 12:39:01 -07008826MaybeObject* ExternalShortArray::SetValue(uint32_t index,
8827 Object* value) {
Steve Block3ce2e202009-11-05 08:53:23 +00008828 return ExternalArrayIntSetter<ExternalShortArray, int16_t>
8829 (this, index, value);
8830}
8831
8832
John Reck59135872010-11-02 12:39:01 -07008833MaybeObject* ExternalUnsignedShortArray::SetValue(uint32_t index,
8834 Object* value) {
Steve Block3ce2e202009-11-05 08:53:23 +00008835 return ExternalArrayIntSetter<ExternalUnsignedShortArray, uint16_t>
8836 (this, index, value);
8837}
8838
8839
John Reck59135872010-11-02 12:39:01 -07008840MaybeObject* ExternalIntArray::SetValue(uint32_t index, Object* value) {
Steve Block3ce2e202009-11-05 08:53:23 +00008841 return ExternalArrayIntSetter<ExternalIntArray, int32_t>
8842 (this, index, value);
8843}
8844
8845
John Reck59135872010-11-02 12:39:01 -07008846MaybeObject* ExternalUnsignedIntArray::SetValue(uint32_t index, Object* value) {
Steve Block3ce2e202009-11-05 08:53:23 +00008847 uint32_t cast_value = 0;
8848 if (index < static_cast<uint32_t>(length())) {
8849 if (value->IsSmi()) {
8850 int int_value = Smi::cast(value)->value();
8851 cast_value = static_cast<uint32_t>(int_value);
8852 } else if (value->IsHeapNumber()) {
8853 double double_value = HeapNumber::cast(value)->value();
8854 cast_value = static_cast<uint32_t>(DoubleToUint32(double_value));
8855 } else {
8856 // Clamp undefined to zero (default). All other types have been
8857 // converted to a number type further up in the call chain.
8858 ASSERT(value->IsUndefined());
8859 }
8860 set(index, cast_value);
8861 }
8862 return Heap::NumberFromUint32(cast_value);
8863}
8864
8865
John Reck59135872010-11-02 12:39:01 -07008866MaybeObject* ExternalFloatArray::SetValue(uint32_t index, Object* value) {
Steve Block3ce2e202009-11-05 08:53:23 +00008867 float cast_value = 0;
8868 if (index < static_cast<uint32_t>(length())) {
8869 if (value->IsSmi()) {
8870 int int_value = Smi::cast(value)->value();
8871 cast_value = static_cast<float>(int_value);
8872 } else if (value->IsHeapNumber()) {
8873 double double_value = HeapNumber::cast(value)->value();
8874 cast_value = static_cast<float>(double_value);
8875 } else {
8876 // Clamp undefined to zero (default). All other types have been
8877 // converted to a number type further up in the call chain.
8878 ASSERT(value->IsUndefined());
8879 }
8880 set(index, cast_value);
8881 }
8882 return Heap::AllocateHeapNumber(cast_value);
8883}
8884
8885
Ben Murdochb0fe1622011-05-05 13:52:32 +01008886JSGlobalPropertyCell* GlobalObject::GetPropertyCell(LookupResult* result) {
Steve Blocka7e24c12009-10-30 11:49:00 +00008887 ASSERT(!HasFastProperties());
8888 Object* value = property_dictionary()->ValueAt(result->GetDictionaryEntry());
Ben Murdochb0fe1622011-05-05 13:52:32 +01008889 return JSGlobalPropertyCell::cast(value);
Steve Blocka7e24c12009-10-30 11:49:00 +00008890}
8891
8892
John Reck59135872010-11-02 12:39:01 -07008893MaybeObject* GlobalObject::EnsurePropertyCell(String* name) {
Steve Blocka7e24c12009-10-30 11:49:00 +00008894 ASSERT(!HasFastProperties());
8895 int entry = property_dictionary()->FindEntry(name);
8896 if (entry == StringDictionary::kNotFound) {
John Reck59135872010-11-02 12:39:01 -07008897 Object* cell;
8898 { MaybeObject* maybe_cell =
8899 Heap::AllocateJSGlobalPropertyCell(Heap::the_hole_value());
8900 if (!maybe_cell->ToObject(&cell)) return maybe_cell;
8901 }
Steve Blocka7e24c12009-10-30 11:49:00 +00008902 PropertyDetails details(NONE, NORMAL);
8903 details = details.AsDeleted();
John Reck59135872010-11-02 12:39:01 -07008904 Object* dictionary;
8905 { MaybeObject* maybe_dictionary =
8906 property_dictionary()->Add(name, cell, details);
8907 if (!maybe_dictionary->ToObject(&dictionary)) return maybe_dictionary;
8908 }
Steve Blocka7e24c12009-10-30 11:49:00 +00008909 set_properties(StringDictionary::cast(dictionary));
8910 return cell;
8911 } else {
8912 Object* value = property_dictionary()->ValueAt(entry);
8913 ASSERT(value->IsJSGlobalPropertyCell());
8914 return value;
8915 }
8916}
8917
8918
John Reck59135872010-11-02 12:39:01 -07008919MaybeObject* SymbolTable::LookupString(String* string, Object** s) {
Steve Blocka7e24c12009-10-30 11:49:00 +00008920 SymbolKey key(string);
8921 return LookupKey(&key, s);
8922}
8923
8924
Steve Blockd0582a62009-12-15 09:54:21 +00008925// This class is used for looking up two character strings in the symbol table.
8926// If we don't have a hit we don't want to waste much time so we unroll the
8927// string hash calculation loop here for speed. Doesn't work if the two
8928// characters form a decimal integer, since such strings have a different hash
8929// algorithm.
8930class TwoCharHashTableKey : public HashTableKey {
8931 public:
8932 TwoCharHashTableKey(uint32_t c1, uint32_t c2)
8933 : c1_(c1), c2_(c2) {
8934 // Char 1.
8935 uint32_t hash = c1 + (c1 << 10);
8936 hash ^= hash >> 6;
8937 // Char 2.
8938 hash += c2;
8939 hash += hash << 10;
8940 hash ^= hash >> 6;
8941 // GetHash.
8942 hash += hash << 3;
8943 hash ^= hash >> 11;
8944 hash += hash << 15;
8945 if (hash == 0) hash = 27;
8946#ifdef DEBUG
8947 StringHasher hasher(2);
8948 hasher.AddCharacter(c1);
8949 hasher.AddCharacter(c2);
8950 // If this assert fails then we failed to reproduce the two-character
8951 // version of the string hashing algorithm above. One reason could be
8952 // that we were passed two digits as characters, since the hash
8953 // algorithm is different in that case.
8954 ASSERT_EQ(static_cast<int>(hasher.GetHash()), static_cast<int>(hash));
8955#endif
8956 hash_ = hash;
8957 }
8958
8959 bool IsMatch(Object* o) {
8960 if (!o->IsString()) return false;
8961 String* other = String::cast(o);
8962 if (other->length() != 2) return false;
8963 if (other->Get(0) != c1_) return false;
8964 return other->Get(1) == c2_;
8965 }
8966
8967 uint32_t Hash() { return hash_; }
8968 uint32_t HashForObject(Object* key) {
8969 if (!key->IsString()) return 0;
8970 return String::cast(key)->Hash();
8971 }
8972
8973 Object* AsObject() {
8974 // The TwoCharHashTableKey is only used for looking in the symbol
8975 // table, not for adding to it.
8976 UNREACHABLE();
8977 return NULL;
8978 }
8979 private:
8980 uint32_t c1_;
8981 uint32_t c2_;
8982 uint32_t hash_;
8983};
8984
8985
Steve Blocka7e24c12009-10-30 11:49:00 +00008986bool SymbolTable::LookupSymbolIfExists(String* string, String** symbol) {
8987 SymbolKey key(string);
8988 int entry = FindEntry(&key);
8989 if (entry == kNotFound) {
8990 return false;
8991 } else {
8992 String* result = String::cast(KeyAt(entry));
8993 ASSERT(StringShape(result).IsSymbol());
8994 *symbol = result;
8995 return true;
8996 }
8997}
8998
8999
Steve Blockd0582a62009-12-15 09:54:21 +00009000bool SymbolTable::LookupTwoCharsSymbolIfExists(uint32_t c1,
9001 uint32_t c2,
9002 String** symbol) {
9003 TwoCharHashTableKey key(c1, c2);
9004 int entry = FindEntry(&key);
9005 if (entry == kNotFound) {
9006 return false;
9007 } else {
9008 String* result = String::cast(KeyAt(entry));
9009 ASSERT(StringShape(result).IsSymbol());
9010 *symbol = result;
9011 return true;
9012 }
9013}
9014
9015
John Reck59135872010-11-02 12:39:01 -07009016MaybeObject* SymbolTable::LookupSymbol(Vector<const char> str, Object** s) {
Steve Blocka7e24c12009-10-30 11:49:00 +00009017 Utf8SymbolKey key(str);
9018 return LookupKey(&key, s);
9019}
9020
9021
Steve Block9fac8402011-05-12 15:51:54 +01009022MaybeObject* SymbolTable::LookupAsciiSymbol(Vector<const char> str,
9023 Object** s) {
9024 AsciiSymbolKey key(str);
9025 return LookupKey(&key, s);
9026}
9027
9028
9029MaybeObject* SymbolTable::LookupTwoByteSymbol(Vector<const uc16> str,
9030 Object** s) {
9031 TwoByteSymbolKey key(str);
9032 return LookupKey(&key, s);
9033}
9034
John Reck59135872010-11-02 12:39:01 -07009035MaybeObject* SymbolTable::LookupKey(HashTableKey* key, Object** s) {
Steve Blocka7e24c12009-10-30 11:49:00 +00009036 int entry = FindEntry(key);
9037
9038 // Symbol already in table.
9039 if (entry != kNotFound) {
9040 *s = KeyAt(entry);
9041 return this;
9042 }
9043
9044 // Adding new symbol. Grow table if needed.
John Reck59135872010-11-02 12:39:01 -07009045 Object* obj;
9046 { MaybeObject* maybe_obj = EnsureCapacity(1, key);
9047 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
9048 }
Steve Blocka7e24c12009-10-30 11:49:00 +00009049
9050 // Create symbol object.
John Reck59135872010-11-02 12:39:01 -07009051 Object* symbol;
9052 { MaybeObject* maybe_symbol = key->AsObject();
9053 if (!maybe_symbol->ToObject(&symbol)) return maybe_symbol;
9054 }
Steve Blocka7e24c12009-10-30 11:49:00 +00009055
9056 // If the symbol table grew as part of EnsureCapacity, obj is not
9057 // the current symbol table and therefore we cannot use
9058 // SymbolTable::cast here.
9059 SymbolTable* table = reinterpret_cast<SymbolTable*>(obj);
9060
9061 // Add the new symbol and return it along with the symbol table.
9062 entry = table->FindInsertionEntry(key->Hash());
9063 table->set(EntryToIndex(entry), symbol);
9064 table->ElementAdded();
9065 *s = symbol;
9066 return table;
9067}
9068
9069
9070Object* CompilationCacheTable::Lookup(String* src) {
9071 StringKey key(src);
9072 int entry = FindEntry(&key);
9073 if (entry == kNotFound) return Heap::undefined_value();
9074 return get(EntryToIndex(entry) + 1);
9075}
9076
9077
Steve Block1e0659c2011-05-24 12:43:12 +01009078Object* CompilationCacheTable::LookupEval(String* src,
9079 Context* context,
9080 StrictModeFlag strict_mode) {
9081 StringSharedKey key(src, context->closure()->shared(), strict_mode);
Steve Blocka7e24c12009-10-30 11:49:00 +00009082 int entry = FindEntry(&key);
9083 if (entry == kNotFound) return Heap::undefined_value();
9084 return get(EntryToIndex(entry) + 1);
9085}
9086
9087
9088Object* CompilationCacheTable::LookupRegExp(String* src,
9089 JSRegExp::Flags flags) {
9090 RegExpKey key(src, flags);
9091 int entry = FindEntry(&key);
9092 if (entry == kNotFound) return Heap::undefined_value();
9093 return get(EntryToIndex(entry) + 1);
9094}
9095
9096
John Reck59135872010-11-02 12:39:01 -07009097MaybeObject* CompilationCacheTable::Put(String* src, Object* value) {
Steve Blocka7e24c12009-10-30 11:49:00 +00009098 StringKey key(src);
John Reck59135872010-11-02 12:39:01 -07009099 Object* obj;
9100 { MaybeObject* maybe_obj = EnsureCapacity(1, &key);
9101 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
9102 }
Steve Blocka7e24c12009-10-30 11:49:00 +00009103
9104 CompilationCacheTable* cache =
9105 reinterpret_cast<CompilationCacheTable*>(obj);
9106 int entry = cache->FindInsertionEntry(key.Hash());
9107 cache->set(EntryToIndex(entry), src);
9108 cache->set(EntryToIndex(entry) + 1, value);
9109 cache->ElementAdded();
9110 return cache;
9111}
9112
9113
John Reck59135872010-11-02 12:39:01 -07009114MaybeObject* CompilationCacheTable::PutEval(String* src,
9115 Context* context,
Steve Block1e0659c2011-05-24 12:43:12 +01009116 SharedFunctionInfo* value) {
9117 StringSharedKey key(src,
9118 context->closure()->shared(),
9119 value->strict_mode() ? kStrictMode : kNonStrictMode);
John Reck59135872010-11-02 12:39:01 -07009120 Object* obj;
9121 { MaybeObject* maybe_obj = EnsureCapacity(1, &key);
9122 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
9123 }
Steve Blocka7e24c12009-10-30 11:49:00 +00009124
9125 CompilationCacheTable* cache =
9126 reinterpret_cast<CompilationCacheTable*>(obj);
9127 int entry = cache->FindInsertionEntry(key.Hash());
9128
John Reck59135872010-11-02 12:39:01 -07009129 Object* k;
9130 { MaybeObject* maybe_k = key.AsObject();
9131 if (!maybe_k->ToObject(&k)) return maybe_k;
9132 }
Steve Blocka7e24c12009-10-30 11:49:00 +00009133
9134 cache->set(EntryToIndex(entry), k);
9135 cache->set(EntryToIndex(entry) + 1, value);
9136 cache->ElementAdded();
9137 return cache;
9138}
9139
9140
John Reck59135872010-11-02 12:39:01 -07009141MaybeObject* CompilationCacheTable::PutRegExp(String* src,
9142 JSRegExp::Flags flags,
9143 FixedArray* value) {
Steve Blocka7e24c12009-10-30 11:49:00 +00009144 RegExpKey key(src, flags);
John Reck59135872010-11-02 12:39:01 -07009145 Object* obj;
9146 { MaybeObject* maybe_obj = EnsureCapacity(1, &key);
9147 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
9148 }
Steve Blocka7e24c12009-10-30 11:49:00 +00009149
9150 CompilationCacheTable* cache =
9151 reinterpret_cast<CompilationCacheTable*>(obj);
9152 int entry = cache->FindInsertionEntry(key.Hash());
Steve Block3ce2e202009-11-05 08:53:23 +00009153 // We store the value in the key slot, and compare the search key
9154 // to the stored value with a custon IsMatch function during lookups.
Steve Blocka7e24c12009-10-30 11:49:00 +00009155 cache->set(EntryToIndex(entry), value);
9156 cache->set(EntryToIndex(entry) + 1, value);
9157 cache->ElementAdded();
9158 return cache;
9159}
9160
9161
Ben Murdochb0fe1622011-05-05 13:52:32 +01009162void CompilationCacheTable::Remove(Object* value) {
9163 for (int entry = 0, size = Capacity(); entry < size; entry++) {
9164 int entry_index = EntryToIndex(entry);
9165 int value_index = entry_index + 1;
9166 if (get(value_index) == value) {
9167 fast_set(this, entry_index, Heap::null_value());
9168 fast_set(this, value_index, Heap::null_value());
9169 ElementRemoved();
9170 }
9171 }
9172 return;
9173}
9174
9175
Steve Blocka7e24c12009-10-30 11:49:00 +00009176// SymbolsKey used for HashTable where key is array of symbols.
9177class SymbolsKey : public HashTableKey {
9178 public:
9179 explicit SymbolsKey(FixedArray* symbols) : symbols_(symbols) { }
9180
9181 bool IsMatch(Object* symbols) {
9182 FixedArray* o = FixedArray::cast(symbols);
9183 int len = symbols_->length();
9184 if (o->length() != len) return false;
9185 for (int i = 0; i < len; i++) {
9186 if (o->get(i) != symbols_->get(i)) return false;
9187 }
9188 return true;
9189 }
9190
9191 uint32_t Hash() { return HashForObject(symbols_); }
9192
9193 uint32_t HashForObject(Object* obj) {
9194 FixedArray* symbols = FixedArray::cast(obj);
9195 int len = symbols->length();
9196 uint32_t hash = 0;
9197 for (int i = 0; i < len; i++) {
9198 hash ^= String::cast(symbols->get(i))->Hash();
9199 }
9200 return hash;
9201 }
9202
9203 Object* AsObject() { return symbols_; }
9204
9205 private:
9206 FixedArray* symbols_;
9207};
9208
9209
9210Object* MapCache::Lookup(FixedArray* array) {
9211 SymbolsKey key(array);
9212 int entry = FindEntry(&key);
9213 if (entry == kNotFound) return Heap::undefined_value();
9214 return get(EntryToIndex(entry) + 1);
9215}
9216
9217
John Reck59135872010-11-02 12:39:01 -07009218MaybeObject* MapCache::Put(FixedArray* array, Map* value) {
Steve Blocka7e24c12009-10-30 11:49:00 +00009219 SymbolsKey key(array);
John Reck59135872010-11-02 12:39:01 -07009220 Object* obj;
9221 { MaybeObject* maybe_obj = EnsureCapacity(1, &key);
9222 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
9223 }
Steve Blocka7e24c12009-10-30 11:49:00 +00009224
9225 MapCache* cache = reinterpret_cast<MapCache*>(obj);
9226 int entry = cache->FindInsertionEntry(key.Hash());
9227 cache->set(EntryToIndex(entry), array);
9228 cache->set(EntryToIndex(entry) + 1, value);
9229 cache->ElementAdded();
9230 return cache;
9231}
9232
9233
9234template<typename Shape, typename Key>
John Reck59135872010-11-02 12:39:01 -07009235MaybeObject* Dictionary<Shape, Key>::Allocate(int at_least_space_for) {
9236 Object* obj;
9237 { MaybeObject* maybe_obj =
9238 HashTable<Shape, Key>::Allocate(at_least_space_for);
9239 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
Steve Blocka7e24c12009-10-30 11:49:00 +00009240 }
John Reck59135872010-11-02 12:39:01 -07009241 // Initialize the next enumeration index.
9242 Dictionary<Shape, Key>::cast(obj)->
9243 SetNextEnumerationIndex(PropertyDetails::kInitialIndex);
Steve Blocka7e24c12009-10-30 11:49:00 +00009244 return obj;
9245}
9246
9247
9248template<typename Shape, typename Key>
John Reck59135872010-11-02 12:39:01 -07009249MaybeObject* Dictionary<Shape, Key>::GenerateNewEnumerationIndices() {
Steve Blocka7e24c12009-10-30 11:49:00 +00009250 int length = HashTable<Shape, Key>::NumberOfElements();
9251
9252 // Allocate and initialize iteration order array.
John Reck59135872010-11-02 12:39:01 -07009253 Object* obj;
9254 { MaybeObject* maybe_obj = Heap::AllocateFixedArray(length);
9255 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
9256 }
Steve Blocka7e24c12009-10-30 11:49:00 +00009257 FixedArray* iteration_order = FixedArray::cast(obj);
9258 for (int i = 0; i < length; i++) {
Leon Clarke4515c472010-02-03 11:58:03 +00009259 iteration_order->set(i, Smi::FromInt(i));
Steve Blocka7e24c12009-10-30 11:49:00 +00009260 }
9261
9262 // Allocate array with enumeration order.
John Reck59135872010-11-02 12:39:01 -07009263 { MaybeObject* maybe_obj = Heap::AllocateFixedArray(length);
9264 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
9265 }
Steve Blocka7e24c12009-10-30 11:49:00 +00009266 FixedArray* enumeration_order = FixedArray::cast(obj);
9267
9268 // Fill the enumeration order array with property details.
9269 int capacity = HashTable<Shape, Key>::Capacity();
9270 int pos = 0;
9271 for (int i = 0; i < capacity; i++) {
9272 if (Dictionary<Shape, Key>::IsKey(Dictionary<Shape, Key>::KeyAt(i))) {
Leon Clarke4515c472010-02-03 11:58:03 +00009273 enumeration_order->set(pos++, Smi::FromInt(DetailsAt(i).index()));
Steve Blocka7e24c12009-10-30 11:49:00 +00009274 }
9275 }
9276
9277 // Sort the arrays wrt. enumeration order.
9278 iteration_order->SortPairs(enumeration_order, enumeration_order->length());
9279
9280 // Overwrite the enumeration_order with the enumeration indices.
9281 for (int i = 0; i < length; i++) {
9282 int index = Smi::cast(iteration_order->get(i))->value();
9283 int enum_index = PropertyDetails::kInitialIndex + i;
Leon Clarke4515c472010-02-03 11:58:03 +00009284 enumeration_order->set(index, Smi::FromInt(enum_index));
Steve Blocka7e24c12009-10-30 11:49:00 +00009285 }
9286
9287 // Update the dictionary with new indices.
9288 capacity = HashTable<Shape, Key>::Capacity();
9289 pos = 0;
9290 for (int i = 0; i < capacity; i++) {
9291 if (Dictionary<Shape, Key>::IsKey(Dictionary<Shape, Key>::KeyAt(i))) {
9292 int enum_index = Smi::cast(enumeration_order->get(pos++))->value();
9293 PropertyDetails details = DetailsAt(i);
9294 PropertyDetails new_details =
9295 PropertyDetails(details.attributes(), details.type(), enum_index);
9296 DetailsAtPut(i, new_details);
9297 }
9298 }
9299
9300 // Set the next enumeration index.
9301 SetNextEnumerationIndex(PropertyDetails::kInitialIndex+length);
9302 return this;
9303}
9304
9305template<typename Shape, typename Key>
John Reck59135872010-11-02 12:39:01 -07009306MaybeObject* Dictionary<Shape, Key>::EnsureCapacity(int n, Key key) {
Steve Blocka7e24c12009-10-30 11:49:00 +00009307 // Check whether there are enough enumeration indices to add n elements.
9308 if (Shape::kIsEnumerable &&
9309 !PropertyDetails::IsValidIndex(NextEnumerationIndex() + n)) {
9310 // If not, we generate new indices for the properties.
John Reck59135872010-11-02 12:39:01 -07009311 Object* result;
9312 { MaybeObject* maybe_result = GenerateNewEnumerationIndices();
9313 if (!maybe_result->ToObject(&result)) return maybe_result;
9314 }
Steve Blocka7e24c12009-10-30 11:49:00 +00009315 }
9316 return HashTable<Shape, Key>::EnsureCapacity(n, key);
9317}
9318
9319
9320void NumberDictionary::RemoveNumberEntries(uint32_t from, uint32_t to) {
9321 // Do nothing if the interval [from, to) is empty.
9322 if (from >= to) return;
9323
9324 int removed_entries = 0;
9325 Object* sentinel = Heap::null_value();
9326 int capacity = Capacity();
9327 for (int i = 0; i < capacity; i++) {
9328 Object* key = KeyAt(i);
9329 if (key->IsNumber()) {
9330 uint32_t number = static_cast<uint32_t>(key->Number());
9331 if (from <= number && number < to) {
9332 SetEntry(i, sentinel, sentinel, Smi::FromInt(0));
9333 removed_entries++;
9334 }
9335 }
9336 }
9337
9338 // Update the number of elements.
Leon Clarkee46be812010-01-19 14:06:41 +00009339 ElementsRemoved(removed_entries);
Steve Blocka7e24c12009-10-30 11:49:00 +00009340}
9341
9342
9343template<typename Shape, typename Key>
9344Object* Dictionary<Shape, Key>::DeleteProperty(int entry,
9345 JSObject::DeleteMode mode) {
9346 PropertyDetails details = DetailsAt(entry);
9347 // Ignore attributes if forcing a deletion.
9348 if (details.IsDontDelete() && mode == JSObject::NORMAL_DELETION) {
9349 return Heap::false_value();
9350 }
9351 SetEntry(entry, Heap::null_value(), Heap::null_value(), Smi::FromInt(0));
9352 HashTable<Shape, Key>::ElementRemoved();
9353 return Heap::true_value();
9354}
9355
9356
9357template<typename Shape, typename Key>
John Reck59135872010-11-02 12:39:01 -07009358MaybeObject* Dictionary<Shape, Key>::AtPut(Key key, Object* value) {
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01009359 int entry = this->FindEntry(key);
Steve Blocka7e24c12009-10-30 11:49:00 +00009360
9361 // If the entry is present set the value;
9362 if (entry != Dictionary<Shape, Key>::kNotFound) {
9363 ValueAtPut(entry, value);
9364 return this;
9365 }
9366
9367 // Check whether the dictionary should be extended.
John Reck59135872010-11-02 12:39:01 -07009368 Object* obj;
9369 { MaybeObject* maybe_obj = EnsureCapacity(1, key);
9370 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
9371 }
Steve Blocka7e24c12009-10-30 11:49:00 +00009372
John Reck59135872010-11-02 12:39:01 -07009373 Object* k;
9374 { MaybeObject* maybe_k = Shape::AsObject(key);
9375 if (!maybe_k->ToObject(&k)) return maybe_k;
9376 }
Steve Blocka7e24c12009-10-30 11:49:00 +00009377 PropertyDetails details = PropertyDetails(NONE, NORMAL);
9378 return Dictionary<Shape, Key>::cast(obj)->
9379 AddEntry(key, value, details, Shape::Hash(key));
9380}
9381
9382
9383template<typename Shape, typename Key>
John Reck59135872010-11-02 12:39:01 -07009384MaybeObject* Dictionary<Shape, Key>::Add(Key key,
9385 Object* value,
9386 PropertyDetails details) {
Steve Blocka7e24c12009-10-30 11:49:00 +00009387 // Valdate key is absent.
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01009388 SLOW_ASSERT((this->FindEntry(key) == Dictionary<Shape, Key>::kNotFound));
Steve Blocka7e24c12009-10-30 11:49:00 +00009389 // Check whether the dictionary should be extended.
John Reck59135872010-11-02 12:39:01 -07009390 Object* obj;
9391 { MaybeObject* maybe_obj = EnsureCapacity(1, key);
9392 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
9393 }
Steve Blocka7e24c12009-10-30 11:49:00 +00009394 return Dictionary<Shape, Key>::cast(obj)->
9395 AddEntry(key, value, details, Shape::Hash(key));
9396}
9397
9398
9399// Add a key, value pair to the dictionary.
9400template<typename Shape, typename Key>
John Reck59135872010-11-02 12:39:01 -07009401MaybeObject* Dictionary<Shape, Key>::AddEntry(Key key,
9402 Object* value,
9403 PropertyDetails details,
9404 uint32_t hash) {
Steve Blocka7e24c12009-10-30 11:49:00 +00009405 // Compute the key object.
John Reck59135872010-11-02 12:39:01 -07009406 Object* k;
9407 { MaybeObject* maybe_k = Shape::AsObject(key);
9408 if (!maybe_k->ToObject(&k)) return maybe_k;
9409 }
Steve Blocka7e24c12009-10-30 11:49:00 +00009410
9411 uint32_t entry = Dictionary<Shape, Key>::FindInsertionEntry(hash);
9412 // Insert element at empty or deleted entry
9413 if (!details.IsDeleted() && details.index() == 0 && Shape::kIsEnumerable) {
9414 // Assign an enumeration index to the property and update
9415 // SetNextEnumerationIndex.
9416 int index = NextEnumerationIndex();
9417 details = PropertyDetails(details.attributes(), details.type(), index);
9418 SetNextEnumerationIndex(index + 1);
9419 }
9420 SetEntry(entry, k, value, details);
9421 ASSERT((Dictionary<Shape, Key>::KeyAt(entry)->IsNumber()
9422 || Dictionary<Shape, Key>::KeyAt(entry)->IsString()));
9423 HashTable<Shape, Key>::ElementAdded();
9424 return this;
9425}
9426
9427
9428void NumberDictionary::UpdateMaxNumberKey(uint32_t key) {
9429 // If the dictionary requires slow elements an element has already
9430 // been added at a high index.
9431 if (requires_slow_elements()) return;
9432 // Check if this index is high enough that we should require slow
9433 // elements.
9434 if (key > kRequiresSlowElementsLimit) {
9435 set_requires_slow_elements();
9436 return;
9437 }
9438 // Update max key value.
9439 Object* max_index_object = get(kMaxNumberKeyIndex);
9440 if (!max_index_object->IsSmi() || max_number_key() < key) {
9441 FixedArray::set(kMaxNumberKeyIndex,
Leon Clarke4515c472010-02-03 11:58:03 +00009442 Smi::FromInt(key << kRequiresSlowElementsTagSize));
Steve Blocka7e24c12009-10-30 11:49:00 +00009443 }
9444}
9445
9446
John Reck59135872010-11-02 12:39:01 -07009447MaybeObject* NumberDictionary::AddNumberEntry(uint32_t key,
9448 Object* value,
9449 PropertyDetails details) {
Steve Blocka7e24c12009-10-30 11:49:00 +00009450 UpdateMaxNumberKey(key);
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01009451 SLOW_ASSERT(this->FindEntry(key) == kNotFound);
Steve Blocka7e24c12009-10-30 11:49:00 +00009452 return Add(key, value, details);
9453}
9454
9455
John Reck59135872010-11-02 12:39:01 -07009456MaybeObject* NumberDictionary::AtNumberPut(uint32_t key, Object* value) {
Steve Blocka7e24c12009-10-30 11:49:00 +00009457 UpdateMaxNumberKey(key);
9458 return AtPut(key, value);
9459}
9460
9461
John Reck59135872010-11-02 12:39:01 -07009462MaybeObject* NumberDictionary::Set(uint32_t key,
9463 Object* value,
9464 PropertyDetails details) {
Steve Blocka7e24c12009-10-30 11:49:00 +00009465 int entry = FindEntry(key);
9466 if (entry == kNotFound) return AddNumberEntry(key, value, details);
9467 // Preserve enumeration index.
9468 details = PropertyDetails(details.attributes(),
9469 details.type(),
9470 DetailsAt(entry).index());
John Reck59135872010-11-02 12:39:01 -07009471 MaybeObject* maybe_object_key = NumberDictionaryShape::AsObject(key);
9472 Object* object_key;
9473 if (!maybe_object_key->ToObject(&object_key)) return maybe_object_key;
Ben Murdochf87a2032010-10-22 12:50:53 +01009474 SetEntry(entry, object_key, value, details);
Steve Blocka7e24c12009-10-30 11:49:00 +00009475 return this;
9476}
9477
9478
9479
9480template<typename Shape, typename Key>
9481int Dictionary<Shape, Key>::NumberOfElementsFilterAttributes(
9482 PropertyAttributes filter) {
9483 int capacity = HashTable<Shape, Key>::Capacity();
9484 int result = 0;
9485 for (int i = 0; i < capacity; i++) {
9486 Object* k = HashTable<Shape, Key>::KeyAt(i);
9487 if (HashTable<Shape, Key>::IsKey(k)) {
9488 PropertyDetails details = DetailsAt(i);
9489 if (details.IsDeleted()) continue;
9490 PropertyAttributes attr = details.attributes();
9491 if ((attr & filter) == 0) result++;
9492 }
9493 }
9494 return result;
9495}
9496
9497
9498template<typename Shape, typename Key>
9499int Dictionary<Shape, Key>::NumberOfEnumElements() {
9500 return NumberOfElementsFilterAttributes(
9501 static_cast<PropertyAttributes>(DONT_ENUM));
9502}
9503
9504
9505template<typename Shape, typename Key>
9506void Dictionary<Shape, Key>::CopyKeysTo(FixedArray* storage,
9507 PropertyAttributes filter) {
9508 ASSERT(storage->length() >= NumberOfEnumElements());
9509 int capacity = HashTable<Shape, Key>::Capacity();
9510 int index = 0;
9511 for (int i = 0; i < capacity; i++) {
9512 Object* k = HashTable<Shape, Key>::KeyAt(i);
9513 if (HashTable<Shape, Key>::IsKey(k)) {
9514 PropertyDetails details = DetailsAt(i);
9515 if (details.IsDeleted()) continue;
9516 PropertyAttributes attr = details.attributes();
9517 if ((attr & filter) == 0) storage->set(index++, k);
9518 }
9519 }
9520 storage->SortPairs(storage, index);
9521 ASSERT(storage->length() >= index);
9522}
9523
9524
9525void StringDictionary::CopyEnumKeysTo(FixedArray* storage,
9526 FixedArray* sort_array) {
9527 ASSERT(storage->length() >= NumberOfEnumElements());
9528 int capacity = Capacity();
9529 int index = 0;
9530 for (int i = 0; i < capacity; i++) {
9531 Object* k = KeyAt(i);
9532 if (IsKey(k)) {
9533 PropertyDetails details = DetailsAt(i);
9534 if (details.IsDeleted() || details.IsDontEnum()) continue;
9535 storage->set(index, k);
Leon Clarke4515c472010-02-03 11:58:03 +00009536 sort_array->set(index, Smi::FromInt(details.index()));
Steve Blocka7e24c12009-10-30 11:49:00 +00009537 index++;
9538 }
9539 }
9540 storage->SortPairs(sort_array, sort_array->length());
9541 ASSERT(storage->length() >= index);
9542}
9543
9544
9545template<typename Shape, typename Key>
9546void Dictionary<Shape, Key>::CopyKeysTo(FixedArray* storage) {
9547 ASSERT(storage->length() >= NumberOfElementsFilterAttributes(
9548 static_cast<PropertyAttributes>(NONE)));
9549 int capacity = HashTable<Shape, Key>::Capacity();
9550 int index = 0;
9551 for (int i = 0; i < capacity; i++) {
9552 Object* k = HashTable<Shape, Key>::KeyAt(i);
9553 if (HashTable<Shape, Key>::IsKey(k)) {
9554 PropertyDetails details = DetailsAt(i);
9555 if (details.IsDeleted()) continue;
9556 storage->set(index++, k);
9557 }
9558 }
9559 ASSERT(storage->length() >= index);
9560}
9561
9562
9563// Backwards lookup (slow).
9564template<typename Shape, typename Key>
9565Object* Dictionary<Shape, Key>::SlowReverseLookup(Object* value) {
9566 int capacity = HashTable<Shape, Key>::Capacity();
9567 for (int i = 0; i < capacity; i++) {
9568 Object* k = HashTable<Shape, Key>::KeyAt(i);
9569 if (Dictionary<Shape, Key>::IsKey(k)) {
9570 Object* e = ValueAt(i);
9571 if (e->IsJSGlobalPropertyCell()) {
9572 e = JSGlobalPropertyCell::cast(e)->value();
9573 }
9574 if (e == value) return k;
9575 }
9576 }
9577 return Heap::undefined_value();
9578}
9579
9580
John Reck59135872010-11-02 12:39:01 -07009581MaybeObject* StringDictionary::TransformPropertiesToFastFor(
Steve Blocka7e24c12009-10-30 11:49:00 +00009582 JSObject* obj, int unused_property_fields) {
9583 // Make sure we preserve dictionary representation if there are too many
9584 // descriptors.
9585 if (NumberOfElements() > DescriptorArray::kMaxNumberOfDescriptors) return obj;
9586
9587 // Figure out if it is necessary to generate new enumeration indices.
9588 int max_enumeration_index =
9589 NextEnumerationIndex() +
9590 (DescriptorArray::kMaxNumberOfDescriptors -
9591 NumberOfElements());
9592 if (!PropertyDetails::IsValidIndex(max_enumeration_index)) {
John Reck59135872010-11-02 12:39:01 -07009593 Object* result;
9594 { MaybeObject* maybe_result = GenerateNewEnumerationIndices();
9595 if (!maybe_result->ToObject(&result)) return maybe_result;
9596 }
Steve Blocka7e24c12009-10-30 11:49:00 +00009597 }
9598
9599 int instance_descriptor_length = 0;
9600 int number_of_fields = 0;
9601
9602 // Compute the length of the instance descriptor.
9603 int capacity = Capacity();
9604 for (int i = 0; i < capacity; i++) {
9605 Object* k = KeyAt(i);
9606 if (IsKey(k)) {
9607 Object* value = ValueAt(i);
9608 PropertyType type = DetailsAt(i).type();
9609 ASSERT(type != FIELD);
9610 instance_descriptor_length++;
Leon Clarkee46be812010-01-19 14:06:41 +00009611 if (type == NORMAL &&
9612 (!value->IsJSFunction() || Heap::InNewSpace(value))) {
9613 number_of_fields += 1;
9614 }
Steve Blocka7e24c12009-10-30 11:49:00 +00009615 }
9616 }
9617
9618 // Allocate the instance descriptor.
John Reck59135872010-11-02 12:39:01 -07009619 Object* descriptors_unchecked;
9620 { MaybeObject* maybe_descriptors_unchecked =
9621 DescriptorArray::Allocate(instance_descriptor_length);
9622 if (!maybe_descriptors_unchecked->ToObject(&descriptors_unchecked)) {
9623 return maybe_descriptors_unchecked;
9624 }
9625 }
Steve Blocka7e24c12009-10-30 11:49:00 +00009626 DescriptorArray* descriptors = DescriptorArray::cast(descriptors_unchecked);
9627
9628 int inobject_props = obj->map()->inobject_properties();
9629 int number_of_allocated_fields =
9630 number_of_fields + unused_property_fields - inobject_props;
Ben Murdochf87a2032010-10-22 12:50:53 +01009631 if (number_of_allocated_fields < 0) {
9632 // There is enough inobject space for all fields (including unused).
9633 number_of_allocated_fields = 0;
9634 unused_property_fields = inobject_props - number_of_fields;
9635 }
Steve Blocka7e24c12009-10-30 11:49:00 +00009636
9637 // Allocate the fixed array for the fields.
John Reck59135872010-11-02 12:39:01 -07009638 Object* fields;
9639 { MaybeObject* maybe_fields =
9640 Heap::AllocateFixedArray(number_of_allocated_fields);
9641 if (!maybe_fields->ToObject(&fields)) return maybe_fields;
9642 }
Steve Blocka7e24c12009-10-30 11:49:00 +00009643
9644 // Fill in the instance descriptor and the fields.
9645 int next_descriptor = 0;
9646 int current_offset = 0;
9647 for (int i = 0; i < capacity; i++) {
9648 Object* k = KeyAt(i);
9649 if (IsKey(k)) {
9650 Object* value = ValueAt(i);
9651 // Ensure the key is a symbol before writing into the instance descriptor.
John Reck59135872010-11-02 12:39:01 -07009652 Object* key;
9653 { MaybeObject* maybe_key = Heap::LookupSymbol(String::cast(k));
9654 if (!maybe_key->ToObject(&key)) return maybe_key;
9655 }
Steve Blocka7e24c12009-10-30 11:49:00 +00009656 PropertyDetails details = DetailsAt(i);
9657 PropertyType type = details.type();
9658
Leon Clarkee46be812010-01-19 14:06:41 +00009659 if (value->IsJSFunction() && !Heap::InNewSpace(value)) {
Steve Blocka7e24c12009-10-30 11:49:00 +00009660 ConstantFunctionDescriptor d(String::cast(key),
9661 JSFunction::cast(value),
9662 details.attributes(),
9663 details.index());
9664 descriptors->Set(next_descriptor++, &d);
9665 } else if (type == NORMAL) {
9666 if (current_offset < inobject_props) {
9667 obj->InObjectPropertyAtPut(current_offset,
9668 value,
9669 UPDATE_WRITE_BARRIER);
9670 } else {
9671 int offset = current_offset - inobject_props;
9672 FixedArray::cast(fields)->set(offset, value);
9673 }
9674 FieldDescriptor d(String::cast(key),
9675 current_offset++,
9676 details.attributes(),
9677 details.index());
9678 descriptors->Set(next_descriptor++, &d);
9679 } else if (type == CALLBACKS) {
9680 CallbacksDescriptor d(String::cast(key),
9681 value,
9682 details.attributes(),
9683 details.index());
9684 descriptors->Set(next_descriptor++, &d);
9685 } else {
9686 UNREACHABLE();
9687 }
9688 }
9689 }
9690 ASSERT(current_offset == number_of_fields);
9691
9692 descriptors->Sort();
9693 // Allocate new map.
John Reck59135872010-11-02 12:39:01 -07009694 Object* new_map;
9695 { MaybeObject* maybe_new_map = obj->map()->CopyDropDescriptors();
9696 if (!maybe_new_map->ToObject(&new_map)) return maybe_new_map;
9697 }
Steve Blocka7e24c12009-10-30 11:49:00 +00009698
9699 // Transform the object.
9700 obj->set_map(Map::cast(new_map));
9701 obj->map()->set_instance_descriptors(descriptors);
9702 obj->map()->set_unused_property_fields(unused_property_fields);
9703
9704 obj->set_properties(FixedArray::cast(fields));
9705 ASSERT(obj->IsJSObject());
9706
9707 descriptors->SetNextEnumerationIndex(NextEnumerationIndex());
9708 // Check that it really works.
9709 ASSERT(obj->HasFastProperties());
9710
9711 return obj;
9712}
9713
9714
9715#ifdef ENABLE_DEBUGGER_SUPPORT
9716// Check if there is a break point at this code position.
9717bool DebugInfo::HasBreakPoint(int code_position) {
9718 // Get the break point info object for this code position.
9719 Object* break_point_info = GetBreakPointInfo(code_position);
9720
9721 // If there is no break point info object or no break points in the break
9722 // point info object there is no break point at this code position.
9723 if (break_point_info->IsUndefined()) return false;
9724 return BreakPointInfo::cast(break_point_info)->GetBreakPointCount() > 0;
9725}
9726
9727
9728// Get the break point info object for this code position.
9729Object* DebugInfo::GetBreakPointInfo(int code_position) {
9730 // Find the index of the break point info object for this code position.
9731 int index = GetBreakPointInfoIndex(code_position);
9732
9733 // Return the break point info object if any.
9734 if (index == kNoBreakPointInfo) return Heap::undefined_value();
9735 return BreakPointInfo::cast(break_points()->get(index));
9736}
9737
9738
9739// Clear a break point at the specified code position.
9740void DebugInfo::ClearBreakPoint(Handle<DebugInfo> debug_info,
9741 int code_position,
9742 Handle<Object> break_point_object) {
9743 Handle<Object> break_point_info(debug_info->GetBreakPointInfo(code_position));
9744 if (break_point_info->IsUndefined()) return;
9745 BreakPointInfo::ClearBreakPoint(
9746 Handle<BreakPointInfo>::cast(break_point_info),
9747 break_point_object);
9748}
9749
9750
9751void DebugInfo::SetBreakPoint(Handle<DebugInfo> debug_info,
9752 int code_position,
9753 int source_position,
9754 int statement_position,
9755 Handle<Object> break_point_object) {
9756 Handle<Object> break_point_info(debug_info->GetBreakPointInfo(code_position));
9757 if (!break_point_info->IsUndefined()) {
9758 BreakPointInfo::SetBreakPoint(
9759 Handle<BreakPointInfo>::cast(break_point_info),
9760 break_point_object);
9761 return;
9762 }
9763
9764 // Adding a new break point for a code position which did not have any
9765 // break points before. Try to find a free slot.
9766 int index = kNoBreakPointInfo;
9767 for (int i = 0; i < debug_info->break_points()->length(); i++) {
9768 if (debug_info->break_points()->get(i)->IsUndefined()) {
9769 index = i;
9770 break;
9771 }
9772 }
9773 if (index == kNoBreakPointInfo) {
9774 // No free slot - extend break point info array.
9775 Handle<FixedArray> old_break_points =
9776 Handle<FixedArray>(FixedArray::cast(debug_info->break_points()));
Steve Blocka7e24c12009-10-30 11:49:00 +00009777 Handle<FixedArray> new_break_points =
Kristian Monsen0d5e1162010-09-30 15:31:59 +01009778 Factory::NewFixedArray(old_break_points->length() +
9779 Debug::kEstimatedNofBreakPointsInFunction);
9780
9781 debug_info->set_break_points(*new_break_points);
Steve Blocka7e24c12009-10-30 11:49:00 +00009782 for (int i = 0; i < old_break_points->length(); i++) {
9783 new_break_points->set(i, old_break_points->get(i));
9784 }
9785 index = old_break_points->length();
9786 }
9787 ASSERT(index != kNoBreakPointInfo);
9788
9789 // Allocate new BreakPointInfo object and set the break point.
9790 Handle<BreakPointInfo> new_break_point_info =
9791 Handle<BreakPointInfo>::cast(Factory::NewStruct(BREAK_POINT_INFO_TYPE));
9792 new_break_point_info->set_code_position(Smi::FromInt(code_position));
9793 new_break_point_info->set_source_position(Smi::FromInt(source_position));
9794 new_break_point_info->
9795 set_statement_position(Smi::FromInt(statement_position));
9796 new_break_point_info->set_break_point_objects(Heap::undefined_value());
9797 BreakPointInfo::SetBreakPoint(new_break_point_info, break_point_object);
9798 debug_info->break_points()->set(index, *new_break_point_info);
9799}
9800
9801
9802// Get the break point objects for a code position.
9803Object* DebugInfo::GetBreakPointObjects(int code_position) {
9804 Object* break_point_info = GetBreakPointInfo(code_position);
9805 if (break_point_info->IsUndefined()) {
9806 return Heap::undefined_value();
9807 }
9808 return BreakPointInfo::cast(break_point_info)->break_point_objects();
9809}
9810
9811
9812// Get the total number of break points.
9813int DebugInfo::GetBreakPointCount() {
9814 if (break_points()->IsUndefined()) return 0;
9815 int count = 0;
9816 for (int i = 0; i < break_points()->length(); i++) {
9817 if (!break_points()->get(i)->IsUndefined()) {
9818 BreakPointInfo* break_point_info =
9819 BreakPointInfo::cast(break_points()->get(i));
9820 count += break_point_info->GetBreakPointCount();
9821 }
9822 }
9823 return count;
9824}
9825
9826
9827Object* DebugInfo::FindBreakPointInfo(Handle<DebugInfo> debug_info,
9828 Handle<Object> break_point_object) {
9829 if (debug_info->break_points()->IsUndefined()) return Heap::undefined_value();
9830 for (int i = 0; i < debug_info->break_points()->length(); i++) {
9831 if (!debug_info->break_points()->get(i)->IsUndefined()) {
9832 Handle<BreakPointInfo> break_point_info =
9833 Handle<BreakPointInfo>(BreakPointInfo::cast(
9834 debug_info->break_points()->get(i)));
9835 if (BreakPointInfo::HasBreakPointObject(break_point_info,
9836 break_point_object)) {
9837 return *break_point_info;
9838 }
9839 }
9840 }
9841 return Heap::undefined_value();
9842}
9843
9844
9845// Find the index of the break point info object for the specified code
9846// position.
9847int DebugInfo::GetBreakPointInfoIndex(int code_position) {
9848 if (break_points()->IsUndefined()) return kNoBreakPointInfo;
9849 for (int i = 0; i < break_points()->length(); i++) {
9850 if (!break_points()->get(i)->IsUndefined()) {
9851 BreakPointInfo* break_point_info =
9852 BreakPointInfo::cast(break_points()->get(i));
9853 if (break_point_info->code_position()->value() == code_position) {
9854 return i;
9855 }
9856 }
9857 }
9858 return kNoBreakPointInfo;
9859}
9860
9861
9862// Remove the specified break point object.
9863void BreakPointInfo::ClearBreakPoint(Handle<BreakPointInfo> break_point_info,
9864 Handle<Object> break_point_object) {
9865 // If there are no break points just ignore.
9866 if (break_point_info->break_point_objects()->IsUndefined()) return;
9867 // If there is a single break point clear it if it is the same.
9868 if (!break_point_info->break_point_objects()->IsFixedArray()) {
9869 if (break_point_info->break_point_objects() == *break_point_object) {
9870 break_point_info->set_break_point_objects(Heap::undefined_value());
9871 }
9872 return;
9873 }
9874 // If there are multiple break points shrink the array
9875 ASSERT(break_point_info->break_point_objects()->IsFixedArray());
9876 Handle<FixedArray> old_array =
9877 Handle<FixedArray>(
9878 FixedArray::cast(break_point_info->break_point_objects()));
9879 Handle<FixedArray> new_array =
9880 Factory::NewFixedArray(old_array->length() - 1);
9881 int found_count = 0;
9882 for (int i = 0; i < old_array->length(); i++) {
9883 if (old_array->get(i) == *break_point_object) {
9884 ASSERT(found_count == 0);
9885 found_count++;
9886 } else {
9887 new_array->set(i - found_count, old_array->get(i));
9888 }
9889 }
9890 // If the break point was found in the list change it.
9891 if (found_count > 0) break_point_info->set_break_point_objects(*new_array);
9892}
9893
9894
9895// Add the specified break point object.
9896void BreakPointInfo::SetBreakPoint(Handle<BreakPointInfo> break_point_info,
9897 Handle<Object> break_point_object) {
9898 // If there was no break point objects before just set it.
9899 if (break_point_info->break_point_objects()->IsUndefined()) {
9900 break_point_info->set_break_point_objects(*break_point_object);
9901 return;
9902 }
9903 // If the break point object is the same as before just ignore.
9904 if (break_point_info->break_point_objects() == *break_point_object) return;
9905 // If there was one break point object before replace with array.
9906 if (!break_point_info->break_point_objects()->IsFixedArray()) {
9907 Handle<FixedArray> array = Factory::NewFixedArray(2);
9908 array->set(0, break_point_info->break_point_objects());
9909 array->set(1, *break_point_object);
9910 break_point_info->set_break_point_objects(*array);
9911 return;
9912 }
9913 // If there was more than one break point before extend array.
9914 Handle<FixedArray> old_array =
9915 Handle<FixedArray>(
9916 FixedArray::cast(break_point_info->break_point_objects()));
9917 Handle<FixedArray> new_array =
9918 Factory::NewFixedArray(old_array->length() + 1);
9919 for (int i = 0; i < old_array->length(); i++) {
9920 // If the break point was there before just ignore.
9921 if (old_array->get(i) == *break_point_object) return;
9922 new_array->set(i, old_array->get(i));
9923 }
9924 // Add the new break point.
9925 new_array->set(old_array->length(), *break_point_object);
9926 break_point_info->set_break_point_objects(*new_array);
9927}
9928
9929
9930bool BreakPointInfo::HasBreakPointObject(
9931 Handle<BreakPointInfo> break_point_info,
9932 Handle<Object> break_point_object) {
9933 // No break point.
9934 if (break_point_info->break_point_objects()->IsUndefined()) return false;
9935 // Single beak point.
9936 if (!break_point_info->break_point_objects()->IsFixedArray()) {
9937 return break_point_info->break_point_objects() == *break_point_object;
9938 }
9939 // Multiple break points.
9940 FixedArray* array = FixedArray::cast(break_point_info->break_point_objects());
9941 for (int i = 0; i < array->length(); i++) {
9942 if (array->get(i) == *break_point_object) {
9943 return true;
9944 }
9945 }
9946 return false;
9947}
9948
9949
9950// Get the number of break points.
9951int BreakPointInfo::GetBreakPointCount() {
9952 // No break point.
9953 if (break_point_objects()->IsUndefined()) return 0;
9954 // Single beak point.
9955 if (!break_point_objects()->IsFixedArray()) return 1;
9956 // Multiple break points.
9957 return FixedArray::cast(break_point_objects())->length();
9958}
9959#endif
9960
9961
9962} } // namespace v8::internal