blob: ab2f9644705f3ac4131b9990d12b7ed2920f2011 [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;
982#define MAKE_STRUCT_CASE(NAME, Name, name) \
983 case NAME##_TYPE: \
984 accumulator->Put('<'); \
985 accumulator->Add(#Name); \
986 accumulator->Put('>'); \
987 break;
988 STRUCT_LIST(MAKE_STRUCT_CASE)
989#undef MAKE_STRUCT_CASE
990 case CODE_TYPE:
991 accumulator->Add("<Code>");
992 break;
993 case ODDBALL_TYPE: {
994 if (IsUndefined())
995 accumulator->Add("<undefined>");
996 else if (IsTheHole())
997 accumulator->Add("<the hole>");
998 else if (IsNull())
999 accumulator->Add("<null>");
1000 else if (IsTrue())
1001 accumulator->Add("<true>");
1002 else if (IsFalse())
1003 accumulator->Add("<false>");
1004 else
1005 accumulator->Add("<Odd Oddball>");
1006 break;
1007 }
1008 case HEAP_NUMBER_TYPE:
1009 accumulator->Add("<Number: ");
1010 HeapNumber::cast(this)->HeapNumberPrint(accumulator);
1011 accumulator->Put('>');
1012 break;
1013 case PROXY_TYPE:
1014 accumulator->Add("<Proxy>");
1015 break;
1016 case JS_GLOBAL_PROPERTY_CELL_TYPE:
1017 accumulator->Add("Cell for ");
1018 JSGlobalPropertyCell::cast(this)->value()->ShortPrint(accumulator);
1019 break;
1020 default:
1021 accumulator->Add("<Other heap object (%d)>", map()->instance_type());
1022 break;
1023 }
1024}
1025
1026
Steve Blocka7e24c12009-10-30 11:49:00 +00001027void HeapObject::Iterate(ObjectVisitor* v) {
1028 // Handle header
1029 IteratePointer(v, kMapOffset);
1030 // Handle object body
1031 Map* m = map();
1032 IterateBody(m->instance_type(), SizeFromMap(m), v);
1033}
1034
1035
1036void HeapObject::IterateBody(InstanceType type, int object_size,
1037 ObjectVisitor* v) {
1038 // Avoiding <Type>::cast(this) because it accesses the map pointer field.
1039 // During GC, the map pointer field is encoded.
1040 if (type < FIRST_NONSTRING_TYPE) {
1041 switch (type & kStringRepresentationMask) {
1042 case kSeqStringTag:
1043 break;
1044 case kConsStringTag:
Iain Merrick75681382010-08-19 15:07:18 +01001045 ConsString::BodyDescriptor::IterateBody(this, v);
Steve Blocka7e24c12009-10-30 11:49:00 +00001046 break;
Steve Blockd0582a62009-12-15 09:54:21 +00001047 case kExternalStringTag:
1048 if ((type & kStringEncodingMask) == kAsciiStringTag) {
1049 reinterpret_cast<ExternalAsciiString*>(this)->
1050 ExternalAsciiStringIterateBody(v);
1051 } else {
1052 reinterpret_cast<ExternalTwoByteString*>(this)->
1053 ExternalTwoByteStringIterateBody(v);
1054 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001055 break;
1056 }
1057 return;
1058 }
1059
1060 switch (type) {
1061 case FIXED_ARRAY_TYPE:
Iain Merrick75681382010-08-19 15:07:18 +01001062 FixedArray::BodyDescriptor::IterateBody(this, object_size, v);
Steve Blocka7e24c12009-10-30 11:49:00 +00001063 break;
1064 case JS_OBJECT_TYPE:
1065 case JS_CONTEXT_EXTENSION_OBJECT_TYPE:
1066 case JS_VALUE_TYPE:
1067 case JS_ARRAY_TYPE:
1068 case JS_REGEXP_TYPE:
Steve Blocka7e24c12009-10-30 11:49:00 +00001069 case JS_GLOBAL_PROXY_TYPE:
1070 case JS_GLOBAL_OBJECT_TYPE:
1071 case JS_BUILTINS_OBJECT_TYPE:
Iain Merrick75681382010-08-19 15:07:18 +01001072 JSObject::BodyDescriptor::IterateBody(this, object_size, v);
Steve Blocka7e24c12009-10-30 11:49:00 +00001073 break;
Steve Block791712a2010-08-27 10:21:07 +01001074 case JS_FUNCTION_TYPE:
1075 reinterpret_cast<JSFunction*>(this)
1076 ->JSFunctionIterateBody(object_size, v);
1077 break;
Steve Blocka7e24c12009-10-30 11:49:00 +00001078 case ODDBALL_TYPE:
Iain Merrick75681382010-08-19 15:07:18 +01001079 Oddball::BodyDescriptor::IterateBody(this, v);
Steve Blocka7e24c12009-10-30 11:49:00 +00001080 break;
1081 case PROXY_TYPE:
1082 reinterpret_cast<Proxy*>(this)->ProxyIterateBody(v);
1083 break;
1084 case MAP_TYPE:
Iain Merrick75681382010-08-19 15:07:18 +01001085 Map::BodyDescriptor::IterateBody(this, v);
Steve Blocka7e24c12009-10-30 11:49:00 +00001086 break;
1087 case CODE_TYPE:
1088 reinterpret_cast<Code*>(this)->CodeIterateBody(v);
1089 break;
1090 case JS_GLOBAL_PROPERTY_CELL_TYPE:
Iain Merrick75681382010-08-19 15:07:18 +01001091 JSGlobalPropertyCell::BodyDescriptor::IterateBody(this, v);
Steve Blocka7e24c12009-10-30 11:49:00 +00001092 break;
1093 case HEAP_NUMBER_TYPE:
1094 case FILLER_TYPE:
1095 case BYTE_ARRAY_TYPE:
1096 case PIXEL_ARRAY_TYPE:
Steve Block3ce2e202009-11-05 08:53:23 +00001097 case EXTERNAL_BYTE_ARRAY_TYPE:
1098 case EXTERNAL_UNSIGNED_BYTE_ARRAY_TYPE:
1099 case EXTERNAL_SHORT_ARRAY_TYPE:
1100 case EXTERNAL_UNSIGNED_SHORT_ARRAY_TYPE:
1101 case EXTERNAL_INT_ARRAY_TYPE:
1102 case EXTERNAL_UNSIGNED_INT_ARRAY_TYPE:
1103 case EXTERNAL_FLOAT_ARRAY_TYPE:
Steve Blocka7e24c12009-10-30 11:49:00 +00001104 break;
Iain Merrick75681382010-08-19 15:07:18 +01001105 case SHARED_FUNCTION_INFO_TYPE:
1106 SharedFunctionInfo::BodyDescriptor::IterateBody(this, v);
Steve Blocka7e24c12009-10-30 11:49:00 +00001107 break;
Iain Merrick75681382010-08-19 15:07:18 +01001108
Steve Blocka7e24c12009-10-30 11:49:00 +00001109#define MAKE_STRUCT_CASE(NAME, Name, name) \
1110 case NAME##_TYPE:
1111 STRUCT_LIST(MAKE_STRUCT_CASE)
1112#undef MAKE_STRUCT_CASE
Iain Merrick75681382010-08-19 15:07:18 +01001113 StructBodyDescriptor::IterateBody(this, object_size, v);
Steve Blocka7e24c12009-10-30 11:49:00 +00001114 break;
1115 default:
1116 PrintF("Unknown type: %d\n", type);
1117 UNREACHABLE();
1118 }
1119}
1120
1121
Steve Blocka7e24c12009-10-30 11:49:00 +00001122Object* HeapNumber::HeapNumberToBoolean() {
1123 // NaN, +0, and -0 should return the false object
Iain Merrick75681382010-08-19 15:07:18 +01001124#if __BYTE_ORDER == __LITTLE_ENDIAN
1125 union IeeeDoubleLittleEndianArchType u;
1126#elif __BYTE_ORDER == __BIG_ENDIAN
1127 union IeeeDoubleBigEndianArchType u;
1128#endif
1129 u.d = value();
1130 if (u.bits.exp == 2047) {
1131 // Detect NaN for IEEE double precision floating point.
1132 if ((u.bits.man_low | u.bits.man_high) != 0)
1133 return Heap::false_value();
Steve Blocka7e24c12009-10-30 11:49:00 +00001134 }
Iain Merrick75681382010-08-19 15:07:18 +01001135 if (u.bits.exp == 0) {
1136 // Detect +0, and -0 for IEEE double precision floating point.
1137 if ((u.bits.man_low | u.bits.man_high) == 0)
1138 return Heap::false_value();
1139 }
1140 return Heap::true_value();
Steve Blocka7e24c12009-10-30 11:49:00 +00001141}
1142
1143
Ben Murdochb0fe1622011-05-05 13:52:32 +01001144void HeapNumber::HeapNumberPrint(FILE* out) {
1145 PrintF(out, "%.16g", Number());
Steve Blocka7e24c12009-10-30 11:49:00 +00001146}
1147
1148
1149void HeapNumber::HeapNumberPrint(StringStream* accumulator) {
1150 // The Windows version of vsnprintf can allocate when printing a %g string
1151 // into a buffer that may not be big enough. We don't want random memory
1152 // allocation when producing post-crash stack traces, so we print into a
1153 // buffer that is plenty big enough for any floating point number, then
1154 // print that using vsnprintf (which may truncate but never allocate if
1155 // there is no more space in the buffer).
1156 EmbeddedVector<char, 100> buffer;
1157 OS::SNPrintF(buffer, "%.16g", Number());
1158 accumulator->Add("%s", buffer.start());
1159}
1160
1161
1162String* JSObject::class_name() {
1163 if (IsJSFunction()) {
1164 return Heap::function_class_symbol();
1165 }
1166 if (map()->constructor()->IsJSFunction()) {
1167 JSFunction* constructor = JSFunction::cast(map()->constructor());
1168 return String::cast(constructor->shared()->instance_class_name());
1169 }
1170 // If the constructor is not present, return "Object".
1171 return Heap::Object_symbol();
1172}
1173
1174
1175String* JSObject::constructor_name() {
Steve Blocka7e24c12009-10-30 11:49:00 +00001176 if (map()->constructor()->IsJSFunction()) {
1177 JSFunction* constructor = JSFunction::cast(map()->constructor());
1178 String* name = String::cast(constructor->shared()->name());
Ben Murdochf87a2032010-10-22 12:50:53 +01001179 if (name->length() > 0) return name;
1180 String* inferred_name = constructor->shared()->inferred_name();
1181 if (inferred_name->length() > 0) return inferred_name;
1182 Object* proto = GetPrototype();
1183 if (proto->IsJSObject()) return JSObject::cast(proto)->constructor_name();
Steve Blocka7e24c12009-10-30 11:49:00 +00001184 }
1185 // If the constructor is not present, return "Object".
1186 return Heap::Object_symbol();
1187}
1188
1189
John Reck59135872010-11-02 12:39:01 -07001190MaybeObject* JSObject::AddFastPropertyUsingMap(Map* new_map,
1191 String* name,
1192 Object* value) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001193 int index = new_map->PropertyIndexFor(name);
1194 if (map()->unused_property_fields() == 0) {
1195 ASSERT(map()->unused_property_fields() == 0);
1196 int new_unused = new_map->unused_property_fields();
John Reck59135872010-11-02 12:39:01 -07001197 Object* values;
1198 { MaybeObject* maybe_values =
1199 properties()->CopySize(properties()->length() + new_unused + 1);
1200 if (!maybe_values->ToObject(&values)) return maybe_values;
1201 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001202 set_properties(FixedArray::cast(values));
1203 }
1204 set_map(new_map);
1205 return FastPropertyAtPut(index, value);
1206}
1207
1208
John Reck59135872010-11-02 12:39:01 -07001209MaybeObject* JSObject::AddFastProperty(String* name,
1210 Object* value,
1211 PropertyAttributes attributes) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001212 // Normalize the object if the name is an actual string (not the
1213 // hidden symbols) and is not a real identifier.
1214 StringInputBuffer buffer(name);
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -08001215 if (!ScannerConstants::IsIdentifier(&buffer)
1216 && name != Heap::hidden_symbol()) {
John Reck59135872010-11-02 12:39:01 -07001217 Object* obj;
1218 { MaybeObject* maybe_obj =
1219 NormalizeProperties(CLEAR_INOBJECT_PROPERTIES, 0);
1220 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
1221 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001222 return AddSlowProperty(name, value, attributes);
1223 }
1224
1225 DescriptorArray* old_descriptors = map()->instance_descriptors();
1226 // Compute the new index for new field.
1227 int index = map()->NextFreePropertyIndex();
1228
1229 // Allocate new instance descriptors with (name, index) added
1230 FieldDescriptor new_field(name, index, attributes);
John Reck59135872010-11-02 12:39:01 -07001231 Object* new_descriptors;
1232 { MaybeObject* maybe_new_descriptors =
1233 old_descriptors->CopyInsert(&new_field, REMOVE_TRANSITIONS);
1234 if (!maybe_new_descriptors->ToObject(&new_descriptors)) {
1235 return maybe_new_descriptors;
1236 }
1237 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001238
1239 // Only allow map transition if the object's map is NOT equal to the
1240 // global object_function's map and there is not a transition for name.
1241 bool allow_map_transition =
1242 !old_descriptors->Contains(name) &&
1243 (Top::context()->global_context()->object_function()->map() != map());
1244
1245 ASSERT(index < map()->inobject_properties() ||
1246 (index - map()->inobject_properties()) < properties()->length() ||
1247 map()->unused_property_fields() == 0);
1248 // Allocate a new map for the object.
John Reck59135872010-11-02 12:39:01 -07001249 Object* r;
1250 { MaybeObject* maybe_r = map()->CopyDropDescriptors();
1251 if (!maybe_r->ToObject(&r)) return maybe_r;
1252 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001253 Map* new_map = Map::cast(r);
1254 if (allow_map_transition) {
1255 // Allocate new instance descriptors for the old map with map transition.
1256 MapTransitionDescriptor d(name, Map::cast(new_map), attributes);
John Reck59135872010-11-02 12:39:01 -07001257 Object* r;
1258 { MaybeObject* maybe_r = old_descriptors->CopyInsert(&d, KEEP_TRANSITIONS);
1259 if (!maybe_r->ToObject(&r)) return maybe_r;
1260 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001261 old_descriptors = DescriptorArray::cast(r);
1262 }
1263
1264 if (map()->unused_property_fields() == 0) {
Steve Block8defd9f2010-07-08 12:39:36 +01001265 if (properties()->length() > MaxFastProperties()) {
John Reck59135872010-11-02 12:39:01 -07001266 Object* obj;
1267 { MaybeObject* maybe_obj =
1268 NormalizeProperties(CLEAR_INOBJECT_PROPERTIES, 0);
1269 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
1270 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001271 return AddSlowProperty(name, value, attributes);
1272 }
1273 // Make room for the new value
John Reck59135872010-11-02 12:39:01 -07001274 Object* values;
1275 { MaybeObject* maybe_values =
1276 properties()->CopySize(properties()->length() + kFieldsAdded);
1277 if (!maybe_values->ToObject(&values)) return maybe_values;
1278 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001279 set_properties(FixedArray::cast(values));
1280 new_map->set_unused_property_fields(kFieldsAdded - 1);
1281 } else {
1282 new_map->set_unused_property_fields(map()->unused_property_fields() - 1);
1283 }
1284 // We have now allocated all the necessary objects.
1285 // All the changes can be applied at once, so they are atomic.
1286 map()->set_instance_descriptors(old_descriptors);
1287 new_map->set_instance_descriptors(DescriptorArray::cast(new_descriptors));
1288 set_map(new_map);
1289 return FastPropertyAtPut(index, value);
1290}
1291
1292
John Reck59135872010-11-02 12:39:01 -07001293MaybeObject* JSObject::AddConstantFunctionProperty(
1294 String* name,
1295 JSFunction* function,
1296 PropertyAttributes attributes) {
Leon Clarkee46be812010-01-19 14:06:41 +00001297 ASSERT(!Heap::InNewSpace(function));
1298
Steve Blocka7e24c12009-10-30 11:49:00 +00001299 // Allocate new instance descriptors with (name, function) added
1300 ConstantFunctionDescriptor d(name, function, attributes);
John Reck59135872010-11-02 12:39:01 -07001301 Object* new_descriptors;
1302 { MaybeObject* maybe_new_descriptors =
1303 map()->instance_descriptors()->CopyInsert(&d, REMOVE_TRANSITIONS);
1304 if (!maybe_new_descriptors->ToObject(&new_descriptors)) {
1305 return maybe_new_descriptors;
1306 }
1307 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001308
1309 // Allocate a new map for the object.
John Reck59135872010-11-02 12:39:01 -07001310 Object* new_map;
1311 { MaybeObject* maybe_new_map = map()->CopyDropDescriptors();
1312 if (!maybe_new_map->ToObject(&new_map)) return maybe_new_map;
1313 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001314
1315 DescriptorArray* descriptors = DescriptorArray::cast(new_descriptors);
1316 Map::cast(new_map)->set_instance_descriptors(descriptors);
1317 Map* old_map = map();
1318 set_map(Map::cast(new_map));
1319
1320 // If the old map is the global object map (from new Object()),
1321 // then transitions are not added to it, so we are done.
1322 if (old_map == Top::context()->global_context()->object_function()->map()) {
1323 return function;
1324 }
1325
1326 // Do not add CONSTANT_TRANSITIONS to global objects
1327 if (IsGlobalObject()) {
1328 return function;
1329 }
1330
1331 // Add a CONSTANT_TRANSITION descriptor to the old map,
1332 // so future assignments to this property on other objects
1333 // of the same type will create a normal field, not a constant function.
1334 // Don't do this for special properties, with non-trival attributes.
1335 if (attributes != NONE) {
1336 return function;
1337 }
Iain Merrick75681382010-08-19 15:07:18 +01001338 ConstTransitionDescriptor mark(name, Map::cast(new_map));
John Reck59135872010-11-02 12:39:01 -07001339 { MaybeObject* maybe_new_descriptors =
1340 old_map->instance_descriptors()->CopyInsert(&mark, KEEP_TRANSITIONS);
1341 if (!maybe_new_descriptors->ToObject(&new_descriptors)) {
1342 // We have accomplished the main goal, so return success.
1343 return function;
1344 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001345 }
1346 old_map->set_instance_descriptors(DescriptorArray::cast(new_descriptors));
1347
1348 return function;
1349}
1350
1351
1352// Add property in slow mode
John Reck59135872010-11-02 12:39:01 -07001353MaybeObject* JSObject::AddSlowProperty(String* name,
1354 Object* value,
1355 PropertyAttributes attributes) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001356 ASSERT(!HasFastProperties());
1357 StringDictionary* dict = property_dictionary();
1358 Object* store_value = value;
1359 if (IsGlobalObject()) {
1360 // In case name is an orphaned property reuse the cell.
1361 int entry = dict->FindEntry(name);
1362 if (entry != StringDictionary::kNotFound) {
1363 store_value = dict->ValueAt(entry);
1364 JSGlobalPropertyCell::cast(store_value)->set_value(value);
1365 // Assign an enumeration index to the property and update
1366 // SetNextEnumerationIndex.
1367 int index = dict->NextEnumerationIndex();
1368 PropertyDetails details = PropertyDetails(attributes, NORMAL, index);
1369 dict->SetNextEnumerationIndex(index + 1);
1370 dict->SetEntry(entry, name, store_value, details);
1371 return value;
1372 }
John Reck59135872010-11-02 12:39:01 -07001373 { MaybeObject* maybe_store_value =
1374 Heap::AllocateJSGlobalPropertyCell(value);
1375 if (!maybe_store_value->ToObject(&store_value)) return maybe_store_value;
1376 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001377 JSGlobalPropertyCell::cast(store_value)->set_value(value);
1378 }
1379 PropertyDetails details = PropertyDetails(attributes, NORMAL);
John Reck59135872010-11-02 12:39:01 -07001380 Object* result;
1381 { MaybeObject* maybe_result = dict->Add(name, store_value, details);
1382 if (!maybe_result->ToObject(&result)) return maybe_result;
1383 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001384 if (dict != result) set_properties(StringDictionary::cast(result));
1385 return value;
1386}
1387
1388
John Reck59135872010-11-02 12:39:01 -07001389MaybeObject* JSObject::AddProperty(String* name,
1390 Object* value,
1391 PropertyAttributes attributes) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001392 ASSERT(!IsJSGlobalProxy());
Steve Block8defd9f2010-07-08 12:39:36 +01001393 if (!map()->is_extensible()) {
1394 Handle<Object> args[1] = {Handle<String>(name)};
1395 return Top::Throw(*Factory::NewTypeError("object_not_extensible",
1396 HandleVector(args, 1)));
1397 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001398 if (HasFastProperties()) {
1399 // Ensure the descriptor array does not get too big.
1400 if (map()->instance_descriptors()->number_of_descriptors() <
1401 DescriptorArray::kMaxNumberOfDescriptors) {
Leon Clarkee46be812010-01-19 14:06:41 +00001402 if (value->IsJSFunction() && !Heap::InNewSpace(value)) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001403 return AddConstantFunctionProperty(name,
1404 JSFunction::cast(value),
1405 attributes);
1406 } else {
1407 return AddFastProperty(name, value, attributes);
1408 }
1409 } else {
1410 // Normalize the object to prevent very large instance descriptors.
1411 // This eliminates unwanted N^2 allocation and lookup behavior.
John Reck59135872010-11-02 12:39:01 -07001412 Object* obj;
1413 { MaybeObject* maybe_obj =
1414 NormalizeProperties(CLEAR_INOBJECT_PROPERTIES, 0);
1415 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
1416 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001417 }
1418 }
1419 return AddSlowProperty(name, value, attributes);
1420}
1421
1422
John Reck59135872010-11-02 12:39:01 -07001423MaybeObject* JSObject::SetPropertyPostInterceptor(
1424 String* name,
1425 Object* value,
1426 PropertyAttributes attributes) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001427 // Check local property, ignore interceptor.
1428 LookupResult result;
1429 LocalLookupRealNamedProperty(name, &result);
Andrei Popescu402d9372010-02-26 13:31:12 +00001430 if (result.IsFound()) {
1431 // An existing property, a map transition or a null descriptor was
1432 // found. Use set property to handle all these cases.
1433 return SetProperty(&result, name, value, attributes);
1434 }
1435 // Add a new real property.
Steve Blocka7e24c12009-10-30 11:49:00 +00001436 return AddProperty(name, value, attributes);
1437}
1438
1439
John Reck59135872010-11-02 12:39:01 -07001440MaybeObject* JSObject::ReplaceSlowProperty(String* name,
1441 Object* value,
1442 PropertyAttributes attributes) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001443 StringDictionary* dictionary = property_dictionary();
1444 int old_index = dictionary->FindEntry(name);
1445 int new_enumeration_index = 0; // 0 means "Use the next available index."
1446 if (old_index != -1) {
1447 // All calls to ReplaceSlowProperty have had all transitions removed.
1448 ASSERT(!dictionary->DetailsAt(old_index).IsTransition());
1449 new_enumeration_index = dictionary->DetailsAt(old_index).index();
1450 }
1451
1452 PropertyDetails new_details(attributes, NORMAL, new_enumeration_index);
1453 return SetNormalizedProperty(name, value, new_details);
1454}
1455
Steve Blockd0582a62009-12-15 09:54:21 +00001456
John Reck59135872010-11-02 12:39:01 -07001457MaybeObject* JSObject::ConvertDescriptorToFieldAndMapTransition(
Steve Blocka7e24c12009-10-30 11:49:00 +00001458 String* name,
1459 Object* new_value,
1460 PropertyAttributes attributes) {
1461 Map* old_map = map();
John Reck59135872010-11-02 12:39:01 -07001462 Object* result;
1463 { MaybeObject* maybe_result =
1464 ConvertDescriptorToField(name, new_value, attributes);
1465 if (!maybe_result->ToObject(&result)) return maybe_result;
1466 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001467 // If we get to this point we have succeeded - do not return failure
1468 // after this point. Later stuff is optional.
1469 if (!HasFastProperties()) {
1470 return result;
1471 }
1472 // Do not add transitions to the map of "new Object()".
1473 if (map() == Top::context()->global_context()->object_function()->map()) {
1474 return result;
1475 }
1476
1477 MapTransitionDescriptor transition(name,
1478 map(),
1479 attributes);
John Reck59135872010-11-02 12:39:01 -07001480 Object* new_descriptors;
1481 { MaybeObject* maybe_new_descriptors = old_map->instance_descriptors()->
1482 CopyInsert(&transition, KEEP_TRANSITIONS);
1483 if (!maybe_new_descriptors->ToObject(&new_descriptors)) {
1484 return result; // Yes, return _result_.
1485 }
1486 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001487 old_map->set_instance_descriptors(DescriptorArray::cast(new_descriptors));
1488 return result;
1489}
1490
1491
John Reck59135872010-11-02 12:39:01 -07001492MaybeObject* JSObject::ConvertDescriptorToField(String* name,
1493 Object* new_value,
1494 PropertyAttributes attributes) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001495 if (map()->unused_property_fields() == 0 &&
Steve Block8defd9f2010-07-08 12:39:36 +01001496 properties()->length() > MaxFastProperties()) {
John Reck59135872010-11-02 12:39:01 -07001497 Object* obj;
1498 { MaybeObject* maybe_obj =
1499 NormalizeProperties(CLEAR_INOBJECT_PROPERTIES, 0);
1500 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
1501 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001502 return ReplaceSlowProperty(name, new_value, attributes);
1503 }
1504
1505 int index = map()->NextFreePropertyIndex();
1506 FieldDescriptor new_field(name, index, attributes);
1507 // Make a new DescriptorArray replacing an entry with FieldDescriptor.
John Reck59135872010-11-02 12:39:01 -07001508 Object* descriptors_unchecked;
1509 { MaybeObject* maybe_descriptors_unchecked = map()->instance_descriptors()->
1510 CopyInsert(&new_field, REMOVE_TRANSITIONS);
1511 if (!maybe_descriptors_unchecked->ToObject(&descriptors_unchecked)) {
1512 return maybe_descriptors_unchecked;
1513 }
1514 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001515 DescriptorArray* new_descriptors =
1516 DescriptorArray::cast(descriptors_unchecked);
1517
1518 // Make a new map for the object.
John Reck59135872010-11-02 12:39:01 -07001519 Object* new_map_unchecked;
1520 { MaybeObject* maybe_new_map_unchecked = map()->CopyDropDescriptors();
1521 if (!maybe_new_map_unchecked->ToObject(&new_map_unchecked)) {
1522 return maybe_new_map_unchecked;
1523 }
1524 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001525 Map* new_map = Map::cast(new_map_unchecked);
1526 new_map->set_instance_descriptors(new_descriptors);
1527
1528 // Make new properties array if necessary.
1529 FixedArray* new_properties = 0; // Will always be NULL or a valid pointer.
1530 int new_unused_property_fields = map()->unused_property_fields() - 1;
1531 if (map()->unused_property_fields() == 0) {
Kristian Monsen0d5e1162010-09-30 15:31:59 +01001532 new_unused_property_fields = kFieldsAdded - 1;
John Reck59135872010-11-02 12:39:01 -07001533 Object* new_properties_object;
1534 { MaybeObject* maybe_new_properties_object =
1535 properties()->CopySize(properties()->length() + kFieldsAdded);
1536 if (!maybe_new_properties_object->ToObject(&new_properties_object)) {
1537 return maybe_new_properties_object;
1538 }
1539 }
1540 new_properties = FixedArray::cast(new_properties_object);
Steve Blocka7e24c12009-10-30 11:49:00 +00001541 }
1542
1543 // Update pointers to commit changes.
1544 // Object points to the new map.
1545 new_map->set_unused_property_fields(new_unused_property_fields);
1546 set_map(new_map);
1547 if (new_properties) {
1548 set_properties(FixedArray::cast(new_properties));
1549 }
1550 return FastPropertyAtPut(index, new_value);
1551}
1552
1553
1554
John Reck59135872010-11-02 12:39:01 -07001555MaybeObject* JSObject::SetPropertyWithInterceptor(
1556 String* name,
1557 Object* value,
1558 PropertyAttributes attributes) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001559 HandleScope scope;
1560 Handle<JSObject> this_handle(this);
1561 Handle<String> name_handle(name);
1562 Handle<Object> value_handle(value);
1563 Handle<InterceptorInfo> interceptor(GetNamedInterceptor());
1564 if (!interceptor->setter()->IsUndefined()) {
1565 LOG(ApiNamedPropertyAccess("interceptor-named-set", this, name));
1566 CustomArguments args(interceptor->data(), this, this);
1567 v8::AccessorInfo info(args.end());
1568 v8::NamedPropertySetter setter =
1569 v8::ToCData<v8::NamedPropertySetter>(interceptor->setter());
1570 v8::Handle<v8::Value> result;
1571 {
1572 // Leaving JavaScript.
1573 VMState state(EXTERNAL);
1574 Handle<Object> value_unhole(value->IsTheHole() ?
1575 Heap::undefined_value() :
1576 value);
1577 result = setter(v8::Utils::ToLocal(name_handle),
1578 v8::Utils::ToLocal(value_unhole),
1579 info);
1580 }
1581 RETURN_IF_SCHEDULED_EXCEPTION();
1582 if (!result.IsEmpty()) return *value_handle;
1583 }
John Reck59135872010-11-02 12:39:01 -07001584 MaybeObject* raw_result =
1585 this_handle->SetPropertyPostInterceptor(*name_handle,
1586 *value_handle,
1587 attributes);
Steve Blocka7e24c12009-10-30 11:49:00 +00001588 RETURN_IF_SCHEDULED_EXCEPTION();
1589 return raw_result;
1590}
1591
1592
John Reck59135872010-11-02 12:39:01 -07001593MaybeObject* JSObject::SetProperty(String* name,
1594 Object* value,
1595 PropertyAttributes attributes) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001596 LookupResult result;
1597 LocalLookup(name, &result);
1598 return SetProperty(&result, name, value, attributes);
1599}
1600
1601
John Reck59135872010-11-02 12:39:01 -07001602MaybeObject* JSObject::SetPropertyWithCallback(Object* structure,
1603 String* name,
1604 Object* value,
1605 JSObject* holder) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001606 HandleScope scope;
1607
1608 // We should never get here to initialize a const with the hole
1609 // value since a const declaration would conflict with the setter.
1610 ASSERT(!value->IsTheHole());
1611 Handle<Object> value_handle(value);
1612
1613 // To accommodate both the old and the new api we switch on the
1614 // data structure used to store the callbacks. Eventually proxy
1615 // callbacks should be phased out.
1616 if (structure->IsProxy()) {
1617 AccessorDescriptor* callback =
1618 reinterpret_cast<AccessorDescriptor*>(Proxy::cast(structure)->proxy());
John Reck59135872010-11-02 12:39:01 -07001619 MaybeObject* obj = (callback->setter)(this, value, callback->data);
Steve Blocka7e24c12009-10-30 11:49:00 +00001620 RETURN_IF_SCHEDULED_EXCEPTION();
1621 if (obj->IsFailure()) return obj;
1622 return *value_handle;
1623 }
1624
1625 if (structure->IsAccessorInfo()) {
1626 // api style callbacks
1627 AccessorInfo* data = AccessorInfo::cast(structure);
1628 Object* call_obj = data->setter();
1629 v8::AccessorSetter call_fun = v8::ToCData<v8::AccessorSetter>(call_obj);
1630 if (call_fun == NULL) return value;
1631 Handle<String> key(name);
1632 LOG(ApiNamedPropertyAccess("store", this, name));
1633 CustomArguments args(data->data(), this, JSObject::cast(holder));
1634 v8::AccessorInfo info(args.end());
1635 {
1636 // Leaving JavaScript.
1637 VMState state(EXTERNAL);
1638 call_fun(v8::Utils::ToLocal(key),
1639 v8::Utils::ToLocal(value_handle),
1640 info);
1641 }
1642 RETURN_IF_SCHEDULED_EXCEPTION();
1643 return *value_handle;
1644 }
1645
1646 if (structure->IsFixedArray()) {
1647 Object* setter = FixedArray::cast(structure)->get(kSetterIndex);
1648 if (setter->IsJSFunction()) {
1649 return SetPropertyWithDefinedSetter(JSFunction::cast(setter), value);
1650 } else {
1651 Handle<String> key(name);
1652 Handle<Object> holder_handle(holder);
1653 Handle<Object> args[2] = { key, holder_handle };
1654 return Top::Throw(*Factory::NewTypeError("no_setter_in_callback",
1655 HandleVector(args, 2)));
1656 }
1657 }
1658
1659 UNREACHABLE();
Leon Clarkef7060e22010-06-03 12:02:55 +01001660 return NULL;
Steve Blocka7e24c12009-10-30 11:49:00 +00001661}
1662
1663
John Reck59135872010-11-02 12:39:01 -07001664MaybeObject* JSObject::SetPropertyWithDefinedSetter(JSFunction* setter,
1665 Object* value) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001666 Handle<Object> value_handle(value);
1667 Handle<JSFunction> fun(JSFunction::cast(setter));
1668 Handle<JSObject> self(this);
1669#ifdef ENABLE_DEBUGGER_SUPPORT
1670 // Handle stepping into a setter if step into is active.
1671 if (Debug::StepInActive()) {
1672 Debug::HandleStepIn(fun, Handle<Object>::null(), 0, false);
1673 }
1674#endif
1675 bool has_pending_exception;
1676 Object** argv[] = { value_handle.location() };
1677 Execution::Call(fun, self, 1, argv, &has_pending_exception);
1678 // Check for pending exception and return the result.
1679 if (has_pending_exception) return Failure::Exception();
1680 return *value_handle;
1681}
1682
1683
1684void JSObject::LookupCallbackSetterInPrototypes(String* name,
1685 LookupResult* result) {
1686 for (Object* pt = GetPrototype();
1687 pt != Heap::null_value();
1688 pt = pt->GetPrototype()) {
1689 JSObject::cast(pt)->LocalLookupRealNamedProperty(name, result);
Andrei Popescu402d9372010-02-26 13:31:12 +00001690 if (result->IsProperty()) {
1691 if (result->IsReadOnly()) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001692 result->NotFound();
1693 return;
1694 }
1695 if (result->type() == CALLBACKS) {
1696 return;
1697 }
1698 }
1699 }
1700 result->NotFound();
1701}
1702
1703
Leon Clarkef7060e22010-06-03 12:02:55 +01001704bool JSObject::SetElementWithCallbackSetterInPrototypes(uint32_t index,
1705 Object* value) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001706 for (Object* pt = GetPrototype();
1707 pt != Heap::null_value();
1708 pt = pt->GetPrototype()) {
1709 if (!JSObject::cast(pt)->HasDictionaryElements()) {
1710 continue;
1711 }
1712 NumberDictionary* dictionary = JSObject::cast(pt)->element_dictionary();
1713 int entry = dictionary->FindEntry(index);
1714 if (entry != NumberDictionary::kNotFound) {
1715 Object* element = dictionary->ValueAt(entry);
1716 PropertyDetails details = dictionary->DetailsAt(entry);
1717 if (details.type() == CALLBACKS) {
Leon Clarkef7060e22010-06-03 12:02:55 +01001718 SetElementWithCallback(element, index, value, JSObject::cast(pt));
1719 return true;
Steve Blocka7e24c12009-10-30 11:49:00 +00001720 }
1721 }
1722 }
Leon Clarkef7060e22010-06-03 12:02:55 +01001723 return false;
Steve Blocka7e24c12009-10-30 11:49:00 +00001724}
1725
1726
1727void JSObject::LookupInDescriptor(String* name, LookupResult* result) {
1728 DescriptorArray* descriptors = map()->instance_descriptors();
Iain Merrick75681382010-08-19 15:07:18 +01001729 int number = descriptors->SearchWithCache(name);
Steve Blocka7e24c12009-10-30 11:49:00 +00001730 if (number != DescriptorArray::kNotFound) {
1731 result->DescriptorResult(this, descriptors->GetDetails(number), number);
1732 } else {
1733 result->NotFound();
1734 }
1735}
1736
1737
Ben Murdochb0fe1622011-05-05 13:52:32 +01001738void Map::LookupInDescriptors(JSObject* holder,
1739 String* name,
1740 LookupResult* result) {
1741 DescriptorArray* descriptors = instance_descriptors();
1742 int number = DescriptorLookupCache::Lookup(descriptors, name);
1743 if (number == DescriptorLookupCache::kAbsent) {
1744 number = descriptors->Search(name);
1745 DescriptorLookupCache::Update(descriptors, name, number);
1746 }
1747 if (number != DescriptorArray::kNotFound) {
1748 result->DescriptorResult(holder, descriptors->GetDetails(number), number);
1749 } else {
1750 result->NotFound();
1751 }
1752}
1753
1754
Steve Blocka7e24c12009-10-30 11:49:00 +00001755void JSObject::LocalLookupRealNamedProperty(String* name,
1756 LookupResult* result) {
1757 if (IsJSGlobalProxy()) {
1758 Object* proto = GetPrototype();
1759 if (proto->IsNull()) return result->NotFound();
1760 ASSERT(proto->IsJSGlobalObject());
1761 return JSObject::cast(proto)->LocalLookupRealNamedProperty(name, result);
1762 }
1763
1764 if (HasFastProperties()) {
1765 LookupInDescriptor(name, result);
Andrei Popescu402d9372010-02-26 13:31:12 +00001766 if (result->IsFound()) {
1767 // A property, a map transition or a null descriptor was found.
1768 // We return all of these result types because
1769 // LocalLookupRealNamedProperty is used when setting properties
1770 // where map transitions and null descriptors are handled.
Steve Blocka7e24c12009-10-30 11:49:00 +00001771 ASSERT(result->holder() == this && result->type() != NORMAL);
1772 // Disallow caching for uninitialized constants. These can only
1773 // occur as fields.
1774 if (result->IsReadOnly() && result->type() == FIELD &&
1775 FastPropertyAt(result->GetFieldIndex())->IsTheHole()) {
1776 result->DisallowCaching();
1777 }
1778 return;
1779 }
1780 } else {
1781 int entry = property_dictionary()->FindEntry(name);
1782 if (entry != StringDictionary::kNotFound) {
1783 Object* value = property_dictionary()->ValueAt(entry);
1784 if (IsGlobalObject()) {
1785 PropertyDetails d = property_dictionary()->DetailsAt(entry);
1786 if (d.IsDeleted()) {
1787 result->NotFound();
1788 return;
1789 }
1790 value = JSGlobalPropertyCell::cast(value)->value();
Steve Blocka7e24c12009-10-30 11:49:00 +00001791 }
1792 // Make sure to disallow caching for uninitialized constants
1793 // found in the dictionary-mode objects.
1794 if (value->IsTheHole()) result->DisallowCaching();
1795 result->DictionaryResult(this, entry);
1796 return;
1797 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001798 }
1799 result->NotFound();
1800}
1801
1802
1803void JSObject::LookupRealNamedProperty(String* name, LookupResult* result) {
1804 LocalLookupRealNamedProperty(name, result);
1805 if (result->IsProperty()) return;
1806
1807 LookupRealNamedPropertyInPrototypes(name, result);
1808}
1809
1810
1811void JSObject::LookupRealNamedPropertyInPrototypes(String* name,
1812 LookupResult* result) {
1813 for (Object* pt = GetPrototype();
1814 pt != Heap::null_value();
1815 pt = JSObject::cast(pt)->GetPrototype()) {
1816 JSObject::cast(pt)->LocalLookupRealNamedProperty(name, result);
Andrei Popescu402d9372010-02-26 13:31:12 +00001817 if (result->IsProperty() && (result->type() != INTERCEPTOR)) return;
Steve Blocka7e24c12009-10-30 11:49:00 +00001818 }
1819 result->NotFound();
1820}
1821
1822
1823// We only need to deal with CALLBACKS and INTERCEPTORS
John Reck59135872010-11-02 12:39:01 -07001824MaybeObject* JSObject::SetPropertyWithFailedAccessCheck(LookupResult* result,
1825 String* name,
1826 Object* value) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001827 if (!result->IsProperty()) {
1828 LookupCallbackSetterInPrototypes(name, result);
1829 }
1830
1831 if (result->IsProperty()) {
1832 if (!result->IsReadOnly()) {
1833 switch (result->type()) {
1834 case CALLBACKS: {
1835 Object* obj = result->GetCallbackObject();
1836 if (obj->IsAccessorInfo()) {
1837 AccessorInfo* info = AccessorInfo::cast(obj);
1838 if (info->all_can_write()) {
1839 return SetPropertyWithCallback(result->GetCallbackObject(),
1840 name,
1841 value,
1842 result->holder());
1843 }
1844 }
1845 break;
1846 }
1847 case INTERCEPTOR: {
1848 // Try lookup real named properties. Note that only property can be
1849 // set is callbacks marked as ALL_CAN_WRITE on the prototype chain.
1850 LookupResult r;
1851 LookupRealNamedProperty(name, &r);
1852 if (r.IsProperty()) {
1853 return SetPropertyWithFailedAccessCheck(&r, name, value);
1854 }
1855 break;
1856 }
1857 default: {
1858 break;
1859 }
1860 }
1861 }
1862 }
1863
Iain Merrick75681382010-08-19 15:07:18 +01001864 HandleScope scope;
1865 Handle<Object> value_handle(value);
Steve Blocka7e24c12009-10-30 11:49:00 +00001866 Top::ReportFailedAccessCheck(this, v8::ACCESS_SET);
Iain Merrick75681382010-08-19 15:07:18 +01001867 return *value_handle;
Steve Blocka7e24c12009-10-30 11:49:00 +00001868}
1869
1870
John Reck59135872010-11-02 12:39:01 -07001871MaybeObject* JSObject::SetProperty(LookupResult* result,
1872 String* name,
1873 Object* value,
1874 PropertyAttributes attributes) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001875 // Make sure that the top context does not change when doing callbacks or
1876 // interceptor calls.
1877 AssertNoContextChange ncc;
1878
Steve Blockd0582a62009-12-15 09:54:21 +00001879 // Optimization for 2-byte strings often used as keys in a decompression
1880 // dictionary. We make these short keys into symbols to avoid constantly
1881 // reallocating them.
1882 if (!name->IsSymbol() && name->length() <= 2) {
John Reck59135872010-11-02 12:39:01 -07001883 Object* symbol_version;
1884 { MaybeObject* maybe_symbol_version = Heap::LookupSymbol(name);
1885 if (maybe_symbol_version->ToObject(&symbol_version)) {
1886 name = String::cast(symbol_version);
1887 }
1888 }
Steve Blockd0582a62009-12-15 09:54:21 +00001889 }
1890
Steve Blocka7e24c12009-10-30 11:49:00 +00001891 // Check access rights if needed.
1892 if (IsAccessCheckNeeded()
1893 && !Top::MayNamedAccess(this, name, v8::ACCESS_SET)) {
1894 return SetPropertyWithFailedAccessCheck(result, name, value);
1895 }
1896
1897 if (IsJSGlobalProxy()) {
1898 Object* proto = GetPrototype();
1899 if (proto->IsNull()) return value;
1900 ASSERT(proto->IsJSGlobalObject());
1901 return JSObject::cast(proto)->SetProperty(result, name, value, attributes);
1902 }
1903
1904 if (!result->IsProperty() && !IsJSContextExtensionObject()) {
1905 // We could not find a local property so let's check whether there is an
1906 // accessor that wants to handle the property.
1907 LookupResult accessor_result;
1908 LookupCallbackSetterInPrototypes(name, &accessor_result);
Andrei Popescu402d9372010-02-26 13:31:12 +00001909 if (accessor_result.IsProperty()) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001910 return SetPropertyWithCallback(accessor_result.GetCallbackObject(),
1911 name,
1912 value,
1913 accessor_result.holder());
1914 }
1915 }
Andrei Popescu402d9372010-02-26 13:31:12 +00001916 if (!result->IsFound()) {
1917 // Neither properties nor transitions found.
Steve Blocka7e24c12009-10-30 11:49:00 +00001918 return AddProperty(name, value, attributes);
1919 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001920 if (result->IsReadOnly() && result->IsProperty()) return value;
1921 // This is a real property that is not read-only, or it is a
1922 // transition or null descriptor and there are no setters in the prototypes.
1923 switch (result->type()) {
1924 case NORMAL:
1925 return SetNormalizedProperty(result, value);
1926 case FIELD:
1927 return FastPropertyAtPut(result->GetFieldIndex(), value);
1928 case MAP_TRANSITION:
1929 if (attributes == result->GetAttributes()) {
1930 // Only use map transition if the attributes match.
1931 return AddFastPropertyUsingMap(result->GetTransitionMap(),
1932 name,
1933 value);
1934 }
1935 return ConvertDescriptorToField(name, value, attributes);
1936 case CONSTANT_FUNCTION:
1937 // Only replace the function if necessary.
1938 if (value == result->GetConstantFunction()) return value;
1939 // Preserve the attributes of this existing property.
1940 attributes = result->GetAttributes();
1941 return ConvertDescriptorToField(name, value, attributes);
1942 case CALLBACKS:
1943 return SetPropertyWithCallback(result->GetCallbackObject(),
1944 name,
1945 value,
1946 result->holder());
1947 case INTERCEPTOR:
1948 return SetPropertyWithInterceptor(name, value, attributes);
Iain Merrick75681382010-08-19 15:07:18 +01001949 case CONSTANT_TRANSITION: {
1950 // If the same constant function is being added we can simply
1951 // transition to the target map.
1952 Map* target_map = result->GetTransitionMap();
1953 DescriptorArray* target_descriptors = target_map->instance_descriptors();
1954 int number = target_descriptors->SearchWithCache(name);
1955 ASSERT(number != DescriptorArray::kNotFound);
1956 ASSERT(target_descriptors->GetType(number) == CONSTANT_FUNCTION);
1957 JSFunction* function =
1958 JSFunction::cast(target_descriptors->GetValue(number));
1959 ASSERT(!Heap::InNewSpace(function));
1960 if (value == function) {
1961 set_map(target_map);
1962 return value;
1963 }
1964 // Otherwise, replace with a MAP_TRANSITION to a new map with a
1965 // FIELD, even if the value is a constant function.
Steve Blocka7e24c12009-10-30 11:49:00 +00001966 return ConvertDescriptorToFieldAndMapTransition(name, value, attributes);
Iain Merrick75681382010-08-19 15:07:18 +01001967 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001968 case NULL_DESCRIPTOR:
1969 return ConvertDescriptorToFieldAndMapTransition(name, value, attributes);
1970 default:
1971 UNREACHABLE();
1972 }
1973 UNREACHABLE();
1974 return value;
1975}
1976
1977
1978// Set a real local property, even if it is READ_ONLY. If the property is not
1979// present, add it with attributes NONE. This code is an exact clone of
1980// SetProperty, with the check for IsReadOnly and the check for a
1981// callback setter removed. The two lines looking up the LookupResult
1982// result are also added. If one of the functions is changed, the other
1983// should be.
John Reck59135872010-11-02 12:39:01 -07001984MaybeObject* JSObject::IgnoreAttributesAndSetLocalProperty(
Steve Blocka7e24c12009-10-30 11:49:00 +00001985 String* name,
1986 Object* value,
1987 PropertyAttributes attributes) {
1988 // Make sure that the top context does not change when doing callbacks or
1989 // interceptor calls.
1990 AssertNoContextChange ncc;
Andrei Popescu402d9372010-02-26 13:31:12 +00001991 LookupResult result;
1992 LocalLookup(name, &result);
Steve Blocka7e24c12009-10-30 11:49:00 +00001993 // Check access rights if needed.
1994 if (IsAccessCheckNeeded()
Andrei Popescu402d9372010-02-26 13:31:12 +00001995 && !Top::MayNamedAccess(this, name, v8::ACCESS_SET)) {
1996 return SetPropertyWithFailedAccessCheck(&result, name, value);
Steve Blocka7e24c12009-10-30 11:49:00 +00001997 }
1998
1999 if (IsJSGlobalProxy()) {
2000 Object* proto = GetPrototype();
2001 if (proto->IsNull()) return value;
2002 ASSERT(proto->IsJSGlobalObject());
2003 return JSObject::cast(proto)->IgnoreAttributesAndSetLocalProperty(
2004 name,
2005 value,
2006 attributes);
2007 }
2008
2009 // Check for accessor in prototype chain removed here in clone.
Andrei Popescu402d9372010-02-26 13:31:12 +00002010 if (!result.IsFound()) {
2011 // Neither properties nor transitions found.
Steve Blocka7e24c12009-10-30 11:49:00 +00002012 return AddProperty(name, value, attributes);
2013 }
Steve Block6ded16b2010-05-10 14:33:55 +01002014
Andrei Popescu402d9372010-02-26 13:31:12 +00002015 PropertyDetails details = PropertyDetails(attributes, NORMAL);
2016
Steve Blocka7e24c12009-10-30 11:49:00 +00002017 // Check of IsReadOnly removed from here in clone.
Andrei Popescu402d9372010-02-26 13:31:12 +00002018 switch (result.type()) {
Steve Blocka7e24c12009-10-30 11:49:00 +00002019 case NORMAL:
Andrei Popescu402d9372010-02-26 13:31:12 +00002020 return SetNormalizedProperty(name, value, details);
Steve Blocka7e24c12009-10-30 11:49:00 +00002021 case FIELD:
Andrei Popescu402d9372010-02-26 13:31:12 +00002022 return FastPropertyAtPut(result.GetFieldIndex(), value);
Steve Blocka7e24c12009-10-30 11:49:00 +00002023 case MAP_TRANSITION:
Andrei Popescu402d9372010-02-26 13:31:12 +00002024 if (attributes == result.GetAttributes()) {
Steve Blocka7e24c12009-10-30 11:49:00 +00002025 // Only use map transition if the attributes match.
Andrei Popescu402d9372010-02-26 13:31:12 +00002026 return AddFastPropertyUsingMap(result.GetTransitionMap(),
Steve Blocka7e24c12009-10-30 11:49:00 +00002027 name,
2028 value);
2029 }
2030 return ConvertDescriptorToField(name, value, attributes);
2031 case CONSTANT_FUNCTION:
2032 // Only replace the function if necessary.
Andrei Popescu402d9372010-02-26 13:31:12 +00002033 if (value == result.GetConstantFunction()) return value;
Steve Blocka7e24c12009-10-30 11:49:00 +00002034 // Preserve the attributes of this existing property.
Andrei Popescu402d9372010-02-26 13:31:12 +00002035 attributes = result.GetAttributes();
Steve Blocka7e24c12009-10-30 11:49:00 +00002036 return ConvertDescriptorToField(name, value, attributes);
2037 case CALLBACKS:
2038 case INTERCEPTOR:
2039 // Override callback in clone
2040 return ConvertDescriptorToField(name, value, attributes);
2041 case CONSTANT_TRANSITION:
2042 // Replace with a MAP_TRANSITION to a new map with a FIELD, even
2043 // if the value is a function.
2044 return ConvertDescriptorToFieldAndMapTransition(name, value, attributes);
2045 case NULL_DESCRIPTOR:
2046 return ConvertDescriptorToFieldAndMapTransition(name, value, attributes);
2047 default:
2048 UNREACHABLE();
2049 }
2050 UNREACHABLE();
2051 return value;
2052}
2053
2054
2055PropertyAttributes JSObject::GetPropertyAttributePostInterceptor(
2056 JSObject* receiver,
2057 String* name,
2058 bool continue_search) {
2059 // Check local property, ignore interceptor.
2060 LookupResult result;
2061 LocalLookupRealNamedProperty(name, &result);
2062 if (result.IsProperty()) return result.GetAttributes();
2063
2064 if (continue_search) {
2065 // Continue searching via the prototype chain.
2066 Object* pt = GetPrototype();
2067 if (pt != Heap::null_value()) {
2068 return JSObject::cast(pt)->
2069 GetPropertyAttributeWithReceiver(receiver, name);
2070 }
2071 }
2072 return ABSENT;
2073}
2074
2075
2076PropertyAttributes JSObject::GetPropertyAttributeWithInterceptor(
2077 JSObject* receiver,
2078 String* name,
2079 bool continue_search) {
2080 // Make sure that the top context does not change when doing
2081 // callbacks or interceptor calls.
2082 AssertNoContextChange ncc;
2083
2084 HandleScope scope;
2085 Handle<InterceptorInfo> interceptor(GetNamedInterceptor());
2086 Handle<JSObject> receiver_handle(receiver);
2087 Handle<JSObject> holder_handle(this);
2088 Handle<String> name_handle(name);
2089 CustomArguments args(interceptor->data(), receiver, this);
2090 v8::AccessorInfo info(args.end());
2091 if (!interceptor->query()->IsUndefined()) {
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01002092 v8::NamedPropertyQuery query =
2093 v8::ToCData<v8::NamedPropertyQuery>(interceptor->query());
Steve Blocka7e24c12009-10-30 11:49:00 +00002094 LOG(ApiNamedPropertyAccess("interceptor-named-has", *holder_handle, name));
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01002095 v8::Handle<v8::Integer> result;
Steve Blocka7e24c12009-10-30 11:49:00 +00002096 {
2097 // Leaving JavaScript.
2098 VMState state(EXTERNAL);
2099 result = query(v8::Utils::ToLocal(name_handle), info);
2100 }
2101 if (!result.IsEmpty()) {
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01002102 ASSERT(result->IsInt32());
2103 return static_cast<PropertyAttributes>(result->Int32Value());
Steve Blocka7e24c12009-10-30 11:49:00 +00002104 }
2105 } else if (!interceptor->getter()->IsUndefined()) {
2106 v8::NamedPropertyGetter getter =
2107 v8::ToCData<v8::NamedPropertyGetter>(interceptor->getter());
2108 LOG(ApiNamedPropertyAccess("interceptor-named-get-has", this, name));
2109 v8::Handle<v8::Value> result;
2110 {
2111 // Leaving JavaScript.
2112 VMState state(EXTERNAL);
2113 result = getter(v8::Utils::ToLocal(name_handle), info);
2114 }
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01002115 if (!result.IsEmpty()) return DONT_ENUM;
Steve Blocka7e24c12009-10-30 11:49:00 +00002116 }
2117 return holder_handle->GetPropertyAttributePostInterceptor(*receiver_handle,
2118 *name_handle,
2119 continue_search);
2120}
2121
2122
2123PropertyAttributes JSObject::GetPropertyAttributeWithReceiver(
2124 JSObject* receiver,
2125 String* key) {
2126 uint32_t index = 0;
2127 if (key->AsArrayIndex(&index)) {
2128 if (HasElementWithReceiver(receiver, index)) return NONE;
2129 return ABSENT;
2130 }
2131 // Named property.
2132 LookupResult result;
2133 Lookup(key, &result);
2134 return GetPropertyAttribute(receiver, &result, key, true);
2135}
2136
2137
2138PropertyAttributes JSObject::GetPropertyAttribute(JSObject* receiver,
2139 LookupResult* result,
2140 String* name,
2141 bool continue_search) {
2142 // Check access rights if needed.
2143 if (IsAccessCheckNeeded() &&
2144 !Top::MayNamedAccess(this, name, v8::ACCESS_HAS)) {
2145 return GetPropertyAttributeWithFailedAccessCheck(receiver,
2146 result,
2147 name,
2148 continue_search);
2149 }
Andrei Popescu402d9372010-02-26 13:31:12 +00002150 if (result->IsProperty()) {
Steve Blocka7e24c12009-10-30 11:49:00 +00002151 switch (result->type()) {
2152 case NORMAL: // fall through
2153 case FIELD:
2154 case CONSTANT_FUNCTION:
2155 case CALLBACKS:
2156 return result->GetAttributes();
2157 case INTERCEPTOR:
2158 return result->holder()->
2159 GetPropertyAttributeWithInterceptor(receiver, name, continue_search);
Steve Blocka7e24c12009-10-30 11:49:00 +00002160 default:
2161 UNREACHABLE();
Steve Blocka7e24c12009-10-30 11:49:00 +00002162 }
2163 }
2164 return ABSENT;
2165}
2166
2167
2168PropertyAttributes JSObject::GetLocalPropertyAttribute(String* name) {
2169 // Check whether the name is an array index.
2170 uint32_t index = 0;
2171 if (name->AsArrayIndex(&index)) {
2172 if (HasLocalElement(index)) return NONE;
2173 return ABSENT;
2174 }
2175 // Named property.
2176 LookupResult result;
2177 LocalLookup(name, &result);
2178 return GetPropertyAttribute(this, &result, name, false);
2179}
2180
2181
John Reck59135872010-11-02 12:39:01 -07002182MaybeObject* NormalizedMapCache::Get(JSObject* obj,
2183 PropertyNormalizationMode mode) {
Kristian Monsen80d68ea2010-09-08 11:05:35 +01002184 Map* fast = obj->map();
Kristian Monsen0d5e1162010-09-30 15:31:59 +01002185 int index = Hash(fast) % kEntries;
2186 Object* result = get(index);
2187 if (result->IsMap() && CheckHit(Map::cast(result), fast, mode)) {
Kristian Monsen80d68ea2010-09-08 11:05:35 +01002188#ifdef DEBUG
Kristian Monsen0d5e1162010-09-30 15:31:59 +01002189 if (FLAG_enable_slow_asserts) {
2190 // The cached map should match newly created normalized map bit-by-bit.
John Reck59135872010-11-02 12:39:01 -07002191 Object* fresh;
2192 { MaybeObject* maybe_fresh =
2193 fast->CopyNormalized(mode, SHARED_NORMALIZED_MAP);
2194 if (maybe_fresh->ToObject(&fresh)) {
2195 ASSERT(memcmp(Map::cast(fresh)->address(),
2196 Map::cast(result)->address(),
2197 Map::kSize) == 0);
2198 }
Kristian Monsen80d68ea2010-09-08 11:05:35 +01002199 }
Kristian Monsen80d68ea2010-09-08 11:05:35 +01002200 }
Kristian Monsen0d5e1162010-09-30 15:31:59 +01002201#endif
2202 return result;
Kristian Monsen80d68ea2010-09-08 11:05:35 +01002203 }
Kristian Monsen0d5e1162010-09-30 15:31:59 +01002204
John Reck59135872010-11-02 12:39:01 -07002205 { MaybeObject* maybe_result =
2206 fast->CopyNormalized(mode, SHARED_NORMALIZED_MAP);
2207 if (!maybe_result->ToObject(&result)) return maybe_result;
2208 }
Kristian Monsen0d5e1162010-09-30 15:31:59 +01002209 set(index, result);
Kristian Monsen80d68ea2010-09-08 11:05:35 +01002210 Counters::normalized_maps.Increment();
2211
2212 return result;
2213}
2214
2215
Kristian Monsen80d68ea2010-09-08 11:05:35 +01002216void NormalizedMapCache::Clear() {
2217 int entries = length();
2218 for (int i = 0; i != entries; i++) {
2219 set_undefined(i);
2220 }
2221}
2222
2223
2224int NormalizedMapCache::Hash(Map* fast) {
2225 // For performance reasons we only hash the 3 most variable fields of a map:
2226 // constructor, prototype and bit_field2.
2227
2228 // Shift away the tag.
2229 int hash = (static_cast<uint32_t>(
2230 reinterpret_cast<uintptr_t>(fast->constructor())) >> 2);
2231
2232 // XOR-ing the prototype and constructor directly yields too many zero bits
2233 // when the two pointers are close (which is fairly common).
2234 // To avoid this we shift the prototype 4 bits relatively to the constructor.
2235 hash ^= (static_cast<uint32_t>(
2236 reinterpret_cast<uintptr_t>(fast->prototype())) << 2);
2237
2238 return hash ^ (hash >> 16) ^ fast->bit_field2();
2239}
2240
2241
2242bool NormalizedMapCache::CheckHit(Map* slow,
2243 Map* fast,
2244 PropertyNormalizationMode mode) {
2245#ifdef DEBUG
Kristian Monsen0d5e1162010-09-30 15:31:59 +01002246 slow->SharedMapVerify();
Kristian Monsen80d68ea2010-09-08 11:05:35 +01002247#endif
2248 return
2249 slow->constructor() == fast->constructor() &&
2250 slow->prototype() == fast->prototype() &&
2251 slow->inobject_properties() == ((mode == CLEAR_INOBJECT_PROPERTIES) ?
2252 0 :
2253 fast->inobject_properties()) &&
2254 slow->instance_type() == fast->instance_type() &&
2255 slow->bit_field() == fast->bit_field() &&
Kristian Monsen0d5e1162010-09-30 15:31:59 +01002256 (slow->bit_field2() & ~(1<<Map::kIsShared)) == fast->bit_field2();
Kristian Monsen80d68ea2010-09-08 11:05:35 +01002257}
2258
2259
John Reck59135872010-11-02 12:39:01 -07002260MaybeObject* JSObject::UpdateMapCodeCache(String* name, Code* code) {
Kristian Monsen0d5e1162010-09-30 15:31:59 +01002261 if (map()->is_shared()) {
2262 // Fast case maps are never marked as shared.
2263 ASSERT(!HasFastProperties());
2264 // Replace the map with an identical copy that can be safely modified.
John Reck59135872010-11-02 12:39:01 -07002265 Object* obj;
2266 { MaybeObject* maybe_obj = map()->CopyNormalized(KEEP_INOBJECT_PROPERTIES,
2267 UNIQUE_NORMALIZED_MAP);
2268 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
2269 }
Kristian Monsen80d68ea2010-09-08 11:05:35 +01002270 Counters::normalized_maps.Increment();
2271
2272 set_map(Map::cast(obj));
2273 }
2274 return map()->UpdateCodeCache(name, code);
2275}
2276
2277
John Reck59135872010-11-02 12:39:01 -07002278MaybeObject* JSObject::NormalizeProperties(PropertyNormalizationMode mode,
2279 int expected_additional_properties) {
Steve Blocka7e24c12009-10-30 11:49:00 +00002280 if (!HasFastProperties()) return this;
2281
2282 // The global object is always normalized.
2283 ASSERT(!IsGlobalObject());
2284
2285 // Allocate new content.
2286 int property_count = map()->NumberOfDescribedProperties();
2287 if (expected_additional_properties > 0) {
2288 property_count += expected_additional_properties;
2289 } else {
2290 property_count += 2; // Make space for two more properties.
2291 }
John Reck59135872010-11-02 12:39:01 -07002292 Object* obj;
2293 { MaybeObject* maybe_obj =
2294 StringDictionary::Allocate(property_count);
2295 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
2296 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002297 StringDictionary* dictionary = StringDictionary::cast(obj);
2298
2299 DescriptorArray* descs = map()->instance_descriptors();
2300 for (int i = 0; i < descs->number_of_descriptors(); i++) {
2301 PropertyDetails details = descs->GetDetails(i);
2302 switch (details.type()) {
2303 case CONSTANT_FUNCTION: {
2304 PropertyDetails d =
2305 PropertyDetails(details.attributes(), NORMAL, details.index());
2306 Object* value = descs->GetConstantFunction(i);
John Reck59135872010-11-02 12:39:01 -07002307 Object* result;
2308 { MaybeObject* maybe_result =
2309 dictionary->Add(descs->GetKey(i), value, d);
2310 if (!maybe_result->ToObject(&result)) return maybe_result;
2311 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002312 dictionary = StringDictionary::cast(result);
2313 break;
2314 }
2315 case FIELD: {
2316 PropertyDetails d =
2317 PropertyDetails(details.attributes(), NORMAL, details.index());
2318 Object* value = FastPropertyAt(descs->GetFieldIndex(i));
John Reck59135872010-11-02 12:39:01 -07002319 Object* result;
2320 { MaybeObject* maybe_result =
2321 dictionary->Add(descs->GetKey(i), value, d);
2322 if (!maybe_result->ToObject(&result)) return maybe_result;
2323 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002324 dictionary = StringDictionary::cast(result);
2325 break;
2326 }
2327 case CALLBACKS: {
2328 PropertyDetails d =
2329 PropertyDetails(details.attributes(), CALLBACKS, details.index());
2330 Object* value = descs->GetCallbacksObject(i);
John Reck59135872010-11-02 12:39:01 -07002331 Object* result;
2332 { MaybeObject* maybe_result =
2333 dictionary->Add(descs->GetKey(i), value, d);
2334 if (!maybe_result->ToObject(&result)) return maybe_result;
2335 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002336 dictionary = StringDictionary::cast(result);
2337 break;
2338 }
2339 case MAP_TRANSITION:
2340 case CONSTANT_TRANSITION:
2341 case NULL_DESCRIPTOR:
2342 case INTERCEPTOR:
2343 break;
2344 default:
2345 UNREACHABLE();
2346 }
2347 }
2348
2349 // Copy the next enumeration index from instance descriptor.
2350 int index = map()->instance_descriptors()->NextEnumerationIndex();
2351 dictionary->SetNextEnumerationIndex(index);
2352
John Reck59135872010-11-02 12:39:01 -07002353 { MaybeObject* maybe_obj = Top::context()->global_context()->
2354 normalized_map_cache()->Get(this, mode);
2355 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
2356 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002357 Map* new_map = Map::cast(obj);
2358
Steve Blocka7e24c12009-10-30 11:49:00 +00002359 // We have now successfully allocated all the necessary objects.
2360 // Changes can now be made with the guarantee that all of them take effect.
Kristian Monsen80d68ea2010-09-08 11:05:35 +01002361
2362 // Resize the object in the heap if necessary.
2363 int new_instance_size = new_map->instance_size();
2364 int instance_size_delta = map()->instance_size() - new_instance_size;
2365 ASSERT(instance_size_delta >= 0);
2366 Heap::CreateFillerObjectAt(this->address() + new_instance_size,
2367 instance_size_delta);
2368
Steve Blocka7e24c12009-10-30 11:49:00 +00002369 set_map(new_map);
Steve Blocka7e24c12009-10-30 11:49:00 +00002370
2371 set_properties(dictionary);
2372
2373 Counters::props_to_dictionary.Increment();
2374
2375#ifdef DEBUG
2376 if (FLAG_trace_normalization) {
2377 PrintF("Object properties have been normalized:\n");
2378 Print();
2379 }
2380#endif
2381 return this;
2382}
2383
2384
John Reck59135872010-11-02 12:39:01 -07002385MaybeObject* JSObject::TransformToFastProperties(int unused_property_fields) {
Steve Blocka7e24c12009-10-30 11:49:00 +00002386 if (HasFastProperties()) return this;
2387 ASSERT(!IsGlobalObject());
2388 return property_dictionary()->
2389 TransformPropertiesToFastFor(this, unused_property_fields);
2390}
2391
2392
John Reck59135872010-11-02 12:39:01 -07002393MaybeObject* JSObject::NormalizeElements() {
Steve Block3ce2e202009-11-05 08:53:23 +00002394 ASSERT(!HasPixelElements() && !HasExternalArrayElements());
Steve Blocka7e24c12009-10-30 11:49:00 +00002395 if (HasDictionaryElements()) return this;
Steve Block8defd9f2010-07-08 12:39:36 +01002396 ASSERT(map()->has_fast_elements());
2397
John Reck59135872010-11-02 12:39:01 -07002398 Object* obj;
2399 { MaybeObject* maybe_obj = map()->GetSlowElementsMap();
2400 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
2401 }
Steve Block8defd9f2010-07-08 12:39:36 +01002402 Map* new_map = Map::cast(obj);
Steve Blocka7e24c12009-10-30 11:49:00 +00002403
2404 // Get number of entries.
2405 FixedArray* array = FixedArray::cast(elements());
2406
2407 // Compute the effective length.
2408 int length = IsJSArray() ?
2409 Smi::cast(JSArray::cast(this)->length())->value() :
2410 array->length();
John Reck59135872010-11-02 12:39:01 -07002411 { MaybeObject* maybe_obj = NumberDictionary::Allocate(length);
2412 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
2413 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002414 NumberDictionary* dictionary = NumberDictionary::cast(obj);
2415 // Copy entries.
2416 for (int i = 0; i < length; i++) {
2417 Object* value = array->get(i);
2418 if (!value->IsTheHole()) {
2419 PropertyDetails details = PropertyDetails(NONE, NORMAL);
John Reck59135872010-11-02 12:39:01 -07002420 Object* result;
2421 { MaybeObject* maybe_result =
2422 dictionary->AddNumberEntry(i, array->get(i), details);
2423 if (!maybe_result->ToObject(&result)) return maybe_result;
2424 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002425 dictionary = NumberDictionary::cast(result);
2426 }
2427 }
Steve Block8defd9f2010-07-08 12:39:36 +01002428 // Switch to using the dictionary as the backing storage for
2429 // elements. Set the new map first to satify the elements type
2430 // assert in set_elements().
2431 set_map(new_map);
Steve Blocka7e24c12009-10-30 11:49:00 +00002432 set_elements(dictionary);
2433
2434 Counters::elements_to_dictionary.Increment();
2435
2436#ifdef DEBUG
2437 if (FLAG_trace_normalization) {
2438 PrintF("Object elements have been normalized:\n");
2439 Print();
2440 }
2441#endif
2442
2443 return this;
2444}
2445
2446
John Reck59135872010-11-02 12:39:01 -07002447MaybeObject* JSObject::DeletePropertyPostInterceptor(String* name,
2448 DeleteMode mode) {
Steve Blocka7e24c12009-10-30 11:49:00 +00002449 // Check local property, ignore interceptor.
2450 LookupResult result;
2451 LocalLookupRealNamedProperty(name, &result);
Andrei Popescu402d9372010-02-26 13:31:12 +00002452 if (!result.IsProperty()) return Heap::true_value();
Steve Blocka7e24c12009-10-30 11:49:00 +00002453
2454 // Normalize object if needed.
John Reck59135872010-11-02 12:39:01 -07002455 Object* obj;
2456 { MaybeObject* maybe_obj = NormalizeProperties(CLEAR_INOBJECT_PROPERTIES, 0);
2457 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
2458 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002459
2460 return DeleteNormalizedProperty(name, mode);
2461}
2462
2463
John Reck59135872010-11-02 12:39:01 -07002464MaybeObject* JSObject::DeletePropertyWithInterceptor(String* name) {
Steve Blocka7e24c12009-10-30 11:49:00 +00002465 HandleScope scope;
2466 Handle<InterceptorInfo> interceptor(GetNamedInterceptor());
2467 Handle<String> name_handle(name);
2468 Handle<JSObject> this_handle(this);
2469 if (!interceptor->deleter()->IsUndefined()) {
2470 v8::NamedPropertyDeleter deleter =
2471 v8::ToCData<v8::NamedPropertyDeleter>(interceptor->deleter());
2472 LOG(ApiNamedPropertyAccess("interceptor-named-delete", *this_handle, name));
2473 CustomArguments args(interceptor->data(), this, this);
2474 v8::AccessorInfo info(args.end());
2475 v8::Handle<v8::Boolean> result;
2476 {
2477 // Leaving JavaScript.
2478 VMState state(EXTERNAL);
2479 result = deleter(v8::Utils::ToLocal(name_handle), info);
2480 }
2481 RETURN_IF_SCHEDULED_EXCEPTION();
2482 if (!result.IsEmpty()) {
2483 ASSERT(result->IsBoolean());
2484 return *v8::Utils::OpenHandle(*result);
2485 }
2486 }
John Reck59135872010-11-02 12:39:01 -07002487 MaybeObject* raw_result =
Steve Blocka7e24c12009-10-30 11:49:00 +00002488 this_handle->DeletePropertyPostInterceptor(*name_handle, NORMAL_DELETION);
2489 RETURN_IF_SCHEDULED_EXCEPTION();
2490 return raw_result;
2491}
2492
2493
John Reck59135872010-11-02 12:39:01 -07002494MaybeObject* JSObject::DeleteElementPostInterceptor(uint32_t index,
2495 DeleteMode mode) {
Steve Block3ce2e202009-11-05 08:53:23 +00002496 ASSERT(!HasPixelElements() && !HasExternalArrayElements());
Steve Blocka7e24c12009-10-30 11:49:00 +00002497 switch (GetElementsKind()) {
2498 case FAST_ELEMENTS: {
John Reck59135872010-11-02 12:39:01 -07002499 Object* obj;
2500 { MaybeObject* maybe_obj = EnsureWritableFastElements();
2501 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
2502 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002503 uint32_t length = IsJSArray() ?
2504 static_cast<uint32_t>(Smi::cast(JSArray::cast(this)->length())->value()) :
2505 static_cast<uint32_t>(FixedArray::cast(elements())->length());
2506 if (index < length) {
2507 FixedArray::cast(elements())->set_the_hole(index);
2508 }
2509 break;
2510 }
2511 case DICTIONARY_ELEMENTS: {
2512 NumberDictionary* dictionary = element_dictionary();
2513 int entry = dictionary->FindEntry(index);
2514 if (entry != NumberDictionary::kNotFound) {
2515 return dictionary->DeleteProperty(entry, mode);
2516 }
2517 break;
2518 }
2519 default:
2520 UNREACHABLE();
2521 break;
2522 }
2523 return Heap::true_value();
2524}
2525
2526
John Reck59135872010-11-02 12:39:01 -07002527MaybeObject* JSObject::DeleteElementWithInterceptor(uint32_t index) {
Steve Blocka7e24c12009-10-30 11:49:00 +00002528 // Make sure that the top context does not change when doing
2529 // callbacks or interceptor calls.
2530 AssertNoContextChange ncc;
2531 HandleScope scope;
2532 Handle<InterceptorInfo> interceptor(GetIndexedInterceptor());
2533 if (interceptor->deleter()->IsUndefined()) return Heap::false_value();
2534 v8::IndexedPropertyDeleter deleter =
2535 v8::ToCData<v8::IndexedPropertyDeleter>(interceptor->deleter());
2536 Handle<JSObject> this_handle(this);
2537 LOG(ApiIndexedPropertyAccess("interceptor-indexed-delete", this, index));
2538 CustomArguments args(interceptor->data(), this, this);
2539 v8::AccessorInfo info(args.end());
2540 v8::Handle<v8::Boolean> result;
2541 {
2542 // Leaving JavaScript.
2543 VMState state(EXTERNAL);
2544 result = deleter(index, info);
2545 }
2546 RETURN_IF_SCHEDULED_EXCEPTION();
2547 if (!result.IsEmpty()) {
2548 ASSERT(result->IsBoolean());
2549 return *v8::Utils::OpenHandle(*result);
2550 }
John Reck59135872010-11-02 12:39:01 -07002551 MaybeObject* raw_result =
Steve Blocka7e24c12009-10-30 11:49:00 +00002552 this_handle->DeleteElementPostInterceptor(index, NORMAL_DELETION);
2553 RETURN_IF_SCHEDULED_EXCEPTION();
2554 return raw_result;
2555}
2556
2557
John Reck59135872010-11-02 12:39:01 -07002558MaybeObject* JSObject::DeleteElement(uint32_t index, DeleteMode mode) {
Steve Blocka7e24c12009-10-30 11:49:00 +00002559 // Check access rights if needed.
2560 if (IsAccessCheckNeeded() &&
2561 !Top::MayIndexedAccess(this, index, v8::ACCESS_DELETE)) {
2562 Top::ReportFailedAccessCheck(this, v8::ACCESS_DELETE);
2563 return Heap::false_value();
2564 }
2565
2566 if (IsJSGlobalProxy()) {
2567 Object* proto = GetPrototype();
2568 if (proto->IsNull()) return Heap::false_value();
2569 ASSERT(proto->IsJSGlobalObject());
2570 return JSGlobalObject::cast(proto)->DeleteElement(index, mode);
2571 }
2572
2573 if (HasIndexedInterceptor()) {
2574 // Skip interceptor if forcing deletion.
2575 if (mode == FORCE_DELETION) {
2576 return DeleteElementPostInterceptor(index, mode);
2577 }
2578 return DeleteElementWithInterceptor(index);
2579 }
2580
2581 switch (GetElementsKind()) {
2582 case FAST_ELEMENTS: {
John Reck59135872010-11-02 12:39:01 -07002583 Object* obj;
2584 { MaybeObject* maybe_obj = EnsureWritableFastElements();
2585 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
2586 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002587 uint32_t length = IsJSArray() ?
2588 static_cast<uint32_t>(Smi::cast(JSArray::cast(this)->length())->value()) :
2589 static_cast<uint32_t>(FixedArray::cast(elements())->length());
2590 if (index < length) {
2591 FixedArray::cast(elements())->set_the_hole(index);
2592 }
2593 break;
2594 }
Steve Block3ce2e202009-11-05 08:53:23 +00002595 case PIXEL_ELEMENTS:
2596 case EXTERNAL_BYTE_ELEMENTS:
2597 case EXTERNAL_UNSIGNED_BYTE_ELEMENTS:
2598 case EXTERNAL_SHORT_ELEMENTS:
2599 case EXTERNAL_UNSIGNED_SHORT_ELEMENTS:
2600 case EXTERNAL_INT_ELEMENTS:
2601 case EXTERNAL_UNSIGNED_INT_ELEMENTS:
2602 case EXTERNAL_FLOAT_ELEMENTS:
2603 // Pixel and external array elements cannot be deleted. Just
2604 // silently ignore here.
Steve Blocka7e24c12009-10-30 11:49:00 +00002605 break;
Steve Blocka7e24c12009-10-30 11:49:00 +00002606 case DICTIONARY_ELEMENTS: {
2607 NumberDictionary* dictionary = element_dictionary();
2608 int entry = dictionary->FindEntry(index);
2609 if (entry != NumberDictionary::kNotFound) {
2610 return dictionary->DeleteProperty(entry, mode);
2611 }
2612 break;
2613 }
2614 default:
2615 UNREACHABLE();
2616 break;
2617 }
2618 return Heap::true_value();
2619}
2620
2621
John Reck59135872010-11-02 12:39:01 -07002622MaybeObject* JSObject::DeleteProperty(String* name, DeleteMode mode) {
Steve Blocka7e24c12009-10-30 11:49:00 +00002623 // ECMA-262, 3rd, 8.6.2.5
2624 ASSERT(name->IsString());
2625
2626 // Check access rights if needed.
2627 if (IsAccessCheckNeeded() &&
2628 !Top::MayNamedAccess(this, name, v8::ACCESS_DELETE)) {
2629 Top::ReportFailedAccessCheck(this, v8::ACCESS_DELETE);
2630 return Heap::false_value();
2631 }
2632
2633 if (IsJSGlobalProxy()) {
2634 Object* proto = GetPrototype();
2635 if (proto->IsNull()) return Heap::false_value();
2636 ASSERT(proto->IsJSGlobalObject());
2637 return JSGlobalObject::cast(proto)->DeleteProperty(name, mode);
2638 }
2639
2640 uint32_t index = 0;
2641 if (name->AsArrayIndex(&index)) {
2642 return DeleteElement(index, mode);
2643 } else {
2644 LookupResult result;
2645 LocalLookup(name, &result);
Andrei Popescu402d9372010-02-26 13:31:12 +00002646 if (!result.IsProperty()) return Heap::true_value();
Steve Blocka7e24c12009-10-30 11:49:00 +00002647 // Ignore attributes if forcing a deletion.
2648 if (result.IsDontDelete() && mode != FORCE_DELETION) {
2649 return Heap::false_value();
2650 }
2651 // Check for interceptor.
2652 if (result.type() == INTERCEPTOR) {
2653 // Skip interceptor if forcing a deletion.
2654 if (mode == FORCE_DELETION) {
2655 return DeletePropertyPostInterceptor(name, mode);
2656 }
2657 return DeletePropertyWithInterceptor(name);
2658 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002659 // Normalize object if needed.
John Reck59135872010-11-02 12:39:01 -07002660 Object* obj;
2661 { MaybeObject* maybe_obj =
2662 NormalizeProperties(CLEAR_INOBJECT_PROPERTIES, 0);
2663 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
2664 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002665 // Make sure the properties are normalized before removing the entry.
2666 return DeleteNormalizedProperty(name, mode);
2667 }
2668}
2669
2670
2671// Check whether this object references another object.
2672bool JSObject::ReferencesObject(Object* obj) {
2673 AssertNoAllocation no_alloc;
2674
2675 // Is the object the constructor for this object?
2676 if (map()->constructor() == obj) {
2677 return true;
2678 }
2679
2680 // Is the object the prototype for this object?
2681 if (map()->prototype() == obj) {
2682 return true;
2683 }
2684
2685 // Check if the object is among the named properties.
2686 Object* key = SlowReverseLookup(obj);
2687 if (key != Heap::undefined_value()) {
2688 return true;
2689 }
2690
2691 // Check if the object is among the indexed properties.
2692 switch (GetElementsKind()) {
2693 case PIXEL_ELEMENTS:
Steve Block3ce2e202009-11-05 08:53:23 +00002694 case EXTERNAL_BYTE_ELEMENTS:
2695 case EXTERNAL_UNSIGNED_BYTE_ELEMENTS:
2696 case EXTERNAL_SHORT_ELEMENTS:
2697 case EXTERNAL_UNSIGNED_SHORT_ELEMENTS:
2698 case EXTERNAL_INT_ELEMENTS:
2699 case EXTERNAL_UNSIGNED_INT_ELEMENTS:
2700 case EXTERNAL_FLOAT_ELEMENTS:
2701 // Raw pixels and external arrays do not reference other
2702 // objects.
Steve Blocka7e24c12009-10-30 11:49:00 +00002703 break;
2704 case FAST_ELEMENTS: {
2705 int length = IsJSArray() ?
2706 Smi::cast(JSArray::cast(this)->length())->value() :
2707 FixedArray::cast(elements())->length();
2708 for (int i = 0; i < length; i++) {
2709 Object* element = FixedArray::cast(elements())->get(i);
2710 if (!element->IsTheHole() && element == obj) {
2711 return true;
2712 }
2713 }
2714 break;
2715 }
2716 case DICTIONARY_ELEMENTS: {
2717 key = element_dictionary()->SlowReverseLookup(obj);
2718 if (key != Heap::undefined_value()) {
2719 return true;
2720 }
2721 break;
2722 }
2723 default:
2724 UNREACHABLE();
2725 break;
2726 }
2727
Steve Block6ded16b2010-05-10 14:33:55 +01002728 // For functions check the context.
2729 if (IsJSFunction()) {
Steve Blocka7e24c12009-10-30 11:49:00 +00002730 // Get the constructor function for arguments array.
2731 JSObject* arguments_boilerplate =
2732 Top::context()->global_context()->arguments_boilerplate();
2733 JSFunction* arguments_function =
2734 JSFunction::cast(arguments_boilerplate->map()->constructor());
2735
2736 // Get the context and don't check if it is the global context.
2737 JSFunction* f = JSFunction::cast(this);
2738 Context* context = f->context();
2739 if (context->IsGlobalContext()) {
2740 return false;
2741 }
2742
2743 // Check the non-special context slots.
2744 for (int i = Context::MIN_CONTEXT_SLOTS; i < context->length(); i++) {
2745 // Only check JS objects.
2746 if (context->get(i)->IsJSObject()) {
2747 JSObject* ctxobj = JSObject::cast(context->get(i));
2748 // If it is an arguments array check the content.
2749 if (ctxobj->map()->constructor() == arguments_function) {
2750 if (ctxobj->ReferencesObject(obj)) {
2751 return true;
2752 }
2753 } else if (ctxobj == obj) {
2754 return true;
2755 }
2756 }
2757 }
2758
2759 // Check the context extension if any.
2760 if (context->has_extension()) {
2761 return context->extension()->ReferencesObject(obj);
2762 }
2763 }
2764
2765 // No references to object.
2766 return false;
2767}
2768
2769
John Reck59135872010-11-02 12:39:01 -07002770MaybeObject* JSObject::PreventExtensions() {
Steve Block8defd9f2010-07-08 12:39:36 +01002771 // If there are fast elements we normalize.
2772 if (HasFastElements()) {
John Reck59135872010-11-02 12:39:01 -07002773 Object* ok;
2774 { MaybeObject* maybe_ok = NormalizeElements();
2775 if (!maybe_ok->ToObject(&ok)) return maybe_ok;
2776 }
Steve Block8defd9f2010-07-08 12:39:36 +01002777 }
2778 // Make sure that we never go back to fast case.
2779 element_dictionary()->set_requires_slow_elements();
2780
2781 // Do a map transition, other objects with this map may still
2782 // be extensible.
John Reck59135872010-11-02 12:39:01 -07002783 Object* new_map;
2784 { MaybeObject* maybe_new_map = map()->CopyDropTransitions();
2785 if (!maybe_new_map->ToObject(&new_map)) return maybe_new_map;
2786 }
Steve Block8defd9f2010-07-08 12:39:36 +01002787 Map::cast(new_map)->set_is_extensible(false);
2788 set_map(Map::cast(new_map));
2789 ASSERT(!map()->is_extensible());
2790 return new_map;
2791}
2792
2793
Steve Blocka7e24c12009-10-30 11:49:00 +00002794// Tests for the fast common case for property enumeration:
Steve Blockd0582a62009-12-15 09:54:21 +00002795// - This object and all prototypes has an enum cache (which means that it has
2796// no interceptors and needs no access checks).
2797// - This object has no elements.
2798// - No prototype has enumerable properties/elements.
Steve Blocka7e24c12009-10-30 11:49:00 +00002799bool JSObject::IsSimpleEnum() {
Steve Blocka7e24c12009-10-30 11:49:00 +00002800 for (Object* o = this;
2801 o != Heap::null_value();
2802 o = JSObject::cast(o)->GetPrototype()) {
2803 JSObject* curr = JSObject::cast(o);
Steve Blocka7e24c12009-10-30 11:49:00 +00002804 if (!curr->map()->instance_descriptors()->HasEnumCache()) return false;
Steve Blockd0582a62009-12-15 09:54:21 +00002805 ASSERT(!curr->HasNamedInterceptor());
2806 ASSERT(!curr->HasIndexedInterceptor());
2807 ASSERT(!curr->IsAccessCheckNeeded());
Steve Blocka7e24c12009-10-30 11:49:00 +00002808 if (curr->NumberOfEnumElements() > 0) return false;
Steve Blocka7e24c12009-10-30 11:49:00 +00002809 if (curr != this) {
2810 FixedArray* curr_fixed_array =
2811 FixedArray::cast(curr->map()->instance_descriptors()->GetEnumCache());
Steve Blockd0582a62009-12-15 09:54:21 +00002812 if (curr_fixed_array->length() > 0) return false;
Steve Blocka7e24c12009-10-30 11:49:00 +00002813 }
2814 }
2815 return true;
2816}
2817
2818
2819int Map::NumberOfDescribedProperties() {
2820 int result = 0;
2821 DescriptorArray* descs = instance_descriptors();
2822 for (int i = 0; i < descs->number_of_descriptors(); i++) {
2823 if (descs->IsProperty(i)) result++;
2824 }
2825 return result;
2826}
2827
2828
2829int Map::PropertyIndexFor(String* name) {
2830 DescriptorArray* descs = instance_descriptors();
2831 for (int i = 0; i < descs->number_of_descriptors(); i++) {
2832 if (name->Equals(descs->GetKey(i)) && !descs->IsNullDescriptor(i)) {
2833 return descs->GetFieldIndex(i);
2834 }
2835 }
2836 return -1;
2837}
2838
2839
2840int Map::NextFreePropertyIndex() {
2841 int max_index = -1;
2842 DescriptorArray* descs = instance_descriptors();
2843 for (int i = 0; i < descs->number_of_descriptors(); i++) {
2844 if (descs->GetType(i) == FIELD) {
2845 int current_index = descs->GetFieldIndex(i);
2846 if (current_index > max_index) max_index = current_index;
2847 }
2848 }
2849 return max_index + 1;
2850}
2851
2852
2853AccessorDescriptor* Map::FindAccessor(String* name) {
2854 DescriptorArray* descs = instance_descriptors();
2855 for (int i = 0; i < descs->number_of_descriptors(); i++) {
2856 if (name->Equals(descs->GetKey(i)) && descs->GetType(i) == CALLBACKS) {
2857 return descs->GetCallbacks(i);
2858 }
2859 }
2860 return NULL;
2861}
2862
2863
2864void JSObject::LocalLookup(String* name, LookupResult* result) {
2865 ASSERT(name->IsString());
2866
2867 if (IsJSGlobalProxy()) {
2868 Object* proto = GetPrototype();
2869 if (proto->IsNull()) return result->NotFound();
2870 ASSERT(proto->IsJSGlobalObject());
2871 return JSObject::cast(proto)->LocalLookup(name, result);
2872 }
2873
2874 // Do not use inline caching if the object is a non-global object
2875 // that requires access checks.
2876 if (!IsJSGlobalProxy() && IsAccessCheckNeeded()) {
2877 result->DisallowCaching();
2878 }
2879
2880 // Check __proto__ before interceptor.
2881 if (name->Equals(Heap::Proto_symbol()) && !IsJSContextExtensionObject()) {
2882 result->ConstantResult(this);
2883 return;
2884 }
2885
2886 // Check for lookup interceptor except when bootstrapping.
2887 if (HasNamedInterceptor() && !Bootstrapper::IsActive()) {
2888 result->InterceptorResult(this);
2889 return;
2890 }
2891
2892 LocalLookupRealNamedProperty(name, result);
2893}
2894
2895
2896void JSObject::Lookup(String* name, LookupResult* result) {
2897 // Ecma-262 3rd 8.6.2.4
2898 for (Object* current = this;
2899 current != Heap::null_value();
2900 current = JSObject::cast(current)->GetPrototype()) {
2901 JSObject::cast(current)->LocalLookup(name, result);
Andrei Popescu402d9372010-02-26 13:31:12 +00002902 if (result->IsProperty()) return;
Steve Blocka7e24c12009-10-30 11:49:00 +00002903 }
2904 result->NotFound();
2905}
2906
2907
2908// Search object and it's prototype chain for callback properties.
2909void JSObject::LookupCallback(String* name, LookupResult* result) {
2910 for (Object* current = this;
2911 current != Heap::null_value();
2912 current = JSObject::cast(current)->GetPrototype()) {
2913 JSObject::cast(current)->LocalLookupRealNamedProperty(name, result);
Andrei Popescu402d9372010-02-26 13:31:12 +00002914 if (result->IsProperty() && result->type() == CALLBACKS) return;
Steve Blocka7e24c12009-10-30 11:49:00 +00002915 }
2916 result->NotFound();
2917}
2918
2919
John Reck59135872010-11-02 12:39:01 -07002920MaybeObject* JSObject::DefineGetterSetter(String* name,
2921 PropertyAttributes attributes) {
Steve Blocka7e24c12009-10-30 11:49:00 +00002922 // Make sure that the top context does not change when doing callbacks or
2923 // interceptor calls.
2924 AssertNoContextChange ncc;
2925
Steve Blocka7e24c12009-10-30 11:49:00 +00002926 // Try to flatten before operating on the string.
Steve Block6ded16b2010-05-10 14:33:55 +01002927 name->TryFlatten();
Steve Blocka7e24c12009-10-30 11:49:00 +00002928
Leon Clarkef7060e22010-06-03 12:02:55 +01002929 if (!CanSetCallback(name)) {
2930 return Heap::undefined_value();
Steve Blocka7e24c12009-10-30 11:49:00 +00002931 }
2932
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01002933 uint32_t index = 0;
Steve Blocka7e24c12009-10-30 11:49:00 +00002934 bool is_element = name->AsArrayIndex(&index);
2935 if (is_element && IsJSArray()) return Heap::undefined_value();
2936
2937 if (is_element) {
2938 switch (GetElementsKind()) {
2939 case FAST_ELEMENTS:
2940 break;
2941 case PIXEL_ELEMENTS:
Steve Block3ce2e202009-11-05 08:53:23 +00002942 case EXTERNAL_BYTE_ELEMENTS:
2943 case EXTERNAL_UNSIGNED_BYTE_ELEMENTS:
2944 case EXTERNAL_SHORT_ELEMENTS:
2945 case EXTERNAL_UNSIGNED_SHORT_ELEMENTS:
2946 case EXTERNAL_INT_ELEMENTS:
2947 case EXTERNAL_UNSIGNED_INT_ELEMENTS:
2948 case EXTERNAL_FLOAT_ELEMENTS:
2949 // Ignore getters and setters on pixel and external array
2950 // elements.
Steve Blocka7e24c12009-10-30 11:49:00 +00002951 return Heap::undefined_value();
2952 case DICTIONARY_ELEMENTS: {
2953 // Lookup the index.
2954 NumberDictionary* dictionary = element_dictionary();
2955 int entry = dictionary->FindEntry(index);
2956 if (entry != NumberDictionary::kNotFound) {
2957 Object* result = dictionary->ValueAt(entry);
2958 PropertyDetails details = dictionary->DetailsAt(entry);
2959 if (details.IsReadOnly()) return Heap::undefined_value();
2960 if (details.type() == CALLBACKS) {
Leon Clarkef7060e22010-06-03 12:02:55 +01002961 if (result->IsFixedArray()) {
2962 return result;
2963 }
2964 // Otherwise allow to override it.
Steve Blocka7e24c12009-10-30 11:49:00 +00002965 }
2966 }
2967 break;
2968 }
2969 default:
2970 UNREACHABLE();
2971 break;
2972 }
2973 } else {
2974 // Lookup the name.
2975 LookupResult result;
2976 LocalLookup(name, &result);
Andrei Popescu402d9372010-02-26 13:31:12 +00002977 if (result.IsProperty()) {
Steve Blocka7e24c12009-10-30 11:49:00 +00002978 if (result.IsReadOnly()) return Heap::undefined_value();
2979 if (result.type() == CALLBACKS) {
2980 Object* obj = result.GetCallbackObject();
Leon Clarkef7060e22010-06-03 12:02:55 +01002981 // Need to preserve old getters/setters.
Leon Clarked91b9f72010-01-27 17:25:45 +00002982 if (obj->IsFixedArray()) {
Leon Clarkef7060e22010-06-03 12:02:55 +01002983 // Use set to update attributes.
2984 return SetPropertyCallback(name, obj, attributes);
Leon Clarked91b9f72010-01-27 17:25:45 +00002985 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002986 }
2987 }
2988 }
2989
2990 // Allocate the fixed array to hold getter and setter.
John Reck59135872010-11-02 12:39:01 -07002991 Object* structure;
2992 { MaybeObject* maybe_structure = Heap::AllocateFixedArray(2, TENURED);
2993 if (!maybe_structure->ToObject(&structure)) return maybe_structure;
2994 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002995
2996 if (is_element) {
Leon Clarkef7060e22010-06-03 12:02:55 +01002997 return SetElementCallback(index, structure, attributes);
Steve Blocka7e24c12009-10-30 11:49:00 +00002998 } else {
Leon Clarkef7060e22010-06-03 12:02:55 +01002999 return SetPropertyCallback(name, structure, attributes);
Steve Blocka7e24c12009-10-30 11:49:00 +00003000 }
Leon Clarkef7060e22010-06-03 12:02:55 +01003001}
3002
3003
3004bool JSObject::CanSetCallback(String* name) {
3005 ASSERT(!IsAccessCheckNeeded()
3006 || Top::MayNamedAccess(this, name, v8::ACCESS_SET));
3007
3008 // Check if there is an API defined callback object which prohibits
3009 // callback overwriting in this object or it's prototype chain.
3010 // This mechanism is needed for instance in a browser setting, where
3011 // certain accessors such as window.location should not be allowed
3012 // to be overwritten because allowing overwriting could potentially
3013 // cause security problems.
3014 LookupResult callback_result;
3015 LookupCallback(name, &callback_result);
3016 if (callback_result.IsProperty()) {
3017 Object* obj = callback_result.GetCallbackObject();
3018 if (obj->IsAccessorInfo() &&
3019 AccessorInfo::cast(obj)->prohibits_overwriting()) {
3020 return false;
3021 }
3022 }
3023
3024 return true;
3025}
3026
3027
John Reck59135872010-11-02 12:39:01 -07003028MaybeObject* JSObject::SetElementCallback(uint32_t index,
3029 Object* structure,
3030 PropertyAttributes attributes) {
Leon Clarkef7060e22010-06-03 12:02:55 +01003031 PropertyDetails details = PropertyDetails(attributes, CALLBACKS);
3032
3033 // Normalize elements to make this operation simple.
John Reck59135872010-11-02 12:39:01 -07003034 Object* ok;
3035 { MaybeObject* maybe_ok = NormalizeElements();
3036 if (!maybe_ok->ToObject(&ok)) return maybe_ok;
3037 }
Leon Clarkef7060e22010-06-03 12:02:55 +01003038
3039 // Update the dictionary with the new CALLBACKS property.
John Reck59135872010-11-02 12:39:01 -07003040 Object* dict;
3041 { MaybeObject* maybe_dict =
3042 element_dictionary()->Set(index, structure, details);
3043 if (!maybe_dict->ToObject(&dict)) return maybe_dict;
3044 }
Leon Clarkef7060e22010-06-03 12:02:55 +01003045
3046 NumberDictionary* elements = NumberDictionary::cast(dict);
3047 elements->set_requires_slow_elements();
3048 // Set the potential new dictionary on the object.
3049 set_elements(elements);
Steve Blocka7e24c12009-10-30 11:49:00 +00003050
3051 return structure;
3052}
3053
3054
John Reck59135872010-11-02 12:39:01 -07003055MaybeObject* JSObject::SetPropertyCallback(String* name,
3056 Object* structure,
3057 PropertyAttributes attributes) {
Leon Clarkef7060e22010-06-03 12:02:55 +01003058 PropertyDetails details = PropertyDetails(attributes, CALLBACKS);
3059
3060 bool convert_back_to_fast = HasFastProperties() &&
3061 (map()->instance_descriptors()->number_of_descriptors()
3062 < DescriptorArray::kMaxNumberOfDescriptors);
3063
3064 // Normalize object to make this operation simple.
John Reck59135872010-11-02 12:39:01 -07003065 Object* ok;
3066 { MaybeObject* maybe_ok = NormalizeProperties(CLEAR_INOBJECT_PROPERTIES, 0);
3067 if (!maybe_ok->ToObject(&ok)) return maybe_ok;
3068 }
Leon Clarkef7060e22010-06-03 12:02:55 +01003069
3070 // For the global object allocate a new map to invalidate the global inline
3071 // caches which have a global property cell reference directly in the code.
3072 if (IsGlobalObject()) {
John Reck59135872010-11-02 12:39:01 -07003073 Object* new_map;
3074 { MaybeObject* maybe_new_map = map()->CopyDropDescriptors();
3075 if (!maybe_new_map->ToObject(&new_map)) return maybe_new_map;
3076 }
Leon Clarkef7060e22010-06-03 12:02:55 +01003077 set_map(Map::cast(new_map));
Ben Murdochb0fe1622011-05-05 13:52:32 +01003078 // When running crankshaft, changing the map is not enough. We
3079 // need to deoptimize all functions that rely on this global
3080 // object.
3081 Deoptimizer::DeoptimizeGlobalObject(this);
Leon Clarkef7060e22010-06-03 12:02:55 +01003082 }
3083
3084 // Update the dictionary with the new CALLBACKS property.
John Reck59135872010-11-02 12:39:01 -07003085 Object* result;
3086 { MaybeObject* maybe_result = SetNormalizedProperty(name, structure, details);
3087 if (!maybe_result->ToObject(&result)) return maybe_result;
3088 }
Leon Clarkef7060e22010-06-03 12:02:55 +01003089
3090 if (convert_back_to_fast) {
John Reck59135872010-11-02 12:39:01 -07003091 { MaybeObject* maybe_ok = TransformToFastProperties(0);
3092 if (!maybe_ok->ToObject(&ok)) return maybe_ok;
3093 }
Leon Clarkef7060e22010-06-03 12:02:55 +01003094 }
3095 return result;
3096}
3097
John Reck59135872010-11-02 12:39:01 -07003098MaybeObject* JSObject::DefineAccessor(String* name,
3099 bool is_getter,
Ben Murdochb0fe1622011-05-05 13:52:32 +01003100 Object* fun,
John Reck59135872010-11-02 12:39:01 -07003101 PropertyAttributes attributes) {
Ben Murdochb0fe1622011-05-05 13:52:32 +01003102 ASSERT(fun->IsJSFunction() || fun->IsUndefined());
Steve Blocka7e24c12009-10-30 11:49:00 +00003103 // Check access rights if needed.
3104 if (IsAccessCheckNeeded() &&
Leon Clarkef7060e22010-06-03 12:02:55 +01003105 !Top::MayNamedAccess(this, name, v8::ACCESS_SET)) {
3106 Top::ReportFailedAccessCheck(this, v8::ACCESS_SET);
Steve Blocka7e24c12009-10-30 11:49:00 +00003107 return Heap::undefined_value();
3108 }
3109
3110 if (IsJSGlobalProxy()) {
3111 Object* proto = GetPrototype();
3112 if (proto->IsNull()) return this;
3113 ASSERT(proto->IsJSGlobalObject());
3114 return JSObject::cast(proto)->DefineAccessor(name, is_getter,
3115 fun, attributes);
3116 }
3117
John Reck59135872010-11-02 12:39:01 -07003118 Object* array;
3119 { MaybeObject* maybe_array = DefineGetterSetter(name, attributes);
3120 if (!maybe_array->ToObject(&array)) return maybe_array;
3121 }
3122 if (array->IsUndefined()) return array;
Steve Blocka7e24c12009-10-30 11:49:00 +00003123 FixedArray::cast(array)->set(is_getter ? 0 : 1, fun);
3124 return this;
3125}
3126
3127
John Reck59135872010-11-02 12:39:01 -07003128MaybeObject* JSObject::DefineAccessor(AccessorInfo* info) {
Leon Clarkef7060e22010-06-03 12:02:55 +01003129 String* name = String::cast(info->name());
3130 // Check access rights if needed.
3131 if (IsAccessCheckNeeded() &&
3132 !Top::MayNamedAccess(this, name, v8::ACCESS_SET)) {
3133 Top::ReportFailedAccessCheck(this, v8::ACCESS_SET);
3134 return Heap::undefined_value();
3135 }
3136
3137 if (IsJSGlobalProxy()) {
3138 Object* proto = GetPrototype();
3139 if (proto->IsNull()) return this;
3140 ASSERT(proto->IsJSGlobalObject());
3141 return JSObject::cast(proto)->DefineAccessor(info);
3142 }
3143
3144 // Make sure that the top context does not change when doing callbacks or
3145 // interceptor calls.
3146 AssertNoContextChange ncc;
3147
3148 // Try to flatten before operating on the string.
3149 name->TryFlatten();
3150
3151 if (!CanSetCallback(name)) {
3152 return Heap::undefined_value();
3153 }
3154
3155 uint32_t index = 0;
3156 bool is_element = name->AsArrayIndex(&index);
3157
3158 if (is_element) {
3159 if (IsJSArray()) return Heap::undefined_value();
3160
3161 // Accessors overwrite previous callbacks (cf. with getters/setters).
3162 switch (GetElementsKind()) {
3163 case FAST_ELEMENTS:
3164 break;
3165 case PIXEL_ELEMENTS:
3166 case EXTERNAL_BYTE_ELEMENTS:
3167 case EXTERNAL_UNSIGNED_BYTE_ELEMENTS:
3168 case EXTERNAL_SHORT_ELEMENTS:
3169 case EXTERNAL_UNSIGNED_SHORT_ELEMENTS:
3170 case EXTERNAL_INT_ELEMENTS:
3171 case EXTERNAL_UNSIGNED_INT_ELEMENTS:
3172 case EXTERNAL_FLOAT_ELEMENTS:
3173 // Ignore getters and setters on pixel and external array
3174 // elements.
3175 return Heap::undefined_value();
3176 case DICTIONARY_ELEMENTS:
3177 break;
3178 default:
3179 UNREACHABLE();
3180 break;
3181 }
3182
John Reck59135872010-11-02 12:39:01 -07003183 Object* ok;
3184 { MaybeObject* maybe_ok =
3185 SetElementCallback(index, info, info->property_attributes());
3186 if (!maybe_ok->ToObject(&ok)) return maybe_ok;
3187 }
Leon Clarkef7060e22010-06-03 12:02:55 +01003188 } else {
3189 // Lookup the name.
3190 LookupResult result;
3191 LocalLookup(name, &result);
3192 // ES5 forbids turning a property into an accessor if it's not
3193 // configurable (that is IsDontDelete in ES3 and v8), see 8.6.1 (Table 5).
3194 if (result.IsProperty() && (result.IsReadOnly() || result.IsDontDelete())) {
3195 return Heap::undefined_value();
3196 }
John Reck59135872010-11-02 12:39:01 -07003197 Object* ok;
3198 { MaybeObject* maybe_ok =
3199 SetPropertyCallback(name, info, info->property_attributes());
3200 if (!maybe_ok->ToObject(&ok)) return maybe_ok;
3201 }
Leon Clarkef7060e22010-06-03 12:02:55 +01003202 }
3203
3204 return this;
3205}
3206
3207
Steve Blocka7e24c12009-10-30 11:49:00 +00003208Object* JSObject::LookupAccessor(String* name, bool is_getter) {
3209 // Make sure that the top context does not change when doing callbacks or
3210 // interceptor calls.
3211 AssertNoContextChange ncc;
3212
3213 // Check access rights if needed.
3214 if (IsAccessCheckNeeded() &&
3215 !Top::MayNamedAccess(this, name, v8::ACCESS_HAS)) {
3216 Top::ReportFailedAccessCheck(this, v8::ACCESS_HAS);
3217 return Heap::undefined_value();
3218 }
3219
3220 // Make the lookup and include prototypes.
3221 int accessor_index = is_getter ? kGetterIndex : kSetterIndex;
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01003222 uint32_t index = 0;
Steve Blocka7e24c12009-10-30 11:49:00 +00003223 if (name->AsArrayIndex(&index)) {
3224 for (Object* obj = this;
3225 obj != Heap::null_value();
3226 obj = JSObject::cast(obj)->GetPrototype()) {
3227 JSObject* js_object = JSObject::cast(obj);
3228 if (js_object->HasDictionaryElements()) {
3229 NumberDictionary* dictionary = js_object->element_dictionary();
3230 int entry = dictionary->FindEntry(index);
3231 if (entry != NumberDictionary::kNotFound) {
3232 Object* element = dictionary->ValueAt(entry);
3233 PropertyDetails details = dictionary->DetailsAt(entry);
3234 if (details.type() == CALLBACKS) {
Leon Clarkef7060e22010-06-03 12:02:55 +01003235 if (element->IsFixedArray()) {
3236 return FixedArray::cast(element)->get(accessor_index);
3237 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003238 }
3239 }
3240 }
3241 }
3242 } else {
3243 for (Object* obj = this;
3244 obj != Heap::null_value();
3245 obj = JSObject::cast(obj)->GetPrototype()) {
3246 LookupResult result;
3247 JSObject::cast(obj)->LocalLookup(name, &result);
Andrei Popescu402d9372010-02-26 13:31:12 +00003248 if (result.IsProperty()) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003249 if (result.IsReadOnly()) return Heap::undefined_value();
3250 if (result.type() == CALLBACKS) {
3251 Object* obj = result.GetCallbackObject();
3252 if (obj->IsFixedArray()) {
3253 return FixedArray::cast(obj)->get(accessor_index);
3254 }
3255 }
3256 }
3257 }
3258 }
3259 return Heap::undefined_value();
3260}
3261
3262
3263Object* JSObject::SlowReverseLookup(Object* value) {
3264 if (HasFastProperties()) {
3265 DescriptorArray* descs = map()->instance_descriptors();
3266 for (int i = 0; i < descs->number_of_descriptors(); i++) {
3267 if (descs->GetType(i) == FIELD) {
3268 if (FastPropertyAt(descs->GetFieldIndex(i)) == value) {
3269 return descs->GetKey(i);
3270 }
3271 } else if (descs->GetType(i) == CONSTANT_FUNCTION) {
3272 if (descs->GetConstantFunction(i) == value) {
3273 return descs->GetKey(i);
3274 }
3275 }
3276 }
3277 return Heap::undefined_value();
3278 } else {
3279 return property_dictionary()->SlowReverseLookup(value);
3280 }
3281}
3282
3283
John Reck59135872010-11-02 12:39:01 -07003284MaybeObject* Map::CopyDropDescriptors() {
3285 Object* result;
3286 { MaybeObject* maybe_result =
3287 Heap::AllocateMap(instance_type(), instance_size());
3288 if (!maybe_result->ToObject(&result)) return maybe_result;
3289 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003290 Map::cast(result)->set_prototype(prototype());
3291 Map::cast(result)->set_constructor(constructor());
3292 // Don't copy descriptors, so map transitions always remain a forest.
3293 // If we retained the same descriptors we would have two maps
3294 // pointing to the same transition which is bad because the garbage
3295 // collector relies on being able to reverse pointers from transitions
3296 // to maps. If properties need to be retained use CopyDropTransitions.
3297 Map::cast(result)->set_instance_descriptors(Heap::empty_descriptor_array());
3298 // Please note instance_type and instance_size are set when allocated.
3299 Map::cast(result)->set_inobject_properties(inobject_properties());
3300 Map::cast(result)->set_unused_property_fields(unused_property_fields());
3301
3302 // If the map has pre-allocated properties always start out with a descriptor
3303 // array describing these properties.
3304 if (pre_allocated_property_fields() > 0) {
3305 ASSERT(constructor()->IsJSFunction());
3306 JSFunction* ctor = JSFunction::cast(constructor());
John Reck59135872010-11-02 12:39:01 -07003307 Object* descriptors;
3308 { MaybeObject* maybe_descriptors =
3309 ctor->initial_map()->instance_descriptors()->RemoveTransitions();
3310 if (!maybe_descriptors->ToObject(&descriptors)) return maybe_descriptors;
3311 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003312 Map::cast(result)->set_instance_descriptors(
3313 DescriptorArray::cast(descriptors));
3314 Map::cast(result)->set_pre_allocated_property_fields(
3315 pre_allocated_property_fields());
3316 }
3317 Map::cast(result)->set_bit_field(bit_field());
3318 Map::cast(result)->set_bit_field2(bit_field2());
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003319 Map::cast(result)->set_is_shared(false);
Steve Blocka7e24c12009-10-30 11:49:00 +00003320 Map::cast(result)->ClearCodeCache();
3321 return result;
3322}
3323
3324
John Reck59135872010-11-02 12:39:01 -07003325MaybeObject* Map::CopyNormalized(PropertyNormalizationMode mode,
3326 NormalizedMapSharingMode sharing) {
Kristian Monsen80d68ea2010-09-08 11:05:35 +01003327 int new_instance_size = instance_size();
3328 if (mode == CLEAR_INOBJECT_PROPERTIES) {
3329 new_instance_size -= inobject_properties() * kPointerSize;
3330 }
3331
John Reck59135872010-11-02 12:39:01 -07003332 Object* result;
3333 { MaybeObject* maybe_result =
3334 Heap::AllocateMap(instance_type(), new_instance_size);
3335 if (!maybe_result->ToObject(&result)) return maybe_result;
3336 }
Kristian Monsen80d68ea2010-09-08 11:05:35 +01003337
3338 if (mode != CLEAR_INOBJECT_PROPERTIES) {
3339 Map::cast(result)->set_inobject_properties(inobject_properties());
3340 }
3341
3342 Map::cast(result)->set_prototype(prototype());
3343 Map::cast(result)->set_constructor(constructor());
3344
3345 Map::cast(result)->set_bit_field(bit_field());
3346 Map::cast(result)->set_bit_field2(bit_field2());
3347
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003348 Map::cast(result)->set_is_shared(sharing == SHARED_NORMALIZED_MAP);
3349
Kristian Monsen80d68ea2010-09-08 11:05:35 +01003350#ifdef DEBUG
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003351 if (Map::cast(result)->is_shared()) {
3352 Map::cast(result)->SharedMapVerify();
3353 }
Kristian Monsen80d68ea2010-09-08 11:05:35 +01003354#endif
3355
3356 return result;
3357}
3358
3359
John Reck59135872010-11-02 12:39:01 -07003360MaybeObject* Map::CopyDropTransitions() {
3361 Object* new_map;
3362 { MaybeObject* maybe_new_map = CopyDropDescriptors();
3363 if (!maybe_new_map->ToObject(&new_map)) return maybe_new_map;
3364 }
3365 Object* descriptors;
3366 { MaybeObject* maybe_descriptors =
3367 instance_descriptors()->RemoveTransitions();
3368 if (!maybe_descriptors->ToObject(&descriptors)) return maybe_descriptors;
3369 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003370 cast(new_map)->set_instance_descriptors(DescriptorArray::cast(descriptors));
Steve Block8defd9f2010-07-08 12:39:36 +01003371 return new_map;
Steve Blocka7e24c12009-10-30 11:49:00 +00003372}
3373
3374
John Reck59135872010-11-02 12:39:01 -07003375MaybeObject* Map::UpdateCodeCache(String* name, Code* code) {
Steve Block6ded16b2010-05-10 14:33:55 +01003376 // Allocate the code cache if not present.
3377 if (code_cache()->IsFixedArray()) {
John Reck59135872010-11-02 12:39:01 -07003378 Object* result;
3379 { MaybeObject* maybe_result = Heap::AllocateCodeCache();
3380 if (!maybe_result->ToObject(&result)) return maybe_result;
3381 }
Steve Block6ded16b2010-05-10 14:33:55 +01003382 set_code_cache(result);
3383 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003384
Steve Block6ded16b2010-05-10 14:33:55 +01003385 // Update the code cache.
3386 return CodeCache::cast(code_cache())->Update(name, code);
3387}
3388
3389
3390Object* Map::FindInCodeCache(String* name, Code::Flags flags) {
3391 // Do a lookup if a code cache exists.
3392 if (!code_cache()->IsFixedArray()) {
3393 return CodeCache::cast(code_cache())->Lookup(name, flags);
3394 } else {
3395 return Heap::undefined_value();
3396 }
3397}
3398
3399
3400int Map::IndexInCodeCache(Object* name, Code* code) {
3401 // Get the internal index if a code cache exists.
3402 if (!code_cache()->IsFixedArray()) {
3403 return CodeCache::cast(code_cache())->GetIndex(name, code);
3404 }
3405 return -1;
3406}
3407
3408
3409void Map::RemoveFromCodeCache(String* name, Code* code, int index) {
3410 // No GC is supposed to happen between a call to IndexInCodeCache and
3411 // RemoveFromCodeCache so the code cache must be there.
3412 ASSERT(!code_cache()->IsFixedArray());
3413 CodeCache::cast(code_cache())->RemoveByIndex(name, code, index);
3414}
3415
3416
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003417void Map::TraverseTransitionTree(TraverseCallback callback, void* data) {
3418 Map* current = this;
3419 while (current != Heap::meta_map()) {
3420 DescriptorArray* d = reinterpret_cast<DescriptorArray*>(
3421 *RawField(current, Map::kInstanceDescriptorsOffset));
3422 if (d == Heap::empty_descriptor_array()) {
3423 Map* prev = current->map();
3424 current->set_map(Heap::meta_map());
3425 callback(current, data);
3426 current = prev;
3427 continue;
3428 }
3429
3430 FixedArray* contents = reinterpret_cast<FixedArray*>(
3431 d->get(DescriptorArray::kContentArrayIndex));
3432 Object** map_or_index_field = RawField(contents, HeapObject::kMapOffset);
3433 Object* map_or_index = *map_or_index_field;
3434 bool map_done = true;
3435 for (int i = map_or_index->IsSmi() ? Smi::cast(map_or_index)->value() : 0;
3436 i < contents->length();
3437 i += 2) {
3438 PropertyDetails details(Smi::cast(contents->get(i + 1)));
3439 if (details.IsTransition()) {
3440 Map* next = reinterpret_cast<Map*>(contents->get(i));
3441 next->set_map(current);
3442 *map_or_index_field = Smi::FromInt(i + 2);
3443 current = next;
3444 map_done = false;
3445 break;
3446 }
3447 }
3448 if (!map_done) continue;
3449 *map_or_index_field = Heap::fixed_array_map();
3450 Map* prev = current->map();
3451 current->set_map(Heap::meta_map());
3452 callback(current, data);
3453 current = prev;
3454 }
3455}
3456
3457
John Reck59135872010-11-02 12:39:01 -07003458MaybeObject* CodeCache::Update(String* name, Code* code) {
Steve Block6ded16b2010-05-10 14:33:55 +01003459 ASSERT(code->ic_state() == MONOMORPHIC);
3460
3461 // The number of monomorphic stubs for normal load/store/call IC's can grow to
3462 // a large number and therefore they need to go into a hash table. They are
3463 // used to load global properties from cells.
3464 if (code->type() == NORMAL) {
3465 // Make sure that a hash table is allocated for the normal load code cache.
3466 if (normal_type_cache()->IsUndefined()) {
John Reck59135872010-11-02 12:39:01 -07003467 Object* result;
3468 { MaybeObject* maybe_result =
3469 CodeCacheHashTable::Allocate(CodeCacheHashTable::kInitialSize);
3470 if (!maybe_result->ToObject(&result)) return maybe_result;
3471 }
Steve Block6ded16b2010-05-10 14:33:55 +01003472 set_normal_type_cache(result);
3473 }
3474 return UpdateNormalTypeCache(name, code);
3475 } else {
3476 ASSERT(default_cache()->IsFixedArray());
3477 return UpdateDefaultCache(name, code);
3478 }
3479}
3480
3481
John Reck59135872010-11-02 12:39:01 -07003482MaybeObject* CodeCache::UpdateDefaultCache(String* name, Code* code) {
Steve Block6ded16b2010-05-10 14:33:55 +01003483 // When updating the default code cache we disregard the type encoded in the
Steve Blocka7e24c12009-10-30 11:49:00 +00003484 // flags. This allows call constant stubs to overwrite call field
3485 // stubs, etc.
3486 Code::Flags flags = Code::RemoveTypeFromFlags(code->flags());
3487
3488 // First check whether we can update existing code cache without
3489 // extending it.
Steve Block6ded16b2010-05-10 14:33:55 +01003490 FixedArray* cache = default_cache();
Steve Blocka7e24c12009-10-30 11:49:00 +00003491 int length = cache->length();
3492 int deleted_index = -1;
Steve Block6ded16b2010-05-10 14:33:55 +01003493 for (int i = 0; i < length; i += kCodeCacheEntrySize) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003494 Object* key = cache->get(i);
3495 if (key->IsNull()) {
3496 if (deleted_index < 0) deleted_index = i;
3497 continue;
3498 }
3499 if (key->IsUndefined()) {
3500 if (deleted_index >= 0) i = deleted_index;
Steve Block6ded16b2010-05-10 14:33:55 +01003501 cache->set(i + kCodeCacheEntryNameOffset, name);
3502 cache->set(i + kCodeCacheEntryCodeOffset, code);
Steve Blocka7e24c12009-10-30 11:49:00 +00003503 return this;
3504 }
3505 if (name->Equals(String::cast(key))) {
Steve Block6ded16b2010-05-10 14:33:55 +01003506 Code::Flags found =
3507 Code::cast(cache->get(i + kCodeCacheEntryCodeOffset))->flags();
Steve Blocka7e24c12009-10-30 11:49:00 +00003508 if (Code::RemoveTypeFromFlags(found) == flags) {
Steve Block6ded16b2010-05-10 14:33:55 +01003509 cache->set(i + kCodeCacheEntryCodeOffset, code);
Steve Blocka7e24c12009-10-30 11:49:00 +00003510 return this;
3511 }
3512 }
3513 }
3514
3515 // Reached the end of the code cache. If there were deleted
3516 // elements, reuse the space for the first of them.
3517 if (deleted_index >= 0) {
Steve Block6ded16b2010-05-10 14:33:55 +01003518 cache->set(deleted_index + kCodeCacheEntryNameOffset, name);
3519 cache->set(deleted_index + kCodeCacheEntryCodeOffset, code);
Steve Blocka7e24c12009-10-30 11:49:00 +00003520 return this;
3521 }
3522
Steve Block6ded16b2010-05-10 14:33:55 +01003523 // Extend the code cache with some new entries (at least one). Must be a
3524 // multiple of the entry size.
3525 int new_length = length + ((length >> 1)) + kCodeCacheEntrySize;
3526 new_length = new_length - new_length % kCodeCacheEntrySize;
3527 ASSERT((new_length % kCodeCacheEntrySize) == 0);
John Reck59135872010-11-02 12:39:01 -07003528 Object* result;
3529 { MaybeObject* maybe_result = cache->CopySize(new_length);
3530 if (!maybe_result->ToObject(&result)) return maybe_result;
3531 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003532
3533 // Add the (name, code) pair to the new cache.
3534 cache = FixedArray::cast(result);
Steve Block6ded16b2010-05-10 14:33:55 +01003535 cache->set(length + kCodeCacheEntryNameOffset, name);
3536 cache->set(length + kCodeCacheEntryCodeOffset, code);
3537 set_default_cache(cache);
Steve Blocka7e24c12009-10-30 11:49:00 +00003538 return this;
3539}
3540
3541
John Reck59135872010-11-02 12:39:01 -07003542MaybeObject* CodeCache::UpdateNormalTypeCache(String* name, Code* code) {
Steve Block6ded16b2010-05-10 14:33:55 +01003543 // Adding a new entry can cause a new cache to be allocated.
3544 CodeCacheHashTable* cache = CodeCacheHashTable::cast(normal_type_cache());
John Reck59135872010-11-02 12:39:01 -07003545 Object* new_cache;
3546 { MaybeObject* maybe_new_cache = cache->Put(name, code);
3547 if (!maybe_new_cache->ToObject(&new_cache)) return maybe_new_cache;
3548 }
Steve Block6ded16b2010-05-10 14:33:55 +01003549 set_normal_type_cache(new_cache);
3550 return this;
3551}
3552
3553
3554Object* CodeCache::Lookup(String* name, Code::Flags flags) {
3555 if (Code::ExtractTypeFromFlags(flags) == NORMAL) {
3556 return LookupNormalTypeCache(name, flags);
3557 } else {
3558 return LookupDefaultCache(name, flags);
3559 }
3560}
3561
3562
3563Object* CodeCache::LookupDefaultCache(String* name, Code::Flags flags) {
3564 FixedArray* cache = default_cache();
Steve Blocka7e24c12009-10-30 11:49:00 +00003565 int length = cache->length();
Steve Block6ded16b2010-05-10 14:33:55 +01003566 for (int i = 0; i < length; i += kCodeCacheEntrySize) {
3567 Object* key = cache->get(i + kCodeCacheEntryNameOffset);
Steve Blocka7e24c12009-10-30 11:49:00 +00003568 // Skip deleted elements.
3569 if (key->IsNull()) continue;
3570 if (key->IsUndefined()) return key;
3571 if (name->Equals(String::cast(key))) {
Steve Block6ded16b2010-05-10 14:33:55 +01003572 Code* code = Code::cast(cache->get(i + kCodeCacheEntryCodeOffset));
3573 if (code->flags() == flags) {
3574 return code;
3575 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003576 }
3577 }
3578 return Heap::undefined_value();
3579}
3580
3581
Steve Block6ded16b2010-05-10 14:33:55 +01003582Object* CodeCache::LookupNormalTypeCache(String* name, Code::Flags flags) {
3583 if (!normal_type_cache()->IsUndefined()) {
3584 CodeCacheHashTable* cache = CodeCacheHashTable::cast(normal_type_cache());
3585 return cache->Lookup(name, flags);
3586 } else {
3587 return Heap::undefined_value();
3588 }
3589}
3590
3591
3592int CodeCache::GetIndex(Object* name, Code* code) {
3593 if (code->type() == NORMAL) {
3594 if (normal_type_cache()->IsUndefined()) return -1;
3595 CodeCacheHashTable* cache = CodeCacheHashTable::cast(normal_type_cache());
3596 return cache->GetIndex(String::cast(name), code->flags());
3597 }
3598
3599 FixedArray* array = default_cache();
Steve Blocka7e24c12009-10-30 11:49:00 +00003600 int len = array->length();
Steve Block6ded16b2010-05-10 14:33:55 +01003601 for (int i = 0; i < len; i += kCodeCacheEntrySize) {
3602 if (array->get(i + kCodeCacheEntryCodeOffset) == code) return i + 1;
Steve Blocka7e24c12009-10-30 11:49:00 +00003603 }
3604 return -1;
3605}
3606
3607
Steve Block6ded16b2010-05-10 14:33:55 +01003608void CodeCache::RemoveByIndex(Object* name, Code* code, int index) {
3609 if (code->type() == NORMAL) {
3610 ASSERT(!normal_type_cache()->IsUndefined());
3611 CodeCacheHashTable* cache = CodeCacheHashTable::cast(normal_type_cache());
3612 ASSERT(cache->GetIndex(String::cast(name), code->flags()) == index);
3613 cache->RemoveByIndex(index);
3614 } else {
3615 FixedArray* array = default_cache();
3616 ASSERT(array->length() >= index && array->get(index)->IsCode());
3617 // Use null instead of undefined for deleted elements to distinguish
3618 // deleted elements from unused elements. This distinction is used
3619 // when looking up in the cache and when updating the cache.
3620 ASSERT_EQ(1, kCodeCacheEntryCodeOffset - kCodeCacheEntryNameOffset);
3621 array->set_null(index - 1); // Name.
3622 array->set_null(index); // Code.
3623 }
3624}
3625
3626
3627// The key in the code cache hash table consists of the property name and the
3628// code object. The actual match is on the name and the code flags. If a key
3629// is created using the flags and not a code object it can only be used for
3630// lookup not to create a new entry.
3631class CodeCacheHashTableKey : public HashTableKey {
3632 public:
3633 CodeCacheHashTableKey(String* name, Code::Flags flags)
3634 : name_(name), flags_(flags), code_(NULL) { }
3635
3636 CodeCacheHashTableKey(String* name, Code* code)
3637 : name_(name),
3638 flags_(code->flags()),
3639 code_(code) { }
3640
3641
3642 bool IsMatch(Object* other) {
3643 if (!other->IsFixedArray()) return false;
3644 FixedArray* pair = FixedArray::cast(other);
3645 String* name = String::cast(pair->get(0));
3646 Code::Flags flags = Code::cast(pair->get(1))->flags();
3647 if (flags != flags_) {
3648 return false;
3649 }
3650 return name_->Equals(name);
3651 }
3652
3653 static uint32_t NameFlagsHashHelper(String* name, Code::Flags flags) {
3654 return name->Hash() ^ flags;
3655 }
3656
3657 uint32_t Hash() { return NameFlagsHashHelper(name_, flags_); }
3658
3659 uint32_t HashForObject(Object* obj) {
3660 FixedArray* pair = FixedArray::cast(obj);
3661 String* name = String::cast(pair->get(0));
3662 Code* code = Code::cast(pair->get(1));
3663 return NameFlagsHashHelper(name, code->flags());
3664 }
3665
John Reck59135872010-11-02 12:39:01 -07003666 MUST_USE_RESULT MaybeObject* AsObject() {
Steve Block6ded16b2010-05-10 14:33:55 +01003667 ASSERT(code_ != NULL);
John Reck59135872010-11-02 12:39:01 -07003668 Object* obj;
3669 { MaybeObject* maybe_obj = Heap::AllocateFixedArray(2);
3670 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
3671 }
Steve Block6ded16b2010-05-10 14:33:55 +01003672 FixedArray* pair = FixedArray::cast(obj);
3673 pair->set(0, name_);
3674 pair->set(1, code_);
3675 return pair;
3676 }
3677
3678 private:
3679 String* name_;
3680 Code::Flags flags_;
3681 Code* code_;
3682};
3683
3684
3685Object* CodeCacheHashTable::Lookup(String* name, Code::Flags flags) {
3686 CodeCacheHashTableKey key(name, flags);
3687 int entry = FindEntry(&key);
3688 if (entry == kNotFound) return Heap::undefined_value();
3689 return get(EntryToIndex(entry) + 1);
3690}
3691
3692
John Reck59135872010-11-02 12:39:01 -07003693MaybeObject* CodeCacheHashTable::Put(String* name, Code* code) {
Steve Block6ded16b2010-05-10 14:33:55 +01003694 CodeCacheHashTableKey key(name, code);
John Reck59135872010-11-02 12:39:01 -07003695 Object* obj;
3696 { MaybeObject* maybe_obj = EnsureCapacity(1, &key);
3697 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
3698 }
Steve Block6ded16b2010-05-10 14:33:55 +01003699
3700 // Don't use this, as the table might have grown.
3701 CodeCacheHashTable* cache = reinterpret_cast<CodeCacheHashTable*>(obj);
3702
3703 int entry = cache->FindInsertionEntry(key.Hash());
John Reck59135872010-11-02 12:39:01 -07003704 Object* k;
3705 { MaybeObject* maybe_k = key.AsObject();
3706 if (!maybe_k->ToObject(&k)) return maybe_k;
3707 }
Steve Block6ded16b2010-05-10 14:33:55 +01003708
3709 cache->set(EntryToIndex(entry), k);
3710 cache->set(EntryToIndex(entry) + 1, code);
3711 cache->ElementAdded();
3712 return cache;
3713}
3714
3715
3716int CodeCacheHashTable::GetIndex(String* name, Code::Flags flags) {
3717 CodeCacheHashTableKey key(name, flags);
3718 int entry = FindEntry(&key);
3719 return (entry == kNotFound) ? -1 : entry;
3720}
3721
3722
3723void CodeCacheHashTable::RemoveByIndex(int index) {
3724 ASSERT(index >= 0);
3725 set(EntryToIndex(index), Heap::null_value());
3726 set(EntryToIndex(index) + 1, Heap::null_value());
3727 ElementRemoved();
Steve Blocka7e24c12009-10-30 11:49:00 +00003728}
3729
3730
Steve Blocka7e24c12009-10-30 11:49:00 +00003731static bool HasKey(FixedArray* array, Object* key) {
3732 int len0 = array->length();
3733 for (int i = 0; i < len0; i++) {
3734 Object* element = array->get(i);
3735 if (element->IsSmi() && key->IsSmi() && (element == key)) return true;
3736 if (element->IsString() &&
3737 key->IsString() && String::cast(element)->Equals(String::cast(key))) {
3738 return true;
3739 }
3740 }
3741 return false;
3742}
3743
3744
John Reck59135872010-11-02 12:39:01 -07003745MaybeObject* FixedArray::AddKeysFromJSArray(JSArray* array) {
Steve Block3ce2e202009-11-05 08:53:23 +00003746 ASSERT(!array->HasPixelElements() && !array->HasExternalArrayElements());
Steve Blocka7e24c12009-10-30 11:49:00 +00003747 switch (array->GetElementsKind()) {
3748 case JSObject::FAST_ELEMENTS:
3749 return UnionOfKeys(FixedArray::cast(array->elements()));
3750 case JSObject::DICTIONARY_ELEMENTS: {
3751 NumberDictionary* dict = array->element_dictionary();
3752 int size = dict->NumberOfElements();
3753
3754 // Allocate a temporary fixed array.
John Reck59135872010-11-02 12:39:01 -07003755 Object* object;
3756 { MaybeObject* maybe_object = Heap::AllocateFixedArray(size);
3757 if (!maybe_object->ToObject(&object)) return maybe_object;
3758 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003759 FixedArray* key_array = FixedArray::cast(object);
3760
3761 int capacity = dict->Capacity();
3762 int pos = 0;
3763 // Copy the elements from the JSArray to the temporary fixed array.
3764 for (int i = 0; i < capacity; i++) {
3765 if (dict->IsKey(dict->KeyAt(i))) {
3766 key_array->set(pos++, dict->ValueAt(i));
3767 }
3768 }
3769 // Compute the union of this and the temporary fixed array.
3770 return UnionOfKeys(key_array);
3771 }
3772 default:
3773 UNREACHABLE();
3774 }
3775 UNREACHABLE();
3776 return Heap::null_value(); // Failure case needs to "return" a value.
3777}
3778
3779
John Reck59135872010-11-02 12:39:01 -07003780MaybeObject* FixedArray::UnionOfKeys(FixedArray* other) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003781 int len0 = length();
Ben Murdochf87a2032010-10-22 12:50:53 +01003782#ifdef DEBUG
3783 if (FLAG_enable_slow_asserts) {
3784 for (int i = 0; i < len0; i++) {
3785 ASSERT(get(i)->IsString() || get(i)->IsNumber());
3786 }
3787 }
3788#endif
Steve Blocka7e24c12009-10-30 11:49:00 +00003789 int len1 = other->length();
Ben Murdochf87a2032010-10-22 12:50:53 +01003790 // Optimize if 'other' is empty.
3791 // We cannot optimize if 'this' is empty, as other may have holes
3792 // or non keys.
Steve Blocka7e24c12009-10-30 11:49:00 +00003793 if (len1 == 0) return this;
3794
3795 // Compute how many elements are not in this.
3796 int extra = 0;
3797 for (int y = 0; y < len1; y++) {
3798 Object* value = other->get(y);
3799 if (!value->IsTheHole() && !HasKey(this, value)) extra++;
3800 }
3801
3802 if (extra == 0) return this;
3803
3804 // Allocate the result
John Reck59135872010-11-02 12:39:01 -07003805 Object* obj;
3806 { MaybeObject* maybe_obj = Heap::AllocateFixedArray(len0 + extra);
3807 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
3808 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003809 // Fill in the content
Leon Clarke4515c472010-02-03 11:58:03 +00003810 AssertNoAllocation no_gc;
Steve Blocka7e24c12009-10-30 11:49:00 +00003811 FixedArray* result = FixedArray::cast(obj);
Leon Clarke4515c472010-02-03 11:58:03 +00003812 WriteBarrierMode mode = result->GetWriteBarrierMode(no_gc);
Steve Blocka7e24c12009-10-30 11:49:00 +00003813 for (int i = 0; i < len0; i++) {
Ben Murdochf87a2032010-10-22 12:50:53 +01003814 Object* e = get(i);
3815 ASSERT(e->IsString() || e->IsNumber());
3816 result->set(i, e, mode);
Steve Blocka7e24c12009-10-30 11:49:00 +00003817 }
3818 // Fill in the extra keys.
3819 int index = 0;
3820 for (int y = 0; y < len1; y++) {
3821 Object* value = other->get(y);
3822 if (!value->IsTheHole() && !HasKey(this, value)) {
Ben Murdochf87a2032010-10-22 12:50:53 +01003823 Object* e = other->get(y);
3824 ASSERT(e->IsString() || e->IsNumber());
3825 result->set(len0 + index, e, mode);
Steve Blocka7e24c12009-10-30 11:49:00 +00003826 index++;
3827 }
3828 }
3829 ASSERT(extra == index);
3830 return result;
3831}
3832
3833
John Reck59135872010-11-02 12:39:01 -07003834MaybeObject* FixedArray::CopySize(int new_length) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003835 if (new_length == 0) return Heap::empty_fixed_array();
John Reck59135872010-11-02 12:39:01 -07003836 Object* obj;
3837 { MaybeObject* maybe_obj = Heap::AllocateFixedArray(new_length);
3838 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
3839 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003840 FixedArray* result = FixedArray::cast(obj);
3841 // Copy the content
Leon Clarke4515c472010-02-03 11:58:03 +00003842 AssertNoAllocation no_gc;
Steve Blocka7e24c12009-10-30 11:49:00 +00003843 int len = length();
3844 if (new_length < len) len = new_length;
3845 result->set_map(map());
Leon Clarke4515c472010-02-03 11:58:03 +00003846 WriteBarrierMode mode = result->GetWriteBarrierMode(no_gc);
Steve Blocka7e24c12009-10-30 11:49:00 +00003847 for (int i = 0; i < len; i++) {
3848 result->set(i, get(i), mode);
3849 }
3850 return result;
3851}
3852
3853
3854void FixedArray::CopyTo(int pos, FixedArray* dest, int dest_pos, int len) {
Leon Clarke4515c472010-02-03 11:58:03 +00003855 AssertNoAllocation no_gc;
3856 WriteBarrierMode mode = dest->GetWriteBarrierMode(no_gc);
Steve Blocka7e24c12009-10-30 11:49:00 +00003857 for (int index = 0; index < len; index++) {
3858 dest->set(dest_pos+index, get(pos+index), mode);
3859 }
3860}
3861
3862
3863#ifdef DEBUG
3864bool FixedArray::IsEqualTo(FixedArray* other) {
3865 if (length() != other->length()) return false;
3866 for (int i = 0 ; i < length(); ++i) {
3867 if (get(i) != other->get(i)) return false;
3868 }
3869 return true;
3870}
3871#endif
3872
3873
John Reck59135872010-11-02 12:39:01 -07003874MaybeObject* DescriptorArray::Allocate(int number_of_descriptors) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003875 if (number_of_descriptors == 0) {
3876 return Heap::empty_descriptor_array();
3877 }
3878 // Allocate the array of keys.
John Reck59135872010-11-02 12:39:01 -07003879 Object* array;
3880 { MaybeObject* maybe_array =
3881 Heap::AllocateFixedArray(ToKeyIndex(number_of_descriptors));
3882 if (!maybe_array->ToObject(&array)) return maybe_array;
3883 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003884 // Do not use DescriptorArray::cast on incomplete object.
3885 FixedArray* result = FixedArray::cast(array);
3886
3887 // Allocate the content array and set it in the descriptor array.
John Reck59135872010-11-02 12:39:01 -07003888 { MaybeObject* maybe_array =
3889 Heap::AllocateFixedArray(number_of_descriptors << 1);
3890 if (!maybe_array->ToObject(&array)) return maybe_array;
3891 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003892 result->set(kContentArrayIndex, array);
3893 result->set(kEnumerationIndexIndex,
Leon Clarke4515c472010-02-03 11:58:03 +00003894 Smi::FromInt(PropertyDetails::kInitialIndex));
Steve Blocka7e24c12009-10-30 11:49:00 +00003895 return result;
3896}
3897
3898
3899void DescriptorArray::SetEnumCache(FixedArray* bridge_storage,
3900 FixedArray* new_cache) {
3901 ASSERT(bridge_storage->length() >= kEnumCacheBridgeLength);
3902 if (HasEnumCache()) {
3903 FixedArray::cast(get(kEnumerationIndexIndex))->
3904 set(kEnumCacheBridgeCacheIndex, new_cache);
3905 } else {
3906 if (IsEmpty()) return; // Do nothing for empty descriptor array.
3907 FixedArray::cast(bridge_storage)->
3908 set(kEnumCacheBridgeCacheIndex, new_cache);
3909 fast_set(FixedArray::cast(bridge_storage),
3910 kEnumCacheBridgeEnumIndex,
3911 get(kEnumerationIndexIndex));
3912 set(kEnumerationIndexIndex, bridge_storage);
3913 }
3914}
3915
3916
John Reck59135872010-11-02 12:39:01 -07003917MaybeObject* DescriptorArray::CopyInsert(Descriptor* descriptor,
3918 TransitionFlag transition_flag) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003919 // Transitions are only kept when inserting another transition.
3920 // This precondition is not required by this function's implementation, but
3921 // is currently required by the semantics of maps, so we check it.
3922 // Conversely, we filter after replacing, so replacing a transition and
3923 // removing all other transitions is not supported.
3924 bool remove_transitions = transition_flag == REMOVE_TRANSITIONS;
3925 ASSERT(remove_transitions == !descriptor->GetDetails().IsTransition());
3926 ASSERT(descriptor->GetDetails().type() != NULL_DESCRIPTOR);
3927
3928 // Ensure the key is a symbol.
John Reck59135872010-11-02 12:39:01 -07003929 Object* result;
3930 { MaybeObject* maybe_result = descriptor->KeyToSymbol();
3931 if (!maybe_result->ToObject(&result)) return maybe_result;
3932 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003933
3934 int transitions = 0;
3935 int null_descriptors = 0;
3936 if (remove_transitions) {
3937 for (int i = 0; i < number_of_descriptors(); i++) {
3938 if (IsTransition(i)) transitions++;
3939 if (IsNullDescriptor(i)) null_descriptors++;
3940 }
3941 } else {
3942 for (int i = 0; i < number_of_descriptors(); i++) {
3943 if (IsNullDescriptor(i)) null_descriptors++;
3944 }
3945 }
3946 int new_size = number_of_descriptors() - transitions - null_descriptors;
3947
3948 // If key is in descriptor, we replace it in-place when filtering.
3949 // Count a null descriptor for key as inserted, not replaced.
3950 int index = Search(descriptor->GetKey());
3951 const bool inserting = (index == kNotFound);
3952 const bool replacing = !inserting;
3953 bool keep_enumeration_index = false;
3954 if (inserting) {
3955 ++new_size;
3956 }
3957 if (replacing) {
3958 // We are replacing an existing descriptor. We keep the enumeration
3959 // index of a visible property.
3960 PropertyType t = PropertyDetails(GetDetails(index)).type();
3961 if (t == CONSTANT_FUNCTION ||
3962 t == FIELD ||
3963 t == CALLBACKS ||
3964 t == INTERCEPTOR) {
3965 keep_enumeration_index = true;
3966 } else if (remove_transitions) {
3967 // Replaced descriptor has been counted as removed if it is
3968 // a transition that will be replaced. Adjust count in this case.
3969 ++new_size;
3970 }
3971 }
John Reck59135872010-11-02 12:39:01 -07003972 { MaybeObject* maybe_result = Allocate(new_size);
3973 if (!maybe_result->ToObject(&result)) return maybe_result;
3974 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003975 DescriptorArray* new_descriptors = DescriptorArray::cast(result);
3976 // Set the enumeration index in the descriptors and set the enumeration index
3977 // in the result.
3978 int enumeration_index = NextEnumerationIndex();
3979 if (!descriptor->GetDetails().IsTransition()) {
3980 if (keep_enumeration_index) {
3981 descriptor->SetEnumerationIndex(
3982 PropertyDetails(GetDetails(index)).index());
3983 } else {
3984 descriptor->SetEnumerationIndex(enumeration_index);
3985 ++enumeration_index;
3986 }
3987 }
3988 new_descriptors->SetNextEnumerationIndex(enumeration_index);
3989
3990 // Copy the descriptors, filtering out transitions and null descriptors,
3991 // and inserting or replacing a descriptor.
3992 uint32_t descriptor_hash = descriptor->GetKey()->Hash();
3993 int from_index = 0;
3994 int to_index = 0;
3995
3996 for (; from_index < number_of_descriptors(); from_index++) {
3997 String* key = GetKey(from_index);
3998 if (key->Hash() > descriptor_hash || key == descriptor->GetKey()) {
3999 break;
4000 }
4001 if (IsNullDescriptor(from_index)) continue;
4002 if (remove_transitions && IsTransition(from_index)) continue;
4003 new_descriptors->CopyFrom(to_index++, this, from_index);
4004 }
4005
4006 new_descriptors->Set(to_index++, descriptor);
4007 if (replacing) from_index++;
4008
4009 for (; from_index < number_of_descriptors(); from_index++) {
4010 if (IsNullDescriptor(from_index)) continue;
4011 if (remove_transitions && IsTransition(from_index)) continue;
4012 new_descriptors->CopyFrom(to_index++, this, from_index);
4013 }
4014
4015 ASSERT(to_index == new_descriptors->number_of_descriptors());
4016 SLOW_ASSERT(new_descriptors->IsSortedNoDuplicates());
4017
4018 return new_descriptors;
4019}
4020
4021
John Reck59135872010-11-02 12:39:01 -07004022MaybeObject* DescriptorArray::RemoveTransitions() {
Steve Blocka7e24c12009-10-30 11:49:00 +00004023 // Remove all transitions and null descriptors. Return a copy of the array
4024 // with all transitions removed, or a Failure object if the new array could
4025 // not be allocated.
4026
4027 // Compute the size of the map transition entries to be removed.
4028 int num_removed = 0;
4029 for (int i = 0; i < number_of_descriptors(); i++) {
4030 if (!IsProperty(i)) num_removed++;
4031 }
4032
4033 // Allocate the new descriptor array.
John Reck59135872010-11-02 12:39:01 -07004034 Object* result;
4035 { MaybeObject* maybe_result = Allocate(number_of_descriptors() - num_removed);
4036 if (!maybe_result->ToObject(&result)) return maybe_result;
4037 }
Steve Blocka7e24c12009-10-30 11:49:00 +00004038 DescriptorArray* new_descriptors = DescriptorArray::cast(result);
4039
4040 // Copy the content.
4041 int next_descriptor = 0;
4042 for (int i = 0; i < number_of_descriptors(); i++) {
4043 if (IsProperty(i)) new_descriptors->CopyFrom(next_descriptor++, this, i);
4044 }
4045 ASSERT(next_descriptor == new_descriptors->number_of_descriptors());
4046
4047 return new_descriptors;
4048}
4049
4050
Kristian Monsen0d5e1162010-09-30 15:31:59 +01004051void DescriptorArray::SortUnchecked() {
Steve Blocka7e24c12009-10-30 11:49:00 +00004052 // In-place heap sort.
4053 int len = number_of_descriptors();
4054
4055 // Bottom-up max-heap construction.
Steve Block6ded16b2010-05-10 14:33:55 +01004056 // Index of the last node with children
4057 const int max_parent_index = (len / 2) - 1;
4058 for (int i = max_parent_index; i >= 0; --i) {
4059 int parent_index = i;
4060 const uint32_t parent_hash = GetKey(i)->Hash();
4061 while (parent_index <= max_parent_index) {
4062 int child_index = 2 * parent_index + 1;
Steve Blocka7e24c12009-10-30 11:49:00 +00004063 uint32_t child_hash = GetKey(child_index)->Hash();
Steve Block6ded16b2010-05-10 14:33:55 +01004064 if (child_index + 1 < len) {
4065 uint32_t right_child_hash = GetKey(child_index + 1)->Hash();
4066 if (right_child_hash > child_hash) {
4067 child_index++;
4068 child_hash = right_child_hash;
4069 }
Steve Blocka7e24c12009-10-30 11:49:00 +00004070 }
Steve Block6ded16b2010-05-10 14:33:55 +01004071 if (child_hash <= parent_hash) break;
4072 Swap(parent_index, child_index);
4073 // Now element at child_index could be < its children.
4074 parent_index = child_index; // parent_hash remains correct.
Steve Blocka7e24c12009-10-30 11:49:00 +00004075 }
4076 }
4077
4078 // Extract elements and create sorted array.
4079 for (int i = len - 1; i > 0; --i) {
4080 // Put max element at the back of the array.
4081 Swap(0, i);
4082 // Sift down the new top element.
4083 int parent_index = 0;
Steve Block6ded16b2010-05-10 14:33:55 +01004084 const uint32_t parent_hash = GetKey(parent_index)->Hash();
4085 const int max_parent_index = (i / 2) - 1;
4086 while (parent_index <= max_parent_index) {
4087 int child_index = parent_index * 2 + 1;
4088 uint32_t child_hash = GetKey(child_index)->Hash();
4089 if (child_index + 1 < i) {
4090 uint32_t right_child_hash = GetKey(child_index + 1)->Hash();
4091 if (right_child_hash > child_hash) {
4092 child_index++;
4093 child_hash = right_child_hash;
4094 }
Steve Blocka7e24c12009-10-30 11:49:00 +00004095 }
Steve Block6ded16b2010-05-10 14:33:55 +01004096 if (child_hash <= parent_hash) break;
4097 Swap(parent_index, child_index);
4098 parent_index = child_index;
Steve Blocka7e24c12009-10-30 11:49:00 +00004099 }
4100 }
Kristian Monsen0d5e1162010-09-30 15:31:59 +01004101}
Steve Blocka7e24c12009-10-30 11:49:00 +00004102
Kristian Monsen0d5e1162010-09-30 15:31:59 +01004103
4104void DescriptorArray::Sort() {
4105 SortUnchecked();
Steve Blocka7e24c12009-10-30 11:49:00 +00004106 SLOW_ASSERT(IsSortedNoDuplicates());
4107}
4108
4109
4110int DescriptorArray::BinarySearch(String* name, int low, int high) {
4111 uint32_t hash = name->Hash();
4112
4113 while (low <= high) {
4114 int mid = (low + high) / 2;
4115 String* mid_name = GetKey(mid);
4116 uint32_t mid_hash = mid_name->Hash();
4117
4118 if (mid_hash > hash) {
4119 high = mid - 1;
4120 continue;
4121 }
4122 if (mid_hash < hash) {
4123 low = mid + 1;
4124 continue;
4125 }
4126 // Found an element with the same hash-code.
4127 ASSERT(hash == mid_hash);
4128 // There might be more, so we find the first one and
4129 // check them all to see if we have a match.
4130 if (name == mid_name && !is_null_descriptor(mid)) return mid;
4131 while ((mid > low) && (GetKey(mid - 1)->Hash() == hash)) mid--;
4132 for (; (mid <= high) && (GetKey(mid)->Hash() == hash); mid++) {
4133 if (GetKey(mid)->Equals(name) && !is_null_descriptor(mid)) return mid;
4134 }
4135 break;
4136 }
4137 return kNotFound;
4138}
4139
4140
4141int DescriptorArray::LinearSearch(String* name, int len) {
4142 uint32_t hash = name->Hash();
4143 for (int number = 0; number < len; number++) {
4144 String* entry = GetKey(number);
4145 if ((entry->Hash() == hash) &&
4146 name->Equals(entry) &&
4147 !is_null_descriptor(number)) {
4148 return number;
4149 }
4150 }
4151 return kNotFound;
4152}
4153
4154
Ben Murdochb0fe1622011-05-05 13:52:32 +01004155MaybeObject* DeoptimizationInputData::Allocate(int deopt_entry_count,
4156 PretenureFlag pretenure) {
4157 ASSERT(deopt_entry_count > 0);
4158 return Heap::AllocateFixedArray(LengthFor(deopt_entry_count),
4159 pretenure);
4160}
4161
4162
4163MaybeObject* DeoptimizationOutputData::Allocate(int number_of_deopt_points,
4164 PretenureFlag pretenure) {
4165 if (number_of_deopt_points == 0) return Heap::empty_fixed_array();
4166 return Heap::AllocateFixedArray(LengthOfFixedArray(number_of_deopt_points),
4167 pretenure);
4168}
4169
4170
Steve Blocka7e24c12009-10-30 11:49:00 +00004171#ifdef DEBUG
4172bool DescriptorArray::IsEqualTo(DescriptorArray* other) {
4173 if (IsEmpty()) return other->IsEmpty();
4174 if (other->IsEmpty()) return false;
4175 if (length() != other->length()) return false;
4176 for (int i = 0; i < length(); ++i) {
4177 if (get(i) != other->get(i) && i != kContentArrayIndex) return false;
4178 }
4179 return GetContentArray()->IsEqualTo(other->GetContentArray());
4180}
4181#endif
4182
4183
4184static StaticResource<StringInputBuffer> string_input_buffer;
4185
4186
4187bool String::LooksValid() {
4188 if (!Heap::Contains(this)) return false;
4189 return true;
4190}
4191
4192
4193int String::Utf8Length() {
4194 if (IsAsciiRepresentation()) return length();
4195 // Attempt to flatten before accessing the string. It probably
4196 // doesn't make Utf8Length faster, but it is very likely that
4197 // the string will be accessed later (for example by WriteUtf8)
4198 // so it's still a good idea.
Steve Block6ded16b2010-05-10 14:33:55 +01004199 TryFlatten();
Steve Blocka7e24c12009-10-30 11:49:00 +00004200 Access<StringInputBuffer> buffer(&string_input_buffer);
4201 buffer->Reset(0, this);
4202 int result = 0;
4203 while (buffer->has_more())
4204 result += unibrow::Utf8::Length(buffer->GetNext());
4205 return result;
4206}
4207
4208
4209Vector<const char> String::ToAsciiVector() {
4210 ASSERT(IsAsciiRepresentation());
4211 ASSERT(IsFlat());
4212
4213 int offset = 0;
4214 int length = this->length();
4215 StringRepresentationTag string_tag = StringShape(this).representation_tag();
4216 String* string = this;
Steve Blockd0582a62009-12-15 09:54:21 +00004217 if (string_tag == kConsStringTag) {
Steve Blocka7e24c12009-10-30 11:49:00 +00004218 ConsString* cons = ConsString::cast(string);
4219 ASSERT(cons->second()->length() == 0);
4220 string = cons->first();
4221 string_tag = StringShape(string).representation_tag();
4222 }
4223 if (string_tag == kSeqStringTag) {
4224 SeqAsciiString* seq = SeqAsciiString::cast(string);
4225 char* start = seq->GetChars();
4226 return Vector<const char>(start + offset, length);
4227 }
4228 ASSERT(string_tag == kExternalStringTag);
4229 ExternalAsciiString* ext = ExternalAsciiString::cast(string);
4230 const char* start = ext->resource()->data();
4231 return Vector<const char>(start + offset, length);
4232}
4233
4234
4235Vector<const uc16> String::ToUC16Vector() {
4236 ASSERT(IsTwoByteRepresentation());
4237 ASSERT(IsFlat());
4238
4239 int offset = 0;
4240 int length = this->length();
4241 StringRepresentationTag string_tag = StringShape(this).representation_tag();
4242 String* string = this;
Steve Blockd0582a62009-12-15 09:54:21 +00004243 if (string_tag == kConsStringTag) {
Steve Blocka7e24c12009-10-30 11:49:00 +00004244 ConsString* cons = ConsString::cast(string);
4245 ASSERT(cons->second()->length() == 0);
4246 string = cons->first();
4247 string_tag = StringShape(string).representation_tag();
4248 }
4249 if (string_tag == kSeqStringTag) {
4250 SeqTwoByteString* seq = SeqTwoByteString::cast(string);
4251 return Vector<const uc16>(seq->GetChars() + offset, length);
4252 }
4253 ASSERT(string_tag == kExternalStringTag);
4254 ExternalTwoByteString* ext = ExternalTwoByteString::cast(string);
4255 const uc16* start =
4256 reinterpret_cast<const uc16*>(ext->resource()->data());
4257 return Vector<const uc16>(start + offset, length);
4258}
4259
4260
4261SmartPointer<char> String::ToCString(AllowNullsFlag allow_nulls,
4262 RobustnessFlag robust_flag,
4263 int offset,
4264 int length,
4265 int* length_return) {
4266 ASSERT(NativeAllocationChecker::allocation_allowed());
4267 if (robust_flag == ROBUST_STRING_TRAVERSAL && !LooksValid()) {
4268 return SmartPointer<char>(NULL);
4269 }
4270
4271 // Negative length means the to the end of the string.
4272 if (length < 0) length = kMaxInt - offset;
4273
4274 // Compute the size of the UTF-8 string. Start at the specified offset.
4275 Access<StringInputBuffer> buffer(&string_input_buffer);
4276 buffer->Reset(offset, this);
4277 int character_position = offset;
4278 int utf8_bytes = 0;
4279 while (buffer->has_more()) {
4280 uint16_t character = buffer->GetNext();
4281 if (character_position < offset + length) {
4282 utf8_bytes += unibrow::Utf8::Length(character);
4283 }
4284 character_position++;
4285 }
4286
4287 if (length_return) {
4288 *length_return = utf8_bytes;
4289 }
4290
4291 char* result = NewArray<char>(utf8_bytes + 1);
4292
4293 // Convert the UTF-16 string to a UTF-8 buffer. Start at the specified offset.
4294 buffer->Rewind();
4295 buffer->Seek(offset);
4296 character_position = offset;
4297 int utf8_byte_position = 0;
4298 while (buffer->has_more()) {
4299 uint16_t character = buffer->GetNext();
4300 if (character_position < offset + length) {
4301 if (allow_nulls == DISALLOW_NULLS && character == 0) {
4302 character = ' ';
4303 }
4304 utf8_byte_position +=
4305 unibrow::Utf8::Encode(result + utf8_byte_position, character);
4306 }
4307 character_position++;
4308 }
4309 result[utf8_byte_position] = 0;
4310 return SmartPointer<char>(result);
4311}
4312
4313
4314SmartPointer<char> String::ToCString(AllowNullsFlag allow_nulls,
4315 RobustnessFlag robust_flag,
4316 int* length_return) {
4317 return ToCString(allow_nulls, robust_flag, 0, -1, length_return);
4318}
4319
4320
4321const uc16* String::GetTwoByteData() {
4322 return GetTwoByteData(0);
4323}
4324
4325
4326const uc16* String::GetTwoByteData(unsigned start) {
4327 ASSERT(!IsAsciiRepresentation());
4328 switch (StringShape(this).representation_tag()) {
4329 case kSeqStringTag:
4330 return SeqTwoByteString::cast(this)->SeqTwoByteStringGetData(start);
4331 case kExternalStringTag:
4332 return ExternalTwoByteString::cast(this)->
4333 ExternalTwoByteStringGetData(start);
Steve Blocka7e24c12009-10-30 11:49:00 +00004334 case kConsStringTag:
4335 UNREACHABLE();
4336 return NULL;
4337 }
4338 UNREACHABLE();
4339 return NULL;
4340}
4341
4342
4343SmartPointer<uc16> String::ToWideCString(RobustnessFlag robust_flag) {
4344 ASSERT(NativeAllocationChecker::allocation_allowed());
4345
4346 if (robust_flag == ROBUST_STRING_TRAVERSAL && !LooksValid()) {
4347 return SmartPointer<uc16>();
4348 }
4349
4350 Access<StringInputBuffer> buffer(&string_input_buffer);
4351 buffer->Reset(this);
4352
4353 uc16* result = NewArray<uc16>(length() + 1);
4354
4355 int i = 0;
4356 while (buffer->has_more()) {
4357 uint16_t character = buffer->GetNext();
4358 result[i++] = character;
4359 }
4360 result[i] = 0;
4361 return SmartPointer<uc16>(result);
4362}
4363
4364
4365const uc16* SeqTwoByteString::SeqTwoByteStringGetData(unsigned start) {
4366 return reinterpret_cast<uc16*>(
4367 reinterpret_cast<char*>(this) - kHeapObjectTag + kHeaderSize) + start;
4368}
4369
4370
4371void SeqTwoByteString::SeqTwoByteStringReadBlockIntoBuffer(ReadBlockBuffer* rbb,
4372 unsigned* offset_ptr,
4373 unsigned max_chars) {
4374 unsigned chars_read = 0;
4375 unsigned offset = *offset_ptr;
4376 while (chars_read < max_chars) {
4377 uint16_t c = *reinterpret_cast<uint16_t*>(
4378 reinterpret_cast<char*>(this) -
4379 kHeapObjectTag + kHeaderSize + offset * kShortSize);
4380 if (c <= kMaxAsciiCharCode) {
4381 // Fast case for ASCII characters. Cursor is an input output argument.
4382 if (!unibrow::CharacterStream::EncodeAsciiCharacter(c,
4383 rbb->util_buffer,
4384 rbb->capacity,
4385 rbb->cursor)) {
4386 break;
4387 }
4388 } else {
4389 if (!unibrow::CharacterStream::EncodeNonAsciiCharacter(c,
4390 rbb->util_buffer,
4391 rbb->capacity,
4392 rbb->cursor)) {
4393 break;
4394 }
4395 }
4396 offset++;
4397 chars_read++;
4398 }
4399 *offset_ptr = offset;
4400 rbb->remaining += chars_read;
4401}
4402
4403
4404const unibrow::byte* SeqAsciiString::SeqAsciiStringReadBlock(
4405 unsigned* remaining,
4406 unsigned* offset_ptr,
4407 unsigned max_chars) {
4408 const unibrow::byte* b = reinterpret_cast<unibrow::byte*>(this) -
4409 kHeapObjectTag + kHeaderSize + *offset_ptr * kCharSize;
4410 *remaining = max_chars;
4411 *offset_ptr += max_chars;
4412 return b;
4413}
4414
4415
4416// This will iterate unless the block of string data spans two 'halves' of
4417// a ConsString, in which case it will recurse. Since the block of string
4418// data to be read has a maximum size this limits the maximum recursion
4419// depth to something sane. Since C++ does not have tail call recursion
4420// elimination, the iteration must be explicit. Since this is not an
4421// -IntoBuffer method it can delegate to one of the efficient
4422// *AsciiStringReadBlock routines.
4423const unibrow::byte* ConsString::ConsStringReadBlock(ReadBlockBuffer* rbb,
4424 unsigned* offset_ptr,
4425 unsigned max_chars) {
4426 ConsString* current = this;
4427 unsigned offset = *offset_ptr;
4428 int offset_correction = 0;
4429
4430 while (true) {
4431 String* left = current->first();
4432 unsigned left_length = (unsigned)left->length();
4433 if (left_length > offset &&
4434 (max_chars <= left_length - offset ||
4435 (rbb->capacity <= left_length - offset &&
4436 (max_chars = left_length - offset, true)))) { // comma operator!
4437 // Left hand side only - iterate unless we have reached the bottom of
4438 // the cons tree. The assignment on the left of the comma operator is
4439 // in order to make use of the fact that the -IntoBuffer routines can
4440 // produce at most 'capacity' characters. This enables us to postpone
4441 // the point where we switch to the -IntoBuffer routines (below) in order
4442 // to maximize the chances of delegating a big chunk of work to the
4443 // efficient *AsciiStringReadBlock routines.
4444 if (StringShape(left).IsCons()) {
4445 current = ConsString::cast(left);
4446 continue;
4447 } else {
4448 const unibrow::byte* answer =
4449 String::ReadBlock(left, rbb, &offset, max_chars);
4450 *offset_ptr = offset + offset_correction;
4451 return answer;
4452 }
4453 } else if (left_length <= offset) {
4454 // Right hand side only - iterate unless we have reached the bottom of
4455 // the cons tree.
4456 String* right = current->second();
4457 offset -= left_length;
4458 offset_correction += left_length;
4459 if (StringShape(right).IsCons()) {
4460 current = ConsString::cast(right);
4461 continue;
4462 } else {
4463 const unibrow::byte* answer =
4464 String::ReadBlock(right, rbb, &offset, max_chars);
4465 *offset_ptr = offset + offset_correction;
4466 return answer;
4467 }
4468 } else {
4469 // The block to be read spans two sides of the ConsString, so we call the
4470 // -IntoBuffer version, which will recurse. The -IntoBuffer methods
4471 // are able to assemble data from several part strings because they use
4472 // the util_buffer to store their data and never return direct pointers
4473 // to their storage. We don't try to read more than the buffer capacity
4474 // here or we can get too much recursion.
4475 ASSERT(rbb->remaining == 0);
4476 ASSERT(rbb->cursor == 0);
4477 current->ConsStringReadBlockIntoBuffer(
4478 rbb,
4479 &offset,
4480 max_chars > rbb->capacity ? rbb->capacity : max_chars);
4481 *offset_ptr = offset + offset_correction;
4482 return rbb->util_buffer;
4483 }
4484 }
4485}
4486
4487
Steve Blocka7e24c12009-10-30 11:49:00 +00004488uint16_t ExternalAsciiString::ExternalAsciiStringGet(int index) {
4489 ASSERT(index >= 0 && index < length());
4490 return resource()->data()[index];
4491}
4492
4493
4494const unibrow::byte* ExternalAsciiString::ExternalAsciiStringReadBlock(
4495 unsigned* remaining,
4496 unsigned* offset_ptr,
4497 unsigned max_chars) {
4498 // Cast const char* to unibrow::byte* (signedness difference).
4499 const unibrow::byte* b =
4500 reinterpret_cast<const unibrow::byte*>(resource()->data()) + *offset_ptr;
4501 *remaining = max_chars;
4502 *offset_ptr += max_chars;
4503 return b;
4504}
4505
4506
4507const uc16* ExternalTwoByteString::ExternalTwoByteStringGetData(
4508 unsigned start) {
4509 return resource()->data() + start;
4510}
4511
4512
4513uint16_t ExternalTwoByteString::ExternalTwoByteStringGet(int index) {
4514 ASSERT(index >= 0 && index < length());
4515 return resource()->data()[index];
4516}
4517
4518
4519void ExternalTwoByteString::ExternalTwoByteStringReadBlockIntoBuffer(
4520 ReadBlockBuffer* rbb,
4521 unsigned* offset_ptr,
4522 unsigned max_chars) {
4523 unsigned chars_read = 0;
4524 unsigned offset = *offset_ptr;
4525 const uint16_t* data = resource()->data();
4526 while (chars_read < max_chars) {
4527 uint16_t c = data[offset];
4528 if (c <= kMaxAsciiCharCode) {
4529 // Fast case for ASCII characters. Cursor is an input output argument.
4530 if (!unibrow::CharacterStream::EncodeAsciiCharacter(c,
4531 rbb->util_buffer,
4532 rbb->capacity,
4533 rbb->cursor))
4534 break;
4535 } else {
4536 if (!unibrow::CharacterStream::EncodeNonAsciiCharacter(c,
4537 rbb->util_buffer,
4538 rbb->capacity,
4539 rbb->cursor))
4540 break;
4541 }
4542 offset++;
4543 chars_read++;
4544 }
4545 *offset_ptr = offset;
4546 rbb->remaining += chars_read;
4547}
4548
4549
4550void SeqAsciiString::SeqAsciiStringReadBlockIntoBuffer(ReadBlockBuffer* rbb,
4551 unsigned* offset_ptr,
4552 unsigned max_chars) {
4553 unsigned capacity = rbb->capacity - rbb->cursor;
4554 if (max_chars > capacity) max_chars = capacity;
4555 memcpy(rbb->util_buffer + rbb->cursor,
4556 reinterpret_cast<char*>(this) - kHeapObjectTag + kHeaderSize +
4557 *offset_ptr * kCharSize,
4558 max_chars);
4559 rbb->remaining += max_chars;
4560 *offset_ptr += max_chars;
4561 rbb->cursor += max_chars;
4562}
4563
4564
4565void ExternalAsciiString::ExternalAsciiStringReadBlockIntoBuffer(
4566 ReadBlockBuffer* rbb,
4567 unsigned* offset_ptr,
4568 unsigned max_chars) {
4569 unsigned capacity = rbb->capacity - rbb->cursor;
4570 if (max_chars > capacity) max_chars = capacity;
4571 memcpy(rbb->util_buffer + rbb->cursor,
4572 resource()->data() + *offset_ptr,
4573 max_chars);
4574 rbb->remaining += max_chars;
4575 *offset_ptr += max_chars;
4576 rbb->cursor += max_chars;
4577}
4578
4579
4580// This method determines the type of string involved and then copies
4581// a whole chunk of characters into a buffer, or returns a pointer to a buffer
4582// where they can be found. The pointer is not necessarily valid across a GC
4583// (see AsciiStringReadBlock).
4584const unibrow::byte* String::ReadBlock(String* input,
4585 ReadBlockBuffer* rbb,
4586 unsigned* offset_ptr,
4587 unsigned max_chars) {
4588 ASSERT(*offset_ptr <= static_cast<unsigned>(input->length()));
4589 if (max_chars == 0) {
4590 rbb->remaining = 0;
4591 return NULL;
4592 }
4593 switch (StringShape(input).representation_tag()) {
4594 case kSeqStringTag:
4595 if (input->IsAsciiRepresentation()) {
4596 SeqAsciiString* str = SeqAsciiString::cast(input);
4597 return str->SeqAsciiStringReadBlock(&rbb->remaining,
4598 offset_ptr,
4599 max_chars);
4600 } else {
4601 SeqTwoByteString* str = SeqTwoByteString::cast(input);
4602 str->SeqTwoByteStringReadBlockIntoBuffer(rbb,
4603 offset_ptr,
4604 max_chars);
4605 return rbb->util_buffer;
4606 }
4607 case kConsStringTag:
4608 return ConsString::cast(input)->ConsStringReadBlock(rbb,
4609 offset_ptr,
4610 max_chars);
Steve Blocka7e24c12009-10-30 11:49:00 +00004611 case kExternalStringTag:
4612 if (input->IsAsciiRepresentation()) {
4613 return ExternalAsciiString::cast(input)->ExternalAsciiStringReadBlock(
4614 &rbb->remaining,
4615 offset_ptr,
4616 max_chars);
4617 } else {
4618 ExternalTwoByteString::cast(input)->
4619 ExternalTwoByteStringReadBlockIntoBuffer(rbb,
4620 offset_ptr,
4621 max_chars);
4622 return rbb->util_buffer;
4623 }
4624 default:
4625 break;
4626 }
4627
4628 UNREACHABLE();
4629 return 0;
4630}
4631
4632
4633Relocatable* Relocatable::top_ = NULL;
4634
4635
4636void Relocatable::PostGarbageCollectionProcessing() {
4637 Relocatable* current = top_;
4638 while (current != NULL) {
4639 current->PostGarbageCollection();
4640 current = current->prev_;
4641 }
4642}
4643
4644
4645// Reserve space for statics needing saving and restoring.
4646int Relocatable::ArchiveSpacePerThread() {
4647 return sizeof(top_);
4648}
4649
4650
4651// Archive statics that are thread local.
4652char* Relocatable::ArchiveState(char* to) {
4653 *reinterpret_cast<Relocatable**>(to) = top_;
4654 top_ = NULL;
4655 return to + ArchiveSpacePerThread();
4656}
4657
4658
4659// Restore statics that are thread local.
4660char* Relocatable::RestoreState(char* from) {
4661 top_ = *reinterpret_cast<Relocatable**>(from);
4662 return from + ArchiveSpacePerThread();
4663}
4664
4665
4666char* Relocatable::Iterate(ObjectVisitor* v, char* thread_storage) {
4667 Relocatable* top = *reinterpret_cast<Relocatable**>(thread_storage);
4668 Iterate(v, top);
4669 return thread_storage + ArchiveSpacePerThread();
4670}
4671
4672
4673void Relocatable::Iterate(ObjectVisitor* v) {
4674 Iterate(v, top_);
4675}
4676
4677
4678void Relocatable::Iterate(ObjectVisitor* v, Relocatable* top) {
4679 Relocatable* current = top;
4680 while (current != NULL) {
4681 current->IterateInstance(v);
4682 current = current->prev_;
4683 }
4684}
4685
4686
4687FlatStringReader::FlatStringReader(Handle<String> str)
4688 : str_(str.location()),
4689 length_(str->length()) {
4690 PostGarbageCollection();
4691}
4692
4693
4694FlatStringReader::FlatStringReader(Vector<const char> input)
4695 : str_(0),
4696 is_ascii_(true),
4697 length_(input.length()),
4698 start_(input.start()) { }
4699
4700
4701void FlatStringReader::PostGarbageCollection() {
4702 if (str_ == NULL) return;
4703 Handle<String> str(str_);
4704 ASSERT(str->IsFlat());
4705 is_ascii_ = str->IsAsciiRepresentation();
4706 if (is_ascii_) {
4707 start_ = str->ToAsciiVector().start();
4708 } else {
4709 start_ = str->ToUC16Vector().start();
4710 }
4711}
4712
4713
4714void StringInputBuffer::Seek(unsigned pos) {
4715 Reset(pos, input_);
4716}
4717
4718
4719void SafeStringInputBuffer::Seek(unsigned pos) {
4720 Reset(pos, input_);
4721}
4722
4723
4724// This method determines the type of string involved and then copies
4725// a whole chunk of characters into a buffer. It can be used with strings
4726// that have been glued together to form a ConsString and which must cooperate
4727// to fill up a buffer.
4728void String::ReadBlockIntoBuffer(String* input,
4729 ReadBlockBuffer* rbb,
4730 unsigned* offset_ptr,
4731 unsigned max_chars) {
4732 ASSERT(*offset_ptr <= (unsigned)input->length());
4733 if (max_chars == 0) return;
4734
4735 switch (StringShape(input).representation_tag()) {
4736 case kSeqStringTag:
4737 if (input->IsAsciiRepresentation()) {
4738 SeqAsciiString::cast(input)->SeqAsciiStringReadBlockIntoBuffer(rbb,
4739 offset_ptr,
4740 max_chars);
4741 return;
4742 } else {
4743 SeqTwoByteString::cast(input)->SeqTwoByteStringReadBlockIntoBuffer(rbb,
4744 offset_ptr,
4745 max_chars);
4746 return;
4747 }
4748 case kConsStringTag:
4749 ConsString::cast(input)->ConsStringReadBlockIntoBuffer(rbb,
4750 offset_ptr,
4751 max_chars);
4752 return;
Steve Blocka7e24c12009-10-30 11:49:00 +00004753 case kExternalStringTag:
4754 if (input->IsAsciiRepresentation()) {
Steve Blockd0582a62009-12-15 09:54:21 +00004755 ExternalAsciiString::cast(input)->
4756 ExternalAsciiStringReadBlockIntoBuffer(rbb, offset_ptr, max_chars);
4757 } else {
4758 ExternalTwoByteString::cast(input)->
4759 ExternalTwoByteStringReadBlockIntoBuffer(rbb,
4760 offset_ptr,
4761 max_chars);
Steve Blocka7e24c12009-10-30 11:49:00 +00004762 }
4763 return;
4764 default:
4765 break;
4766 }
4767
4768 UNREACHABLE();
4769 return;
4770}
4771
4772
4773const unibrow::byte* String::ReadBlock(String* input,
4774 unibrow::byte* util_buffer,
4775 unsigned capacity,
4776 unsigned* remaining,
4777 unsigned* offset_ptr) {
4778 ASSERT(*offset_ptr <= (unsigned)input->length());
4779 unsigned chars = input->length() - *offset_ptr;
4780 ReadBlockBuffer rbb(util_buffer, 0, capacity, 0);
4781 const unibrow::byte* answer = ReadBlock(input, &rbb, offset_ptr, chars);
4782 ASSERT(rbb.remaining <= static_cast<unsigned>(input->length()));
4783 *remaining = rbb.remaining;
4784 return answer;
4785}
4786
4787
4788const unibrow::byte* String::ReadBlock(String** raw_input,
4789 unibrow::byte* util_buffer,
4790 unsigned capacity,
4791 unsigned* remaining,
4792 unsigned* offset_ptr) {
4793 Handle<String> input(raw_input);
4794 ASSERT(*offset_ptr <= (unsigned)input->length());
4795 unsigned chars = input->length() - *offset_ptr;
4796 if (chars > capacity) chars = capacity;
4797 ReadBlockBuffer rbb(util_buffer, 0, capacity, 0);
4798 ReadBlockIntoBuffer(*input, &rbb, offset_ptr, chars);
4799 ASSERT(rbb.remaining <= static_cast<unsigned>(input->length()));
4800 *remaining = rbb.remaining;
4801 return rbb.util_buffer;
4802}
4803
4804
4805// This will iterate unless the block of string data spans two 'halves' of
4806// a ConsString, in which case it will recurse. Since the block of string
4807// data to be read has a maximum size this limits the maximum recursion
4808// depth to something sane. Since C++ does not have tail call recursion
4809// elimination, the iteration must be explicit.
4810void ConsString::ConsStringReadBlockIntoBuffer(ReadBlockBuffer* rbb,
4811 unsigned* offset_ptr,
4812 unsigned max_chars) {
4813 ConsString* current = this;
4814 unsigned offset = *offset_ptr;
4815 int offset_correction = 0;
4816
4817 while (true) {
4818 String* left = current->first();
4819 unsigned left_length = (unsigned)left->length();
4820 if (left_length > offset &&
4821 max_chars <= left_length - offset) {
4822 // Left hand side only - iterate unless we have reached the bottom of
4823 // the cons tree.
4824 if (StringShape(left).IsCons()) {
4825 current = ConsString::cast(left);
4826 continue;
4827 } else {
4828 String::ReadBlockIntoBuffer(left, rbb, &offset, max_chars);
4829 *offset_ptr = offset + offset_correction;
4830 return;
4831 }
4832 } else if (left_length <= offset) {
4833 // Right hand side only - iterate unless we have reached the bottom of
4834 // the cons tree.
4835 offset -= left_length;
4836 offset_correction += left_length;
4837 String* right = current->second();
4838 if (StringShape(right).IsCons()) {
4839 current = ConsString::cast(right);
4840 continue;
4841 } else {
4842 String::ReadBlockIntoBuffer(right, rbb, &offset, max_chars);
4843 *offset_ptr = offset + offset_correction;
4844 return;
4845 }
4846 } else {
4847 // The block to be read spans two sides of the ConsString, so we recurse.
4848 // First recurse on the left.
4849 max_chars -= left_length - offset;
4850 String::ReadBlockIntoBuffer(left, rbb, &offset, left_length - offset);
4851 // We may have reached the max or there may not have been enough space
4852 // in the buffer for the characters in the left hand side.
4853 if (offset == left_length) {
4854 // Recurse on the right.
4855 String* right = String::cast(current->second());
4856 offset -= left_length;
4857 offset_correction += left_length;
4858 String::ReadBlockIntoBuffer(right, rbb, &offset, max_chars);
4859 }
4860 *offset_ptr = offset + offset_correction;
4861 return;
4862 }
4863 }
4864}
4865
4866
Steve Blocka7e24c12009-10-30 11:49:00 +00004867uint16_t ConsString::ConsStringGet(int index) {
4868 ASSERT(index >= 0 && index < this->length());
4869
4870 // Check for a flattened cons string
4871 if (second()->length() == 0) {
4872 String* left = first();
4873 return left->Get(index);
4874 }
4875
4876 String* string = String::cast(this);
4877
4878 while (true) {
4879 if (StringShape(string).IsCons()) {
4880 ConsString* cons_string = ConsString::cast(string);
4881 String* left = cons_string->first();
4882 if (left->length() > index) {
4883 string = left;
4884 } else {
4885 index -= left->length();
4886 string = cons_string->second();
4887 }
4888 } else {
4889 return string->Get(index);
4890 }
4891 }
4892
4893 UNREACHABLE();
4894 return 0;
4895}
4896
4897
4898template <typename sinkchar>
4899void String::WriteToFlat(String* src,
4900 sinkchar* sink,
4901 int f,
4902 int t) {
4903 String* source = src;
4904 int from = f;
4905 int to = t;
4906 while (true) {
4907 ASSERT(0 <= from && from <= to && to <= source->length());
4908 switch (StringShape(source).full_representation_tag()) {
4909 case kAsciiStringTag | kExternalStringTag: {
4910 CopyChars(sink,
4911 ExternalAsciiString::cast(source)->resource()->data() + from,
4912 to - from);
4913 return;
4914 }
4915 case kTwoByteStringTag | kExternalStringTag: {
4916 const uc16* data =
4917 ExternalTwoByteString::cast(source)->resource()->data();
4918 CopyChars(sink,
4919 data + from,
4920 to - from);
4921 return;
4922 }
4923 case kAsciiStringTag | kSeqStringTag: {
4924 CopyChars(sink,
4925 SeqAsciiString::cast(source)->GetChars() + from,
4926 to - from);
4927 return;
4928 }
4929 case kTwoByteStringTag | kSeqStringTag: {
4930 CopyChars(sink,
4931 SeqTwoByteString::cast(source)->GetChars() + from,
4932 to - from);
4933 return;
4934 }
Steve Blocka7e24c12009-10-30 11:49:00 +00004935 case kAsciiStringTag | kConsStringTag:
4936 case kTwoByteStringTag | kConsStringTag: {
4937 ConsString* cons_string = ConsString::cast(source);
4938 String* first = cons_string->first();
4939 int boundary = first->length();
4940 if (to - boundary >= boundary - from) {
4941 // Right hand side is longer. Recurse over left.
4942 if (from < boundary) {
4943 WriteToFlat(first, sink, from, boundary);
4944 sink += boundary - from;
4945 from = 0;
4946 } else {
4947 from -= boundary;
4948 }
4949 to -= boundary;
4950 source = cons_string->second();
4951 } else {
4952 // Left hand side is longer. Recurse over right.
4953 if (to > boundary) {
4954 String* second = cons_string->second();
4955 WriteToFlat(second,
4956 sink + boundary - from,
4957 0,
4958 to - boundary);
4959 to = boundary;
4960 }
4961 source = first;
4962 }
4963 break;
4964 }
4965 }
4966 }
4967}
4968
4969
Steve Blocka7e24c12009-10-30 11:49:00 +00004970template <typename IteratorA, typename IteratorB>
4971static inline bool CompareStringContents(IteratorA* ia, IteratorB* ib) {
4972 // General slow case check. We know that the ia and ib iterators
4973 // have the same length.
4974 while (ia->has_more()) {
4975 uc32 ca = ia->GetNext();
4976 uc32 cb = ib->GetNext();
4977 if (ca != cb)
4978 return false;
4979 }
4980 return true;
4981}
4982
4983
4984// Compares the contents of two strings by reading and comparing
4985// int-sized blocks of characters.
4986template <typename Char>
4987static inline bool CompareRawStringContents(Vector<Char> a, Vector<Char> b) {
4988 int length = a.length();
4989 ASSERT_EQ(length, b.length());
4990 const Char* pa = a.start();
4991 const Char* pb = b.start();
4992 int i = 0;
4993#ifndef V8_HOST_CAN_READ_UNALIGNED
4994 // If this architecture isn't comfortable reading unaligned ints
4995 // then we have to check that the strings are aligned before
4996 // comparing them blockwise.
4997 const int kAlignmentMask = sizeof(uint32_t) - 1; // NOLINT
4998 uint32_t pa_addr = reinterpret_cast<uint32_t>(pa);
4999 uint32_t pb_addr = reinterpret_cast<uint32_t>(pb);
5000 if (((pa_addr & kAlignmentMask) | (pb_addr & kAlignmentMask)) == 0) {
5001#endif
5002 const int kStepSize = sizeof(int) / sizeof(Char); // NOLINT
5003 int endpoint = length - kStepSize;
5004 // Compare blocks until we reach near the end of the string.
5005 for (; i <= endpoint; i += kStepSize) {
5006 uint32_t wa = *reinterpret_cast<const uint32_t*>(pa + i);
5007 uint32_t wb = *reinterpret_cast<const uint32_t*>(pb + i);
5008 if (wa != wb) {
5009 return false;
5010 }
5011 }
5012#ifndef V8_HOST_CAN_READ_UNALIGNED
5013 }
5014#endif
5015 // Compare the remaining characters that didn't fit into a block.
5016 for (; i < length; i++) {
5017 if (a[i] != b[i]) {
5018 return false;
5019 }
5020 }
5021 return true;
5022}
5023
5024
5025static StringInputBuffer string_compare_buffer_b;
5026
5027
5028template <typename IteratorA>
5029static inline bool CompareStringContentsPartial(IteratorA* ia, String* b) {
5030 if (b->IsFlat()) {
5031 if (b->IsAsciiRepresentation()) {
5032 VectorIterator<char> ib(b->ToAsciiVector());
5033 return CompareStringContents(ia, &ib);
5034 } else {
5035 VectorIterator<uc16> ib(b->ToUC16Vector());
5036 return CompareStringContents(ia, &ib);
5037 }
5038 } else {
5039 string_compare_buffer_b.Reset(0, b);
5040 return CompareStringContents(ia, &string_compare_buffer_b);
5041 }
5042}
5043
5044
5045static StringInputBuffer string_compare_buffer_a;
5046
5047
5048bool String::SlowEquals(String* other) {
5049 // Fast check: negative check with lengths.
5050 int len = length();
5051 if (len != other->length()) return false;
5052 if (len == 0) return true;
5053
5054 // Fast check: if hash code is computed for both strings
5055 // a fast negative check can be performed.
5056 if (HasHashCode() && other->HasHashCode()) {
5057 if (Hash() != other->Hash()) return false;
5058 }
5059
Leon Clarkef7060e22010-06-03 12:02:55 +01005060 // We know the strings are both non-empty. Compare the first chars
5061 // before we try to flatten the strings.
5062 if (this->Get(0) != other->Get(0)) return false;
5063
5064 String* lhs = this->TryFlattenGetString();
5065 String* rhs = other->TryFlattenGetString();
5066
5067 if (StringShape(lhs).IsSequentialAscii() &&
5068 StringShape(rhs).IsSequentialAscii()) {
5069 const char* str1 = SeqAsciiString::cast(lhs)->GetChars();
5070 const char* str2 = SeqAsciiString::cast(rhs)->GetChars();
Steve Blocka7e24c12009-10-30 11:49:00 +00005071 return CompareRawStringContents(Vector<const char>(str1, len),
5072 Vector<const char>(str2, len));
5073 }
5074
Leon Clarkef7060e22010-06-03 12:02:55 +01005075 if (lhs->IsFlat()) {
Ben Murdochbb769b22010-08-11 14:56:33 +01005076 if (lhs->IsAsciiRepresentation()) {
Leon Clarkef7060e22010-06-03 12:02:55 +01005077 Vector<const char> vec1 = lhs->ToAsciiVector();
5078 if (rhs->IsFlat()) {
5079 if (rhs->IsAsciiRepresentation()) {
5080 Vector<const char> vec2 = rhs->ToAsciiVector();
Steve Blocka7e24c12009-10-30 11:49:00 +00005081 return CompareRawStringContents(vec1, vec2);
5082 } else {
5083 VectorIterator<char> buf1(vec1);
Leon Clarkef7060e22010-06-03 12:02:55 +01005084 VectorIterator<uc16> ib(rhs->ToUC16Vector());
Steve Blocka7e24c12009-10-30 11:49:00 +00005085 return CompareStringContents(&buf1, &ib);
5086 }
5087 } else {
5088 VectorIterator<char> buf1(vec1);
Leon Clarkef7060e22010-06-03 12:02:55 +01005089 string_compare_buffer_b.Reset(0, rhs);
Steve Blocka7e24c12009-10-30 11:49:00 +00005090 return CompareStringContents(&buf1, &string_compare_buffer_b);
5091 }
5092 } else {
Leon Clarkef7060e22010-06-03 12:02:55 +01005093 Vector<const uc16> vec1 = lhs->ToUC16Vector();
5094 if (rhs->IsFlat()) {
5095 if (rhs->IsAsciiRepresentation()) {
Steve Blocka7e24c12009-10-30 11:49:00 +00005096 VectorIterator<uc16> buf1(vec1);
Leon Clarkef7060e22010-06-03 12:02:55 +01005097 VectorIterator<char> ib(rhs->ToAsciiVector());
Steve Blocka7e24c12009-10-30 11:49:00 +00005098 return CompareStringContents(&buf1, &ib);
5099 } else {
Leon Clarkef7060e22010-06-03 12:02:55 +01005100 Vector<const uc16> vec2(rhs->ToUC16Vector());
Steve Blocka7e24c12009-10-30 11:49:00 +00005101 return CompareRawStringContents(vec1, vec2);
5102 }
5103 } else {
5104 VectorIterator<uc16> buf1(vec1);
Leon Clarkef7060e22010-06-03 12:02:55 +01005105 string_compare_buffer_b.Reset(0, rhs);
Steve Blocka7e24c12009-10-30 11:49:00 +00005106 return CompareStringContents(&buf1, &string_compare_buffer_b);
5107 }
5108 }
5109 } else {
Leon Clarkef7060e22010-06-03 12:02:55 +01005110 string_compare_buffer_a.Reset(0, lhs);
5111 return CompareStringContentsPartial(&string_compare_buffer_a, rhs);
Steve Blocka7e24c12009-10-30 11:49:00 +00005112 }
5113}
5114
5115
5116bool String::MarkAsUndetectable() {
5117 if (StringShape(this).IsSymbol()) return false;
5118
5119 Map* map = this->map();
Steve Blockd0582a62009-12-15 09:54:21 +00005120 if (map == Heap::string_map()) {
5121 this->set_map(Heap::undetectable_string_map());
Steve Blocka7e24c12009-10-30 11:49:00 +00005122 return true;
Steve Blockd0582a62009-12-15 09:54:21 +00005123 } else if (map == Heap::ascii_string_map()) {
5124 this->set_map(Heap::undetectable_ascii_string_map());
Steve Blocka7e24c12009-10-30 11:49:00 +00005125 return true;
5126 }
5127 // Rest cannot be marked as undetectable
5128 return false;
5129}
5130
5131
5132bool String::IsEqualTo(Vector<const char> str) {
5133 int slen = length();
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -08005134 Access<ScannerConstants::Utf8Decoder>
5135 decoder(ScannerConstants::utf8_decoder());
Steve Blocka7e24c12009-10-30 11:49:00 +00005136 decoder->Reset(str.start(), str.length());
5137 int i;
5138 for (i = 0; i < slen && decoder->has_more(); i++) {
5139 uc32 r = decoder->GetNext();
5140 if (Get(i) != r) return false;
5141 }
5142 return i == slen && !decoder->has_more();
5143}
5144
5145
Steve Block6ded16b2010-05-10 14:33:55 +01005146template <typename schar>
5147static inline uint32_t HashSequentialString(const schar* chars, int length) {
5148 StringHasher hasher(length);
5149 if (!hasher.has_trivial_hash()) {
5150 int i;
5151 for (i = 0; hasher.is_array_index() && (i < length); i++) {
5152 hasher.AddCharacter(chars[i]);
5153 }
5154 for (; i < length; i++) {
5155 hasher.AddCharacterNoIndex(chars[i]);
5156 }
5157 }
5158 return hasher.GetHashField();
5159}
5160
5161
Steve Blocka7e24c12009-10-30 11:49:00 +00005162uint32_t String::ComputeAndSetHash() {
5163 // Should only be called if hash code has not yet been computed.
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01005164 ASSERT(!HasHashCode());
Steve Blocka7e24c12009-10-30 11:49:00 +00005165
Steve Block6ded16b2010-05-10 14:33:55 +01005166 const int len = length();
5167
Steve Blocka7e24c12009-10-30 11:49:00 +00005168 // Compute the hash code.
Steve Block6ded16b2010-05-10 14:33:55 +01005169 uint32_t field = 0;
5170 if (StringShape(this).IsSequentialAscii()) {
5171 field = HashSequentialString(SeqAsciiString::cast(this)->GetChars(), len);
5172 } else if (StringShape(this).IsSequentialTwoByte()) {
5173 field = HashSequentialString(SeqTwoByteString::cast(this)->GetChars(), len);
5174 } else {
5175 StringInputBuffer buffer(this);
5176 field = ComputeHashField(&buffer, len);
5177 }
Steve Blocka7e24c12009-10-30 11:49:00 +00005178
5179 // Store the hash code in the object.
Steve Blockd0582a62009-12-15 09:54:21 +00005180 set_hash_field(field);
Steve Blocka7e24c12009-10-30 11:49:00 +00005181
5182 // Check the hash code is there.
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01005183 ASSERT(HasHashCode());
Steve Blocka7e24c12009-10-30 11:49:00 +00005184 uint32_t result = field >> kHashShift;
5185 ASSERT(result != 0); // Ensure that the hash value of 0 is never computed.
5186 return result;
5187}
5188
5189
5190bool String::ComputeArrayIndex(unibrow::CharacterStream* buffer,
5191 uint32_t* index,
5192 int length) {
5193 if (length == 0 || length > kMaxArrayIndexSize) return false;
5194 uc32 ch = buffer->GetNext();
5195
5196 // If the string begins with a '0' character, it must only consist
5197 // of it to be a legal array index.
5198 if (ch == '0') {
5199 *index = 0;
5200 return length == 1;
5201 }
5202
5203 // Convert string to uint32 array index; character by character.
5204 int d = ch - '0';
5205 if (d < 0 || d > 9) return false;
5206 uint32_t result = d;
5207 while (buffer->has_more()) {
5208 d = buffer->GetNext() - '0';
5209 if (d < 0 || d > 9) return false;
5210 // Check that the new result is below the 32 bit limit.
5211 if (result > 429496729U - ((d > 5) ? 1 : 0)) return false;
5212 result = (result * 10) + d;
5213 }
5214
5215 *index = result;
5216 return true;
5217}
5218
5219
5220bool String::SlowAsArrayIndex(uint32_t* index) {
5221 if (length() <= kMaxCachedArrayIndexLength) {
5222 Hash(); // force computation of hash code
Steve Blockd0582a62009-12-15 09:54:21 +00005223 uint32_t field = hash_field();
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01005224 if ((field & kIsNotArrayIndexMask) != 0) return false;
Steve Blockd0582a62009-12-15 09:54:21 +00005225 // Isolate the array index form the full hash field.
5226 *index = (kArrayIndexHashMask & field) >> kHashShift;
Steve Blocka7e24c12009-10-30 11:49:00 +00005227 return true;
5228 } else {
5229 StringInputBuffer buffer(this);
5230 return ComputeArrayIndex(&buffer, index, length());
5231 }
5232}
5233
5234
Iain Merrick9ac36c92010-09-13 15:29:50 +01005235uint32_t StringHasher::MakeArrayIndexHash(uint32_t value, int length) {
Kristian Monsen80d68ea2010-09-08 11:05:35 +01005236 // For array indexes mix the length into the hash as an array index could
5237 // be zero.
5238 ASSERT(length > 0);
5239 ASSERT(length <= String::kMaxArrayIndexSize);
5240 ASSERT(TenToThe(String::kMaxCachedArrayIndexLength) <
5241 (1 << String::kArrayIndexValueBits));
Iain Merrick9ac36c92010-09-13 15:29:50 +01005242
5243 value <<= String::kHashShift;
Kristian Monsen80d68ea2010-09-08 11:05:35 +01005244 value |= length << String::kArrayIndexHashLengthShift;
Iain Merrick9ac36c92010-09-13 15:29:50 +01005245
5246 ASSERT((value & String::kIsNotArrayIndexMask) == 0);
5247 ASSERT((length > String::kMaxCachedArrayIndexLength) ||
5248 (value & String::kContainsCachedArrayIndexMask) == 0);
Kristian Monsen80d68ea2010-09-08 11:05:35 +01005249 return value;
Steve Blocka7e24c12009-10-30 11:49:00 +00005250}
5251
5252
5253uint32_t StringHasher::GetHashField() {
5254 ASSERT(is_valid());
Steve Blockd0582a62009-12-15 09:54:21 +00005255 if (length_ <= String::kMaxHashCalcLength) {
Steve Blocka7e24c12009-10-30 11:49:00 +00005256 if (is_array_index()) {
Iain Merrick9ac36c92010-09-13 15:29:50 +01005257 return MakeArrayIndexHash(array_index(), length_);
Steve Blocka7e24c12009-10-30 11:49:00 +00005258 }
Kristian Monsen80d68ea2010-09-08 11:05:35 +01005259 return (GetHash() << String::kHashShift) | String::kIsNotArrayIndexMask;
Steve Blocka7e24c12009-10-30 11:49:00 +00005260 } else {
Kristian Monsen80d68ea2010-09-08 11:05:35 +01005261 return (length_ << String::kHashShift) | String::kIsNotArrayIndexMask;
Steve Blocka7e24c12009-10-30 11:49:00 +00005262 }
5263}
5264
5265
Steve Blockd0582a62009-12-15 09:54:21 +00005266uint32_t String::ComputeHashField(unibrow::CharacterStream* buffer,
5267 int length) {
Steve Blocka7e24c12009-10-30 11:49:00 +00005268 StringHasher hasher(length);
5269
5270 // Very long strings have a trivial hash that doesn't inspect the
5271 // string contents.
5272 if (hasher.has_trivial_hash()) {
5273 return hasher.GetHashField();
5274 }
5275
5276 // Do the iterative array index computation as long as there is a
5277 // chance this is an array index.
5278 while (buffer->has_more() && hasher.is_array_index()) {
5279 hasher.AddCharacter(buffer->GetNext());
5280 }
5281
5282 // Process the remaining characters without updating the array
5283 // index.
5284 while (buffer->has_more()) {
5285 hasher.AddCharacterNoIndex(buffer->GetNext());
5286 }
5287
5288 return hasher.GetHashField();
5289}
5290
5291
John Reck59135872010-11-02 12:39:01 -07005292MaybeObject* String::SubString(int start, int end, PretenureFlag pretenure) {
Steve Blocka7e24c12009-10-30 11:49:00 +00005293 if (start == 0 && end == length()) return this;
John Reck59135872010-11-02 12:39:01 -07005294 MaybeObject* result = Heap::AllocateSubString(this, start, end, pretenure);
Steve Blockd0582a62009-12-15 09:54:21 +00005295 return result;
Steve Blocka7e24c12009-10-30 11:49:00 +00005296}
5297
5298
5299void String::PrintOn(FILE* file) {
5300 int length = this->length();
5301 for (int i = 0; i < length; i++) {
5302 fprintf(file, "%c", Get(i));
5303 }
5304}
5305
5306
5307void Map::CreateBackPointers() {
5308 DescriptorArray* descriptors = instance_descriptors();
5309 for (int i = 0; i < descriptors->number_of_descriptors(); i++) {
Iain Merrick75681382010-08-19 15:07:18 +01005310 if (descriptors->GetType(i) == MAP_TRANSITION ||
5311 descriptors->GetType(i) == CONSTANT_TRANSITION) {
Steve Blocka7e24c12009-10-30 11:49:00 +00005312 // Get target.
5313 Map* target = Map::cast(descriptors->GetValue(i));
5314#ifdef DEBUG
5315 // Verify target.
5316 Object* source_prototype = prototype();
5317 Object* target_prototype = target->prototype();
5318 ASSERT(source_prototype->IsJSObject() ||
5319 source_prototype->IsMap() ||
5320 source_prototype->IsNull());
5321 ASSERT(target_prototype->IsJSObject() ||
5322 target_prototype->IsNull());
5323 ASSERT(source_prototype->IsMap() ||
5324 source_prototype == target_prototype);
5325#endif
5326 // Point target back to source. set_prototype() will not let us set
5327 // the prototype to a map, as we do here.
5328 *RawField(target, kPrototypeOffset) = this;
5329 }
5330 }
5331}
5332
5333
5334void Map::ClearNonLiveTransitions(Object* real_prototype) {
5335 // Live DescriptorArray objects will be marked, so we must use
5336 // low-level accessors to get and modify their data.
5337 DescriptorArray* d = reinterpret_cast<DescriptorArray*>(
5338 *RawField(this, Map::kInstanceDescriptorsOffset));
5339 if (d == Heap::raw_unchecked_empty_descriptor_array()) return;
5340 Smi* NullDescriptorDetails =
5341 PropertyDetails(NONE, NULL_DESCRIPTOR).AsSmi();
5342 FixedArray* contents = reinterpret_cast<FixedArray*>(
5343 d->get(DescriptorArray::kContentArrayIndex));
5344 ASSERT(contents->length() >= 2);
5345 for (int i = 0; i < contents->length(); i += 2) {
5346 // If the pair (value, details) is a map transition,
5347 // check if the target is live. If not, null the descriptor.
5348 // Also drop the back pointer for that map transition, so that this
5349 // map is not reached again by following a back pointer from a
5350 // non-live object.
5351 PropertyDetails details(Smi::cast(contents->get(i + 1)));
Iain Merrick75681382010-08-19 15:07:18 +01005352 if (details.type() == MAP_TRANSITION ||
5353 details.type() == CONSTANT_TRANSITION) {
Steve Blocka7e24c12009-10-30 11:49:00 +00005354 Map* target = reinterpret_cast<Map*>(contents->get(i));
5355 ASSERT(target->IsHeapObject());
5356 if (!target->IsMarked()) {
5357 ASSERT(target->IsMap());
Iain Merrick75681382010-08-19 15:07:18 +01005358 contents->set_unchecked(i + 1, NullDescriptorDetails);
5359 contents->set_null_unchecked(i);
Steve Blocka7e24c12009-10-30 11:49:00 +00005360 ASSERT(target->prototype() == this ||
5361 target->prototype() == real_prototype);
5362 // Getter prototype() is read-only, set_prototype() has side effects.
5363 *RawField(target, Map::kPrototypeOffset) = real_prototype;
5364 }
5365 }
5366 }
5367}
5368
5369
Steve Block791712a2010-08-27 10:21:07 +01005370void JSFunction::JSFunctionIterateBody(int object_size, ObjectVisitor* v) {
5371 // Iterate over all fields in the body but take care in dealing with
5372 // the code entry.
5373 IteratePointers(v, kPropertiesOffset, kCodeEntryOffset);
5374 v->VisitCodeEntry(this->address() + kCodeEntryOffset);
5375 IteratePointers(v, kCodeEntryOffset + kPointerSize, object_size);
5376}
5377
5378
Ben Murdochb0fe1622011-05-05 13:52:32 +01005379void JSFunction::MarkForLazyRecompilation() {
5380 ASSERT(is_compiled() && !IsOptimized());
5381 ASSERT(shared()->allows_lazy_compilation());
5382 ReplaceCode(Builtins::builtin(Builtins::LazyRecompile));
5383}
5384
5385
5386uint32_t JSFunction::SourceHash() {
5387 uint32_t hash = 0;
5388 Object* script = shared()->script();
5389 if (!script->IsUndefined()) {
5390 Object* source = Script::cast(script)->source();
5391 if (source->IsUndefined()) hash = String::cast(source)->Hash();
5392 }
5393 hash ^= ComputeIntegerHash(shared()->start_position_and_type());
5394 hash += ComputeIntegerHash(shared()->end_position());
5395 return hash;
5396}
5397
5398
5399bool JSFunction::IsInlineable() {
5400 if (IsBuiltin()) return false;
5401 // Check that the function has a script associated with it.
5402 if (!shared()->script()->IsScript()) return false;
5403 Code* code = shared()->code();
5404 if (code->kind() == Code::OPTIMIZED_FUNCTION) return true;
5405 // If we never ran this (unlikely) then lets try to optimize it.
5406 if (code->kind() != Code::FUNCTION) return true;
5407 return code->optimizable();
5408}
5409
5410
Steve Blocka7e24c12009-10-30 11:49:00 +00005411Object* JSFunction::SetInstancePrototype(Object* value) {
5412 ASSERT(value->IsJSObject());
5413
5414 if (has_initial_map()) {
5415 initial_map()->set_prototype(value);
5416 } else {
5417 // Put the value in the initial map field until an initial map is
5418 // needed. At that point, a new initial map is created and the
5419 // prototype is put into the initial map where it belongs.
5420 set_prototype_or_initial_map(value);
5421 }
Kristian Monsen25f61362010-05-21 11:50:48 +01005422 Heap::ClearInstanceofCache();
Steve Blocka7e24c12009-10-30 11:49:00 +00005423 return value;
5424}
5425
5426
John Reck59135872010-11-02 12:39:01 -07005427MaybeObject* JSFunction::SetPrototype(Object* value) {
Steve Block6ded16b2010-05-10 14:33:55 +01005428 ASSERT(should_have_prototype());
Steve Blocka7e24c12009-10-30 11:49:00 +00005429 Object* construct_prototype = value;
5430
5431 // If the value is not a JSObject, store the value in the map's
5432 // constructor field so it can be accessed. Also, set the prototype
5433 // used for constructing objects to the original object prototype.
5434 // See ECMA-262 13.2.2.
5435 if (!value->IsJSObject()) {
5436 // Copy the map so this does not affect unrelated functions.
5437 // Remove map transitions because they point to maps with a
5438 // different prototype.
John Reck59135872010-11-02 12:39:01 -07005439 Object* new_map;
5440 { MaybeObject* maybe_new_map = map()->CopyDropTransitions();
5441 if (!maybe_new_map->ToObject(&new_map)) return maybe_new_map;
5442 }
Steve Blocka7e24c12009-10-30 11:49:00 +00005443 set_map(Map::cast(new_map));
5444 map()->set_constructor(value);
5445 map()->set_non_instance_prototype(true);
5446 construct_prototype =
5447 Top::context()->global_context()->initial_object_prototype();
5448 } else {
5449 map()->set_non_instance_prototype(false);
5450 }
5451
5452 return SetInstancePrototype(construct_prototype);
5453}
5454
5455
Steve Block6ded16b2010-05-10 14:33:55 +01005456Object* JSFunction::RemovePrototype() {
5457 ASSERT(map() == context()->global_context()->function_map());
5458 set_map(context()->global_context()->function_without_prototype_map());
5459 set_prototype_or_initial_map(Heap::the_hole_value());
5460 return this;
5461}
5462
5463
Steve Blocka7e24c12009-10-30 11:49:00 +00005464Object* JSFunction::SetInstanceClassName(String* name) {
5465 shared()->set_instance_class_name(name);
5466 return this;
5467}
5468
5469
Ben Murdochb0fe1622011-05-05 13:52:32 +01005470void JSFunction::PrintName(FILE* out) {
5471 SmartPointer<char> name = shared()->DebugName()->ToCString();
5472 PrintF(out, "%s", *name);
5473}
5474
5475
Steve Blocka7e24c12009-10-30 11:49:00 +00005476Context* JSFunction::GlobalContextFromLiterals(FixedArray* literals) {
5477 return Context::cast(literals->get(JSFunction::kLiteralGlobalContextIndex));
5478}
5479
5480
John Reck59135872010-11-02 12:39:01 -07005481MaybeObject* Oddball::Initialize(const char* to_string, Object* to_number) {
5482 Object* symbol;
5483 { MaybeObject* maybe_symbol = Heap::LookupAsciiSymbol(to_string);
5484 if (!maybe_symbol->ToObject(&symbol)) return maybe_symbol;
5485 }
Steve Blocka7e24c12009-10-30 11:49:00 +00005486 set_to_string(String::cast(symbol));
5487 set_to_number(to_number);
5488 return this;
5489}
5490
5491
Ben Murdochf87a2032010-10-22 12:50:53 +01005492String* SharedFunctionInfo::DebugName() {
5493 Object* n = name();
5494 if (!n->IsString() || String::cast(n)->length() == 0) return inferred_name();
5495 return String::cast(n);
5496}
5497
5498
Steve Blocka7e24c12009-10-30 11:49:00 +00005499bool SharedFunctionInfo::HasSourceCode() {
5500 return !script()->IsUndefined() &&
Iain Merrick75681382010-08-19 15:07:18 +01005501 !reinterpret_cast<Script*>(script())->source()->IsUndefined();
Steve Blocka7e24c12009-10-30 11:49:00 +00005502}
5503
5504
5505Object* SharedFunctionInfo::GetSourceCode() {
Ben Murdochb0fe1622011-05-05 13:52:32 +01005506 if (!HasSourceCode()) return Heap::undefined_value();
Steve Blocka7e24c12009-10-30 11:49:00 +00005507 HandleScope scope;
Steve Blocka7e24c12009-10-30 11:49:00 +00005508 Object* source = Script::cast(script())->source();
Steve Blocka7e24c12009-10-30 11:49:00 +00005509 return *SubString(Handle<String>(String::cast(source)),
5510 start_position(), end_position());
5511}
5512
5513
Ben Murdochb0fe1622011-05-05 13:52:32 +01005514int SharedFunctionInfo::SourceSize() {
5515 return end_position() - start_position();
5516}
5517
5518
Steve Blocka7e24c12009-10-30 11:49:00 +00005519int SharedFunctionInfo::CalculateInstanceSize() {
5520 int instance_size =
5521 JSObject::kHeaderSize +
5522 expected_nof_properties() * kPointerSize;
5523 if (instance_size > JSObject::kMaxInstanceSize) {
5524 instance_size = JSObject::kMaxInstanceSize;
5525 }
5526 return instance_size;
5527}
5528
5529
5530int SharedFunctionInfo::CalculateInObjectProperties() {
5531 return (CalculateInstanceSize() - JSObject::kHeaderSize) / kPointerSize;
5532}
5533
5534
Andrei Popescu402d9372010-02-26 13:31:12 +00005535bool SharedFunctionInfo::CanGenerateInlineConstructor(Object* prototype) {
5536 // Check the basic conditions for generating inline constructor code.
5537 if (!FLAG_inline_new
5538 || !has_only_simple_this_property_assignments()
5539 || this_property_assignments_count() == 0) {
5540 return false;
5541 }
5542
5543 // If the prototype is null inline constructors cause no problems.
5544 if (!prototype->IsJSObject()) {
5545 ASSERT(prototype->IsNull());
5546 return true;
5547 }
5548
5549 // Traverse the proposed prototype chain looking for setters for properties of
5550 // the same names as are set by the inline constructor.
5551 for (Object* obj = prototype;
5552 obj != Heap::null_value();
5553 obj = obj->GetPrototype()) {
5554 JSObject* js_object = JSObject::cast(obj);
5555 for (int i = 0; i < this_property_assignments_count(); i++) {
5556 LookupResult result;
5557 String* name = GetThisPropertyAssignmentName(i);
5558 js_object->LocalLookupRealNamedProperty(name, &result);
5559 if (result.IsProperty() && result.type() == CALLBACKS) {
5560 return false;
5561 }
5562 }
5563 }
5564
5565 return true;
5566}
5567
5568
Kristian Monsen0d5e1162010-09-30 15:31:59 +01005569void SharedFunctionInfo::ForbidInlineConstructor() {
5570 set_compiler_hints(BooleanBit::set(compiler_hints(),
5571 kHasOnlySimpleThisPropertyAssignments,
5572 false));
5573}
5574
5575
Steve Blocka7e24c12009-10-30 11:49:00 +00005576void SharedFunctionInfo::SetThisPropertyAssignmentsInfo(
Steve Blocka7e24c12009-10-30 11:49:00 +00005577 bool only_simple_this_property_assignments,
5578 FixedArray* assignments) {
5579 set_compiler_hints(BooleanBit::set(compiler_hints(),
Steve Blocka7e24c12009-10-30 11:49:00 +00005580 kHasOnlySimpleThisPropertyAssignments,
5581 only_simple_this_property_assignments));
5582 set_this_property_assignments(assignments);
5583 set_this_property_assignments_count(assignments->length() / 3);
5584}
5585
5586
5587void SharedFunctionInfo::ClearThisPropertyAssignmentsInfo() {
5588 set_compiler_hints(BooleanBit::set(compiler_hints(),
Steve Blocka7e24c12009-10-30 11:49:00 +00005589 kHasOnlySimpleThisPropertyAssignments,
5590 false));
5591 set_this_property_assignments(Heap::undefined_value());
5592 set_this_property_assignments_count(0);
5593}
5594
5595
5596String* SharedFunctionInfo::GetThisPropertyAssignmentName(int index) {
5597 Object* obj = this_property_assignments();
5598 ASSERT(obj->IsFixedArray());
5599 ASSERT(index < this_property_assignments_count());
5600 obj = FixedArray::cast(obj)->get(index * 3);
5601 ASSERT(obj->IsString());
5602 return String::cast(obj);
5603}
5604
5605
5606bool SharedFunctionInfo::IsThisPropertyAssignmentArgument(int index) {
5607 Object* obj = this_property_assignments();
5608 ASSERT(obj->IsFixedArray());
5609 ASSERT(index < this_property_assignments_count());
5610 obj = FixedArray::cast(obj)->get(index * 3 + 1);
5611 return Smi::cast(obj)->value() != -1;
5612}
5613
5614
5615int SharedFunctionInfo::GetThisPropertyAssignmentArgument(int index) {
5616 ASSERT(IsThisPropertyAssignmentArgument(index));
5617 Object* obj =
5618 FixedArray::cast(this_property_assignments())->get(index * 3 + 1);
5619 return Smi::cast(obj)->value();
5620}
5621
5622
5623Object* SharedFunctionInfo::GetThisPropertyAssignmentConstant(int index) {
5624 ASSERT(!IsThisPropertyAssignmentArgument(index));
5625 Object* obj =
5626 FixedArray::cast(this_property_assignments())->get(index * 3 + 2);
5627 return obj;
5628}
5629
5630
Steve Blocka7e24c12009-10-30 11:49:00 +00005631// Support function for printing the source code to a StringStream
5632// without any allocation in the heap.
5633void SharedFunctionInfo::SourceCodePrint(StringStream* accumulator,
5634 int max_length) {
5635 // For some native functions there is no source.
Ben Murdochb0fe1622011-05-05 13:52:32 +01005636 if (!HasSourceCode()) {
Steve Blocka7e24c12009-10-30 11:49:00 +00005637 accumulator->Add("<No Source>");
5638 return;
5639 }
5640
Steve Blockd0582a62009-12-15 09:54:21 +00005641 // Get the source for the script which this function came from.
Steve Blocka7e24c12009-10-30 11:49:00 +00005642 // Don't use String::cast because we don't want more assertion errors while
5643 // we are already creating a stack dump.
5644 String* script_source =
5645 reinterpret_cast<String*>(Script::cast(script())->source());
5646
5647 if (!script_source->LooksValid()) {
5648 accumulator->Add("<Invalid Source>");
5649 return;
5650 }
5651
5652 if (!is_toplevel()) {
5653 accumulator->Add("function ");
5654 Object* name = this->name();
5655 if (name->IsString() && String::cast(name)->length() > 0) {
5656 accumulator->PrintName(name);
5657 }
5658 }
5659
5660 int len = end_position() - start_position();
Ben Murdochb0fe1622011-05-05 13:52:32 +01005661 if (len <= max_length || max_length < 0) {
5662 accumulator->Put(script_source, start_position(), end_position());
5663 } else {
Steve Blocka7e24c12009-10-30 11:49:00 +00005664 accumulator->Put(script_source,
5665 start_position(),
5666 start_position() + max_length);
5667 accumulator->Add("...\n");
Steve Blocka7e24c12009-10-30 11:49:00 +00005668 }
5669}
5670
5671
Ben Murdochb0fe1622011-05-05 13:52:32 +01005672static bool IsCodeEquivalent(Code* code, Code* recompiled) {
5673 if (code->instruction_size() != recompiled->instruction_size()) return false;
5674 ByteArray* code_relocation = code->relocation_info();
5675 ByteArray* recompiled_relocation = recompiled->relocation_info();
5676 int length = code_relocation->length();
5677 if (length != recompiled_relocation->length()) return false;
5678 int compare = memcmp(code_relocation->GetDataStartAddress(),
5679 recompiled_relocation->GetDataStartAddress(),
5680 length);
5681 return compare == 0;
5682}
5683
5684
5685void SharedFunctionInfo::EnableDeoptimizationSupport(Code* recompiled) {
5686 ASSERT(!has_deoptimization_support());
5687 AssertNoAllocation no_allocation;
5688 Code* code = this->code();
5689 if (IsCodeEquivalent(code, recompiled)) {
5690 // Copy the deoptimization data from the recompiled code.
5691 code->set_deoptimization_data(recompiled->deoptimization_data());
5692 code->set_has_deoptimization_support(true);
5693 } else {
5694 // TODO(3025757): In case the recompiled isn't equivalent to the
5695 // old code, we have to replace it. We should try to avoid this
5696 // altogether because it flushes valuable type feedback by
5697 // effectively resetting all IC state.
5698 set_code(recompiled);
5699 }
5700 ASSERT(has_deoptimization_support());
5701}
5702
5703
5704bool SharedFunctionInfo::VerifyBailoutId(int id) {
5705 // TODO(srdjan): debugging ARM crashes in hydrogen. OK to disable while
5706 // we are always bailing out on ARM.
5707
5708 ASSERT(id != AstNode::kNoNumber);
5709 Code* unoptimized = code();
5710 DeoptimizationOutputData* data =
5711 DeoptimizationOutputData::cast(unoptimized->deoptimization_data());
5712 unsigned ignore = Deoptimizer::GetOutputInfo(data, id, this);
5713 USE(ignore);
5714 return true; // Return true if there was no ASSERT.
5715}
5716
5717
Kristian Monsen0d5e1162010-09-30 15:31:59 +01005718void SharedFunctionInfo::StartInobjectSlackTracking(Map* map) {
5719 ASSERT(!IsInobjectSlackTrackingInProgress());
5720
5721 // Only initiate the tracking the first time.
5722 if (live_objects_may_exist()) return;
5723 set_live_objects_may_exist(true);
5724
5725 // No tracking during the snapshot construction phase.
5726 if (Serializer::enabled()) return;
5727
5728 if (map->unused_property_fields() == 0) return;
5729
5730 // Nonzero counter is a leftover from the previous attempt interrupted
5731 // by GC, keep it.
5732 if (construction_count() == 0) {
5733 set_construction_count(kGenerousAllocationCount);
5734 }
5735 set_initial_map(map);
5736 ASSERT_EQ(Builtins::builtin(Builtins::JSConstructStubGeneric),
5737 construct_stub());
5738 set_construct_stub(Builtins::builtin(Builtins::JSConstructStubCountdown));
5739}
5740
5741
5742// Called from GC, hence reinterpret_cast and unchecked accessors.
5743void SharedFunctionInfo::DetachInitialMap() {
5744 Map* map = reinterpret_cast<Map*>(initial_map());
5745
5746 // Make the map remember to restore the link if it survives the GC.
5747 map->set_bit_field2(
5748 map->bit_field2() | (1 << Map::kAttachedToSharedFunctionInfo));
5749
5750 // Undo state changes made by StartInobjectTracking (except the
5751 // construction_count). This way if the initial map does not survive the GC
5752 // then StartInobjectTracking will be called again the next time the
5753 // constructor is called. The countdown will continue and (possibly after
5754 // several more GCs) CompleteInobjectSlackTracking will eventually be called.
5755 set_initial_map(Heap::raw_unchecked_undefined_value());
5756 ASSERT_EQ(Builtins::builtin(Builtins::JSConstructStubCountdown),
5757 *RawField(this, kConstructStubOffset));
5758 set_construct_stub(Builtins::builtin(Builtins::JSConstructStubGeneric));
5759 // It is safe to clear the flag: it will be set again if the map is live.
5760 set_live_objects_may_exist(false);
5761}
5762
5763
5764// Called from GC, hence reinterpret_cast and unchecked accessors.
5765void SharedFunctionInfo::AttachInitialMap(Map* map) {
5766 map->set_bit_field2(
5767 map->bit_field2() & ~(1 << Map::kAttachedToSharedFunctionInfo));
5768
5769 // Resume inobject slack tracking.
5770 set_initial_map(map);
5771 ASSERT_EQ(Builtins::builtin(Builtins::JSConstructStubGeneric),
5772 *RawField(this, kConstructStubOffset));
5773 set_construct_stub(Builtins::builtin(Builtins::JSConstructStubCountdown));
5774 // The map survived the gc, so there may be objects referencing it.
5775 set_live_objects_may_exist(true);
5776}
5777
5778
5779static void GetMinInobjectSlack(Map* map, void* data) {
5780 int slack = map->unused_property_fields();
5781 if (*reinterpret_cast<int*>(data) > slack) {
5782 *reinterpret_cast<int*>(data) = slack;
5783 }
5784}
5785
5786
5787static void ShrinkInstanceSize(Map* map, void* data) {
5788 int slack = *reinterpret_cast<int*>(data);
5789 map->set_inobject_properties(map->inobject_properties() - slack);
5790 map->set_unused_property_fields(map->unused_property_fields() - slack);
5791 map->set_instance_size(map->instance_size() - slack * kPointerSize);
5792
5793 // Visitor id might depend on the instance size, recalculate it.
5794 map->set_visitor_id(StaticVisitorBase::GetVisitorId(map));
5795}
5796
5797
5798void SharedFunctionInfo::CompleteInobjectSlackTracking() {
5799 ASSERT(live_objects_may_exist() && IsInobjectSlackTrackingInProgress());
5800 Map* map = Map::cast(initial_map());
5801
5802 set_initial_map(Heap::undefined_value());
5803 ASSERT_EQ(Builtins::builtin(Builtins::JSConstructStubCountdown),
5804 construct_stub());
5805 set_construct_stub(Builtins::builtin(Builtins::JSConstructStubGeneric));
5806
5807 int slack = map->unused_property_fields();
5808 map->TraverseTransitionTree(&GetMinInobjectSlack, &slack);
5809 if (slack != 0) {
5810 // Resize the initial map and all maps in its transition tree.
5811 map->TraverseTransitionTree(&ShrinkInstanceSize, &slack);
5812 // Give the correct expected_nof_properties to initial maps created later.
5813 ASSERT(expected_nof_properties() >= slack);
5814 set_expected_nof_properties(expected_nof_properties() - slack);
5815 }
5816}
5817
5818
Steve Blocka7e24c12009-10-30 11:49:00 +00005819void ObjectVisitor::VisitCodeTarget(RelocInfo* rinfo) {
5820 ASSERT(RelocInfo::IsCodeTarget(rinfo->rmode()));
5821 Object* target = Code::GetCodeFromTargetAddress(rinfo->target_address());
5822 Object* old_target = target;
5823 VisitPointer(&target);
5824 CHECK_EQ(target, old_target); // VisitPointer doesn't change Code* *target.
5825}
5826
5827
Steve Block791712a2010-08-27 10:21:07 +01005828void ObjectVisitor::VisitCodeEntry(Address entry_address) {
5829 Object* code = Code::GetObjectFromEntryAddress(entry_address);
5830 Object* old_code = code;
5831 VisitPointer(&code);
5832 if (code != old_code) {
5833 Memory::Address_at(entry_address) = reinterpret_cast<Code*>(code)->entry();
5834 }
5835}
5836
5837
Ben Murdochb0fe1622011-05-05 13:52:32 +01005838void ObjectVisitor::VisitGlobalPropertyCell(RelocInfo* rinfo) {
5839 ASSERT(rinfo->rmode() == RelocInfo::GLOBAL_PROPERTY_CELL);
5840 Object* cell = rinfo->target_cell();
5841 Object* old_cell = cell;
5842 VisitPointer(&cell);
5843 if (cell != old_cell) {
5844 rinfo->set_target_cell(reinterpret_cast<JSGlobalPropertyCell*>(cell));
5845 }
5846}
5847
5848
Steve Blocka7e24c12009-10-30 11:49:00 +00005849void ObjectVisitor::VisitDebugTarget(RelocInfo* rinfo) {
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01005850 ASSERT((RelocInfo::IsJSReturn(rinfo->rmode()) &&
5851 rinfo->IsPatchedReturnSequence()) ||
5852 (RelocInfo::IsDebugBreakSlot(rinfo->rmode()) &&
5853 rinfo->IsPatchedDebugBreakSlotSequence()));
Steve Blocka7e24c12009-10-30 11:49:00 +00005854 Object* target = Code::GetCodeFromTargetAddress(rinfo->call_address());
5855 Object* old_target = target;
5856 VisitPointer(&target);
5857 CHECK_EQ(target, old_target); // VisitPointer doesn't change Code* *target.
5858}
5859
5860
Ben Murdochb0fe1622011-05-05 13:52:32 +01005861void Code::InvalidateRelocation() {
5862 HandleScope scope;
5863 set_relocation_info(Heap::empty_byte_array());
5864}
5865
5866
Steve Blockd0582a62009-12-15 09:54:21 +00005867void Code::Relocate(intptr_t delta) {
Steve Blocka7e24c12009-10-30 11:49:00 +00005868 for (RelocIterator it(this, RelocInfo::kApplyMask); !it.done(); it.next()) {
5869 it.rinfo()->apply(delta);
5870 }
5871 CPU::FlushICache(instruction_start(), instruction_size());
5872}
5873
5874
5875void Code::CopyFrom(const CodeDesc& desc) {
5876 // copy code
5877 memmove(instruction_start(), desc.buffer, desc.instr_size);
5878
Steve Blocka7e24c12009-10-30 11:49:00 +00005879 // copy reloc info
5880 memmove(relocation_start(),
5881 desc.buffer + desc.buffer_size - desc.reloc_size,
5882 desc.reloc_size);
5883
5884 // unbox handles and relocate
Steve Block3ce2e202009-11-05 08:53:23 +00005885 intptr_t delta = instruction_start() - desc.buffer;
Steve Blocka7e24c12009-10-30 11:49:00 +00005886 int mode_mask = RelocInfo::kCodeTargetMask |
5887 RelocInfo::ModeMask(RelocInfo::EMBEDDED_OBJECT) |
Ben Murdochb0fe1622011-05-05 13:52:32 +01005888 RelocInfo::ModeMask(RelocInfo::GLOBAL_PROPERTY_CELL) |
Steve Blocka7e24c12009-10-30 11:49:00 +00005889 RelocInfo::kApplyMask;
Steve Block3ce2e202009-11-05 08:53:23 +00005890 Assembler* origin = desc.origin; // Needed to find target_object on X64.
Steve Blocka7e24c12009-10-30 11:49:00 +00005891 for (RelocIterator it(this, mode_mask); !it.done(); it.next()) {
5892 RelocInfo::Mode mode = it.rinfo()->rmode();
5893 if (mode == RelocInfo::EMBEDDED_OBJECT) {
Steve Block3ce2e202009-11-05 08:53:23 +00005894 Handle<Object> p = it.rinfo()->target_object_handle(origin);
Steve Blocka7e24c12009-10-30 11:49:00 +00005895 it.rinfo()->set_target_object(*p);
Ben Murdochb0fe1622011-05-05 13:52:32 +01005896 } else if (mode == RelocInfo::GLOBAL_PROPERTY_CELL) {
5897 Handle<JSGlobalPropertyCell> cell = it.rinfo()->target_cell_handle();
5898 it.rinfo()->set_target_cell(*cell);
Steve Blocka7e24c12009-10-30 11:49:00 +00005899 } else if (RelocInfo::IsCodeTarget(mode)) {
5900 // rewrite code handles in inline cache targets to direct
5901 // pointers to the first instruction in the code object
Steve Block3ce2e202009-11-05 08:53:23 +00005902 Handle<Object> p = it.rinfo()->target_object_handle(origin);
Steve Blocka7e24c12009-10-30 11:49:00 +00005903 Code* code = Code::cast(*p);
5904 it.rinfo()->set_target_address(code->instruction_start());
5905 } else {
5906 it.rinfo()->apply(delta);
5907 }
5908 }
5909 CPU::FlushICache(instruction_start(), instruction_size());
5910}
5911
5912
5913// Locate the source position which is closest to the address in the code. This
5914// is using the source position information embedded in the relocation info.
5915// The position returned is relative to the beginning of the script where the
5916// source for this function is found.
5917int Code::SourcePosition(Address pc) {
5918 int distance = kMaxInt;
5919 int position = RelocInfo::kNoPosition; // Initially no position found.
5920 // Run through all the relocation info to find the best matching source
5921 // position. All the code needs to be considered as the sequence of the
5922 // instructions in the code does not necessarily follow the same order as the
5923 // source.
5924 RelocIterator it(this, RelocInfo::kPositionMask);
5925 while (!it.done()) {
5926 // Only look at positions after the current pc.
5927 if (it.rinfo()->pc() < pc) {
5928 // Get position and distance.
Steve Blockd0582a62009-12-15 09:54:21 +00005929
5930 int dist = static_cast<int>(pc - it.rinfo()->pc());
5931 int pos = static_cast<int>(it.rinfo()->data());
Steve Blocka7e24c12009-10-30 11:49:00 +00005932 // If this position is closer than the current candidate or if it has the
5933 // same distance as the current candidate and the position is higher then
5934 // this position is the new candidate.
5935 if ((dist < distance) ||
5936 (dist == distance && pos > position)) {
5937 position = pos;
5938 distance = dist;
5939 }
5940 }
5941 it.next();
5942 }
5943 return position;
5944}
5945
5946
5947// Same as Code::SourcePosition above except it only looks for statement
5948// positions.
5949int Code::SourceStatementPosition(Address pc) {
5950 // First find the position as close as possible using all position
5951 // information.
5952 int position = SourcePosition(pc);
5953 // Now find the closest statement position before the position.
5954 int statement_position = 0;
5955 RelocIterator it(this, RelocInfo::kPositionMask);
5956 while (!it.done()) {
5957 if (RelocInfo::IsStatementPosition(it.rinfo()->rmode())) {
Steve Blockd0582a62009-12-15 09:54:21 +00005958 int p = static_cast<int>(it.rinfo()->data());
Steve Blocka7e24c12009-10-30 11:49:00 +00005959 if (statement_position < p && p <= position) {
5960 statement_position = p;
5961 }
5962 }
5963 it.next();
5964 }
5965 return statement_position;
5966}
5967
5968
Ben Murdochb0fe1622011-05-05 13:52:32 +01005969uint8_t* Code::GetSafepointEntry(Address pc) {
5970 SafepointTable table(this);
5971 unsigned pc_offset = static_cast<unsigned>(pc - instruction_start());
5972 for (unsigned i = 0; i < table.length(); i++) {
5973 // TODO(kasperl): Replace the linear search with binary search.
5974 if (table.GetPcOffset(i) == pc_offset) return table.GetEntry(i);
5975 }
5976 return NULL;
5977}
5978
5979
5980void Code::SetNoStackCheckTable() {
5981 // Indicate the absence of a stack-check table by a table start after the
5982 // end of the instructions. Table start must be aligned, so round up.
5983 set_stack_check_table_start(RoundUp(instruction_size(), kIntSize));
5984}
5985
5986
5987Map* Code::FindFirstMap() {
5988 ASSERT(is_inline_cache_stub());
5989 AssertNoAllocation no_allocation;
5990 int mask = RelocInfo::ModeMask(RelocInfo::EMBEDDED_OBJECT);
5991 for (RelocIterator it(this, mask); !it.done(); it.next()) {
5992 RelocInfo* info = it.rinfo();
5993 Object* object = info->target_object();
5994 if (object->IsMap()) return Map::cast(object);
5995 }
5996 return NULL;
5997}
5998
5999
Steve Blocka7e24c12009-10-30 11:49:00 +00006000#ifdef ENABLE_DISASSEMBLER
Ben Murdochb0fe1622011-05-05 13:52:32 +01006001
6002#ifdef OBJECT_PRINT
6003
6004void DeoptimizationInputData::DeoptimizationInputDataPrint(FILE* out) {
6005 disasm::NameConverter converter;
6006 int deopt_count = DeoptCount();
6007 PrintF(out, "Deoptimization Input Data (deopt points = %d)\n", deopt_count);
6008 if (0 == deopt_count) return;
6009
6010 PrintF(out, "%6s %6s %6s %12s\n", "index", "ast id", "argc", "commands");
6011 for (int i = 0; i < deopt_count; i++) {
6012 int command_count = 0;
6013 PrintF(out, "%6d %6d %6d",
6014 i, AstId(i)->value(), ArgumentsStackHeight(i)->value());
6015 int translation_index = TranslationIndex(i)->value();
6016 TranslationIterator iterator(TranslationByteArray(), translation_index);
6017 Translation::Opcode opcode =
6018 static_cast<Translation::Opcode>(iterator.Next());
6019 ASSERT(Translation::BEGIN == opcode);
6020 int frame_count = iterator.Next();
6021 if (FLAG_print_code_verbose) {
6022 PrintF(out, " %s {count=%d}\n", Translation::StringFor(opcode),
6023 frame_count);
6024 }
6025
6026 for (int i = 0; i < frame_count; ++i) {
6027 opcode = static_cast<Translation::Opcode>(iterator.Next());
6028 ASSERT(Translation::FRAME == opcode);
6029 int ast_id = iterator.Next();
6030 int function_id = iterator.Next();
6031 JSFunction* function =
6032 JSFunction::cast(LiteralArray()->get(function_id));
6033 unsigned height = iterator.Next();
6034 if (FLAG_print_code_verbose) {
6035 PrintF(out, "%24s %s {ast_id=%d, function=",
6036 "", Translation::StringFor(opcode), ast_id);
6037 function->PrintName(out);
6038 PrintF(out, ", height=%u}\n", height);
6039 }
6040
6041 // Size of translation is height plus all incoming arguments including
6042 // receiver.
6043 int size = height + function->shared()->formal_parameter_count() + 1;
6044 command_count += size;
6045 for (int j = 0; j < size; ++j) {
6046 opcode = static_cast<Translation::Opcode>(iterator.Next());
6047 if (FLAG_print_code_verbose) {
6048 PrintF(out, "%24s %s ", "", Translation::StringFor(opcode));
6049 }
6050
6051 if (opcode == Translation::DUPLICATE) {
6052 opcode = static_cast<Translation::Opcode>(iterator.Next());
6053 if (FLAG_print_code_verbose) {
6054 PrintF(out, "%s ", Translation::StringFor(opcode));
6055 }
6056 --j; // Two commands share the same frame index.
6057 }
6058
6059 switch (opcode) {
6060 case Translation::BEGIN:
6061 case Translation::FRAME:
6062 case Translation::DUPLICATE:
6063 UNREACHABLE();
6064 break;
6065
6066 case Translation::REGISTER: {
6067 int reg_code = iterator.Next();
6068 if (FLAG_print_code_verbose) {
6069 PrintF(out, "{input=%s}", converter.NameOfCPURegister(reg_code));
6070 }
6071 break;
6072 }
6073
6074 case Translation::INT32_REGISTER: {
6075 int reg_code = iterator.Next();
6076 if (FLAG_print_code_verbose) {
6077 PrintF(out, "{input=%s}", converter.NameOfCPURegister(reg_code));
6078 }
6079 break;
6080 }
6081
6082 case Translation::DOUBLE_REGISTER: {
6083 int reg_code = iterator.Next();
6084 if (FLAG_print_code_verbose) {
6085 PrintF(out, "{input=%s}",
6086 DoubleRegister::AllocationIndexToString(reg_code));
6087 }
6088 break;
6089 }
6090
6091 case Translation::STACK_SLOT: {
6092 int input_slot_index = iterator.Next();
6093 if (FLAG_print_code_verbose) {
6094 PrintF(out, "{input=%d}", input_slot_index);
6095 }
6096 break;
6097 }
6098
6099 case Translation::INT32_STACK_SLOT: {
6100 int input_slot_index = iterator.Next();
6101 if (FLAG_print_code_verbose) {
6102 PrintF(out, "{input=%d}", input_slot_index);
6103 }
6104 break;
6105 }
6106
6107 case Translation::DOUBLE_STACK_SLOT: {
6108 int input_slot_index = iterator.Next();
6109 if (FLAG_print_code_verbose) {
6110 PrintF(out, "{input=%d}", input_slot_index);
6111 }
6112 break;
6113 }
6114
6115 case Translation::LITERAL: {
6116 unsigned literal_index = iterator.Next();
6117 if (FLAG_print_code_verbose) {
6118 PrintF(out, "{literal_id=%u}", literal_index);
6119 }
6120 break;
6121 }
6122
6123 case Translation::ARGUMENTS_OBJECT:
6124 break;
6125 }
6126 if (FLAG_print_code_verbose) PrintF(out, "\n");
6127 }
6128 }
6129 if (!FLAG_print_code_verbose) PrintF(out, " %12d\n", command_count);
6130 }
6131}
6132
6133
6134void DeoptimizationOutputData::DeoptimizationOutputDataPrint(FILE* out) {
6135 PrintF(out, "Deoptimization Output Data (deopt points = %d)\n",
6136 this->DeoptPoints());
6137 if (this->DeoptPoints() == 0) return;
6138
6139 PrintF("%6s %8s %s\n", "ast id", "pc", "state");
6140 for (int i = 0; i < this->DeoptPoints(); i++) {
6141 int pc_and_state = this->PcAndState(i)->value();
6142 PrintF("%6d %8d %s\n",
6143 this->AstId(i)->value(),
6144 FullCodeGenerator::PcField::decode(pc_and_state),
6145 FullCodeGenerator::State2String(
6146 FullCodeGenerator::StateField::decode(pc_and_state)));
6147 }
6148}
6149
6150#endif
6151
6152
Steve Blocka7e24c12009-10-30 11:49:00 +00006153// Identify kind of code.
6154const char* Code::Kind2String(Kind kind) {
6155 switch (kind) {
6156 case FUNCTION: return "FUNCTION";
Ben Murdochb0fe1622011-05-05 13:52:32 +01006157 case OPTIMIZED_FUNCTION: return "OPTIMIZED_FUNCTION";
Steve Blocka7e24c12009-10-30 11:49:00 +00006158 case STUB: return "STUB";
6159 case BUILTIN: return "BUILTIN";
6160 case LOAD_IC: return "LOAD_IC";
6161 case KEYED_LOAD_IC: return "KEYED_LOAD_IC";
6162 case STORE_IC: return "STORE_IC";
6163 case KEYED_STORE_IC: return "KEYED_STORE_IC";
6164 case CALL_IC: return "CALL_IC";
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01006165 case KEYED_CALL_IC: return "KEYED_CALL_IC";
Steve Block6ded16b2010-05-10 14:33:55 +01006166 case BINARY_OP_IC: return "BINARY_OP_IC";
Ben Murdochb0fe1622011-05-05 13:52:32 +01006167 case TYPE_RECORDING_BINARY_OP_IC: return "TYPE_RECORDING_BINARY_OP_IC";
6168 case COMPARE_IC: return "COMPARE_IC";
Steve Blocka7e24c12009-10-30 11:49:00 +00006169 }
6170 UNREACHABLE();
6171 return NULL;
6172}
6173
6174
6175const char* Code::ICState2String(InlineCacheState state) {
6176 switch (state) {
6177 case UNINITIALIZED: return "UNINITIALIZED";
6178 case PREMONOMORPHIC: return "PREMONOMORPHIC";
6179 case MONOMORPHIC: return "MONOMORPHIC";
6180 case MONOMORPHIC_PROTOTYPE_FAILURE: return "MONOMORPHIC_PROTOTYPE_FAILURE";
6181 case MEGAMORPHIC: return "MEGAMORPHIC";
6182 case DEBUG_BREAK: return "DEBUG_BREAK";
6183 case DEBUG_PREPARE_STEP_IN: return "DEBUG_PREPARE_STEP_IN";
6184 }
6185 UNREACHABLE();
6186 return NULL;
6187}
6188
6189
6190const char* Code::PropertyType2String(PropertyType type) {
6191 switch (type) {
6192 case NORMAL: return "NORMAL";
6193 case FIELD: return "FIELD";
6194 case CONSTANT_FUNCTION: return "CONSTANT_FUNCTION";
6195 case CALLBACKS: return "CALLBACKS";
6196 case INTERCEPTOR: return "INTERCEPTOR";
6197 case MAP_TRANSITION: return "MAP_TRANSITION";
6198 case CONSTANT_TRANSITION: return "CONSTANT_TRANSITION";
6199 case NULL_DESCRIPTOR: return "NULL_DESCRIPTOR";
6200 }
6201 UNREACHABLE();
6202 return NULL;
6203}
6204
Ben Murdochb0fe1622011-05-05 13:52:32 +01006205
6206void Code::Disassemble(const char* name, FILE* out) {
6207 PrintF(out, "kind = %s\n", Kind2String(kind()));
Steve Blocka7e24c12009-10-30 11:49:00 +00006208 if (is_inline_cache_stub()) {
Ben Murdochb0fe1622011-05-05 13:52:32 +01006209 PrintF(out, "ic_state = %s\n", ICState2String(ic_state()));
6210 PrintF(out, "ic_in_loop = %d\n", ic_in_loop() == IN_LOOP);
Steve Blocka7e24c12009-10-30 11:49:00 +00006211 if (ic_state() == MONOMORPHIC) {
Ben Murdochb0fe1622011-05-05 13:52:32 +01006212 PrintF(out, "type = %s\n", PropertyType2String(type()));
Steve Blocka7e24c12009-10-30 11:49:00 +00006213 }
6214 }
6215 if ((name != NULL) && (name[0] != '\0')) {
Ben Murdochb0fe1622011-05-05 13:52:32 +01006216 PrintF(out, "name = %s\n", name);
6217 }
6218 if (kind() == OPTIMIZED_FUNCTION) {
6219 PrintF(out, "stack_slots = %d\n", stack_slots());
Steve Blocka7e24c12009-10-30 11:49:00 +00006220 }
6221
Ben Murdochb0fe1622011-05-05 13:52:32 +01006222 PrintF(out, "Instructions (size = %d)\n", instruction_size());
6223 Disassembler::Decode(out, this);
6224 PrintF(out, "\n");
6225
6226#ifdef DEBUG
6227 if (kind() == FUNCTION) {
6228 DeoptimizationOutputData* data =
6229 DeoptimizationOutputData::cast(this->deoptimization_data());
6230 data->DeoptimizationOutputDataPrint(out);
6231 } else if (kind() == OPTIMIZED_FUNCTION) {
6232 DeoptimizationInputData* data =
6233 DeoptimizationInputData::cast(this->deoptimization_data());
6234 data->DeoptimizationInputDataPrint(out);
6235 }
Steve Blocka7e24c12009-10-30 11:49:00 +00006236 PrintF("\n");
Ben Murdochb0fe1622011-05-05 13:52:32 +01006237#endif
6238
6239 if (kind() == OPTIMIZED_FUNCTION) {
6240 SafepointTable table(this);
6241 PrintF(out, "Safepoints (size = %u)\n", table.size());
6242 for (unsigned i = 0; i < table.length(); i++) {
6243 unsigned pc_offset = table.GetPcOffset(i);
6244 PrintF(out, "%p %4d ", (instruction_start() + pc_offset), pc_offset);
6245 table.PrintEntry(i);
6246 PrintF(out, " (sp -> fp)");
6247 int deoptimization_index = table.GetDeoptimizationIndex(i);
6248 if (deoptimization_index != Safepoint::kNoDeoptimizationIndex) {
6249 PrintF(out, " %6d", deoptimization_index);
6250 } else {
6251 PrintF(out, " <none>");
6252 }
6253 PrintF(out, "\n");
6254 }
6255 PrintF(out, "\n");
6256 } else if (kind() == FUNCTION) {
6257 unsigned offset = stack_check_table_start();
6258 // If there is no stack check table, the "table start" will at or after
6259 // (due to alignment) the end of the instruction stream.
6260 if (static_cast<int>(offset) < instruction_size()) {
6261 unsigned* address =
6262 reinterpret_cast<unsigned*>(instruction_start() + offset);
6263 unsigned length = address[0];
6264 PrintF(out, "Stack checks (size = %u)\n", length);
6265 PrintF(out, "ast_id pc_offset\n");
6266 for (unsigned i = 0; i < length; ++i) {
6267 unsigned index = (2 * i) + 1;
6268 PrintF(out, "%6u %9u\n", address[index], address[index + 1]);
6269 }
6270 PrintF(out, "\n");
6271 }
6272 }
Steve Blocka7e24c12009-10-30 11:49:00 +00006273
6274 PrintF("RelocInfo (size = %d)\n", relocation_size());
Ben Murdochb0fe1622011-05-05 13:52:32 +01006275 for (RelocIterator it(this); !it.done(); it.next()) it.rinfo()->Print(out);
6276 PrintF(out, "\n");
Steve Blocka7e24c12009-10-30 11:49:00 +00006277}
6278#endif // ENABLE_DISASSEMBLER
6279
6280
John Reck59135872010-11-02 12:39:01 -07006281MaybeObject* JSObject::SetFastElementsCapacityAndLength(int capacity,
6282 int length) {
Steve Block3ce2e202009-11-05 08:53:23 +00006283 // We should never end in here with a pixel or external array.
6284 ASSERT(!HasPixelElements() && !HasExternalArrayElements());
Steve Block8defd9f2010-07-08 12:39:36 +01006285
John Reck59135872010-11-02 12:39:01 -07006286 Object* obj;
6287 { MaybeObject* maybe_obj = Heap::AllocateFixedArrayWithHoles(capacity);
6288 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
6289 }
Steve Block8defd9f2010-07-08 12:39:36 +01006290 FixedArray* elems = FixedArray::cast(obj);
6291
John Reck59135872010-11-02 12:39:01 -07006292 { MaybeObject* maybe_obj = map()->GetFastElementsMap();
6293 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
6294 }
Steve Block8defd9f2010-07-08 12:39:36 +01006295 Map* new_map = Map::cast(obj);
6296
Leon Clarke4515c472010-02-03 11:58:03 +00006297 AssertNoAllocation no_gc;
6298 WriteBarrierMode mode = elems->GetWriteBarrierMode(no_gc);
Steve Blocka7e24c12009-10-30 11:49:00 +00006299 switch (GetElementsKind()) {
6300 case FAST_ELEMENTS: {
6301 FixedArray* old_elements = FixedArray::cast(elements());
6302 uint32_t old_length = static_cast<uint32_t>(old_elements->length());
6303 // Fill out the new array with this content and array holes.
6304 for (uint32_t i = 0; i < old_length; i++) {
6305 elems->set(i, old_elements->get(i), mode);
6306 }
6307 break;
6308 }
6309 case DICTIONARY_ELEMENTS: {
6310 NumberDictionary* dictionary = NumberDictionary::cast(elements());
6311 for (int i = 0; i < dictionary->Capacity(); i++) {
6312 Object* key = dictionary->KeyAt(i);
6313 if (key->IsNumber()) {
6314 uint32_t entry = static_cast<uint32_t>(key->Number());
6315 elems->set(entry, dictionary->ValueAt(i), mode);
6316 }
6317 }
6318 break;
6319 }
6320 default:
6321 UNREACHABLE();
6322 break;
6323 }
Steve Block8defd9f2010-07-08 12:39:36 +01006324
6325 set_map(new_map);
Steve Blocka7e24c12009-10-30 11:49:00 +00006326 set_elements(elems);
Steve Block8defd9f2010-07-08 12:39:36 +01006327
6328 if (IsJSArray()) {
6329 JSArray::cast(this)->set_length(Smi::FromInt(length));
6330 }
6331
6332 return this;
Steve Blocka7e24c12009-10-30 11:49:00 +00006333}
6334
6335
John Reck59135872010-11-02 12:39:01 -07006336MaybeObject* JSObject::SetSlowElements(Object* len) {
Steve Block3ce2e202009-11-05 08:53:23 +00006337 // We should never end in here with a pixel or external array.
6338 ASSERT(!HasPixelElements() && !HasExternalArrayElements());
Steve Blocka7e24c12009-10-30 11:49:00 +00006339
6340 uint32_t new_length = static_cast<uint32_t>(len->Number());
6341
6342 switch (GetElementsKind()) {
6343 case FAST_ELEMENTS: {
6344 // Make sure we never try to shrink dense arrays into sparse arrays.
6345 ASSERT(static_cast<uint32_t>(FixedArray::cast(elements())->length()) <=
6346 new_length);
John Reck59135872010-11-02 12:39:01 -07006347 Object* obj;
6348 { MaybeObject* maybe_obj = NormalizeElements();
6349 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
6350 }
Steve Blocka7e24c12009-10-30 11:49:00 +00006351
6352 // Update length for JSArrays.
6353 if (IsJSArray()) JSArray::cast(this)->set_length(len);
6354 break;
6355 }
6356 case DICTIONARY_ELEMENTS: {
6357 if (IsJSArray()) {
6358 uint32_t old_length =
Steve Block6ded16b2010-05-10 14:33:55 +01006359 static_cast<uint32_t>(JSArray::cast(this)->length()->Number());
Steve Blocka7e24c12009-10-30 11:49:00 +00006360 element_dictionary()->RemoveNumberEntries(new_length, old_length),
6361 JSArray::cast(this)->set_length(len);
6362 }
6363 break;
6364 }
6365 default:
6366 UNREACHABLE();
6367 break;
6368 }
6369 return this;
6370}
6371
6372
John Reck59135872010-11-02 12:39:01 -07006373MaybeObject* JSArray::Initialize(int capacity) {
Steve Blocka7e24c12009-10-30 11:49:00 +00006374 ASSERT(capacity >= 0);
Leon Clarke4515c472010-02-03 11:58:03 +00006375 set_length(Smi::FromInt(0));
Steve Blocka7e24c12009-10-30 11:49:00 +00006376 FixedArray* new_elements;
6377 if (capacity == 0) {
6378 new_elements = Heap::empty_fixed_array();
6379 } else {
John Reck59135872010-11-02 12:39:01 -07006380 Object* obj;
6381 { MaybeObject* maybe_obj = Heap::AllocateFixedArrayWithHoles(capacity);
6382 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
6383 }
Steve Blocka7e24c12009-10-30 11:49:00 +00006384 new_elements = FixedArray::cast(obj);
6385 }
6386 set_elements(new_elements);
6387 return this;
6388}
6389
6390
6391void JSArray::Expand(int required_size) {
6392 Handle<JSArray> self(this);
6393 Handle<FixedArray> old_backing(FixedArray::cast(elements()));
6394 int old_size = old_backing->length();
Steve Blockd0582a62009-12-15 09:54:21 +00006395 int new_size = required_size > old_size ? required_size : old_size;
Steve Blocka7e24c12009-10-30 11:49:00 +00006396 Handle<FixedArray> new_backing = Factory::NewFixedArray(new_size);
6397 // Can't use this any more now because we may have had a GC!
6398 for (int i = 0; i < old_size; i++) new_backing->set(i, old_backing->get(i));
6399 self->SetContent(*new_backing);
6400}
6401
6402
6403// Computes the new capacity when expanding the elements of a JSObject.
6404static int NewElementsCapacity(int old_capacity) {
6405 // (old_capacity + 50%) + 16
6406 return old_capacity + (old_capacity >> 1) + 16;
6407}
6408
6409
John Reck59135872010-11-02 12:39:01 -07006410static Failure* ArrayLengthRangeError() {
Steve Blocka7e24c12009-10-30 11:49:00 +00006411 HandleScope scope;
6412 return Top::Throw(*Factory::NewRangeError("invalid_array_length",
6413 HandleVector<Object>(NULL, 0)));
6414}
6415
6416
John Reck59135872010-11-02 12:39:01 -07006417MaybeObject* JSObject::SetElementsLength(Object* len) {
Steve Block3ce2e202009-11-05 08:53:23 +00006418 // We should never end in here with a pixel or external array.
Steve Block6ded16b2010-05-10 14:33:55 +01006419 ASSERT(AllowsSetElementsLength());
Steve Blocka7e24c12009-10-30 11:49:00 +00006420
John Reck59135872010-11-02 12:39:01 -07006421 MaybeObject* maybe_smi_length = len->ToSmi();
6422 Object* smi_length = Smi::FromInt(0);
6423 if (maybe_smi_length->ToObject(&smi_length) && smi_length->IsSmi()) {
Steve Block8defd9f2010-07-08 12:39:36 +01006424 const int value = Smi::cast(smi_length)->value();
Steve Blocka7e24c12009-10-30 11:49:00 +00006425 if (value < 0) return ArrayLengthRangeError();
6426 switch (GetElementsKind()) {
6427 case FAST_ELEMENTS: {
6428 int old_capacity = FixedArray::cast(elements())->length();
6429 if (value <= old_capacity) {
6430 if (IsJSArray()) {
John Reck59135872010-11-02 12:39:01 -07006431 Object* obj;
6432 { MaybeObject* maybe_obj = EnsureWritableFastElements();
6433 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
6434 }
Steve Blocka7e24c12009-10-30 11:49:00 +00006435 int old_length = FastD2I(JSArray::cast(this)->length()->Number());
6436 // NOTE: We may be able to optimize this by removing the
6437 // last part of the elements backing storage array and
6438 // setting the capacity to the new size.
6439 for (int i = value; i < old_length; i++) {
6440 FixedArray::cast(elements())->set_the_hole(i);
6441 }
Leon Clarke4515c472010-02-03 11:58:03 +00006442 JSArray::cast(this)->set_length(Smi::cast(smi_length));
Steve Blocka7e24c12009-10-30 11:49:00 +00006443 }
6444 return this;
6445 }
6446 int min = NewElementsCapacity(old_capacity);
6447 int new_capacity = value > min ? value : min;
6448 if (new_capacity <= kMaxFastElementsLength ||
6449 !ShouldConvertToSlowElements(new_capacity)) {
John Reck59135872010-11-02 12:39:01 -07006450 Object* obj;
6451 { MaybeObject* maybe_obj =
6452 SetFastElementsCapacityAndLength(new_capacity, value);
6453 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
6454 }
Steve Blocka7e24c12009-10-30 11:49:00 +00006455 return this;
6456 }
6457 break;
6458 }
6459 case DICTIONARY_ELEMENTS: {
6460 if (IsJSArray()) {
6461 if (value == 0) {
6462 // If the length of a slow array is reset to zero, we clear
6463 // the array and flush backing storage. This has the added
6464 // benefit that the array returns to fast mode.
John Reck59135872010-11-02 12:39:01 -07006465 Object* obj;
6466 { MaybeObject* maybe_obj = ResetElements();
6467 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
6468 }
Steve Blocka7e24c12009-10-30 11:49:00 +00006469 } else {
6470 // Remove deleted elements.
6471 uint32_t old_length =
6472 static_cast<uint32_t>(JSArray::cast(this)->length()->Number());
6473 element_dictionary()->RemoveNumberEntries(value, old_length);
6474 }
Leon Clarke4515c472010-02-03 11:58:03 +00006475 JSArray::cast(this)->set_length(Smi::cast(smi_length));
Steve Blocka7e24c12009-10-30 11:49:00 +00006476 }
6477 return this;
6478 }
6479 default:
6480 UNREACHABLE();
6481 break;
6482 }
6483 }
6484
6485 // General slow case.
6486 if (len->IsNumber()) {
6487 uint32_t length;
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01006488 if (len->ToArrayIndex(&length)) {
Steve Blocka7e24c12009-10-30 11:49:00 +00006489 return SetSlowElements(len);
6490 } else {
6491 return ArrayLengthRangeError();
6492 }
6493 }
6494
6495 // len is not a number so make the array size one and
6496 // set only element to len.
John Reck59135872010-11-02 12:39:01 -07006497 Object* obj;
6498 { MaybeObject* maybe_obj = Heap::AllocateFixedArray(1);
6499 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
6500 }
Steve Blocka7e24c12009-10-30 11:49:00 +00006501 FixedArray::cast(obj)->set(0, len);
Leon Clarke4515c472010-02-03 11:58:03 +00006502 if (IsJSArray()) JSArray::cast(this)->set_length(Smi::FromInt(1));
Steve Blocka7e24c12009-10-30 11:49:00 +00006503 set_elements(FixedArray::cast(obj));
6504 return this;
6505}
6506
6507
John Reck59135872010-11-02 12:39:01 -07006508MaybeObject* JSObject::SetPrototype(Object* value,
6509 bool skip_hidden_prototypes) {
Andrei Popescu402d9372010-02-26 13:31:12 +00006510 // Silently ignore the change if value is not a JSObject or null.
6511 // SpiderMonkey behaves this way.
6512 if (!value->IsJSObject() && !value->IsNull()) return value;
6513
6514 // Before we can set the prototype we need to be sure
6515 // prototype cycles are prevented.
6516 // It is sufficient to validate that the receiver is not in the new prototype
6517 // chain.
6518 for (Object* pt = value; pt != Heap::null_value(); pt = pt->GetPrototype()) {
6519 if (JSObject::cast(pt) == this) {
6520 // Cycle detected.
6521 HandleScope scope;
6522 return Top::Throw(*Factory::NewError("cyclic_proto",
6523 HandleVector<Object>(NULL, 0)));
6524 }
6525 }
6526
6527 JSObject* real_receiver = this;
6528
6529 if (skip_hidden_prototypes) {
6530 // Find the first object in the chain whose prototype object is not
6531 // hidden and set the new prototype on that object.
6532 Object* current_proto = real_receiver->GetPrototype();
6533 while (current_proto->IsJSObject() &&
6534 JSObject::cast(current_proto)->map()->is_hidden_prototype()) {
6535 real_receiver = JSObject::cast(current_proto);
6536 current_proto = current_proto->GetPrototype();
6537 }
6538 }
6539
6540 // Set the new prototype of the object.
John Reck59135872010-11-02 12:39:01 -07006541 Object* new_map;
6542 { MaybeObject* maybe_new_map = real_receiver->map()->CopyDropTransitions();
6543 if (!maybe_new_map->ToObject(&new_map)) return maybe_new_map;
6544 }
Andrei Popescu402d9372010-02-26 13:31:12 +00006545 Map::cast(new_map)->set_prototype(value);
6546 real_receiver->set_map(Map::cast(new_map));
6547
Kristian Monsen25f61362010-05-21 11:50:48 +01006548 Heap::ClearInstanceofCache();
6549
Andrei Popescu402d9372010-02-26 13:31:12 +00006550 return value;
6551}
6552
6553
Steve Blocka7e24c12009-10-30 11:49:00 +00006554bool JSObject::HasElementPostInterceptor(JSObject* receiver, uint32_t index) {
6555 switch (GetElementsKind()) {
6556 case FAST_ELEMENTS: {
6557 uint32_t length = IsJSArray() ?
6558 static_cast<uint32_t>
6559 (Smi::cast(JSArray::cast(this)->length())->value()) :
6560 static_cast<uint32_t>(FixedArray::cast(elements())->length());
6561 if ((index < length) &&
6562 !FixedArray::cast(elements())->get(index)->IsTheHole()) {
6563 return true;
6564 }
6565 break;
6566 }
6567 case PIXEL_ELEMENTS: {
6568 // TODO(iposva): Add testcase.
6569 PixelArray* pixels = PixelArray::cast(elements());
6570 if (index < static_cast<uint32_t>(pixels->length())) {
6571 return true;
6572 }
6573 break;
6574 }
Steve Block3ce2e202009-11-05 08:53:23 +00006575 case EXTERNAL_BYTE_ELEMENTS:
6576 case EXTERNAL_UNSIGNED_BYTE_ELEMENTS:
6577 case EXTERNAL_SHORT_ELEMENTS:
6578 case EXTERNAL_UNSIGNED_SHORT_ELEMENTS:
6579 case EXTERNAL_INT_ELEMENTS:
6580 case EXTERNAL_UNSIGNED_INT_ELEMENTS:
6581 case EXTERNAL_FLOAT_ELEMENTS: {
6582 // TODO(kbr): Add testcase.
6583 ExternalArray* array = ExternalArray::cast(elements());
6584 if (index < static_cast<uint32_t>(array->length())) {
6585 return true;
6586 }
6587 break;
6588 }
Steve Blocka7e24c12009-10-30 11:49:00 +00006589 case DICTIONARY_ELEMENTS: {
6590 if (element_dictionary()->FindEntry(index)
6591 != NumberDictionary::kNotFound) {
6592 return true;
6593 }
6594 break;
6595 }
6596 default:
6597 UNREACHABLE();
6598 break;
6599 }
6600
6601 // Handle [] on String objects.
6602 if (this->IsStringObjectWithCharacterAt(index)) return true;
6603
6604 Object* pt = GetPrototype();
6605 if (pt == Heap::null_value()) return false;
6606 return JSObject::cast(pt)->HasElementWithReceiver(receiver, index);
6607}
6608
6609
6610bool JSObject::HasElementWithInterceptor(JSObject* receiver, uint32_t index) {
6611 // Make sure that the top context does not change when doing
6612 // callbacks or interceptor calls.
6613 AssertNoContextChange ncc;
6614 HandleScope scope;
6615 Handle<InterceptorInfo> interceptor(GetIndexedInterceptor());
6616 Handle<JSObject> receiver_handle(receiver);
6617 Handle<JSObject> holder_handle(this);
6618 CustomArguments args(interceptor->data(), receiver, this);
6619 v8::AccessorInfo info(args.end());
6620 if (!interceptor->query()->IsUndefined()) {
6621 v8::IndexedPropertyQuery query =
6622 v8::ToCData<v8::IndexedPropertyQuery>(interceptor->query());
6623 LOG(ApiIndexedPropertyAccess("interceptor-indexed-has", this, index));
Iain Merrick75681382010-08-19 15:07:18 +01006624 v8::Handle<v8::Integer> result;
Steve Blocka7e24c12009-10-30 11:49:00 +00006625 {
6626 // Leaving JavaScript.
6627 VMState state(EXTERNAL);
6628 result = query(index, info);
6629 }
Iain Merrick75681382010-08-19 15:07:18 +01006630 if (!result.IsEmpty()) {
6631 ASSERT(result->IsInt32());
6632 return true; // absence of property is signaled by empty handle.
6633 }
Steve Blocka7e24c12009-10-30 11:49:00 +00006634 } else if (!interceptor->getter()->IsUndefined()) {
6635 v8::IndexedPropertyGetter getter =
6636 v8::ToCData<v8::IndexedPropertyGetter>(interceptor->getter());
6637 LOG(ApiIndexedPropertyAccess("interceptor-indexed-has-get", this, index));
6638 v8::Handle<v8::Value> result;
6639 {
6640 // Leaving JavaScript.
6641 VMState state(EXTERNAL);
6642 result = getter(index, info);
6643 }
6644 if (!result.IsEmpty()) return true;
6645 }
6646 return holder_handle->HasElementPostInterceptor(*receiver_handle, index);
6647}
6648
6649
Kristian Monsen0d5e1162010-09-30 15:31:59 +01006650JSObject::LocalElementType JSObject::HasLocalElement(uint32_t index) {
Steve Blocka7e24c12009-10-30 11:49:00 +00006651 // Check access rights if needed.
6652 if (IsAccessCheckNeeded() &&
6653 !Top::MayIndexedAccess(this, index, v8::ACCESS_HAS)) {
6654 Top::ReportFailedAccessCheck(this, v8::ACCESS_HAS);
Kristian Monsen0d5e1162010-09-30 15:31:59 +01006655 return UNDEFINED_ELEMENT;
Steve Blocka7e24c12009-10-30 11:49:00 +00006656 }
6657
6658 // Check for lookup interceptor
6659 if (HasIndexedInterceptor()) {
Kristian Monsen0d5e1162010-09-30 15:31:59 +01006660 return HasElementWithInterceptor(this, index) ? INTERCEPTED_ELEMENT
6661 : UNDEFINED_ELEMENT;
Steve Blocka7e24c12009-10-30 11:49:00 +00006662 }
6663
6664 // Handle [] on String objects.
Kristian Monsen0d5e1162010-09-30 15:31:59 +01006665 if (this->IsStringObjectWithCharacterAt(index)) {
6666 return STRING_CHARACTER_ELEMENT;
6667 }
Steve Blocka7e24c12009-10-30 11:49:00 +00006668
6669 switch (GetElementsKind()) {
6670 case FAST_ELEMENTS: {
6671 uint32_t length = IsJSArray() ?
6672 static_cast<uint32_t>
6673 (Smi::cast(JSArray::cast(this)->length())->value()) :
6674 static_cast<uint32_t>(FixedArray::cast(elements())->length());
Kristian Monsen0d5e1162010-09-30 15:31:59 +01006675 if ((index < length) &&
6676 !FixedArray::cast(elements())->get(index)->IsTheHole()) {
6677 return FAST_ELEMENT;
6678 }
6679 break;
Steve Blocka7e24c12009-10-30 11:49:00 +00006680 }
6681 case PIXEL_ELEMENTS: {
6682 PixelArray* pixels = PixelArray::cast(elements());
Kristian Monsen0d5e1162010-09-30 15:31:59 +01006683 if (index < static_cast<uint32_t>(pixels->length())) return FAST_ELEMENT;
6684 break;
Steve Blocka7e24c12009-10-30 11:49:00 +00006685 }
Steve Block3ce2e202009-11-05 08:53:23 +00006686 case EXTERNAL_BYTE_ELEMENTS:
6687 case EXTERNAL_UNSIGNED_BYTE_ELEMENTS:
6688 case EXTERNAL_SHORT_ELEMENTS:
6689 case EXTERNAL_UNSIGNED_SHORT_ELEMENTS:
6690 case EXTERNAL_INT_ELEMENTS:
6691 case EXTERNAL_UNSIGNED_INT_ELEMENTS:
6692 case EXTERNAL_FLOAT_ELEMENTS: {
6693 ExternalArray* array = ExternalArray::cast(elements());
Kristian Monsen0d5e1162010-09-30 15:31:59 +01006694 if (index < static_cast<uint32_t>(array->length())) return FAST_ELEMENT;
6695 break;
Steve Block3ce2e202009-11-05 08:53:23 +00006696 }
Steve Blocka7e24c12009-10-30 11:49:00 +00006697 case DICTIONARY_ELEMENTS: {
Kristian Monsen0d5e1162010-09-30 15:31:59 +01006698 if (element_dictionary()->FindEntry(index) !=
6699 NumberDictionary::kNotFound) {
6700 return DICTIONARY_ELEMENT;
6701 }
6702 break;
Steve Blocka7e24c12009-10-30 11:49:00 +00006703 }
6704 default:
6705 UNREACHABLE();
6706 break;
6707 }
Kristian Monsen0d5e1162010-09-30 15:31:59 +01006708
6709 return UNDEFINED_ELEMENT;
Steve Blocka7e24c12009-10-30 11:49:00 +00006710}
6711
6712
6713bool JSObject::HasElementWithReceiver(JSObject* receiver, uint32_t index) {
6714 // Check access rights if needed.
6715 if (IsAccessCheckNeeded() &&
6716 !Top::MayIndexedAccess(this, index, v8::ACCESS_HAS)) {
6717 Top::ReportFailedAccessCheck(this, v8::ACCESS_HAS);
6718 return false;
6719 }
6720
6721 // Check for lookup interceptor
6722 if (HasIndexedInterceptor()) {
6723 return HasElementWithInterceptor(receiver, index);
6724 }
6725
6726 switch (GetElementsKind()) {
6727 case FAST_ELEMENTS: {
6728 uint32_t length = IsJSArray() ?
6729 static_cast<uint32_t>
6730 (Smi::cast(JSArray::cast(this)->length())->value()) :
6731 static_cast<uint32_t>(FixedArray::cast(elements())->length());
6732 if ((index < length) &&
6733 !FixedArray::cast(elements())->get(index)->IsTheHole()) return true;
6734 break;
6735 }
6736 case PIXEL_ELEMENTS: {
6737 PixelArray* pixels = PixelArray::cast(elements());
6738 if (index < static_cast<uint32_t>(pixels->length())) {
6739 return true;
6740 }
6741 break;
6742 }
Steve Block3ce2e202009-11-05 08:53:23 +00006743 case EXTERNAL_BYTE_ELEMENTS:
6744 case EXTERNAL_UNSIGNED_BYTE_ELEMENTS:
6745 case EXTERNAL_SHORT_ELEMENTS:
6746 case EXTERNAL_UNSIGNED_SHORT_ELEMENTS:
6747 case EXTERNAL_INT_ELEMENTS:
6748 case EXTERNAL_UNSIGNED_INT_ELEMENTS:
6749 case EXTERNAL_FLOAT_ELEMENTS: {
6750 ExternalArray* array = ExternalArray::cast(elements());
6751 if (index < static_cast<uint32_t>(array->length())) {
6752 return true;
6753 }
6754 break;
6755 }
Steve Blocka7e24c12009-10-30 11:49:00 +00006756 case DICTIONARY_ELEMENTS: {
6757 if (element_dictionary()->FindEntry(index)
6758 != NumberDictionary::kNotFound) {
6759 return true;
6760 }
6761 break;
6762 }
6763 default:
6764 UNREACHABLE();
6765 break;
6766 }
6767
6768 // Handle [] on String objects.
6769 if (this->IsStringObjectWithCharacterAt(index)) return true;
6770
6771 Object* pt = GetPrototype();
6772 if (pt == Heap::null_value()) return false;
6773 return JSObject::cast(pt)->HasElementWithReceiver(receiver, index);
6774}
6775
6776
John Reck59135872010-11-02 12:39:01 -07006777MaybeObject* JSObject::SetElementWithInterceptor(uint32_t index,
6778 Object* value) {
Steve Blocka7e24c12009-10-30 11:49:00 +00006779 // Make sure that the top context does not change when doing
6780 // callbacks or interceptor calls.
6781 AssertNoContextChange ncc;
6782 HandleScope scope;
6783 Handle<InterceptorInfo> interceptor(GetIndexedInterceptor());
6784 Handle<JSObject> this_handle(this);
6785 Handle<Object> value_handle(value);
6786 if (!interceptor->setter()->IsUndefined()) {
6787 v8::IndexedPropertySetter setter =
6788 v8::ToCData<v8::IndexedPropertySetter>(interceptor->setter());
6789 LOG(ApiIndexedPropertyAccess("interceptor-indexed-set", this, index));
6790 CustomArguments args(interceptor->data(), this, this);
6791 v8::AccessorInfo info(args.end());
6792 v8::Handle<v8::Value> result;
6793 {
6794 // Leaving JavaScript.
6795 VMState state(EXTERNAL);
6796 result = setter(index, v8::Utils::ToLocal(value_handle), info);
6797 }
6798 RETURN_IF_SCHEDULED_EXCEPTION();
6799 if (!result.IsEmpty()) return *value_handle;
6800 }
John Reck59135872010-11-02 12:39:01 -07006801 MaybeObject* raw_result =
Steve Blocka7e24c12009-10-30 11:49:00 +00006802 this_handle->SetElementWithoutInterceptor(index, *value_handle);
6803 RETURN_IF_SCHEDULED_EXCEPTION();
6804 return raw_result;
6805}
6806
6807
John Reck59135872010-11-02 12:39:01 -07006808MaybeObject* JSObject::GetElementWithCallback(Object* receiver,
6809 Object* structure,
6810 uint32_t index,
6811 Object* holder) {
Leon Clarkef7060e22010-06-03 12:02:55 +01006812 ASSERT(!structure->IsProxy());
6813
6814 // api style callbacks.
6815 if (structure->IsAccessorInfo()) {
6816 AccessorInfo* data = AccessorInfo::cast(structure);
6817 Object* fun_obj = data->getter();
6818 v8::AccessorGetter call_fun = v8::ToCData<v8::AccessorGetter>(fun_obj);
6819 HandleScope scope;
6820 Handle<JSObject> self(JSObject::cast(receiver));
6821 Handle<JSObject> holder_handle(JSObject::cast(holder));
6822 Handle<Object> number = Factory::NewNumberFromUint(index);
6823 Handle<String> key(Factory::NumberToString(number));
6824 LOG(ApiNamedPropertyAccess("load", *self, *key));
6825 CustomArguments args(data->data(), *self, *holder_handle);
6826 v8::AccessorInfo info(args.end());
6827 v8::Handle<v8::Value> result;
6828 {
6829 // Leaving JavaScript.
6830 VMState state(EXTERNAL);
6831 result = call_fun(v8::Utils::ToLocal(key), info);
6832 }
6833 RETURN_IF_SCHEDULED_EXCEPTION();
6834 if (result.IsEmpty()) return Heap::undefined_value();
6835 return *v8::Utils::OpenHandle(*result);
6836 }
6837
6838 // __defineGetter__ callback
6839 if (structure->IsFixedArray()) {
6840 Object* getter = FixedArray::cast(structure)->get(kGetterIndex);
6841 if (getter->IsJSFunction()) {
6842 return Object::GetPropertyWithDefinedGetter(receiver,
6843 JSFunction::cast(getter));
6844 }
6845 // Getter is not a function.
6846 return Heap::undefined_value();
6847 }
6848
6849 UNREACHABLE();
6850 return NULL;
6851}
6852
6853
John Reck59135872010-11-02 12:39:01 -07006854MaybeObject* JSObject::SetElementWithCallback(Object* structure,
6855 uint32_t index,
6856 Object* value,
6857 JSObject* holder) {
Leon Clarkef7060e22010-06-03 12:02:55 +01006858 HandleScope scope;
6859
6860 // We should never get here to initialize a const with the hole
6861 // value since a const declaration would conflict with the setter.
6862 ASSERT(!value->IsTheHole());
6863 Handle<Object> value_handle(value);
6864
6865 // To accommodate both the old and the new api we switch on the
6866 // data structure used to store the callbacks. Eventually proxy
6867 // callbacks should be phased out.
6868 ASSERT(!structure->IsProxy());
6869
6870 if (structure->IsAccessorInfo()) {
6871 // api style callbacks
6872 AccessorInfo* data = AccessorInfo::cast(structure);
6873 Object* call_obj = data->setter();
6874 v8::AccessorSetter call_fun = v8::ToCData<v8::AccessorSetter>(call_obj);
6875 if (call_fun == NULL) return value;
6876 Handle<Object> number = Factory::NewNumberFromUint(index);
6877 Handle<String> key(Factory::NumberToString(number));
6878 LOG(ApiNamedPropertyAccess("store", this, *key));
6879 CustomArguments args(data->data(), this, JSObject::cast(holder));
6880 v8::AccessorInfo info(args.end());
6881 {
6882 // Leaving JavaScript.
6883 VMState state(EXTERNAL);
6884 call_fun(v8::Utils::ToLocal(key),
6885 v8::Utils::ToLocal(value_handle),
6886 info);
6887 }
6888 RETURN_IF_SCHEDULED_EXCEPTION();
6889 return *value_handle;
6890 }
6891
6892 if (structure->IsFixedArray()) {
6893 Object* setter = FixedArray::cast(structure)->get(kSetterIndex);
6894 if (setter->IsJSFunction()) {
6895 return SetPropertyWithDefinedSetter(JSFunction::cast(setter), value);
6896 } else {
6897 Handle<Object> holder_handle(holder);
6898 Handle<Object> key(Factory::NewNumberFromUint(index));
6899 Handle<Object> args[2] = { key, holder_handle };
6900 return Top::Throw(*Factory::NewTypeError("no_setter_in_callback",
6901 HandleVector(args, 2)));
6902 }
6903 }
6904
6905 UNREACHABLE();
6906 return NULL;
6907}
6908
6909
Steve Blocka7e24c12009-10-30 11:49:00 +00006910// Adding n elements in fast case is O(n*n).
6911// Note: revisit design to have dual undefined values to capture absent
6912// elements.
John Reck59135872010-11-02 12:39:01 -07006913MaybeObject* JSObject::SetFastElement(uint32_t index, Object* value) {
Steve Blocka7e24c12009-10-30 11:49:00 +00006914 ASSERT(HasFastElements());
6915
John Reck59135872010-11-02 12:39:01 -07006916 Object* elms_obj;
6917 { MaybeObject* maybe_elms_obj = EnsureWritableFastElements();
6918 if (!maybe_elms_obj->ToObject(&elms_obj)) return maybe_elms_obj;
6919 }
Iain Merrick75681382010-08-19 15:07:18 +01006920 FixedArray* elms = FixedArray::cast(elms_obj);
Steve Blocka7e24c12009-10-30 11:49:00 +00006921 uint32_t elms_length = static_cast<uint32_t>(elms->length());
6922
6923 if (!IsJSArray() && (index >= elms_length || elms->get(index)->IsTheHole())) {
Leon Clarkef7060e22010-06-03 12:02:55 +01006924 if (SetElementWithCallbackSetterInPrototypes(index, value)) {
6925 return value;
Steve Blocka7e24c12009-10-30 11:49:00 +00006926 }
6927 }
6928
6929 // Check whether there is extra space in fixed array..
6930 if (index < elms_length) {
6931 elms->set(index, value);
6932 if (IsJSArray()) {
6933 // Update the length of the array if needed.
6934 uint32_t array_length = 0;
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01006935 CHECK(JSArray::cast(this)->length()->ToArrayIndex(&array_length));
Steve Blocka7e24c12009-10-30 11:49:00 +00006936 if (index >= array_length) {
Leon Clarke4515c472010-02-03 11:58:03 +00006937 JSArray::cast(this)->set_length(Smi::FromInt(index + 1));
Steve Blocka7e24c12009-10-30 11:49:00 +00006938 }
6939 }
6940 return value;
6941 }
6942
6943 // Allow gap in fast case.
6944 if ((index - elms_length) < kMaxGap) {
6945 // Try allocating extra space.
6946 int new_capacity = NewElementsCapacity(index+1);
6947 if (new_capacity <= kMaxFastElementsLength ||
6948 !ShouldConvertToSlowElements(new_capacity)) {
6949 ASSERT(static_cast<uint32_t>(new_capacity) > index);
John Reck59135872010-11-02 12:39:01 -07006950 Object* obj;
6951 { MaybeObject* maybe_obj =
6952 SetFastElementsCapacityAndLength(new_capacity, index + 1);
6953 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
6954 }
Steve Blocka7e24c12009-10-30 11:49:00 +00006955 FixedArray::cast(elements())->set(index, value);
6956 return value;
6957 }
6958 }
6959
6960 // Otherwise default to slow case.
John Reck59135872010-11-02 12:39:01 -07006961 Object* obj;
6962 { MaybeObject* maybe_obj = NormalizeElements();
6963 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
6964 }
Steve Blocka7e24c12009-10-30 11:49:00 +00006965 ASSERT(HasDictionaryElements());
6966 return SetElement(index, value);
6967}
6968
Iain Merrick75681382010-08-19 15:07:18 +01006969
John Reck59135872010-11-02 12:39:01 -07006970MaybeObject* JSObject::SetElement(uint32_t index, Object* value) {
Steve Blocka7e24c12009-10-30 11:49:00 +00006971 // Check access rights if needed.
6972 if (IsAccessCheckNeeded() &&
6973 !Top::MayIndexedAccess(this, index, v8::ACCESS_SET)) {
Iain Merrick75681382010-08-19 15:07:18 +01006974 HandleScope scope;
6975 Handle<Object> value_handle(value);
Steve Blocka7e24c12009-10-30 11:49:00 +00006976 Top::ReportFailedAccessCheck(this, v8::ACCESS_SET);
Iain Merrick75681382010-08-19 15:07:18 +01006977 return *value_handle;
Steve Blocka7e24c12009-10-30 11:49:00 +00006978 }
6979
6980 if (IsJSGlobalProxy()) {
6981 Object* proto = GetPrototype();
6982 if (proto->IsNull()) return value;
6983 ASSERT(proto->IsJSGlobalObject());
6984 return JSObject::cast(proto)->SetElement(index, value);
6985 }
6986
6987 // Check for lookup interceptor
6988 if (HasIndexedInterceptor()) {
6989 return SetElementWithInterceptor(index, value);
6990 }
6991
6992 return SetElementWithoutInterceptor(index, value);
6993}
6994
6995
John Reck59135872010-11-02 12:39:01 -07006996MaybeObject* JSObject::SetElementWithoutInterceptor(uint32_t index,
6997 Object* value) {
Steve Blocka7e24c12009-10-30 11:49:00 +00006998 switch (GetElementsKind()) {
6999 case FAST_ELEMENTS:
7000 // Fast case.
7001 return SetFastElement(index, value);
7002 case PIXEL_ELEMENTS: {
7003 PixelArray* pixels = PixelArray::cast(elements());
7004 return pixels->SetValue(index, value);
7005 }
Steve Block3ce2e202009-11-05 08:53:23 +00007006 case EXTERNAL_BYTE_ELEMENTS: {
7007 ExternalByteArray* array = ExternalByteArray::cast(elements());
7008 return array->SetValue(index, value);
7009 }
7010 case EXTERNAL_UNSIGNED_BYTE_ELEMENTS: {
7011 ExternalUnsignedByteArray* array =
7012 ExternalUnsignedByteArray::cast(elements());
7013 return array->SetValue(index, value);
7014 }
7015 case EXTERNAL_SHORT_ELEMENTS: {
7016 ExternalShortArray* array = ExternalShortArray::cast(elements());
7017 return array->SetValue(index, value);
7018 }
7019 case EXTERNAL_UNSIGNED_SHORT_ELEMENTS: {
7020 ExternalUnsignedShortArray* array =
7021 ExternalUnsignedShortArray::cast(elements());
7022 return array->SetValue(index, value);
7023 }
7024 case EXTERNAL_INT_ELEMENTS: {
7025 ExternalIntArray* array = ExternalIntArray::cast(elements());
7026 return array->SetValue(index, value);
7027 }
7028 case EXTERNAL_UNSIGNED_INT_ELEMENTS: {
7029 ExternalUnsignedIntArray* array =
7030 ExternalUnsignedIntArray::cast(elements());
7031 return array->SetValue(index, value);
7032 }
7033 case EXTERNAL_FLOAT_ELEMENTS: {
7034 ExternalFloatArray* array = ExternalFloatArray::cast(elements());
7035 return array->SetValue(index, value);
7036 }
Steve Blocka7e24c12009-10-30 11:49:00 +00007037 case DICTIONARY_ELEMENTS: {
7038 // Insert element in the dictionary.
7039 FixedArray* elms = FixedArray::cast(elements());
7040 NumberDictionary* dictionary = NumberDictionary::cast(elms);
7041
7042 int entry = dictionary->FindEntry(index);
7043 if (entry != NumberDictionary::kNotFound) {
7044 Object* element = dictionary->ValueAt(entry);
7045 PropertyDetails details = dictionary->DetailsAt(entry);
7046 if (details.type() == CALLBACKS) {
Leon Clarkef7060e22010-06-03 12:02:55 +01007047 return SetElementWithCallback(element, index, value, this);
Steve Blocka7e24c12009-10-30 11:49:00 +00007048 } else {
7049 dictionary->UpdateMaxNumberKey(index);
7050 dictionary->ValueAtPut(entry, value);
7051 }
7052 } else {
7053 // Index not already used. Look for an accessor in the prototype chain.
7054 if (!IsJSArray()) {
Leon Clarkef7060e22010-06-03 12:02:55 +01007055 if (SetElementWithCallbackSetterInPrototypes(index, value)) {
7056 return value;
Steve Blocka7e24c12009-10-30 11:49:00 +00007057 }
7058 }
Steve Block8defd9f2010-07-08 12:39:36 +01007059 // When we set the is_extensible flag to false we always force
7060 // the element into dictionary mode (and force them to stay there).
7061 if (!map()->is_extensible()) {
Ben Murdochf87a2032010-10-22 12:50:53 +01007062 Handle<Object> number(Factory::NewNumberFromUint(index));
Steve Block8defd9f2010-07-08 12:39:36 +01007063 Handle<String> index_string(Factory::NumberToString(number));
7064 Handle<Object> args[1] = { index_string };
7065 return Top::Throw(*Factory::NewTypeError("object_not_extensible",
7066 HandleVector(args, 1)));
7067 }
John Reck59135872010-11-02 12:39:01 -07007068 Object* result;
7069 { MaybeObject* maybe_result = dictionary->AtNumberPut(index, value);
7070 if (!maybe_result->ToObject(&result)) return maybe_result;
7071 }
Steve Blocka7e24c12009-10-30 11:49:00 +00007072 if (elms != FixedArray::cast(result)) {
7073 set_elements(FixedArray::cast(result));
7074 }
7075 }
7076
7077 // Update the array length if this JSObject is an array.
7078 if (IsJSArray()) {
7079 JSArray* array = JSArray::cast(this);
John Reck59135872010-11-02 12:39:01 -07007080 Object* return_value;
7081 { MaybeObject* maybe_return_value =
7082 array->JSArrayUpdateLengthFromIndex(index, value);
7083 if (!maybe_return_value->ToObject(&return_value)) {
7084 return maybe_return_value;
7085 }
7086 }
Steve Blocka7e24c12009-10-30 11:49:00 +00007087 }
7088
7089 // Attempt to put this object back in fast case.
7090 if (ShouldConvertToFastElements()) {
7091 uint32_t new_length = 0;
7092 if (IsJSArray()) {
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01007093 CHECK(JSArray::cast(this)->length()->ToArrayIndex(&new_length));
Steve Blocka7e24c12009-10-30 11:49:00 +00007094 } else {
7095 new_length = NumberDictionary::cast(elements())->max_number_key() + 1;
7096 }
John Reck59135872010-11-02 12:39:01 -07007097 Object* obj;
7098 { MaybeObject* maybe_obj =
7099 SetFastElementsCapacityAndLength(new_length, new_length);
7100 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
7101 }
Steve Blocka7e24c12009-10-30 11:49:00 +00007102#ifdef DEBUG
7103 if (FLAG_trace_normalization) {
7104 PrintF("Object elements are fast case again:\n");
7105 Print();
7106 }
7107#endif
7108 }
7109
7110 return value;
7111 }
7112 default:
7113 UNREACHABLE();
7114 break;
7115 }
7116 // All possible cases have been handled above. Add a return to avoid the
7117 // complaints from the compiler.
7118 UNREACHABLE();
7119 return Heap::null_value();
7120}
7121
7122
John Reck59135872010-11-02 12:39:01 -07007123MaybeObject* JSArray::JSArrayUpdateLengthFromIndex(uint32_t index,
7124 Object* value) {
Steve Blocka7e24c12009-10-30 11:49:00 +00007125 uint32_t old_len = 0;
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01007126 CHECK(length()->ToArrayIndex(&old_len));
Steve Blocka7e24c12009-10-30 11:49:00 +00007127 // Check to see if we need to update the length. For now, we make
7128 // sure that the length stays within 32-bits (unsigned).
7129 if (index >= old_len && index != 0xffffffff) {
John Reck59135872010-11-02 12:39:01 -07007130 Object* len;
7131 { MaybeObject* maybe_len =
7132 Heap::NumberFromDouble(static_cast<double>(index) + 1);
7133 if (!maybe_len->ToObject(&len)) return maybe_len;
7134 }
Steve Blocka7e24c12009-10-30 11:49:00 +00007135 set_length(len);
7136 }
7137 return value;
7138}
7139
7140
John Reck59135872010-11-02 12:39:01 -07007141MaybeObject* JSObject::GetElementPostInterceptor(JSObject* receiver,
7142 uint32_t index) {
Steve Blocka7e24c12009-10-30 11:49:00 +00007143 // Get element works for both JSObject and JSArray since
7144 // JSArray::length cannot change.
7145 switch (GetElementsKind()) {
7146 case FAST_ELEMENTS: {
7147 FixedArray* elms = FixedArray::cast(elements());
7148 if (index < static_cast<uint32_t>(elms->length())) {
7149 Object* value = elms->get(index);
7150 if (!value->IsTheHole()) return value;
7151 }
7152 break;
7153 }
7154 case PIXEL_ELEMENTS: {
7155 // TODO(iposva): Add testcase and implement.
7156 UNIMPLEMENTED();
7157 break;
7158 }
Steve Block3ce2e202009-11-05 08:53:23 +00007159 case EXTERNAL_BYTE_ELEMENTS:
7160 case EXTERNAL_UNSIGNED_BYTE_ELEMENTS:
7161 case EXTERNAL_SHORT_ELEMENTS:
7162 case EXTERNAL_UNSIGNED_SHORT_ELEMENTS:
7163 case EXTERNAL_INT_ELEMENTS:
7164 case EXTERNAL_UNSIGNED_INT_ELEMENTS:
7165 case EXTERNAL_FLOAT_ELEMENTS: {
7166 // TODO(kbr): Add testcase and implement.
7167 UNIMPLEMENTED();
7168 break;
7169 }
Steve Blocka7e24c12009-10-30 11:49:00 +00007170 case DICTIONARY_ELEMENTS: {
7171 NumberDictionary* dictionary = element_dictionary();
7172 int entry = dictionary->FindEntry(index);
7173 if (entry != NumberDictionary::kNotFound) {
7174 Object* element = dictionary->ValueAt(entry);
7175 PropertyDetails details = dictionary->DetailsAt(entry);
7176 if (details.type() == CALLBACKS) {
Leon Clarkef7060e22010-06-03 12:02:55 +01007177 return GetElementWithCallback(receiver,
7178 element,
7179 index,
7180 this);
Steve Blocka7e24c12009-10-30 11:49:00 +00007181 }
7182 return element;
7183 }
7184 break;
7185 }
7186 default:
7187 UNREACHABLE();
7188 break;
7189 }
7190
7191 // Continue searching via the prototype chain.
7192 Object* pt = GetPrototype();
7193 if (pt == Heap::null_value()) return Heap::undefined_value();
7194 return pt->GetElementWithReceiver(receiver, index);
7195}
7196
7197
John Reck59135872010-11-02 12:39:01 -07007198MaybeObject* JSObject::GetElementWithInterceptor(JSObject* receiver,
7199 uint32_t index) {
Steve Blocka7e24c12009-10-30 11:49:00 +00007200 // Make sure that the top context does not change when doing
7201 // callbacks or interceptor calls.
7202 AssertNoContextChange ncc;
7203 HandleScope scope;
7204 Handle<InterceptorInfo> interceptor(GetIndexedInterceptor());
7205 Handle<JSObject> this_handle(receiver);
7206 Handle<JSObject> holder_handle(this);
7207
7208 if (!interceptor->getter()->IsUndefined()) {
7209 v8::IndexedPropertyGetter getter =
7210 v8::ToCData<v8::IndexedPropertyGetter>(interceptor->getter());
7211 LOG(ApiIndexedPropertyAccess("interceptor-indexed-get", this, index));
7212 CustomArguments args(interceptor->data(), receiver, this);
7213 v8::AccessorInfo info(args.end());
7214 v8::Handle<v8::Value> result;
7215 {
7216 // Leaving JavaScript.
7217 VMState state(EXTERNAL);
7218 result = getter(index, info);
7219 }
7220 RETURN_IF_SCHEDULED_EXCEPTION();
7221 if (!result.IsEmpty()) return *v8::Utils::OpenHandle(*result);
7222 }
7223
John Reck59135872010-11-02 12:39:01 -07007224 MaybeObject* raw_result =
Steve Blocka7e24c12009-10-30 11:49:00 +00007225 holder_handle->GetElementPostInterceptor(*this_handle, index);
7226 RETURN_IF_SCHEDULED_EXCEPTION();
7227 return raw_result;
7228}
7229
7230
John Reck59135872010-11-02 12:39:01 -07007231MaybeObject* JSObject::GetElementWithReceiver(JSObject* receiver,
7232 uint32_t index) {
Steve Blocka7e24c12009-10-30 11:49:00 +00007233 // Check access rights if needed.
7234 if (IsAccessCheckNeeded() &&
7235 !Top::MayIndexedAccess(this, index, v8::ACCESS_GET)) {
7236 Top::ReportFailedAccessCheck(this, v8::ACCESS_GET);
7237 return Heap::undefined_value();
7238 }
7239
7240 if (HasIndexedInterceptor()) {
7241 return GetElementWithInterceptor(receiver, index);
7242 }
7243
7244 // Get element works for both JSObject and JSArray since
7245 // JSArray::length cannot change.
7246 switch (GetElementsKind()) {
7247 case FAST_ELEMENTS: {
7248 FixedArray* elms = FixedArray::cast(elements());
7249 if (index < static_cast<uint32_t>(elms->length())) {
7250 Object* value = elms->get(index);
7251 if (!value->IsTheHole()) return value;
7252 }
7253 break;
7254 }
7255 case PIXEL_ELEMENTS: {
7256 PixelArray* pixels = PixelArray::cast(elements());
7257 if (index < static_cast<uint32_t>(pixels->length())) {
7258 uint8_t value = pixels->get(index);
7259 return Smi::FromInt(value);
7260 }
7261 break;
7262 }
Steve Block3ce2e202009-11-05 08:53:23 +00007263 case EXTERNAL_BYTE_ELEMENTS: {
7264 ExternalByteArray* array = ExternalByteArray::cast(elements());
7265 if (index < static_cast<uint32_t>(array->length())) {
7266 int8_t value = array->get(index);
7267 return Smi::FromInt(value);
7268 }
7269 break;
7270 }
7271 case EXTERNAL_UNSIGNED_BYTE_ELEMENTS: {
7272 ExternalUnsignedByteArray* array =
7273 ExternalUnsignedByteArray::cast(elements());
7274 if (index < static_cast<uint32_t>(array->length())) {
7275 uint8_t value = array->get(index);
7276 return Smi::FromInt(value);
7277 }
7278 break;
7279 }
7280 case EXTERNAL_SHORT_ELEMENTS: {
7281 ExternalShortArray* array = ExternalShortArray::cast(elements());
7282 if (index < static_cast<uint32_t>(array->length())) {
7283 int16_t value = array->get(index);
7284 return Smi::FromInt(value);
7285 }
7286 break;
7287 }
7288 case EXTERNAL_UNSIGNED_SHORT_ELEMENTS: {
7289 ExternalUnsignedShortArray* array =
7290 ExternalUnsignedShortArray::cast(elements());
7291 if (index < static_cast<uint32_t>(array->length())) {
7292 uint16_t value = array->get(index);
7293 return Smi::FromInt(value);
7294 }
7295 break;
7296 }
7297 case EXTERNAL_INT_ELEMENTS: {
7298 ExternalIntArray* array = ExternalIntArray::cast(elements());
7299 if (index < static_cast<uint32_t>(array->length())) {
7300 int32_t value = array->get(index);
7301 return Heap::NumberFromInt32(value);
7302 }
7303 break;
7304 }
7305 case EXTERNAL_UNSIGNED_INT_ELEMENTS: {
7306 ExternalUnsignedIntArray* array =
7307 ExternalUnsignedIntArray::cast(elements());
7308 if (index < static_cast<uint32_t>(array->length())) {
7309 uint32_t value = array->get(index);
7310 return Heap::NumberFromUint32(value);
7311 }
7312 break;
7313 }
7314 case EXTERNAL_FLOAT_ELEMENTS: {
7315 ExternalFloatArray* array = ExternalFloatArray::cast(elements());
7316 if (index < static_cast<uint32_t>(array->length())) {
7317 float value = array->get(index);
7318 return Heap::AllocateHeapNumber(value);
7319 }
7320 break;
7321 }
Steve Blocka7e24c12009-10-30 11:49:00 +00007322 case DICTIONARY_ELEMENTS: {
7323 NumberDictionary* dictionary = element_dictionary();
7324 int entry = dictionary->FindEntry(index);
7325 if (entry != NumberDictionary::kNotFound) {
7326 Object* element = dictionary->ValueAt(entry);
7327 PropertyDetails details = dictionary->DetailsAt(entry);
7328 if (details.type() == CALLBACKS) {
Leon Clarkef7060e22010-06-03 12:02:55 +01007329 return GetElementWithCallback(receiver,
7330 element,
7331 index,
7332 this);
Steve Blocka7e24c12009-10-30 11:49:00 +00007333 }
7334 return element;
7335 }
7336 break;
7337 }
7338 }
7339
7340 Object* pt = GetPrototype();
7341 if (pt == Heap::null_value()) return Heap::undefined_value();
7342 return pt->GetElementWithReceiver(receiver, index);
7343}
7344
7345
7346bool JSObject::HasDenseElements() {
7347 int capacity = 0;
7348 int number_of_elements = 0;
7349
7350 switch (GetElementsKind()) {
7351 case FAST_ELEMENTS: {
7352 FixedArray* elms = FixedArray::cast(elements());
7353 capacity = elms->length();
7354 for (int i = 0; i < capacity; i++) {
7355 if (!elms->get(i)->IsTheHole()) number_of_elements++;
7356 }
7357 break;
7358 }
Steve Block3ce2e202009-11-05 08:53:23 +00007359 case PIXEL_ELEMENTS:
7360 case EXTERNAL_BYTE_ELEMENTS:
7361 case EXTERNAL_UNSIGNED_BYTE_ELEMENTS:
7362 case EXTERNAL_SHORT_ELEMENTS:
7363 case EXTERNAL_UNSIGNED_SHORT_ELEMENTS:
7364 case EXTERNAL_INT_ELEMENTS:
7365 case EXTERNAL_UNSIGNED_INT_ELEMENTS:
7366 case EXTERNAL_FLOAT_ELEMENTS: {
Steve Blocka7e24c12009-10-30 11:49:00 +00007367 return true;
7368 }
7369 case DICTIONARY_ELEMENTS: {
7370 NumberDictionary* dictionary = NumberDictionary::cast(elements());
7371 capacity = dictionary->Capacity();
7372 number_of_elements = dictionary->NumberOfElements();
7373 break;
7374 }
7375 default:
7376 UNREACHABLE();
7377 break;
7378 }
7379
7380 if (capacity == 0) return true;
7381 return (number_of_elements > (capacity / 2));
7382}
7383
7384
7385bool JSObject::ShouldConvertToSlowElements(int new_capacity) {
7386 ASSERT(HasFastElements());
7387 // Keep the array in fast case if the current backing storage is
7388 // almost filled and if the new capacity is no more than twice the
7389 // old capacity.
7390 int elements_length = FixedArray::cast(elements())->length();
7391 return !HasDenseElements() || ((new_capacity / 2) > elements_length);
7392}
7393
7394
7395bool JSObject::ShouldConvertToFastElements() {
7396 ASSERT(HasDictionaryElements());
7397 NumberDictionary* dictionary = NumberDictionary::cast(elements());
7398 // If the elements are sparse, we should not go back to fast case.
7399 if (!HasDenseElements()) return false;
7400 // If an element has been added at a very high index in the elements
7401 // dictionary, we cannot go back to fast case.
7402 if (dictionary->requires_slow_elements()) return false;
7403 // An object requiring access checks is never allowed to have fast
7404 // elements. If it had fast elements we would skip security checks.
7405 if (IsAccessCheckNeeded()) return false;
7406 // If the dictionary backing storage takes up roughly half as much
7407 // space as a fast-case backing storage would the array should have
7408 // fast elements.
7409 uint32_t length = 0;
7410 if (IsJSArray()) {
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01007411 CHECK(JSArray::cast(this)->length()->ToArrayIndex(&length));
Steve Blocka7e24c12009-10-30 11:49:00 +00007412 } else {
7413 length = dictionary->max_number_key();
7414 }
7415 return static_cast<uint32_t>(dictionary->Capacity()) >=
7416 (length / (2 * NumberDictionary::kEntrySize));
7417}
7418
7419
7420// Certain compilers request function template instantiation when they
7421// see the definition of the other template functions in the
7422// class. This requires us to have the template functions put
7423// together, so even though this function belongs in objects-debug.cc,
7424// we keep it here instead to satisfy certain compilers.
Ben Murdochb0fe1622011-05-05 13:52:32 +01007425#ifdef OBJECT_PRINT
Steve Blocka7e24c12009-10-30 11:49:00 +00007426template<typename Shape, typename Key>
Ben Murdochb0fe1622011-05-05 13:52:32 +01007427void Dictionary<Shape, Key>::Print(FILE* out) {
Steve Blocka7e24c12009-10-30 11:49:00 +00007428 int capacity = HashTable<Shape, Key>::Capacity();
7429 for (int i = 0; i < capacity; i++) {
7430 Object* k = HashTable<Shape, Key>::KeyAt(i);
7431 if (HashTable<Shape, Key>::IsKey(k)) {
Ben Murdochb0fe1622011-05-05 13:52:32 +01007432 PrintF(out, " ");
Steve Blocka7e24c12009-10-30 11:49:00 +00007433 if (k->IsString()) {
Ben Murdochb0fe1622011-05-05 13:52:32 +01007434 String::cast(k)->StringPrint(out);
Steve Blocka7e24c12009-10-30 11:49:00 +00007435 } else {
Ben Murdochb0fe1622011-05-05 13:52:32 +01007436 k->ShortPrint(out);
Steve Blocka7e24c12009-10-30 11:49:00 +00007437 }
Ben Murdochb0fe1622011-05-05 13:52:32 +01007438 PrintF(out, ": ");
7439 ValueAt(i)->ShortPrint(out);
7440 PrintF(out, "\n");
Steve Blocka7e24c12009-10-30 11:49:00 +00007441 }
7442 }
7443}
7444#endif
7445
7446
7447template<typename Shape, typename Key>
7448void Dictionary<Shape, Key>::CopyValuesTo(FixedArray* elements) {
7449 int pos = 0;
7450 int capacity = HashTable<Shape, Key>::Capacity();
Leon Clarke4515c472010-02-03 11:58:03 +00007451 AssertNoAllocation no_gc;
7452 WriteBarrierMode mode = elements->GetWriteBarrierMode(no_gc);
Steve Blocka7e24c12009-10-30 11:49:00 +00007453 for (int i = 0; i < capacity; i++) {
7454 Object* k = Dictionary<Shape, Key>::KeyAt(i);
7455 if (Dictionary<Shape, Key>::IsKey(k)) {
7456 elements->set(pos++, ValueAt(i), mode);
7457 }
7458 }
7459 ASSERT(pos == elements->length());
7460}
7461
7462
7463InterceptorInfo* JSObject::GetNamedInterceptor() {
7464 ASSERT(map()->has_named_interceptor());
7465 JSFunction* constructor = JSFunction::cast(map()->constructor());
Steve Block6ded16b2010-05-10 14:33:55 +01007466 ASSERT(constructor->shared()->IsApiFunction());
Steve Blocka7e24c12009-10-30 11:49:00 +00007467 Object* result =
Steve Block6ded16b2010-05-10 14:33:55 +01007468 constructor->shared()->get_api_func_data()->named_property_handler();
Steve Blocka7e24c12009-10-30 11:49:00 +00007469 return InterceptorInfo::cast(result);
7470}
7471
7472
7473InterceptorInfo* JSObject::GetIndexedInterceptor() {
7474 ASSERT(map()->has_indexed_interceptor());
7475 JSFunction* constructor = JSFunction::cast(map()->constructor());
Steve Block6ded16b2010-05-10 14:33:55 +01007476 ASSERT(constructor->shared()->IsApiFunction());
Steve Blocka7e24c12009-10-30 11:49:00 +00007477 Object* result =
Steve Block6ded16b2010-05-10 14:33:55 +01007478 constructor->shared()->get_api_func_data()->indexed_property_handler();
Steve Blocka7e24c12009-10-30 11:49:00 +00007479 return InterceptorInfo::cast(result);
7480}
7481
7482
John Reck59135872010-11-02 12:39:01 -07007483MaybeObject* JSObject::GetPropertyPostInterceptor(
7484 JSObject* receiver,
7485 String* name,
7486 PropertyAttributes* attributes) {
Steve Blocka7e24c12009-10-30 11:49:00 +00007487 // Check local property in holder, ignore interceptor.
7488 LookupResult result;
7489 LocalLookupRealNamedProperty(name, &result);
Andrei Popescu402d9372010-02-26 13:31:12 +00007490 if (result.IsProperty()) {
7491 return GetProperty(receiver, &result, name, attributes);
7492 }
Steve Blocka7e24c12009-10-30 11:49:00 +00007493 // Continue searching via the prototype chain.
7494 Object* pt = GetPrototype();
7495 *attributes = ABSENT;
7496 if (pt == Heap::null_value()) return Heap::undefined_value();
7497 return pt->GetPropertyWithReceiver(receiver, name, attributes);
7498}
7499
7500
John Reck59135872010-11-02 12:39:01 -07007501MaybeObject* JSObject::GetLocalPropertyPostInterceptor(
Steve Blockd0582a62009-12-15 09:54:21 +00007502 JSObject* receiver,
7503 String* name,
7504 PropertyAttributes* attributes) {
7505 // Check local property in holder, ignore interceptor.
7506 LookupResult result;
7507 LocalLookupRealNamedProperty(name, &result);
Andrei Popescu402d9372010-02-26 13:31:12 +00007508 if (result.IsProperty()) {
7509 return GetProperty(receiver, &result, name, attributes);
7510 }
7511 return Heap::undefined_value();
Steve Blockd0582a62009-12-15 09:54:21 +00007512}
7513
7514
John Reck59135872010-11-02 12:39:01 -07007515MaybeObject* JSObject::GetPropertyWithInterceptor(
Steve Blocka7e24c12009-10-30 11:49:00 +00007516 JSObject* receiver,
7517 String* name,
7518 PropertyAttributes* attributes) {
7519 InterceptorInfo* interceptor = GetNamedInterceptor();
7520 HandleScope scope;
7521 Handle<JSObject> receiver_handle(receiver);
7522 Handle<JSObject> holder_handle(this);
7523 Handle<String> name_handle(name);
7524
7525 if (!interceptor->getter()->IsUndefined()) {
7526 v8::NamedPropertyGetter getter =
7527 v8::ToCData<v8::NamedPropertyGetter>(interceptor->getter());
7528 LOG(ApiNamedPropertyAccess("interceptor-named-get", *holder_handle, name));
7529 CustomArguments args(interceptor->data(), receiver, this);
7530 v8::AccessorInfo info(args.end());
7531 v8::Handle<v8::Value> result;
7532 {
7533 // Leaving JavaScript.
7534 VMState state(EXTERNAL);
7535 result = getter(v8::Utils::ToLocal(name_handle), info);
7536 }
7537 RETURN_IF_SCHEDULED_EXCEPTION();
7538 if (!result.IsEmpty()) {
7539 *attributes = NONE;
7540 return *v8::Utils::OpenHandle(*result);
7541 }
7542 }
7543
John Reck59135872010-11-02 12:39:01 -07007544 MaybeObject* result = holder_handle->GetPropertyPostInterceptor(
Steve Blocka7e24c12009-10-30 11:49:00 +00007545 *receiver_handle,
7546 *name_handle,
7547 attributes);
7548 RETURN_IF_SCHEDULED_EXCEPTION();
7549 return result;
7550}
7551
7552
7553bool JSObject::HasRealNamedProperty(String* key) {
7554 // Check access rights if needed.
7555 if (IsAccessCheckNeeded() &&
7556 !Top::MayNamedAccess(this, key, v8::ACCESS_HAS)) {
7557 Top::ReportFailedAccessCheck(this, v8::ACCESS_HAS);
7558 return false;
7559 }
7560
7561 LookupResult result;
7562 LocalLookupRealNamedProperty(key, &result);
Andrei Popescu402d9372010-02-26 13:31:12 +00007563 return result.IsProperty() && (result.type() != INTERCEPTOR);
Steve Blocka7e24c12009-10-30 11:49:00 +00007564}
7565
7566
7567bool JSObject::HasRealElementProperty(uint32_t index) {
7568 // Check access rights if needed.
7569 if (IsAccessCheckNeeded() &&
7570 !Top::MayIndexedAccess(this, index, v8::ACCESS_HAS)) {
7571 Top::ReportFailedAccessCheck(this, v8::ACCESS_HAS);
7572 return false;
7573 }
7574
7575 // Handle [] on String objects.
7576 if (this->IsStringObjectWithCharacterAt(index)) return true;
7577
7578 switch (GetElementsKind()) {
7579 case FAST_ELEMENTS: {
7580 uint32_t length = IsJSArray() ?
7581 static_cast<uint32_t>(
7582 Smi::cast(JSArray::cast(this)->length())->value()) :
7583 static_cast<uint32_t>(FixedArray::cast(elements())->length());
7584 return (index < length) &&
7585 !FixedArray::cast(elements())->get(index)->IsTheHole();
7586 }
7587 case PIXEL_ELEMENTS: {
7588 PixelArray* pixels = PixelArray::cast(elements());
7589 return index < static_cast<uint32_t>(pixels->length());
7590 }
Steve Block3ce2e202009-11-05 08:53:23 +00007591 case EXTERNAL_BYTE_ELEMENTS:
7592 case EXTERNAL_UNSIGNED_BYTE_ELEMENTS:
7593 case EXTERNAL_SHORT_ELEMENTS:
7594 case EXTERNAL_UNSIGNED_SHORT_ELEMENTS:
7595 case EXTERNAL_INT_ELEMENTS:
7596 case EXTERNAL_UNSIGNED_INT_ELEMENTS:
7597 case EXTERNAL_FLOAT_ELEMENTS: {
7598 ExternalArray* array = ExternalArray::cast(elements());
7599 return index < static_cast<uint32_t>(array->length());
7600 }
Steve Blocka7e24c12009-10-30 11:49:00 +00007601 case DICTIONARY_ELEMENTS: {
7602 return element_dictionary()->FindEntry(index)
7603 != NumberDictionary::kNotFound;
7604 }
7605 default:
7606 UNREACHABLE();
7607 break;
7608 }
7609 // All possibilities have been handled above already.
7610 UNREACHABLE();
7611 return Heap::null_value();
7612}
7613
7614
7615bool JSObject::HasRealNamedCallbackProperty(String* key) {
7616 // Check access rights if needed.
7617 if (IsAccessCheckNeeded() &&
7618 !Top::MayNamedAccess(this, key, v8::ACCESS_HAS)) {
7619 Top::ReportFailedAccessCheck(this, v8::ACCESS_HAS);
7620 return false;
7621 }
7622
7623 LookupResult result;
7624 LocalLookupRealNamedProperty(key, &result);
Andrei Popescu402d9372010-02-26 13:31:12 +00007625 return result.IsProperty() && (result.type() == CALLBACKS);
Steve Blocka7e24c12009-10-30 11:49:00 +00007626}
7627
7628
7629int JSObject::NumberOfLocalProperties(PropertyAttributes filter) {
7630 if (HasFastProperties()) {
7631 DescriptorArray* descs = map()->instance_descriptors();
7632 int result = 0;
7633 for (int i = 0; i < descs->number_of_descriptors(); i++) {
7634 PropertyDetails details = descs->GetDetails(i);
7635 if (details.IsProperty() && (details.attributes() & filter) == 0) {
7636 result++;
7637 }
7638 }
7639 return result;
7640 } else {
7641 return property_dictionary()->NumberOfElementsFilterAttributes(filter);
7642 }
7643}
7644
7645
7646int JSObject::NumberOfEnumProperties() {
7647 return NumberOfLocalProperties(static_cast<PropertyAttributes>(DONT_ENUM));
7648}
7649
7650
7651void FixedArray::SwapPairs(FixedArray* numbers, int i, int j) {
7652 Object* temp = get(i);
7653 set(i, get(j));
7654 set(j, temp);
7655 if (this != numbers) {
7656 temp = numbers->get(i);
7657 numbers->set(i, numbers->get(j));
7658 numbers->set(j, temp);
7659 }
7660}
7661
7662
7663static void InsertionSortPairs(FixedArray* content,
7664 FixedArray* numbers,
7665 int len) {
7666 for (int i = 1; i < len; i++) {
7667 int j = i;
7668 while (j > 0 &&
7669 (NumberToUint32(numbers->get(j - 1)) >
7670 NumberToUint32(numbers->get(j)))) {
7671 content->SwapPairs(numbers, j - 1, j);
7672 j--;
7673 }
7674 }
7675}
7676
7677
7678void HeapSortPairs(FixedArray* content, FixedArray* numbers, int len) {
7679 // In-place heap sort.
7680 ASSERT(content->length() == numbers->length());
7681
7682 // Bottom-up max-heap construction.
7683 for (int i = 1; i < len; ++i) {
7684 int child_index = i;
7685 while (child_index > 0) {
7686 int parent_index = ((child_index + 1) >> 1) - 1;
7687 uint32_t parent_value = NumberToUint32(numbers->get(parent_index));
7688 uint32_t child_value = NumberToUint32(numbers->get(child_index));
7689 if (parent_value < child_value) {
7690 content->SwapPairs(numbers, parent_index, child_index);
7691 } else {
7692 break;
7693 }
7694 child_index = parent_index;
7695 }
7696 }
7697
7698 // Extract elements and create sorted array.
7699 for (int i = len - 1; i > 0; --i) {
7700 // Put max element at the back of the array.
7701 content->SwapPairs(numbers, 0, i);
7702 // Sift down the new top element.
7703 int parent_index = 0;
7704 while (true) {
7705 int child_index = ((parent_index + 1) << 1) - 1;
7706 if (child_index >= i) break;
7707 uint32_t child1_value = NumberToUint32(numbers->get(child_index));
7708 uint32_t child2_value = NumberToUint32(numbers->get(child_index + 1));
7709 uint32_t parent_value = NumberToUint32(numbers->get(parent_index));
7710 if (child_index + 1 >= i || child1_value > child2_value) {
7711 if (parent_value > child1_value) break;
7712 content->SwapPairs(numbers, parent_index, child_index);
7713 parent_index = child_index;
7714 } else {
7715 if (parent_value > child2_value) break;
7716 content->SwapPairs(numbers, parent_index, child_index + 1);
7717 parent_index = child_index + 1;
7718 }
7719 }
7720 }
7721}
7722
7723
7724// Sort this array and the numbers as pairs wrt. the (distinct) numbers.
7725void FixedArray::SortPairs(FixedArray* numbers, uint32_t len) {
7726 ASSERT(this->length() == numbers->length());
7727 // For small arrays, simply use insertion sort.
7728 if (len <= 10) {
7729 InsertionSortPairs(this, numbers, len);
7730 return;
7731 }
7732 // Check the range of indices.
7733 uint32_t min_index = NumberToUint32(numbers->get(0));
7734 uint32_t max_index = min_index;
7735 uint32_t i;
7736 for (i = 1; i < len; i++) {
7737 if (NumberToUint32(numbers->get(i)) < min_index) {
7738 min_index = NumberToUint32(numbers->get(i));
7739 } else if (NumberToUint32(numbers->get(i)) > max_index) {
7740 max_index = NumberToUint32(numbers->get(i));
7741 }
7742 }
7743 if (max_index - min_index + 1 == len) {
7744 // Indices form a contiguous range, unless there are duplicates.
7745 // Do an in-place linear time sort assuming distinct numbers, but
7746 // avoid hanging in case they are not.
7747 for (i = 0; i < len; i++) {
7748 uint32_t p;
7749 uint32_t j = 0;
7750 // While the current element at i is not at its correct position p,
7751 // swap the elements at these two positions.
7752 while ((p = NumberToUint32(numbers->get(i)) - min_index) != i &&
7753 j++ < len) {
7754 SwapPairs(numbers, i, p);
7755 }
7756 }
7757 } else {
7758 HeapSortPairs(this, numbers, len);
7759 return;
7760 }
7761}
7762
7763
7764// Fill in the names of local properties into the supplied storage. The main
7765// purpose of this function is to provide reflection information for the object
7766// mirrors.
7767void JSObject::GetLocalPropertyNames(FixedArray* storage, int index) {
7768 ASSERT(storage->length() >= (NumberOfLocalProperties(NONE) - index));
7769 if (HasFastProperties()) {
7770 DescriptorArray* descs = map()->instance_descriptors();
7771 for (int i = 0; i < descs->number_of_descriptors(); i++) {
7772 if (descs->IsProperty(i)) storage->set(index++, descs->GetKey(i));
7773 }
7774 ASSERT(storage->length() >= index);
7775 } else {
7776 property_dictionary()->CopyKeysTo(storage);
7777 }
7778}
7779
7780
7781int JSObject::NumberOfLocalElements(PropertyAttributes filter) {
7782 return GetLocalElementKeys(NULL, filter);
7783}
7784
7785
7786int JSObject::NumberOfEnumElements() {
Steve Blockd0582a62009-12-15 09:54:21 +00007787 // Fast case for objects with no elements.
7788 if (!IsJSValue() && HasFastElements()) {
7789 uint32_t length = IsJSArray() ?
7790 static_cast<uint32_t>(
7791 Smi::cast(JSArray::cast(this)->length())->value()) :
7792 static_cast<uint32_t>(FixedArray::cast(elements())->length());
7793 if (length == 0) return 0;
7794 }
7795 // Compute the number of enumerable elements.
Steve Blocka7e24c12009-10-30 11:49:00 +00007796 return NumberOfLocalElements(static_cast<PropertyAttributes>(DONT_ENUM));
7797}
7798
7799
7800int JSObject::GetLocalElementKeys(FixedArray* storage,
7801 PropertyAttributes filter) {
7802 int counter = 0;
7803 switch (GetElementsKind()) {
7804 case FAST_ELEMENTS: {
7805 int length = IsJSArray() ?
7806 Smi::cast(JSArray::cast(this)->length())->value() :
7807 FixedArray::cast(elements())->length();
7808 for (int i = 0; i < length; i++) {
7809 if (!FixedArray::cast(elements())->get(i)->IsTheHole()) {
7810 if (storage != NULL) {
Leon Clarke4515c472010-02-03 11:58:03 +00007811 storage->set(counter, Smi::FromInt(i));
Steve Blocka7e24c12009-10-30 11:49:00 +00007812 }
7813 counter++;
7814 }
7815 }
7816 ASSERT(!storage || storage->length() >= counter);
7817 break;
7818 }
7819 case PIXEL_ELEMENTS: {
7820 int length = PixelArray::cast(elements())->length();
7821 while (counter < length) {
7822 if (storage != NULL) {
Leon Clarke4515c472010-02-03 11:58:03 +00007823 storage->set(counter, Smi::FromInt(counter));
Steve Blocka7e24c12009-10-30 11:49:00 +00007824 }
7825 counter++;
7826 }
7827 ASSERT(!storage || storage->length() >= counter);
7828 break;
7829 }
Steve Block3ce2e202009-11-05 08:53:23 +00007830 case EXTERNAL_BYTE_ELEMENTS:
7831 case EXTERNAL_UNSIGNED_BYTE_ELEMENTS:
7832 case EXTERNAL_SHORT_ELEMENTS:
7833 case EXTERNAL_UNSIGNED_SHORT_ELEMENTS:
7834 case EXTERNAL_INT_ELEMENTS:
7835 case EXTERNAL_UNSIGNED_INT_ELEMENTS:
7836 case EXTERNAL_FLOAT_ELEMENTS: {
7837 int length = ExternalArray::cast(elements())->length();
7838 while (counter < length) {
7839 if (storage != NULL) {
Leon Clarke4515c472010-02-03 11:58:03 +00007840 storage->set(counter, Smi::FromInt(counter));
Steve Block3ce2e202009-11-05 08:53:23 +00007841 }
7842 counter++;
7843 }
7844 ASSERT(!storage || storage->length() >= counter);
7845 break;
7846 }
Steve Blocka7e24c12009-10-30 11:49:00 +00007847 case DICTIONARY_ELEMENTS: {
7848 if (storage != NULL) {
7849 element_dictionary()->CopyKeysTo(storage, filter);
7850 }
7851 counter = element_dictionary()->NumberOfElementsFilterAttributes(filter);
7852 break;
7853 }
7854 default:
7855 UNREACHABLE();
7856 break;
7857 }
7858
7859 if (this->IsJSValue()) {
7860 Object* val = JSValue::cast(this)->value();
7861 if (val->IsString()) {
7862 String* str = String::cast(val);
7863 if (storage) {
7864 for (int i = 0; i < str->length(); i++) {
Leon Clarke4515c472010-02-03 11:58:03 +00007865 storage->set(counter + i, Smi::FromInt(i));
Steve Blocka7e24c12009-10-30 11:49:00 +00007866 }
7867 }
7868 counter += str->length();
7869 }
7870 }
7871 ASSERT(!storage || storage->length() == counter);
7872 return counter;
7873}
7874
7875
7876int JSObject::GetEnumElementKeys(FixedArray* storage) {
7877 return GetLocalElementKeys(storage,
7878 static_cast<PropertyAttributes>(DONT_ENUM));
7879}
7880
7881
7882bool NumberDictionaryShape::IsMatch(uint32_t key, Object* other) {
7883 ASSERT(other->IsNumber());
7884 return key == static_cast<uint32_t>(other->Number());
7885}
7886
7887
7888uint32_t NumberDictionaryShape::Hash(uint32_t key) {
7889 return ComputeIntegerHash(key);
7890}
7891
7892
7893uint32_t NumberDictionaryShape::HashForObject(uint32_t key, Object* other) {
7894 ASSERT(other->IsNumber());
7895 return ComputeIntegerHash(static_cast<uint32_t>(other->Number()));
7896}
7897
7898
John Reck59135872010-11-02 12:39:01 -07007899MaybeObject* NumberDictionaryShape::AsObject(uint32_t key) {
Steve Blocka7e24c12009-10-30 11:49:00 +00007900 return Heap::NumberFromUint32(key);
7901}
7902
7903
7904bool StringDictionaryShape::IsMatch(String* key, Object* other) {
7905 // We know that all entries in a hash table had their hash keys created.
7906 // Use that knowledge to have fast failure.
7907 if (key->Hash() != String::cast(other)->Hash()) return false;
7908 return key->Equals(String::cast(other));
7909}
7910
7911
7912uint32_t StringDictionaryShape::Hash(String* key) {
7913 return key->Hash();
7914}
7915
7916
7917uint32_t StringDictionaryShape::HashForObject(String* key, Object* other) {
7918 return String::cast(other)->Hash();
7919}
7920
7921
John Reck59135872010-11-02 12:39:01 -07007922MaybeObject* StringDictionaryShape::AsObject(String* key) {
Steve Blocka7e24c12009-10-30 11:49:00 +00007923 return key;
7924}
7925
7926
7927// StringKey simply carries a string object as key.
7928class StringKey : public HashTableKey {
7929 public:
7930 explicit StringKey(String* string) :
7931 string_(string),
7932 hash_(HashForObject(string)) { }
7933
7934 bool IsMatch(Object* string) {
7935 // We know that all entries in a hash table had their hash keys created.
7936 // Use that knowledge to have fast failure.
7937 if (hash_ != HashForObject(string)) {
7938 return false;
7939 }
7940 return string_->Equals(String::cast(string));
7941 }
7942
7943 uint32_t Hash() { return hash_; }
7944
7945 uint32_t HashForObject(Object* other) { return String::cast(other)->Hash(); }
7946
7947 Object* AsObject() { return string_; }
7948
7949 String* string_;
7950 uint32_t hash_;
7951};
7952
7953
7954// StringSharedKeys are used as keys in the eval cache.
7955class StringSharedKey : public HashTableKey {
7956 public:
7957 StringSharedKey(String* source, SharedFunctionInfo* shared)
7958 : source_(source), shared_(shared) { }
7959
7960 bool IsMatch(Object* other) {
7961 if (!other->IsFixedArray()) return false;
7962 FixedArray* pair = FixedArray::cast(other);
7963 SharedFunctionInfo* shared = SharedFunctionInfo::cast(pair->get(0));
7964 if (shared != shared_) return false;
7965 String* source = String::cast(pair->get(1));
7966 return source->Equals(source_);
7967 }
7968
7969 static uint32_t StringSharedHashHelper(String* source,
7970 SharedFunctionInfo* shared) {
7971 uint32_t hash = source->Hash();
7972 if (shared->HasSourceCode()) {
7973 // Instead of using the SharedFunctionInfo pointer in the hash
7974 // code computation, we use a combination of the hash of the
7975 // script source code and the start and end positions. We do
7976 // this to ensure that the cache entries can survive garbage
7977 // collection.
7978 Script* script = Script::cast(shared->script());
7979 hash ^= String::cast(script->source())->Hash();
7980 hash += shared->start_position();
7981 }
7982 return hash;
7983 }
7984
7985 uint32_t Hash() {
7986 return StringSharedHashHelper(source_, shared_);
7987 }
7988
7989 uint32_t HashForObject(Object* obj) {
7990 FixedArray* pair = FixedArray::cast(obj);
7991 SharedFunctionInfo* shared = SharedFunctionInfo::cast(pair->get(0));
7992 String* source = String::cast(pair->get(1));
7993 return StringSharedHashHelper(source, shared);
7994 }
7995
John Reck59135872010-11-02 12:39:01 -07007996 MUST_USE_RESULT MaybeObject* AsObject() {
7997 Object* obj;
7998 { MaybeObject* maybe_obj = Heap::AllocateFixedArray(2);
7999 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
8000 }
Steve Blocka7e24c12009-10-30 11:49:00 +00008001 FixedArray* pair = FixedArray::cast(obj);
8002 pair->set(0, shared_);
8003 pair->set(1, source_);
8004 return pair;
8005 }
8006
8007 private:
8008 String* source_;
8009 SharedFunctionInfo* shared_;
8010};
8011
8012
8013// RegExpKey carries the source and flags of a regular expression as key.
8014class RegExpKey : public HashTableKey {
8015 public:
8016 RegExpKey(String* string, JSRegExp::Flags flags)
8017 : string_(string),
8018 flags_(Smi::FromInt(flags.value())) { }
8019
Steve Block3ce2e202009-11-05 08:53:23 +00008020 // Rather than storing the key in the hash table, a pointer to the
8021 // stored value is stored where the key should be. IsMatch then
8022 // compares the search key to the found object, rather than comparing
8023 // a key to a key.
Steve Blocka7e24c12009-10-30 11:49:00 +00008024 bool IsMatch(Object* obj) {
8025 FixedArray* val = FixedArray::cast(obj);
8026 return string_->Equals(String::cast(val->get(JSRegExp::kSourceIndex)))
8027 && (flags_ == val->get(JSRegExp::kFlagsIndex));
8028 }
8029
8030 uint32_t Hash() { return RegExpHash(string_, flags_); }
8031
8032 Object* AsObject() {
8033 // Plain hash maps, which is where regexp keys are used, don't
8034 // use this function.
8035 UNREACHABLE();
8036 return NULL;
8037 }
8038
8039 uint32_t HashForObject(Object* obj) {
8040 FixedArray* val = FixedArray::cast(obj);
8041 return RegExpHash(String::cast(val->get(JSRegExp::kSourceIndex)),
8042 Smi::cast(val->get(JSRegExp::kFlagsIndex)));
8043 }
8044
8045 static uint32_t RegExpHash(String* string, Smi* flags) {
8046 return string->Hash() + flags->value();
8047 }
8048
8049 String* string_;
8050 Smi* flags_;
8051};
8052
8053// Utf8SymbolKey carries a vector of chars as key.
8054class Utf8SymbolKey : public HashTableKey {
8055 public:
8056 explicit Utf8SymbolKey(Vector<const char> string)
Steve Blockd0582a62009-12-15 09:54:21 +00008057 : string_(string), hash_field_(0) { }
Steve Blocka7e24c12009-10-30 11:49:00 +00008058
8059 bool IsMatch(Object* string) {
8060 return String::cast(string)->IsEqualTo(string_);
8061 }
8062
8063 uint32_t Hash() {
Steve Blockd0582a62009-12-15 09:54:21 +00008064 if (hash_field_ != 0) return hash_field_ >> String::kHashShift;
Steve Blocka7e24c12009-10-30 11:49:00 +00008065 unibrow::Utf8InputBuffer<> buffer(string_.start(),
8066 static_cast<unsigned>(string_.length()));
8067 chars_ = buffer.Length();
Steve Blockd0582a62009-12-15 09:54:21 +00008068 hash_field_ = String::ComputeHashField(&buffer, chars_);
8069 uint32_t result = hash_field_ >> String::kHashShift;
Steve Blocka7e24c12009-10-30 11:49:00 +00008070 ASSERT(result != 0); // Ensure that the hash value of 0 is never computed.
8071 return result;
8072 }
8073
8074 uint32_t HashForObject(Object* other) {
8075 return String::cast(other)->Hash();
8076 }
8077
John Reck59135872010-11-02 12:39:01 -07008078 MaybeObject* AsObject() {
Steve Blockd0582a62009-12-15 09:54:21 +00008079 if (hash_field_ == 0) Hash();
8080 return Heap::AllocateSymbol(string_, chars_, hash_field_);
Steve Blocka7e24c12009-10-30 11:49:00 +00008081 }
8082
8083 Vector<const char> string_;
Steve Blockd0582a62009-12-15 09:54:21 +00008084 uint32_t hash_field_;
Steve Blocka7e24c12009-10-30 11:49:00 +00008085 int chars_; // Caches the number of characters when computing the hash code.
8086};
8087
8088
8089// SymbolKey carries a string/symbol object as key.
8090class SymbolKey : public HashTableKey {
8091 public:
8092 explicit SymbolKey(String* string) : string_(string) { }
8093
8094 bool IsMatch(Object* string) {
8095 return String::cast(string)->Equals(string_);
8096 }
8097
8098 uint32_t Hash() { return string_->Hash(); }
8099
8100 uint32_t HashForObject(Object* other) {
8101 return String::cast(other)->Hash();
8102 }
8103
John Reck59135872010-11-02 12:39:01 -07008104 MaybeObject* AsObject() {
Leon Clarkef7060e22010-06-03 12:02:55 +01008105 // Attempt to flatten the string, so that symbols will most often
8106 // be flat strings.
8107 string_ = string_->TryFlattenGetString();
Steve Blocka7e24c12009-10-30 11:49:00 +00008108 // Transform string to symbol if possible.
8109 Map* map = Heap::SymbolMapForString(string_);
8110 if (map != NULL) {
8111 string_->set_map(map);
8112 ASSERT(string_->IsSymbol());
8113 return string_;
8114 }
8115 // Otherwise allocate a new symbol.
8116 StringInputBuffer buffer(string_);
8117 return Heap::AllocateInternalSymbol(&buffer,
8118 string_->length(),
Steve Blockd0582a62009-12-15 09:54:21 +00008119 string_->hash_field());
Steve Blocka7e24c12009-10-30 11:49:00 +00008120 }
8121
8122 static uint32_t StringHash(Object* obj) {
8123 return String::cast(obj)->Hash();
8124 }
8125
8126 String* string_;
8127};
8128
8129
8130template<typename Shape, typename Key>
8131void HashTable<Shape, Key>::IteratePrefix(ObjectVisitor* v) {
8132 IteratePointers(v, 0, kElementsStartOffset);
8133}
8134
8135
8136template<typename Shape, typename Key>
8137void HashTable<Shape, Key>::IterateElements(ObjectVisitor* v) {
8138 IteratePointers(v,
8139 kElementsStartOffset,
8140 kHeaderSize + length() * kPointerSize);
8141}
8142
8143
8144template<typename Shape, typename Key>
John Reck59135872010-11-02 12:39:01 -07008145MaybeObject* HashTable<Shape, Key>::Allocate(int at_least_space_for,
8146 PretenureFlag pretenure) {
Steve Block6ded16b2010-05-10 14:33:55 +01008147 const int kMinCapacity = 32;
8148 int capacity = RoundUpToPowerOf2(at_least_space_for * 2);
8149 if (capacity < kMinCapacity) {
8150 capacity = kMinCapacity; // Guarantee min capacity.
Leon Clarkee46be812010-01-19 14:06:41 +00008151 } else if (capacity > HashTable::kMaxCapacity) {
8152 return Failure::OutOfMemoryException();
8153 }
8154
John Reck59135872010-11-02 12:39:01 -07008155 Object* obj;
8156 { MaybeObject* maybe_obj =
8157 Heap::AllocateHashTable(EntryToIndex(capacity), pretenure);
8158 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
Steve Blocka7e24c12009-10-30 11:49:00 +00008159 }
John Reck59135872010-11-02 12:39:01 -07008160 HashTable::cast(obj)->SetNumberOfElements(0);
8161 HashTable::cast(obj)->SetNumberOfDeletedElements(0);
8162 HashTable::cast(obj)->SetCapacity(capacity);
Steve Blocka7e24c12009-10-30 11:49:00 +00008163 return obj;
8164}
8165
8166
Leon Clarkee46be812010-01-19 14:06:41 +00008167// Find entry for key otherwise return kNotFound.
Steve Blocka7e24c12009-10-30 11:49:00 +00008168template<typename Shape, typename Key>
8169int HashTable<Shape, Key>::FindEntry(Key key) {
Steve Blocka7e24c12009-10-30 11:49:00 +00008170 uint32_t capacity = Capacity();
Leon Clarkee46be812010-01-19 14:06:41 +00008171 uint32_t entry = FirstProbe(Shape::Hash(key), capacity);
8172 uint32_t count = 1;
8173 // EnsureCapacity will guarantee the hash table is never full.
8174 while (true) {
8175 Object* element = KeyAt(entry);
8176 if (element->IsUndefined()) break; // Empty entry.
8177 if (!element->IsNull() && Shape::IsMatch(key, element)) return entry;
8178 entry = NextProbe(entry, count++, capacity);
Steve Blocka7e24c12009-10-30 11:49:00 +00008179 }
8180 return kNotFound;
8181}
8182
8183
Ben Murdoch3bec4d22010-07-22 14:51:16 +01008184// Find entry for key otherwise return kNotFound.
8185int StringDictionary::FindEntry(String* key) {
8186 if (!key->IsSymbol()) {
8187 return HashTable<StringDictionaryShape, String*>::FindEntry(key);
8188 }
8189
8190 // Optimized for symbol key. Knowledge of the key type allows:
8191 // 1. Move the check if the key is a symbol out of the loop.
8192 // 2. Avoid comparing hash codes in symbol to symbol comparision.
8193 // 3. Detect a case when a dictionary key is not a symbol but the key is.
8194 // In case of positive result the dictionary key may be replaced by
8195 // the symbol with minimal performance penalty. It gives a chance to
8196 // perform further lookups in code stubs (and significant performance boost
8197 // a certain style of code).
8198
8199 // EnsureCapacity will guarantee the hash table is never full.
8200 uint32_t capacity = Capacity();
8201 uint32_t entry = FirstProbe(key->Hash(), capacity);
8202 uint32_t count = 1;
8203
8204 while (true) {
8205 int index = EntryToIndex(entry);
8206 Object* element = get(index);
8207 if (element->IsUndefined()) break; // Empty entry.
8208 if (key == element) return entry;
8209 if (!element->IsSymbol() &&
8210 !element->IsNull() &&
8211 String::cast(element)->Equals(key)) {
8212 // Replace a non-symbol key by the equivalent symbol for faster further
8213 // lookups.
8214 set(index, key);
8215 return entry;
8216 }
8217 ASSERT(element->IsNull() || !String::cast(element)->Equals(key));
8218 entry = NextProbe(entry, count++, capacity);
8219 }
8220 return kNotFound;
8221}
8222
8223
Steve Blocka7e24c12009-10-30 11:49:00 +00008224template<typename Shape, typename Key>
John Reck59135872010-11-02 12:39:01 -07008225MaybeObject* HashTable<Shape, Key>::EnsureCapacity(int n, Key key) {
Steve Blocka7e24c12009-10-30 11:49:00 +00008226 int capacity = Capacity();
8227 int nof = NumberOfElements() + n;
Leon Clarkee46be812010-01-19 14:06:41 +00008228 int nod = NumberOfDeletedElements();
8229 // Return if:
8230 // 50% is still free after adding n elements and
8231 // at most 50% of the free elements are deleted elements.
Steve Block6ded16b2010-05-10 14:33:55 +01008232 if (nod <= (capacity - nof) >> 1) {
8233 int needed_free = nof >> 1;
8234 if (nof + needed_free <= capacity) return this;
8235 }
Steve Blocka7e24c12009-10-30 11:49:00 +00008236
Steve Block6ded16b2010-05-10 14:33:55 +01008237 const int kMinCapacityForPretenure = 256;
8238 bool pretenure =
8239 (capacity > kMinCapacityForPretenure) && !Heap::InNewSpace(this);
John Reck59135872010-11-02 12:39:01 -07008240 Object* obj;
8241 { MaybeObject* maybe_obj =
8242 Allocate(nof * 2, pretenure ? TENURED : NOT_TENURED);
8243 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
8244 }
Leon Clarke4515c472010-02-03 11:58:03 +00008245
8246 AssertNoAllocation no_gc;
Steve Blocka7e24c12009-10-30 11:49:00 +00008247 HashTable* table = HashTable::cast(obj);
Leon Clarke4515c472010-02-03 11:58:03 +00008248 WriteBarrierMode mode = table->GetWriteBarrierMode(no_gc);
Steve Blocka7e24c12009-10-30 11:49:00 +00008249
8250 // Copy prefix to new array.
8251 for (int i = kPrefixStartIndex;
8252 i < kPrefixStartIndex + Shape::kPrefixSize;
8253 i++) {
8254 table->set(i, get(i), mode);
8255 }
8256 // Rehash the elements.
8257 for (int i = 0; i < capacity; i++) {
8258 uint32_t from_index = EntryToIndex(i);
8259 Object* k = get(from_index);
8260 if (IsKey(k)) {
8261 uint32_t hash = Shape::HashForObject(key, k);
8262 uint32_t insertion_index =
8263 EntryToIndex(table->FindInsertionEntry(hash));
8264 for (int j = 0; j < Shape::kEntrySize; j++) {
8265 table->set(insertion_index + j, get(from_index + j), mode);
8266 }
8267 }
8268 }
8269 table->SetNumberOfElements(NumberOfElements());
Leon Clarkee46be812010-01-19 14:06:41 +00008270 table->SetNumberOfDeletedElements(0);
Steve Blocka7e24c12009-10-30 11:49:00 +00008271 return table;
8272}
8273
8274
8275template<typename Shape, typename Key>
8276uint32_t HashTable<Shape, Key>::FindInsertionEntry(uint32_t hash) {
8277 uint32_t capacity = Capacity();
Leon Clarkee46be812010-01-19 14:06:41 +00008278 uint32_t entry = FirstProbe(hash, capacity);
8279 uint32_t count = 1;
8280 // EnsureCapacity will guarantee the hash table is never full.
8281 while (true) {
8282 Object* element = KeyAt(entry);
8283 if (element->IsUndefined() || element->IsNull()) break;
8284 entry = NextProbe(entry, count++, capacity);
Steve Blocka7e24c12009-10-30 11:49:00 +00008285 }
Steve Blocka7e24c12009-10-30 11:49:00 +00008286 return entry;
8287}
8288
8289// Force instantiation of template instances class.
8290// Please note this list is compiler dependent.
8291
8292template class HashTable<SymbolTableShape, HashTableKey*>;
8293
8294template class HashTable<CompilationCacheShape, HashTableKey*>;
8295
8296template class HashTable<MapCacheShape, HashTableKey*>;
8297
8298template class Dictionary<StringDictionaryShape, String*>;
8299
8300template class Dictionary<NumberDictionaryShape, uint32_t>;
8301
John Reck59135872010-11-02 12:39:01 -07008302template MaybeObject* Dictionary<NumberDictionaryShape, uint32_t>::Allocate(
Steve Blocka7e24c12009-10-30 11:49:00 +00008303 int);
8304
John Reck59135872010-11-02 12:39:01 -07008305template MaybeObject* Dictionary<StringDictionaryShape, String*>::Allocate(
Steve Blocka7e24c12009-10-30 11:49:00 +00008306 int);
8307
John Reck59135872010-11-02 12:39:01 -07008308template MaybeObject* Dictionary<NumberDictionaryShape, uint32_t>::AtPut(
Steve Blocka7e24c12009-10-30 11:49:00 +00008309 uint32_t, Object*);
8310
8311template Object* Dictionary<NumberDictionaryShape, uint32_t>::SlowReverseLookup(
8312 Object*);
8313
8314template Object* Dictionary<StringDictionaryShape, String*>::SlowReverseLookup(
8315 Object*);
8316
8317template void Dictionary<NumberDictionaryShape, uint32_t>::CopyKeysTo(
8318 FixedArray*, PropertyAttributes);
8319
8320template Object* Dictionary<StringDictionaryShape, String*>::DeleteProperty(
8321 int, JSObject::DeleteMode);
8322
8323template Object* Dictionary<NumberDictionaryShape, uint32_t>::DeleteProperty(
8324 int, JSObject::DeleteMode);
8325
8326template void Dictionary<StringDictionaryShape, String*>::CopyKeysTo(
8327 FixedArray*);
8328
8329template int
8330Dictionary<StringDictionaryShape, String*>::NumberOfElementsFilterAttributes(
8331 PropertyAttributes);
8332
John Reck59135872010-11-02 12:39:01 -07008333template MaybeObject* Dictionary<StringDictionaryShape, String*>::Add(
Steve Blocka7e24c12009-10-30 11:49:00 +00008334 String*, Object*, PropertyDetails);
8335
John Reck59135872010-11-02 12:39:01 -07008336template MaybeObject*
Steve Blocka7e24c12009-10-30 11:49:00 +00008337Dictionary<StringDictionaryShape, String*>::GenerateNewEnumerationIndices();
8338
8339template int
8340Dictionary<NumberDictionaryShape, uint32_t>::NumberOfElementsFilterAttributes(
8341 PropertyAttributes);
8342
John Reck59135872010-11-02 12:39:01 -07008343template MaybeObject* Dictionary<NumberDictionaryShape, uint32_t>::Add(
Steve Blocka7e24c12009-10-30 11:49:00 +00008344 uint32_t, Object*, PropertyDetails);
8345
John Reck59135872010-11-02 12:39:01 -07008346template MaybeObject* Dictionary<NumberDictionaryShape, uint32_t>::
8347 EnsureCapacity(int, uint32_t);
Steve Blocka7e24c12009-10-30 11:49:00 +00008348
John Reck59135872010-11-02 12:39:01 -07008349template MaybeObject* Dictionary<StringDictionaryShape, String*>::
8350 EnsureCapacity(int, String*);
Steve Blocka7e24c12009-10-30 11:49:00 +00008351
John Reck59135872010-11-02 12:39:01 -07008352template MaybeObject* Dictionary<NumberDictionaryShape, uint32_t>::AddEntry(
Steve Blocka7e24c12009-10-30 11:49:00 +00008353 uint32_t, Object*, PropertyDetails, uint32_t);
8354
John Reck59135872010-11-02 12:39:01 -07008355template MaybeObject* Dictionary<StringDictionaryShape, String*>::AddEntry(
Steve Blocka7e24c12009-10-30 11:49:00 +00008356 String*, Object*, PropertyDetails, uint32_t);
8357
8358template
8359int Dictionary<NumberDictionaryShape, uint32_t>::NumberOfEnumElements();
8360
8361template
8362int Dictionary<StringDictionaryShape, String*>::NumberOfEnumElements();
8363
Leon Clarkee46be812010-01-19 14:06:41 +00008364template
8365int HashTable<NumberDictionaryShape, uint32_t>::FindEntry(uint32_t);
8366
8367
Steve Blocka7e24c12009-10-30 11:49:00 +00008368// Collates undefined and unexisting elements below limit from position
8369// zero of the elements. The object stays in Dictionary mode.
John Reck59135872010-11-02 12:39:01 -07008370MaybeObject* JSObject::PrepareSlowElementsForSort(uint32_t limit) {
Steve Blocka7e24c12009-10-30 11:49:00 +00008371 ASSERT(HasDictionaryElements());
8372 // Must stay in dictionary mode, either because of requires_slow_elements,
8373 // or because we are not going to sort (and therefore compact) all of the
8374 // elements.
8375 NumberDictionary* dict = element_dictionary();
8376 HeapNumber* result_double = NULL;
8377 if (limit > static_cast<uint32_t>(Smi::kMaxValue)) {
8378 // Allocate space for result before we start mutating the object.
John Reck59135872010-11-02 12:39:01 -07008379 Object* new_double;
8380 { MaybeObject* maybe_new_double = Heap::AllocateHeapNumber(0.0);
8381 if (!maybe_new_double->ToObject(&new_double)) return maybe_new_double;
8382 }
Steve Blocka7e24c12009-10-30 11:49:00 +00008383 result_double = HeapNumber::cast(new_double);
8384 }
8385
John Reck59135872010-11-02 12:39:01 -07008386 Object* obj;
8387 { MaybeObject* maybe_obj =
8388 NumberDictionary::Allocate(dict->NumberOfElements());
8389 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
8390 }
Steve Blocka7e24c12009-10-30 11:49:00 +00008391 NumberDictionary* new_dict = NumberDictionary::cast(obj);
8392
8393 AssertNoAllocation no_alloc;
8394
8395 uint32_t pos = 0;
8396 uint32_t undefs = 0;
Steve Block6ded16b2010-05-10 14:33:55 +01008397 int capacity = dict->Capacity();
Steve Blocka7e24c12009-10-30 11:49:00 +00008398 for (int i = 0; i < capacity; i++) {
8399 Object* k = dict->KeyAt(i);
8400 if (dict->IsKey(k)) {
8401 ASSERT(k->IsNumber());
8402 ASSERT(!k->IsSmi() || Smi::cast(k)->value() >= 0);
8403 ASSERT(!k->IsHeapNumber() || HeapNumber::cast(k)->value() >= 0);
8404 ASSERT(!k->IsHeapNumber() || HeapNumber::cast(k)->value() <= kMaxUInt32);
8405 Object* value = dict->ValueAt(i);
8406 PropertyDetails details = dict->DetailsAt(i);
8407 if (details.type() == CALLBACKS) {
8408 // Bail out and do the sorting of undefineds and array holes in JS.
8409 return Smi::FromInt(-1);
8410 }
8411 uint32_t key = NumberToUint32(k);
John Reck59135872010-11-02 12:39:01 -07008412 // In the following we assert that adding the entry to the new dictionary
8413 // does not cause GC. This is the case because we made sure to allocate
8414 // the dictionary big enough above, so it need not grow.
Steve Blocka7e24c12009-10-30 11:49:00 +00008415 if (key < limit) {
8416 if (value->IsUndefined()) {
8417 undefs++;
8418 } else {
John Reck59135872010-11-02 12:39:01 -07008419 new_dict->AddNumberEntry(pos, value, details)->ToObjectUnchecked();
Steve Blocka7e24c12009-10-30 11:49:00 +00008420 pos++;
8421 }
8422 } else {
John Reck59135872010-11-02 12:39:01 -07008423 new_dict->AddNumberEntry(key, value, details)->ToObjectUnchecked();
Steve Blocka7e24c12009-10-30 11:49:00 +00008424 }
8425 }
8426 }
8427
8428 uint32_t result = pos;
8429 PropertyDetails no_details = PropertyDetails(NONE, NORMAL);
8430 while (undefs > 0) {
John Reck59135872010-11-02 12:39:01 -07008431 new_dict->AddNumberEntry(pos, Heap::undefined_value(), no_details)->
8432 ToObjectUnchecked();
Steve Blocka7e24c12009-10-30 11:49:00 +00008433 pos++;
8434 undefs--;
8435 }
8436
8437 set_elements(new_dict);
8438
8439 if (result <= static_cast<uint32_t>(Smi::kMaxValue)) {
8440 return Smi::FromInt(static_cast<int>(result));
8441 }
8442
8443 ASSERT_NE(NULL, result_double);
8444 result_double->set_value(static_cast<double>(result));
8445 return result_double;
8446}
8447
8448
8449// Collects all defined (non-hole) and non-undefined (array) elements at
8450// the start of the elements array.
8451// If the object is in dictionary mode, it is converted to fast elements
8452// mode.
John Reck59135872010-11-02 12:39:01 -07008453MaybeObject* JSObject::PrepareElementsForSort(uint32_t limit) {
Steve Block3ce2e202009-11-05 08:53:23 +00008454 ASSERT(!HasPixelElements() && !HasExternalArrayElements());
Steve Blocka7e24c12009-10-30 11:49:00 +00008455
8456 if (HasDictionaryElements()) {
8457 // Convert to fast elements containing only the existing properties.
8458 // Ordering is irrelevant, since we are going to sort anyway.
8459 NumberDictionary* dict = element_dictionary();
8460 if (IsJSArray() || dict->requires_slow_elements() ||
8461 dict->max_number_key() >= limit) {
8462 return PrepareSlowElementsForSort(limit);
8463 }
8464 // Convert to fast elements.
8465
John Reck59135872010-11-02 12:39:01 -07008466 Object* obj;
8467 { MaybeObject* maybe_obj = map()->GetFastElementsMap();
8468 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
8469 }
Steve Block8defd9f2010-07-08 12:39:36 +01008470 Map* new_map = Map::cast(obj);
8471
Steve Blocka7e24c12009-10-30 11:49:00 +00008472 PretenureFlag tenure = Heap::InNewSpace(this) ? NOT_TENURED: TENURED;
John Reck59135872010-11-02 12:39:01 -07008473 Object* new_array;
8474 { MaybeObject* maybe_new_array =
8475 Heap::AllocateFixedArray(dict->NumberOfElements(), tenure);
8476 if (!maybe_new_array->ToObject(&new_array)) return maybe_new_array;
8477 }
Steve Blocka7e24c12009-10-30 11:49:00 +00008478 FixedArray* fast_elements = FixedArray::cast(new_array);
8479 dict->CopyValuesTo(fast_elements);
Steve Block8defd9f2010-07-08 12:39:36 +01008480
8481 set_map(new_map);
Steve Blocka7e24c12009-10-30 11:49:00 +00008482 set_elements(fast_elements);
Iain Merrick75681382010-08-19 15:07:18 +01008483 } else {
John Reck59135872010-11-02 12:39:01 -07008484 Object* obj;
8485 { MaybeObject* maybe_obj = EnsureWritableFastElements();
8486 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
8487 }
Steve Blocka7e24c12009-10-30 11:49:00 +00008488 }
8489 ASSERT(HasFastElements());
8490
8491 // Collect holes at the end, undefined before that and the rest at the
8492 // start, and return the number of non-hole, non-undefined values.
8493
8494 FixedArray* elements = FixedArray::cast(this->elements());
8495 uint32_t elements_length = static_cast<uint32_t>(elements->length());
8496 if (limit > elements_length) {
8497 limit = elements_length ;
8498 }
8499 if (limit == 0) {
8500 return Smi::FromInt(0);
8501 }
8502
8503 HeapNumber* result_double = NULL;
8504 if (limit > static_cast<uint32_t>(Smi::kMaxValue)) {
8505 // Pessimistically allocate space for return value before
8506 // we start mutating the array.
John Reck59135872010-11-02 12:39:01 -07008507 Object* new_double;
8508 { MaybeObject* maybe_new_double = Heap::AllocateHeapNumber(0.0);
8509 if (!maybe_new_double->ToObject(&new_double)) return maybe_new_double;
8510 }
Steve Blocka7e24c12009-10-30 11:49:00 +00008511 result_double = HeapNumber::cast(new_double);
8512 }
8513
8514 AssertNoAllocation no_alloc;
8515
8516 // Split elements into defined, undefined and the_hole, in that order.
8517 // Only count locations for undefined and the hole, and fill them afterwards.
Leon Clarke4515c472010-02-03 11:58:03 +00008518 WriteBarrierMode write_barrier = elements->GetWriteBarrierMode(no_alloc);
Steve Blocka7e24c12009-10-30 11:49:00 +00008519 unsigned int undefs = limit;
8520 unsigned int holes = limit;
8521 // Assume most arrays contain no holes and undefined values, so minimize the
8522 // number of stores of non-undefined, non-the-hole values.
8523 for (unsigned int i = 0; i < undefs; i++) {
8524 Object* current = elements->get(i);
8525 if (current->IsTheHole()) {
8526 holes--;
8527 undefs--;
8528 } else if (current->IsUndefined()) {
8529 undefs--;
8530 } else {
8531 continue;
8532 }
8533 // Position i needs to be filled.
8534 while (undefs > i) {
8535 current = elements->get(undefs);
8536 if (current->IsTheHole()) {
8537 holes--;
8538 undefs--;
8539 } else if (current->IsUndefined()) {
8540 undefs--;
8541 } else {
8542 elements->set(i, current, write_barrier);
8543 break;
8544 }
8545 }
8546 }
8547 uint32_t result = undefs;
8548 while (undefs < holes) {
8549 elements->set_undefined(undefs);
8550 undefs++;
8551 }
8552 while (holes < limit) {
8553 elements->set_the_hole(holes);
8554 holes++;
8555 }
8556
8557 if (result <= static_cast<uint32_t>(Smi::kMaxValue)) {
8558 return Smi::FromInt(static_cast<int>(result));
8559 }
8560 ASSERT_NE(NULL, result_double);
8561 result_double->set_value(static_cast<double>(result));
8562 return result_double;
8563}
8564
8565
8566Object* PixelArray::SetValue(uint32_t index, Object* value) {
8567 uint8_t clamped_value = 0;
8568 if (index < static_cast<uint32_t>(length())) {
8569 if (value->IsSmi()) {
8570 int int_value = Smi::cast(value)->value();
8571 if (int_value < 0) {
8572 clamped_value = 0;
8573 } else if (int_value > 255) {
8574 clamped_value = 255;
8575 } else {
8576 clamped_value = static_cast<uint8_t>(int_value);
8577 }
8578 } else if (value->IsHeapNumber()) {
8579 double double_value = HeapNumber::cast(value)->value();
8580 if (!(double_value > 0)) {
8581 // NaN and less than zero clamp to zero.
8582 clamped_value = 0;
8583 } else if (double_value > 255) {
8584 // Greater than 255 clamp to 255.
8585 clamped_value = 255;
8586 } else {
8587 // Other doubles are rounded to the nearest integer.
8588 clamped_value = static_cast<uint8_t>(double_value + 0.5);
8589 }
8590 } else {
8591 // Clamp undefined to zero (default). All other types have been
8592 // converted to a number type further up in the call chain.
8593 ASSERT(value->IsUndefined());
8594 }
8595 set(index, clamped_value);
8596 }
8597 return Smi::FromInt(clamped_value);
8598}
8599
8600
Steve Block3ce2e202009-11-05 08:53:23 +00008601template<typename ExternalArrayClass, typename ValueType>
John Reck59135872010-11-02 12:39:01 -07008602static MaybeObject* ExternalArrayIntSetter(ExternalArrayClass* receiver,
8603 uint32_t index,
8604 Object* value) {
Steve Block3ce2e202009-11-05 08:53:23 +00008605 ValueType cast_value = 0;
8606 if (index < static_cast<uint32_t>(receiver->length())) {
8607 if (value->IsSmi()) {
8608 int int_value = Smi::cast(value)->value();
8609 cast_value = static_cast<ValueType>(int_value);
8610 } else if (value->IsHeapNumber()) {
8611 double double_value = HeapNumber::cast(value)->value();
8612 cast_value = static_cast<ValueType>(DoubleToInt32(double_value));
8613 } else {
8614 // Clamp undefined to zero (default). All other types have been
8615 // converted to a number type further up in the call chain.
8616 ASSERT(value->IsUndefined());
8617 }
8618 receiver->set(index, cast_value);
8619 }
8620 return Heap::NumberFromInt32(cast_value);
8621}
8622
8623
John Reck59135872010-11-02 12:39:01 -07008624MaybeObject* ExternalByteArray::SetValue(uint32_t index, Object* value) {
Steve Block3ce2e202009-11-05 08:53:23 +00008625 return ExternalArrayIntSetter<ExternalByteArray, int8_t>
8626 (this, index, value);
8627}
8628
8629
John Reck59135872010-11-02 12:39:01 -07008630MaybeObject* ExternalUnsignedByteArray::SetValue(uint32_t index,
8631 Object* value) {
Steve Block3ce2e202009-11-05 08:53:23 +00008632 return ExternalArrayIntSetter<ExternalUnsignedByteArray, uint8_t>
8633 (this, index, value);
8634}
8635
8636
John Reck59135872010-11-02 12:39:01 -07008637MaybeObject* ExternalShortArray::SetValue(uint32_t index,
8638 Object* value) {
Steve Block3ce2e202009-11-05 08:53:23 +00008639 return ExternalArrayIntSetter<ExternalShortArray, int16_t>
8640 (this, index, value);
8641}
8642
8643
John Reck59135872010-11-02 12:39:01 -07008644MaybeObject* ExternalUnsignedShortArray::SetValue(uint32_t index,
8645 Object* value) {
Steve Block3ce2e202009-11-05 08:53:23 +00008646 return ExternalArrayIntSetter<ExternalUnsignedShortArray, uint16_t>
8647 (this, index, value);
8648}
8649
8650
John Reck59135872010-11-02 12:39:01 -07008651MaybeObject* ExternalIntArray::SetValue(uint32_t index, Object* value) {
Steve Block3ce2e202009-11-05 08:53:23 +00008652 return ExternalArrayIntSetter<ExternalIntArray, int32_t>
8653 (this, index, value);
8654}
8655
8656
John Reck59135872010-11-02 12:39:01 -07008657MaybeObject* ExternalUnsignedIntArray::SetValue(uint32_t index, Object* value) {
Steve Block3ce2e202009-11-05 08:53:23 +00008658 uint32_t cast_value = 0;
8659 if (index < static_cast<uint32_t>(length())) {
8660 if (value->IsSmi()) {
8661 int int_value = Smi::cast(value)->value();
8662 cast_value = static_cast<uint32_t>(int_value);
8663 } else if (value->IsHeapNumber()) {
8664 double double_value = HeapNumber::cast(value)->value();
8665 cast_value = static_cast<uint32_t>(DoubleToUint32(double_value));
8666 } else {
8667 // Clamp undefined to zero (default). All other types have been
8668 // converted to a number type further up in the call chain.
8669 ASSERT(value->IsUndefined());
8670 }
8671 set(index, cast_value);
8672 }
8673 return Heap::NumberFromUint32(cast_value);
8674}
8675
8676
John Reck59135872010-11-02 12:39:01 -07008677MaybeObject* ExternalFloatArray::SetValue(uint32_t index, Object* value) {
Steve Block3ce2e202009-11-05 08:53:23 +00008678 float cast_value = 0;
8679 if (index < static_cast<uint32_t>(length())) {
8680 if (value->IsSmi()) {
8681 int int_value = Smi::cast(value)->value();
8682 cast_value = static_cast<float>(int_value);
8683 } else if (value->IsHeapNumber()) {
8684 double double_value = HeapNumber::cast(value)->value();
8685 cast_value = static_cast<float>(double_value);
8686 } else {
8687 // Clamp undefined to zero (default). All other types have been
8688 // converted to a number type further up in the call chain.
8689 ASSERT(value->IsUndefined());
8690 }
8691 set(index, cast_value);
8692 }
8693 return Heap::AllocateHeapNumber(cast_value);
8694}
8695
8696
Ben Murdochb0fe1622011-05-05 13:52:32 +01008697JSGlobalPropertyCell* GlobalObject::GetPropertyCell(LookupResult* result) {
Steve Blocka7e24c12009-10-30 11:49:00 +00008698 ASSERT(!HasFastProperties());
8699 Object* value = property_dictionary()->ValueAt(result->GetDictionaryEntry());
Ben Murdochb0fe1622011-05-05 13:52:32 +01008700 return JSGlobalPropertyCell::cast(value);
Steve Blocka7e24c12009-10-30 11:49:00 +00008701}
8702
8703
John Reck59135872010-11-02 12:39:01 -07008704MaybeObject* GlobalObject::EnsurePropertyCell(String* name) {
Steve Blocka7e24c12009-10-30 11:49:00 +00008705 ASSERT(!HasFastProperties());
8706 int entry = property_dictionary()->FindEntry(name);
8707 if (entry == StringDictionary::kNotFound) {
John Reck59135872010-11-02 12:39:01 -07008708 Object* cell;
8709 { MaybeObject* maybe_cell =
8710 Heap::AllocateJSGlobalPropertyCell(Heap::the_hole_value());
8711 if (!maybe_cell->ToObject(&cell)) return maybe_cell;
8712 }
Steve Blocka7e24c12009-10-30 11:49:00 +00008713 PropertyDetails details(NONE, NORMAL);
8714 details = details.AsDeleted();
John Reck59135872010-11-02 12:39:01 -07008715 Object* dictionary;
8716 { MaybeObject* maybe_dictionary =
8717 property_dictionary()->Add(name, cell, details);
8718 if (!maybe_dictionary->ToObject(&dictionary)) return maybe_dictionary;
8719 }
Steve Blocka7e24c12009-10-30 11:49:00 +00008720 set_properties(StringDictionary::cast(dictionary));
8721 return cell;
8722 } else {
8723 Object* value = property_dictionary()->ValueAt(entry);
8724 ASSERT(value->IsJSGlobalPropertyCell());
8725 return value;
8726 }
8727}
8728
8729
John Reck59135872010-11-02 12:39:01 -07008730MaybeObject* SymbolTable::LookupString(String* string, Object** s) {
Steve Blocka7e24c12009-10-30 11:49:00 +00008731 SymbolKey key(string);
8732 return LookupKey(&key, s);
8733}
8734
8735
Steve Blockd0582a62009-12-15 09:54:21 +00008736// This class is used for looking up two character strings in the symbol table.
8737// If we don't have a hit we don't want to waste much time so we unroll the
8738// string hash calculation loop here for speed. Doesn't work if the two
8739// characters form a decimal integer, since such strings have a different hash
8740// algorithm.
8741class TwoCharHashTableKey : public HashTableKey {
8742 public:
8743 TwoCharHashTableKey(uint32_t c1, uint32_t c2)
8744 : c1_(c1), c2_(c2) {
8745 // Char 1.
8746 uint32_t hash = c1 + (c1 << 10);
8747 hash ^= hash >> 6;
8748 // Char 2.
8749 hash += c2;
8750 hash += hash << 10;
8751 hash ^= hash >> 6;
8752 // GetHash.
8753 hash += hash << 3;
8754 hash ^= hash >> 11;
8755 hash += hash << 15;
8756 if (hash == 0) hash = 27;
8757#ifdef DEBUG
8758 StringHasher hasher(2);
8759 hasher.AddCharacter(c1);
8760 hasher.AddCharacter(c2);
8761 // If this assert fails then we failed to reproduce the two-character
8762 // version of the string hashing algorithm above. One reason could be
8763 // that we were passed two digits as characters, since the hash
8764 // algorithm is different in that case.
8765 ASSERT_EQ(static_cast<int>(hasher.GetHash()), static_cast<int>(hash));
8766#endif
8767 hash_ = hash;
8768 }
8769
8770 bool IsMatch(Object* o) {
8771 if (!o->IsString()) return false;
8772 String* other = String::cast(o);
8773 if (other->length() != 2) return false;
8774 if (other->Get(0) != c1_) return false;
8775 return other->Get(1) == c2_;
8776 }
8777
8778 uint32_t Hash() { return hash_; }
8779 uint32_t HashForObject(Object* key) {
8780 if (!key->IsString()) return 0;
8781 return String::cast(key)->Hash();
8782 }
8783
8784 Object* AsObject() {
8785 // The TwoCharHashTableKey is only used for looking in the symbol
8786 // table, not for adding to it.
8787 UNREACHABLE();
8788 return NULL;
8789 }
8790 private:
8791 uint32_t c1_;
8792 uint32_t c2_;
8793 uint32_t hash_;
8794};
8795
8796
Steve Blocka7e24c12009-10-30 11:49:00 +00008797bool SymbolTable::LookupSymbolIfExists(String* string, String** symbol) {
8798 SymbolKey key(string);
8799 int entry = FindEntry(&key);
8800 if (entry == kNotFound) {
8801 return false;
8802 } else {
8803 String* result = String::cast(KeyAt(entry));
8804 ASSERT(StringShape(result).IsSymbol());
8805 *symbol = result;
8806 return true;
8807 }
8808}
8809
8810
Steve Blockd0582a62009-12-15 09:54:21 +00008811bool SymbolTable::LookupTwoCharsSymbolIfExists(uint32_t c1,
8812 uint32_t c2,
8813 String** symbol) {
8814 TwoCharHashTableKey key(c1, c2);
8815 int entry = FindEntry(&key);
8816 if (entry == kNotFound) {
8817 return false;
8818 } else {
8819 String* result = String::cast(KeyAt(entry));
8820 ASSERT(StringShape(result).IsSymbol());
8821 *symbol = result;
8822 return true;
8823 }
8824}
8825
8826
John Reck59135872010-11-02 12:39:01 -07008827MaybeObject* SymbolTable::LookupSymbol(Vector<const char> str, Object** s) {
Steve Blocka7e24c12009-10-30 11:49:00 +00008828 Utf8SymbolKey key(str);
8829 return LookupKey(&key, s);
8830}
8831
8832
John Reck59135872010-11-02 12:39:01 -07008833MaybeObject* SymbolTable::LookupKey(HashTableKey* key, Object** s) {
Steve Blocka7e24c12009-10-30 11:49:00 +00008834 int entry = FindEntry(key);
8835
8836 // Symbol already in table.
8837 if (entry != kNotFound) {
8838 *s = KeyAt(entry);
8839 return this;
8840 }
8841
8842 // Adding new symbol. Grow table if needed.
John Reck59135872010-11-02 12:39:01 -07008843 Object* obj;
8844 { MaybeObject* maybe_obj = EnsureCapacity(1, key);
8845 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
8846 }
Steve Blocka7e24c12009-10-30 11:49:00 +00008847
8848 // Create symbol object.
John Reck59135872010-11-02 12:39:01 -07008849 Object* symbol;
8850 { MaybeObject* maybe_symbol = key->AsObject();
8851 if (!maybe_symbol->ToObject(&symbol)) return maybe_symbol;
8852 }
Steve Blocka7e24c12009-10-30 11:49:00 +00008853
8854 // If the symbol table grew as part of EnsureCapacity, obj is not
8855 // the current symbol table and therefore we cannot use
8856 // SymbolTable::cast here.
8857 SymbolTable* table = reinterpret_cast<SymbolTable*>(obj);
8858
8859 // Add the new symbol and return it along with the symbol table.
8860 entry = table->FindInsertionEntry(key->Hash());
8861 table->set(EntryToIndex(entry), symbol);
8862 table->ElementAdded();
8863 *s = symbol;
8864 return table;
8865}
8866
8867
8868Object* CompilationCacheTable::Lookup(String* src) {
8869 StringKey key(src);
8870 int entry = FindEntry(&key);
8871 if (entry == kNotFound) return Heap::undefined_value();
8872 return get(EntryToIndex(entry) + 1);
8873}
8874
8875
8876Object* CompilationCacheTable::LookupEval(String* src, Context* context) {
8877 StringSharedKey key(src, context->closure()->shared());
8878 int entry = FindEntry(&key);
8879 if (entry == kNotFound) return Heap::undefined_value();
8880 return get(EntryToIndex(entry) + 1);
8881}
8882
8883
8884Object* CompilationCacheTable::LookupRegExp(String* src,
8885 JSRegExp::Flags flags) {
8886 RegExpKey key(src, flags);
8887 int entry = FindEntry(&key);
8888 if (entry == kNotFound) return Heap::undefined_value();
8889 return get(EntryToIndex(entry) + 1);
8890}
8891
8892
John Reck59135872010-11-02 12:39:01 -07008893MaybeObject* CompilationCacheTable::Put(String* src, Object* value) {
Steve Blocka7e24c12009-10-30 11:49:00 +00008894 StringKey key(src);
John Reck59135872010-11-02 12:39:01 -07008895 Object* obj;
8896 { MaybeObject* maybe_obj = EnsureCapacity(1, &key);
8897 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
8898 }
Steve Blocka7e24c12009-10-30 11:49:00 +00008899
8900 CompilationCacheTable* cache =
8901 reinterpret_cast<CompilationCacheTable*>(obj);
8902 int entry = cache->FindInsertionEntry(key.Hash());
8903 cache->set(EntryToIndex(entry), src);
8904 cache->set(EntryToIndex(entry) + 1, value);
8905 cache->ElementAdded();
8906 return cache;
8907}
8908
8909
John Reck59135872010-11-02 12:39:01 -07008910MaybeObject* CompilationCacheTable::PutEval(String* src,
8911 Context* context,
8912 Object* value) {
Steve Blocka7e24c12009-10-30 11:49:00 +00008913 StringSharedKey key(src, context->closure()->shared());
John Reck59135872010-11-02 12:39:01 -07008914 Object* obj;
8915 { MaybeObject* maybe_obj = EnsureCapacity(1, &key);
8916 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
8917 }
Steve Blocka7e24c12009-10-30 11:49:00 +00008918
8919 CompilationCacheTable* cache =
8920 reinterpret_cast<CompilationCacheTable*>(obj);
8921 int entry = cache->FindInsertionEntry(key.Hash());
8922
John Reck59135872010-11-02 12:39:01 -07008923 Object* k;
8924 { MaybeObject* maybe_k = key.AsObject();
8925 if (!maybe_k->ToObject(&k)) return maybe_k;
8926 }
Steve Blocka7e24c12009-10-30 11:49:00 +00008927
8928 cache->set(EntryToIndex(entry), k);
8929 cache->set(EntryToIndex(entry) + 1, value);
8930 cache->ElementAdded();
8931 return cache;
8932}
8933
8934
John Reck59135872010-11-02 12:39:01 -07008935MaybeObject* CompilationCacheTable::PutRegExp(String* src,
8936 JSRegExp::Flags flags,
8937 FixedArray* value) {
Steve Blocka7e24c12009-10-30 11:49:00 +00008938 RegExpKey key(src, flags);
John Reck59135872010-11-02 12:39:01 -07008939 Object* obj;
8940 { MaybeObject* maybe_obj = EnsureCapacity(1, &key);
8941 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
8942 }
Steve Blocka7e24c12009-10-30 11:49:00 +00008943
8944 CompilationCacheTable* cache =
8945 reinterpret_cast<CompilationCacheTable*>(obj);
8946 int entry = cache->FindInsertionEntry(key.Hash());
Steve Block3ce2e202009-11-05 08:53:23 +00008947 // We store the value in the key slot, and compare the search key
8948 // to the stored value with a custon IsMatch function during lookups.
Steve Blocka7e24c12009-10-30 11:49:00 +00008949 cache->set(EntryToIndex(entry), value);
8950 cache->set(EntryToIndex(entry) + 1, value);
8951 cache->ElementAdded();
8952 return cache;
8953}
8954
8955
Ben Murdochb0fe1622011-05-05 13:52:32 +01008956void CompilationCacheTable::Remove(Object* value) {
8957 for (int entry = 0, size = Capacity(); entry < size; entry++) {
8958 int entry_index = EntryToIndex(entry);
8959 int value_index = entry_index + 1;
8960 if (get(value_index) == value) {
8961 fast_set(this, entry_index, Heap::null_value());
8962 fast_set(this, value_index, Heap::null_value());
8963 ElementRemoved();
8964 }
8965 }
8966 return;
8967}
8968
8969
Steve Blocka7e24c12009-10-30 11:49:00 +00008970// SymbolsKey used for HashTable where key is array of symbols.
8971class SymbolsKey : public HashTableKey {
8972 public:
8973 explicit SymbolsKey(FixedArray* symbols) : symbols_(symbols) { }
8974
8975 bool IsMatch(Object* symbols) {
8976 FixedArray* o = FixedArray::cast(symbols);
8977 int len = symbols_->length();
8978 if (o->length() != len) return false;
8979 for (int i = 0; i < len; i++) {
8980 if (o->get(i) != symbols_->get(i)) return false;
8981 }
8982 return true;
8983 }
8984
8985 uint32_t Hash() { return HashForObject(symbols_); }
8986
8987 uint32_t HashForObject(Object* obj) {
8988 FixedArray* symbols = FixedArray::cast(obj);
8989 int len = symbols->length();
8990 uint32_t hash = 0;
8991 for (int i = 0; i < len; i++) {
8992 hash ^= String::cast(symbols->get(i))->Hash();
8993 }
8994 return hash;
8995 }
8996
8997 Object* AsObject() { return symbols_; }
8998
8999 private:
9000 FixedArray* symbols_;
9001};
9002
9003
9004Object* MapCache::Lookup(FixedArray* array) {
9005 SymbolsKey key(array);
9006 int entry = FindEntry(&key);
9007 if (entry == kNotFound) return Heap::undefined_value();
9008 return get(EntryToIndex(entry) + 1);
9009}
9010
9011
John Reck59135872010-11-02 12:39:01 -07009012MaybeObject* MapCache::Put(FixedArray* array, Map* value) {
Steve Blocka7e24c12009-10-30 11:49:00 +00009013 SymbolsKey key(array);
John Reck59135872010-11-02 12:39:01 -07009014 Object* obj;
9015 { MaybeObject* maybe_obj = EnsureCapacity(1, &key);
9016 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
9017 }
Steve Blocka7e24c12009-10-30 11:49:00 +00009018
9019 MapCache* cache = reinterpret_cast<MapCache*>(obj);
9020 int entry = cache->FindInsertionEntry(key.Hash());
9021 cache->set(EntryToIndex(entry), array);
9022 cache->set(EntryToIndex(entry) + 1, value);
9023 cache->ElementAdded();
9024 return cache;
9025}
9026
9027
9028template<typename Shape, typename Key>
John Reck59135872010-11-02 12:39:01 -07009029MaybeObject* Dictionary<Shape, Key>::Allocate(int at_least_space_for) {
9030 Object* obj;
9031 { MaybeObject* maybe_obj =
9032 HashTable<Shape, Key>::Allocate(at_least_space_for);
9033 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
Steve Blocka7e24c12009-10-30 11:49:00 +00009034 }
John Reck59135872010-11-02 12:39:01 -07009035 // Initialize the next enumeration index.
9036 Dictionary<Shape, Key>::cast(obj)->
9037 SetNextEnumerationIndex(PropertyDetails::kInitialIndex);
Steve Blocka7e24c12009-10-30 11:49:00 +00009038 return obj;
9039}
9040
9041
9042template<typename Shape, typename Key>
John Reck59135872010-11-02 12:39:01 -07009043MaybeObject* Dictionary<Shape, Key>::GenerateNewEnumerationIndices() {
Steve Blocka7e24c12009-10-30 11:49:00 +00009044 int length = HashTable<Shape, Key>::NumberOfElements();
9045
9046 // Allocate and initialize iteration order array.
John Reck59135872010-11-02 12:39:01 -07009047 Object* obj;
9048 { MaybeObject* maybe_obj = Heap::AllocateFixedArray(length);
9049 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
9050 }
Steve Blocka7e24c12009-10-30 11:49:00 +00009051 FixedArray* iteration_order = FixedArray::cast(obj);
9052 for (int i = 0; i < length; i++) {
Leon Clarke4515c472010-02-03 11:58:03 +00009053 iteration_order->set(i, Smi::FromInt(i));
Steve Blocka7e24c12009-10-30 11:49:00 +00009054 }
9055
9056 // Allocate array with enumeration order.
John Reck59135872010-11-02 12:39:01 -07009057 { MaybeObject* maybe_obj = Heap::AllocateFixedArray(length);
9058 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
9059 }
Steve Blocka7e24c12009-10-30 11:49:00 +00009060 FixedArray* enumeration_order = FixedArray::cast(obj);
9061
9062 // Fill the enumeration order array with property details.
9063 int capacity = HashTable<Shape, Key>::Capacity();
9064 int pos = 0;
9065 for (int i = 0; i < capacity; i++) {
9066 if (Dictionary<Shape, Key>::IsKey(Dictionary<Shape, Key>::KeyAt(i))) {
Leon Clarke4515c472010-02-03 11:58:03 +00009067 enumeration_order->set(pos++, Smi::FromInt(DetailsAt(i).index()));
Steve Blocka7e24c12009-10-30 11:49:00 +00009068 }
9069 }
9070
9071 // Sort the arrays wrt. enumeration order.
9072 iteration_order->SortPairs(enumeration_order, enumeration_order->length());
9073
9074 // Overwrite the enumeration_order with the enumeration indices.
9075 for (int i = 0; i < length; i++) {
9076 int index = Smi::cast(iteration_order->get(i))->value();
9077 int enum_index = PropertyDetails::kInitialIndex + i;
Leon Clarke4515c472010-02-03 11:58:03 +00009078 enumeration_order->set(index, Smi::FromInt(enum_index));
Steve Blocka7e24c12009-10-30 11:49:00 +00009079 }
9080
9081 // Update the dictionary with new indices.
9082 capacity = HashTable<Shape, Key>::Capacity();
9083 pos = 0;
9084 for (int i = 0; i < capacity; i++) {
9085 if (Dictionary<Shape, Key>::IsKey(Dictionary<Shape, Key>::KeyAt(i))) {
9086 int enum_index = Smi::cast(enumeration_order->get(pos++))->value();
9087 PropertyDetails details = DetailsAt(i);
9088 PropertyDetails new_details =
9089 PropertyDetails(details.attributes(), details.type(), enum_index);
9090 DetailsAtPut(i, new_details);
9091 }
9092 }
9093
9094 // Set the next enumeration index.
9095 SetNextEnumerationIndex(PropertyDetails::kInitialIndex+length);
9096 return this;
9097}
9098
9099template<typename Shape, typename Key>
John Reck59135872010-11-02 12:39:01 -07009100MaybeObject* Dictionary<Shape, Key>::EnsureCapacity(int n, Key key) {
Steve Blocka7e24c12009-10-30 11:49:00 +00009101 // Check whether there are enough enumeration indices to add n elements.
9102 if (Shape::kIsEnumerable &&
9103 !PropertyDetails::IsValidIndex(NextEnumerationIndex() + n)) {
9104 // If not, we generate new indices for the properties.
John Reck59135872010-11-02 12:39:01 -07009105 Object* result;
9106 { MaybeObject* maybe_result = GenerateNewEnumerationIndices();
9107 if (!maybe_result->ToObject(&result)) return maybe_result;
9108 }
Steve Blocka7e24c12009-10-30 11:49:00 +00009109 }
9110 return HashTable<Shape, Key>::EnsureCapacity(n, key);
9111}
9112
9113
9114void NumberDictionary::RemoveNumberEntries(uint32_t from, uint32_t to) {
9115 // Do nothing if the interval [from, to) is empty.
9116 if (from >= to) return;
9117
9118 int removed_entries = 0;
9119 Object* sentinel = Heap::null_value();
9120 int capacity = Capacity();
9121 for (int i = 0; i < capacity; i++) {
9122 Object* key = KeyAt(i);
9123 if (key->IsNumber()) {
9124 uint32_t number = static_cast<uint32_t>(key->Number());
9125 if (from <= number && number < to) {
9126 SetEntry(i, sentinel, sentinel, Smi::FromInt(0));
9127 removed_entries++;
9128 }
9129 }
9130 }
9131
9132 // Update the number of elements.
Leon Clarkee46be812010-01-19 14:06:41 +00009133 ElementsRemoved(removed_entries);
Steve Blocka7e24c12009-10-30 11:49:00 +00009134}
9135
9136
9137template<typename Shape, typename Key>
9138Object* Dictionary<Shape, Key>::DeleteProperty(int entry,
9139 JSObject::DeleteMode mode) {
9140 PropertyDetails details = DetailsAt(entry);
9141 // Ignore attributes if forcing a deletion.
9142 if (details.IsDontDelete() && mode == JSObject::NORMAL_DELETION) {
9143 return Heap::false_value();
9144 }
9145 SetEntry(entry, Heap::null_value(), Heap::null_value(), Smi::FromInt(0));
9146 HashTable<Shape, Key>::ElementRemoved();
9147 return Heap::true_value();
9148}
9149
9150
9151template<typename Shape, typename Key>
John Reck59135872010-11-02 12:39:01 -07009152MaybeObject* Dictionary<Shape, Key>::AtPut(Key key, Object* value) {
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01009153 int entry = this->FindEntry(key);
Steve Blocka7e24c12009-10-30 11:49:00 +00009154
9155 // If the entry is present set the value;
9156 if (entry != Dictionary<Shape, Key>::kNotFound) {
9157 ValueAtPut(entry, value);
9158 return this;
9159 }
9160
9161 // Check whether the dictionary should be extended.
John Reck59135872010-11-02 12:39:01 -07009162 Object* obj;
9163 { MaybeObject* maybe_obj = EnsureCapacity(1, key);
9164 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
9165 }
Steve Blocka7e24c12009-10-30 11:49:00 +00009166
John Reck59135872010-11-02 12:39:01 -07009167 Object* k;
9168 { MaybeObject* maybe_k = Shape::AsObject(key);
9169 if (!maybe_k->ToObject(&k)) return maybe_k;
9170 }
Steve Blocka7e24c12009-10-30 11:49:00 +00009171 PropertyDetails details = PropertyDetails(NONE, NORMAL);
9172 return Dictionary<Shape, Key>::cast(obj)->
9173 AddEntry(key, value, details, Shape::Hash(key));
9174}
9175
9176
9177template<typename Shape, typename Key>
John Reck59135872010-11-02 12:39:01 -07009178MaybeObject* Dictionary<Shape, Key>::Add(Key key,
9179 Object* value,
9180 PropertyDetails details) {
Steve Blocka7e24c12009-10-30 11:49:00 +00009181 // Valdate key is absent.
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01009182 SLOW_ASSERT((this->FindEntry(key) == Dictionary<Shape, Key>::kNotFound));
Steve Blocka7e24c12009-10-30 11:49:00 +00009183 // Check whether the dictionary should be extended.
John Reck59135872010-11-02 12:39:01 -07009184 Object* obj;
9185 { MaybeObject* maybe_obj = EnsureCapacity(1, key);
9186 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
9187 }
Steve Blocka7e24c12009-10-30 11:49:00 +00009188 return Dictionary<Shape, Key>::cast(obj)->
9189 AddEntry(key, value, details, Shape::Hash(key));
9190}
9191
9192
9193// Add a key, value pair to the dictionary.
9194template<typename Shape, typename Key>
John Reck59135872010-11-02 12:39:01 -07009195MaybeObject* Dictionary<Shape, Key>::AddEntry(Key key,
9196 Object* value,
9197 PropertyDetails details,
9198 uint32_t hash) {
Steve Blocka7e24c12009-10-30 11:49:00 +00009199 // Compute the key object.
John Reck59135872010-11-02 12:39:01 -07009200 Object* k;
9201 { MaybeObject* maybe_k = Shape::AsObject(key);
9202 if (!maybe_k->ToObject(&k)) return maybe_k;
9203 }
Steve Blocka7e24c12009-10-30 11:49:00 +00009204
9205 uint32_t entry = Dictionary<Shape, Key>::FindInsertionEntry(hash);
9206 // Insert element at empty or deleted entry
9207 if (!details.IsDeleted() && details.index() == 0 && Shape::kIsEnumerable) {
9208 // Assign an enumeration index to the property and update
9209 // SetNextEnumerationIndex.
9210 int index = NextEnumerationIndex();
9211 details = PropertyDetails(details.attributes(), details.type(), index);
9212 SetNextEnumerationIndex(index + 1);
9213 }
9214 SetEntry(entry, k, value, details);
9215 ASSERT((Dictionary<Shape, Key>::KeyAt(entry)->IsNumber()
9216 || Dictionary<Shape, Key>::KeyAt(entry)->IsString()));
9217 HashTable<Shape, Key>::ElementAdded();
9218 return this;
9219}
9220
9221
9222void NumberDictionary::UpdateMaxNumberKey(uint32_t key) {
9223 // If the dictionary requires slow elements an element has already
9224 // been added at a high index.
9225 if (requires_slow_elements()) return;
9226 // Check if this index is high enough that we should require slow
9227 // elements.
9228 if (key > kRequiresSlowElementsLimit) {
9229 set_requires_slow_elements();
9230 return;
9231 }
9232 // Update max key value.
9233 Object* max_index_object = get(kMaxNumberKeyIndex);
9234 if (!max_index_object->IsSmi() || max_number_key() < key) {
9235 FixedArray::set(kMaxNumberKeyIndex,
Leon Clarke4515c472010-02-03 11:58:03 +00009236 Smi::FromInt(key << kRequiresSlowElementsTagSize));
Steve Blocka7e24c12009-10-30 11:49:00 +00009237 }
9238}
9239
9240
John Reck59135872010-11-02 12:39:01 -07009241MaybeObject* NumberDictionary::AddNumberEntry(uint32_t key,
9242 Object* value,
9243 PropertyDetails details) {
Steve Blocka7e24c12009-10-30 11:49:00 +00009244 UpdateMaxNumberKey(key);
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01009245 SLOW_ASSERT(this->FindEntry(key) == kNotFound);
Steve Blocka7e24c12009-10-30 11:49:00 +00009246 return Add(key, value, details);
9247}
9248
9249
John Reck59135872010-11-02 12:39:01 -07009250MaybeObject* NumberDictionary::AtNumberPut(uint32_t key, Object* value) {
Steve Blocka7e24c12009-10-30 11:49:00 +00009251 UpdateMaxNumberKey(key);
9252 return AtPut(key, value);
9253}
9254
9255
John Reck59135872010-11-02 12:39:01 -07009256MaybeObject* NumberDictionary::Set(uint32_t key,
9257 Object* value,
9258 PropertyDetails details) {
Steve Blocka7e24c12009-10-30 11:49:00 +00009259 int entry = FindEntry(key);
9260 if (entry == kNotFound) return AddNumberEntry(key, value, details);
9261 // Preserve enumeration index.
9262 details = PropertyDetails(details.attributes(),
9263 details.type(),
9264 DetailsAt(entry).index());
John Reck59135872010-11-02 12:39:01 -07009265 MaybeObject* maybe_object_key = NumberDictionaryShape::AsObject(key);
9266 Object* object_key;
9267 if (!maybe_object_key->ToObject(&object_key)) return maybe_object_key;
Ben Murdochf87a2032010-10-22 12:50:53 +01009268 SetEntry(entry, object_key, value, details);
Steve Blocka7e24c12009-10-30 11:49:00 +00009269 return this;
9270}
9271
9272
9273
9274template<typename Shape, typename Key>
9275int Dictionary<Shape, Key>::NumberOfElementsFilterAttributes(
9276 PropertyAttributes filter) {
9277 int capacity = HashTable<Shape, Key>::Capacity();
9278 int result = 0;
9279 for (int i = 0; i < capacity; i++) {
9280 Object* k = HashTable<Shape, Key>::KeyAt(i);
9281 if (HashTable<Shape, Key>::IsKey(k)) {
9282 PropertyDetails details = DetailsAt(i);
9283 if (details.IsDeleted()) continue;
9284 PropertyAttributes attr = details.attributes();
9285 if ((attr & filter) == 0) result++;
9286 }
9287 }
9288 return result;
9289}
9290
9291
9292template<typename Shape, typename Key>
9293int Dictionary<Shape, Key>::NumberOfEnumElements() {
9294 return NumberOfElementsFilterAttributes(
9295 static_cast<PropertyAttributes>(DONT_ENUM));
9296}
9297
9298
9299template<typename Shape, typename Key>
9300void Dictionary<Shape, Key>::CopyKeysTo(FixedArray* storage,
9301 PropertyAttributes filter) {
9302 ASSERT(storage->length() >= NumberOfEnumElements());
9303 int capacity = HashTable<Shape, Key>::Capacity();
9304 int index = 0;
9305 for (int i = 0; i < capacity; i++) {
9306 Object* k = HashTable<Shape, Key>::KeyAt(i);
9307 if (HashTable<Shape, Key>::IsKey(k)) {
9308 PropertyDetails details = DetailsAt(i);
9309 if (details.IsDeleted()) continue;
9310 PropertyAttributes attr = details.attributes();
9311 if ((attr & filter) == 0) storage->set(index++, k);
9312 }
9313 }
9314 storage->SortPairs(storage, index);
9315 ASSERT(storage->length() >= index);
9316}
9317
9318
9319void StringDictionary::CopyEnumKeysTo(FixedArray* storage,
9320 FixedArray* sort_array) {
9321 ASSERT(storage->length() >= NumberOfEnumElements());
9322 int capacity = Capacity();
9323 int index = 0;
9324 for (int i = 0; i < capacity; i++) {
9325 Object* k = KeyAt(i);
9326 if (IsKey(k)) {
9327 PropertyDetails details = DetailsAt(i);
9328 if (details.IsDeleted() || details.IsDontEnum()) continue;
9329 storage->set(index, k);
Leon Clarke4515c472010-02-03 11:58:03 +00009330 sort_array->set(index, Smi::FromInt(details.index()));
Steve Blocka7e24c12009-10-30 11:49:00 +00009331 index++;
9332 }
9333 }
9334 storage->SortPairs(sort_array, sort_array->length());
9335 ASSERT(storage->length() >= index);
9336}
9337
9338
9339template<typename Shape, typename Key>
9340void Dictionary<Shape, Key>::CopyKeysTo(FixedArray* storage) {
9341 ASSERT(storage->length() >= NumberOfElementsFilterAttributes(
9342 static_cast<PropertyAttributes>(NONE)));
9343 int capacity = HashTable<Shape, Key>::Capacity();
9344 int index = 0;
9345 for (int i = 0; i < capacity; i++) {
9346 Object* k = HashTable<Shape, Key>::KeyAt(i);
9347 if (HashTable<Shape, Key>::IsKey(k)) {
9348 PropertyDetails details = DetailsAt(i);
9349 if (details.IsDeleted()) continue;
9350 storage->set(index++, k);
9351 }
9352 }
9353 ASSERT(storage->length() >= index);
9354}
9355
9356
9357// Backwards lookup (slow).
9358template<typename Shape, typename Key>
9359Object* Dictionary<Shape, Key>::SlowReverseLookup(Object* value) {
9360 int capacity = HashTable<Shape, Key>::Capacity();
9361 for (int i = 0; i < capacity; i++) {
9362 Object* k = HashTable<Shape, Key>::KeyAt(i);
9363 if (Dictionary<Shape, Key>::IsKey(k)) {
9364 Object* e = ValueAt(i);
9365 if (e->IsJSGlobalPropertyCell()) {
9366 e = JSGlobalPropertyCell::cast(e)->value();
9367 }
9368 if (e == value) return k;
9369 }
9370 }
9371 return Heap::undefined_value();
9372}
9373
9374
John Reck59135872010-11-02 12:39:01 -07009375MaybeObject* StringDictionary::TransformPropertiesToFastFor(
Steve Blocka7e24c12009-10-30 11:49:00 +00009376 JSObject* obj, int unused_property_fields) {
9377 // Make sure we preserve dictionary representation if there are too many
9378 // descriptors.
9379 if (NumberOfElements() > DescriptorArray::kMaxNumberOfDescriptors) return obj;
9380
9381 // Figure out if it is necessary to generate new enumeration indices.
9382 int max_enumeration_index =
9383 NextEnumerationIndex() +
9384 (DescriptorArray::kMaxNumberOfDescriptors -
9385 NumberOfElements());
9386 if (!PropertyDetails::IsValidIndex(max_enumeration_index)) {
John Reck59135872010-11-02 12:39:01 -07009387 Object* result;
9388 { MaybeObject* maybe_result = GenerateNewEnumerationIndices();
9389 if (!maybe_result->ToObject(&result)) return maybe_result;
9390 }
Steve Blocka7e24c12009-10-30 11:49:00 +00009391 }
9392
9393 int instance_descriptor_length = 0;
9394 int number_of_fields = 0;
9395
9396 // Compute the length of the instance descriptor.
9397 int capacity = Capacity();
9398 for (int i = 0; i < capacity; i++) {
9399 Object* k = KeyAt(i);
9400 if (IsKey(k)) {
9401 Object* value = ValueAt(i);
9402 PropertyType type = DetailsAt(i).type();
9403 ASSERT(type != FIELD);
9404 instance_descriptor_length++;
Leon Clarkee46be812010-01-19 14:06:41 +00009405 if (type == NORMAL &&
9406 (!value->IsJSFunction() || Heap::InNewSpace(value))) {
9407 number_of_fields += 1;
9408 }
Steve Blocka7e24c12009-10-30 11:49:00 +00009409 }
9410 }
9411
9412 // Allocate the instance descriptor.
John Reck59135872010-11-02 12:39:01 -07009413 Object* descriptors_unchecked;
9414 { MaybeObject* maybe_descriptors_unchecked =
9415 DescriptorArray::Allocate(instance_descriptor_length);
9416 if (!maybe_descriptors_unchecked->ToObject(&descriptors_unchecked)) {
9417 return maybe_descriptors_unchecked;
9418 }
9419 }
Steve Blocka7e24c12009-10-30 11:49:00 +00009420 DescriptorArray* descriptors = DescriptorArray::cast(descriptors_unchecked);
9421
9422 int inobject_props = obj->map()->inobject_properties();
9423 int number_of_allocated_fields =
9424 number_of_fields + unused_property_fields - inobject_props;
Ben Murdochf87a2032010-10-22 12:50:53 +01009425 if (number_of_allocated_fields < 0) {
9426 // There is enough inobject space for all fields (including unused).
9427 number_of_allocated_fields = 0;
9428 unused_property_fields = inobject_props - number_of_fields;
9429 }
Steve Blocka7e24c12009-10-30 11:49:00 +00009430
9431 // Allocate the fixed array for the fields.
John Reck59135872010-11-02 12:39:01 -07009432 Object* fields;
9433 { MaybeObject* maybe_fields =
9434 Heap::AllocateFixedArray(number_of_allocated_fields);
9435 if (!maybe_fields->ToObject(&fields)) return maybe_fields;
9436 }
Steve Blocka7e24c12009-10-30 11:49:00 +00009437
9438 // Fill in the instance descriptor and the fields.
9439 int next_descriptor = 0;
9440 int current_offset = 0;
9441 for (int i = 0; i < capacity; i++) {
9442 Object* k = KeyAt(i);
9443 if (IsKey(k)) {
9444 Object* value = ValueAt(i);
9445 // Ensure the key is a symbol before writing into the instance descriptor.
John Reck59135872010-11-02 12:39:01 -07009446 Object* key;
9447 { MaybeObject* maybe_key = Heap::LookupSymbol(String::cast(k));
9448 if (!maybe_key->ToObject(&key)) return maybe_key;
9449 }
Steve Blocka7e24c12009-10-30 11:49:00 +00009450 PropertyDetails details = DetailsAt(i);
9451 PropertyType type = details.type();
9452
Leon Clarkee46be812010-01-19 14:06:41 +00009453 if (value->IsJSFunction() && !Heap::InNewSpace(value)) {
Steve Blocka7e24c12009-10-30 11:49:00 +00009454 ConstantFunctionDescriptor d(String::cast(key),
9455 JSFunction::cast(value),
9456 details.attributes(),
9457 details.index());
9458 descriptors->Set(next_descriptor++, &d);
9459 } else if (type == NORMAL) {
9460 if (current_offset < inobject_props) {
9461 obj->InObjectPropertyAtPut(current_offset,
9462 value,
9463 UPDATE_WRITE_BARRIER);
9464 } else {
9465 int offset = current_offset - inobject_props;
9466 FixedArray::cast(fields)->set(offset, value);
9467 }
9468 FieldDescriptor d(String::cast(key),
9469 current_offset++,
9470 details.attributes(),
9471 details.index());
9472 descriptors->Set(next_descriptor++, &d);
9473 } else if (type == CALLBACKS) {
9474 CallbacksDescriptor d(String::cast(key),
9475 value,
9476 details.attributes(),
9477 details.index());
9478 descriptors->Set(next_descriptor++, &d);
9479 } else {
9480 UNREACHABLE();
9481 }
9482 }
9483 }
9484 ASSERT(current_offset == number_of_fields);
9485
9486 descriptors->Sort();
9487 // Allocate new map.
John Reck59135872010-11-02 12:39:01 -07009488 Object* new_map;
9489 { MaybeObject* maybe_new_map = obj->map()->CopyDropDescriptors();
9490 if (!maybe_new_map->ToObject(&new_map)) return maybe_new_map;
9491 }
Steve Blocka7e24c12009-10-30 11:49:00 +00009492
9493 // Transform the object.
9494 obj->set_map(Map::cast(new_map));
9495 obj->map()->set_instance_descriptors(descriptors);
9496 obj->map()->set_unused_property_fields(unused_property_fields);
9497
9498 obj->set_properties(FixedArray::cast(fields));
9499 ASSERT(obj->IsJSObject());
9500
9501 descriptors->SetNextEnumerationIndex(NextEnumerationIndex());
9502 // Check that it really works.
9503 ASSERT(obj->HasFastProperties());
9504
9505 return obj;
9506}
9507
9508
9509#ifdef ENABLE_DEBUGGER_SUPPORT
9510// Check if there is a break point at this code position.
9511bool DebugInfo::HasBreakPoint(int code_position) {
9512 // Get the break point info object for this code position.
9513 Object* break_point_info = GetBreakPointInfo(code_position);
9514
9515 // If there is no break point info object or no break points in the break
9516 // point info object there is no break point at this code position.
9517 if (break_point_info->IsUndefined()) return false;
9518 return BreakPointInfo::cast(break_point_info)->GetBreakPointCount() > 0;
9519}
9520
9521
9522// Get the break point info object for this code position.
9523Object* DebugInfo::GetBreakPointInfo(int code_position) {
9524 // Find the index of the break point info object for this code position.
9525 int index = GetBreakPointInfoIndex(code_position);
9526
9527 // Return the break point info object if any.
9528 if (index == kNoBreakPointInfo) return Heap::undefined_value();
9529 return BreakPointInfo::cast(break_points()->get(index));
9530}
9531
9532
9533// Clear a break point at the specified code position.
9534void DebugInfo::ClearBreakPoint(Handle<DebugInfo> debug_info,
9535 int code_position,
9536 Handle<Object> break_point_object) {
9537 Handle<Object> break_point_info(debug_info->GetBreakPointInfo(code_position));
9538 if (break_point_info->IsUndefined()) return;
9539 BreakPointInfo::ClearBreakPoint(
9540 Handle<BreakPointInfo>::cast(break_point_info),
9541 break_point_object);
9542}
9543
9544
9545void DebugInfo::SetBreakPoint(Handle<DebugInfo> debug_info,
9546 int code_position,
9547 int source_position,
9548 int statement_position,
9549 Handle<Object> break_point_object) {
9550 Handle<Object> break_point_info(debug_info->GetBreakPointInfo(code_position));
9551 if (!break_point_info->IsUndefined()) {
9552 BreakPointInfo::SetBreakPoint(
9553 Handle<BreakPointInfo>::cast(break_point_info),
9554 break_point_object);
9555 return;
9556 }
9557
9558 // Adding a new break point for a code position which did not have any
9559 // break points before. Try to find a free slot.
9560 int index = kNoBreakPointInfo;
9561 for (int i = 0; i < debug_info->break_points()->length(); i++) {
9562 if (debug_info->break_points()->get(i)->IsUndefined()) {
9563 index = i;
9564 break;
9565 }
9566 }
9567 if (index == kNoBreakPointInfo) {
9568 // No free slot - extend break point info array.
9569 Handle<FixedArray> old_break_points =
9570 Handle<FixedArray>(FixedArray::cast(debug_info->break_points()));
Steve Blocka7e24c12009-10-30 11:49:00 +00009571 Handle<FixedArray> new_break_points =
Kristian Monsen0d5e1162010-09-30 15:31:59 +01009572 Factory::NewFixedArray(old_break_points->length() +
9573 Debug::kEstimatedNofBreakPointsInFunction);
9574
9575 debug_info->set_break_points(*new_break_points);
Steve Blocka7e24c12009-10-30 11:49:00 +00009576 for (int i = 0; i < old_break_points->length(); i++) {
9577 new_break_points->set(i, old_break_points->get(i));
9578 }
9579 index = old_break_points->length();
9580 }
9581 ASSERT(index != kNoBreakPointInfo);
9582
9583 // Allocate new BreakPointInfo object and set the break point.
9584 Handle<BreakPointInfo> new_break_point_info =
9585 Handle<BreakPointInfo>::cast(Factory::NewStruct(BREAK_POINT_INFO_TYPE));
9586 new_break_point_info->set_code_position(Smi::FromInt(code_position));
9587 new_break_point_info->set_source_position(Smi::FromInt(source_position));
9588 new_break_point_info->
9589 set_statement_position(Smi::FromInt(statement_position));
9590 new_break_point_info->set_break_point_objects(Heap::undefined_value());
9591 BreakPointInfo::SetBreakPoint(new_break_point_info, break_point_object);
9592 debug_info->break_points()->set(index, *new_break_point_info);
9593}
9594
9595
9596// Get the break point objects for a code position.
9597Object* DebugInfo::GetBreakPointObjects(int code_position) {
9598 Object* break_point_info = GetBreakPointInfo(code_position);
9599 if (break_point_info->IsUndefined()) {
9600 return Heap::undefined_value();
9601 }
9602 return BreakPointInfo::cast(break_point_info)->break_point_objects();
9603}
9604
9605
9606// Get the total number of break points.
9607int DebugInfo::GetBreakPointCount() {
9608 if (break_points()->IsUndefined()) return 0;
9609 int count = 0;
9610 for (int i = 0; i < break_points()->length(); i++) {
9611 if (!break_points()->get(i)->IsUndefined()) {
9612 BreakPointInfo* break_point_info =
9613 BreakPointInfo::cast(break_points()->get(i));
9614 count += break_point_info->GetBreakPointCount();
9615 }
9616 }
9617 return count;
9618}
9619
9620
9621Object* DebugInfo::FindBreakPointInfo(Handle<DebugInfo> debug_info,
9622 Handle<Object> break_point_object) {
9623 if (debug_info->break_points()->IsUndefined()) return Heap::undefined_value();
9624 for (int i = 0; i < debug_info->break_points()->length(); i++) {
9625 if (!debug_info->break_points()->get(i)->IsUndefined()) {
9626 Handle<BreakPointInfo> break_point_info =
9627 Handle<BreakPointInfo>(BreakPointInfo::cast(
9628 debug_info->break_points()->get(i)));
9629 if (BreakPointInfo::HasBreakPointObject(break_point_info,
9630 break_point_object)) {
9631 return *break_point_info;
9632 }
9633 }
9634 }
9635 return Heap::undefined_value();
9636}
9637
9638
9639// Find the index of the break point info object for the specified code
9640// position.
9641int DebugInfo::GetBreakPointInfoIndex(int code_position) {
9642 if (break_points()->IsUndefined()) return kNoBreakPointInfo;
9643 for (int i = 0; i < break_points()->length(); i++) {
9644 if (!break_points()->get(i)->IsUndefined()) {
9645 BreakPointInfo* break_point_info =
9646 BreakPointInfo::cast(break_points()->get(i));
9647 if (break_point_info->code_position()->value() == code_position) {
9648 return i;
9649 }
9650 }
9651 }
9652 return kNoBreakPointInfo;
9653}
9654
9655
9656// Remove the specified break point object.
9657void BreakPointInfo::ClearBreakPoint(Handle<BreakPointInfo> break_point_info,
9658 Handle<Object> break_point_object) {
9659 // If there are no break points just ignore.
9660 if (break_point_info->break_point_objects()->IsUndefined()) return;
9661 // If there is a single break point clear it if it is the same.
9662 if (!break_point_info->break_point_objects()->IsFixedArray()) {
9663 if (break_point_info->break_point_objects() == *break_point_object) {
9664 break_point_info->set_break_point_objects(Heap::undefined_value());
9665 }
9666 return;
9667 }
9668 // If there are multiple break points shrink the array
9669 ASSERT(break_point_info->break_point_objects()->IsFixedArray());
9670 Handle<FixedArray> old_array =
9671 Handle<FixedArray>(
9672 FixedArray::cast(break_point_info->break_point_objects()));
9673 Handle<FixedArray> new_array =
9674 Factory::NewFixedArray(old_array->length() - 1);
9675 int found_count = 0;
9676 for (int i = 0; i < old_array->length(); i++) {
9677 if (old_array->get(i) == *break_point_object) {
9678 ASSERT(found_count == 0);
9679 found_count++;
9680 } else {
9681 new_array->set(i - found_count, old_array->get(i));
9682 }
9683 }
9684 // If the break point was found in the list change it.
9685 if (found_count > 0) break_point_info->set_break_point_objects(*new_array);
9686}
9687
9688
9689// Add the specified break point object.
9690void BreakPointInfo::SetBreakPoint(Handle<BreakPointInfo> break_point_info,
9691 Handle<Object> break_point_object) {
9692 // If there was no break point objects before just set it.
9693 if (break_point_info->break_point_objects()->IsUndefined()) {
9694 break_point_info->set_break_point_objects(*break_point_object);
9695 return;
9696 }
9697 // If the break point object is the same as before just ignore.
9698 if (break_point_info->break_point_objects() == *break_point_object) return;
9699 // If there was one break point object before replace with array.
9700 if (!break_point_info->break_point_objects()->IsFixedArray()) {
9701 Handle<FixedArray> array = Factory::NewFixedArray(2);
9702 array->set(0, break_point_info->break_point_objects());
9703 array->set(1, *break_point_object);
9704 break_point_info->set_break_point_objects(*array);
9705 return;
9706 }
9707 // If there was more than one break point before extend array.
9708 Handle<FixedArray> old_array =
9709 Handle<FixedArray>(
9710 FixedArray::cast(break_point_info->break_point_objects()));
9711 Handle<FixedArray> new_array =
9712 Factory::NewFixedArray(old_array->length() + 1);
9713 for (int i = 0; i < old_array->length(); i++) {
9714 // If the break point was there before just ignore.
9715 if (old_array->get(i) == *break_point_object) return;
9716 new_array->set(i, old_array->get(i));
9717 }
9718 // Add the new break point.
9719 new_array->set(old_array->length(), *break_point_object);
9720 break_point_info->set_break_point_objects(*new_array);
9721}
9722
9723
9724bool BreakPointInfo::HasBreakPointObject(
9725 Handle<BreakPointInfo> break_point_info,
9726 Handle<Object> break_point_object) {
9727 // No break point.
9728 if (break_point_info->break_point_objects()->IsUndefined()) return false;
9729 // Single beak point.
9730 if (!break_point_info->break_point_objects()->IsFixedArray()) {
9731 return break_point_info->break_point_objects() == *break_point_object;
9732 }
9733 // Multiple break points.
9734 FixedArray* array = FixedArray::cast(break_point_info->break_point_objects());
9735 for (int i = 0; i < array->length(); i++) {
9736 if (array->get(i) == *break_point_object) {
9737 return true;
9738 }
9739 }
9740 return false;
9741}
9742
9743
9744// Get the number of break points.
9745int BreakPointInfo::GetBreakPointCount() {
9746 // No break point.
9747 if (break_point_objects()->IsUndefined()) return 0;
9748 // Single beak point.
9749 if (!break_point_objects()->IsFixedArray()) return 1;
9750 // Multiple break points.
9751 return FixedArray::cast(break_point_objects())->length();
9752}
9753#endif
9754
9755
9756} } // namespace v8::internal