blob: 36a8e5c2aabc360e74cb58a40acd35fb6f4ed151 [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,
Ben Murdoch086aeea2011-05-13 15:57:08 +01001826 Object* value,
1827 bool check_prototype) {
1828 if (check_prototype && !result->IsProperty()) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001829 LookupCallbackSetterInPrototypes(name, result);
1830 }
1831
1832 if (result->IsProperty()) {
1833 if (!result->IsReadOnly()) {
1834 switch (result->type()) {
1835 case CALLBACKS: {
1836 Object* obj = result->GetCallbackObject();
1837 if (obj->IsAccessorInfo()) {
1838 AccessorInfo* info = AccessorInfo::cast(obj);
1839 if (info->all_can_write()) {
1840 return SetPropertyWithCallback(result->GetCallbackObject(),
1841 name,
1842 value,
1843 result->holder());
1844 }
1845 }
1846 break;
1847 }
1848 case INTERCEPTOR: {
1849 // Try lookup real named properties. Note that only property can be
1850 // set is callbacks marked as ALL_CAN_WRITE on the prototype chain.
1851 LookupResult r;
1852 LookupRealNamedProperty(name, &r);
1853 if (r.IsProperty()) {
Ben Murdoch086aeea2011-05-13 15:57:08 +01001854 return SetPropertyWithFailedAccessCheck(&r, name, value,
1855 check_prototype);
Steve Blocka7e24c12009-10-30 11:49:00 +00001856 }
1857 break;
1858 }
1859 default: {
1860 break;
1861 }
1862 }
1863 }
1864 }
1865
Iain Merrick75681382010-08-19 15:07:18 +01001866 HandleScope scope;
1867 Handle<Object> value_handle(value);
Steve Blocka7e24c12009-10-30 11:49:00 +00001868 Top::ReportFailedAccessCheck(this, v8::ACCESS_SET);
Iain Merrick75681382010-08-19 15:07:18 +01001869 return *value_handle;
Steve Blocka7e24c12009-10-30 11:49:00 +00001870}
1871
1872
John Reck59135872010-11-02 12:39:01 -07001873MaybeObject* JSObject::SetProperty(LookupResult* result,
1874 String* name,
1875 Object* value,
1876 PropertyAttributes attributes) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001877 // Make sure that the top context does not change when doing callbacks or
1878 // interceptor calls.
1879 AssertNoContextChange ncc;
1880
Steve Blockd0582a62009-12-15 09:54:21 +00001881 // Optimization for 2-byte strings often used as keys in a decompression
1882 // dictionary. We make these short keys into symbols to avoid constantly
1883 // reallocating them.
1884 if (!name->IsSymbol() && name->length() <= 2) {
John Reck59135872010-11-02 12:39:01 -07001885 Object* symbol_version;
1886 { MaybeObject* maybe_symbol_version = Heap::LookupSymbol(name);
1887 if (maybe_symbol_version->ToObject(&symbol_version)) {
1888 name = String::cast(symbol_version);
1889 }
1890 }
Steve Blockd0582a62009-12-15 09:54:21 +00001891 }
1892
Steve Blocka7e24c12009-10-30 11:49:00 +00001893 // Check access rights if needed.
1894 if (IsAccessCheckNeeded()
1895 && !Top::MayNamedAccess(this, name, v8::ACCESS_SET)) {
Ben Murdoch086aeea2011-05-13 15:57:08 +01001896 return SetPropertyWithFailedAccessCheck(result, name, value, true);
Steve Blocka7e24c12009-10-30 11:49:00 +00001897 }
1898
1899 if (IsJSGlobalProxy()) {
1900 Object* proto = GetPrototype();
1901 if (proto->IsNull()) return value;
1902 ASSERT(proto->IsJSGlobalObject());
1903 return JSObject::cast(proto)->SetProperty(result, name, value, attributes);
1904 }
1905
1906 if (!result->IsProperty() && !IsJSContextExtensionObject()) {
1907 // We could not find a local property so let's check whether there is an
1908 // accessor that wants to handle the property.
1909 LookupResult accessor_result;
1910 LookupCallbackSetterInPrototypes(name, &accessor_result);
Andrei Popescu402d9372010-02-26 13:31:12 +00001911 if (accessor_result.IsProperty()) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001912 return SetPropertyWithCallback(accessor_result.GetCallbackObject(),
1913 name,
1914 value,
1915 accessor_result.holder());
1916 }
1917 }
Andrei Popescu402d9372010-02-26 13:31:12 +00001918 if (!result->IsFound()) {
1919 // Neither properties nor transitions found.
Steve Blocka7e24c12009-10-30 11:49:00 +00001920 return AddProperty(name, value, attributes);
1921 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001922 if (result->IsReadOnly() && result->IsProperty()) return value;
1923 // This is a real property that is not read-only, or it is a
1924 // transition or null descriptor and there are no setters in the prototypes.
1925 switch (result->type()) {
1926 case NORMAL:
1927 return SetNormalizedProperty(result, value);
1928 case FIELD:
1929 return FastPropertyAtPut(result->GetFieldIndex(), value);
1930 case MAP_TRANSITION:
1931 if (attributes == result->GetAttributes()) {
1932 // Only use map transition if the attributes match.
1933 return AddFastPropertyUsingMap(result->GetTransitionMap(),
1934 name,
1935 value);
1936 }
1937 return ConvertDescriptorToField(name, value, attributes);
1938 case CONSTANT_FUNCTION:
1939 // Only replace the function if necessary.
1940 if (value == result->GetConstantFunction()) return value;
1941 // Preserve the attributes of this existing property.
1942 attributes = result->GetAttributes();
1943 return ConvertDescriptorToField(name, value, attributes);
1944 case CALLBACKS:
1945 return SetPropertyWithCallback(result->GetCallbackObject(),
1946 name,
1947 value,
1948 result->holder());
1949 case INTERCEPTOR:
1950 return SetPropertyWithInterceptor(name, value, attributes);
Iain Merrick75681382010-08-19 15:07:18 +01001951 case CONSTANT_TRANSITION: {
1952 // If the same constant function is being added we can simply
1953 // transition to the target map.
1954 Map* target_map = result->GetTransitionMap();
1955 DescriptorArray* target_descriptors = target_map->instance_descriptors();
1956 int number = target_descriptors->SearchWithCache(name);
1957 ASSERT(number != DescriptorArray::kNotFound);
1958 ASSERT(target_descriptors->GetType(number) == CONSTANT_FUNCTION);
1959 JSFunction* function =
1960 JSFunction::cast(target_descriptors->GetValue(number));
1961 ASSERT(!Heap::InNewSpace(function));
1962 if (value == function) {
1963 set_map(target_map);
1964 return value;
1965 }
1966 // Otherwise, replace with a MAP_TRANSITION to a new map with a
1967 // FIELD, even if the value is a constant function.
Steve Blocka7e24c12009-10-30 11:49:00 +00001968 return ConvertDescriptorToFieldAndMapTransition(name, value, attributes);
Iain Merrick75681382010-08-19 15:07:18 +01001969 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001970 case NULL_DESCRIPTOR:
1971 return ConvertDescriptorToFieldAndMapTransition(name, value, attributes);
1972 default:
1973 UNREACHABLE();
1974 }
1975 UNREACHABLE();
1976 return value;
1977}
1978
1979
1980// Set a real local property, even if it is READ_ONLY. If the property is not
1981// present, add it with attributes NONE. This code is an exact clone of
1982// SetProperty, with the check for IsReadOnly and the check for a
1983// callback setter removed. The two lines looking up the LookupResult
1984// result are also added. If one of the functions is changed, the other
1985// should be.
Ben Murdoch086aeea2011-05-13 15:57:08 +01001986MaybeObject* JSObject::SetLocalPropertyIgnoreAttributes(
Steve Blocka7e24c12009-10-30 11:49:00 +00001987 String* name,
1988 Object* value,
1989 PropertyAttributes attributes) {
1990 // Make sure that the top context does not change when doing callbacks or
1991 // interceptor calls.
1992 AssertNoContextChange ncc;
Andrei Popescu402d9372010-02-26 13:31:12 +00001993 LookupResult result;
1994 LocalLookup(name, &result);
Steve Blocka7e24c12009-10-30 11:49:00 +00001995 // Check access rights if needed.
1996 if (IsAccessCheckNeeded()
Andrei Popescu402d9372010-02-26 13:31:12 +00001997 && !Top::MayNamedAccess(this, name, v8::ACCESS_SET)) {
Ben Murdoch086aeea2011-05-13 15:57:08 +01001998 return SetPropertyWithFailedAccessCheck(&result, name, value, false);
Steve Blocka7e24c12009-10-30 11:49:00 +00001999 }
2000
2001 if (IsJSGlobalProxy()) {
2002 Object* proto = GetPrototype();
2003 if (proto->IsNull()) return value;
2004 ASSERT(proto->IsJSGlobalObject());
Ben Murdoch086aeea2011-05-13 15:57:08 +01002005 return JSObject::cast(proto)->SetLocalPropertyIgnoreAttributes(
Steve Blocka7e24c12009-10-30 11:49:00 +00002006 name,
2007 value,
2008 attributes);
2009 }
2010
2011 // Check for accessor in prototype chain removed here in clone.
Andrei Popescu402d9372010-02-26 13:31:12 +00002012 if (!result.IsFound()) {
2013 // Neither properties nor transitions found.
Steve Blocka7e24c12009-10-30 11:49:00 +00002014 return AddProperty(name, value, attributes);
2015 }
Steve Block6ded16b2010-05-10 14:33:55 +01002016
Andrei Popescu402d9372010-02-26 13:31:12 +00002017 PropertyDetails details = PropertyDetails(attributes, NORMAL);
2018
Steve Blocka7e24c12009-10-30 11:49:00 +00002019 // Check of IsReadOnly removed from here in clone.
Andrei Popescu402d9372010-02-26 13:31:12 +00002020 switch (result.type()) {
Steve Blocka7e24c12009-10-30 11:49:00 +00002021 case NORMAL:
Andrei Popescu402d9372010-02-26 13:31:12 +00002022 return SetNormalizedProperty(name, value, details);
Steve Blocka7e24c12009-10-30 11:49:00 +00002023 case FIELD:
Andrei Popescu402d9372010-02-26 13:31:12 +00002024 return FastPropertyAtPut(result.GetFieldIndex(), value);
Steve Blocka7e24c12009-10-30 11:49:00 +00002025 case MAP_TRANSITION:
Andrei Popescu402d9372010-02-26 13:31:12 +00002026 if (attributes == result.GetAttributes()) {
Steve Blocka7e24c12009-10-30 11:49:00 +00002027 // Only use map transition if the attributes match.
Andrei Popescu402d9372010-02-26 13:31:12 +00002028 return AddFastPropertyUsingMap(result.GetTransitionMap(),
Steve Blocka7e24c12009-10-30 11:49:00 +00002029 name,
2030 value);
2031 }
2032 return ConvertDescriptorToField(name, value, attributes);
2033 case CONSTANT_FUNCTION:
2034 // Only replace the function if necessary.
Andrei Popescu402d9372010-02-26 13:31:12 +00002035 if (value == result.GetConstantFunction()) return value;
Steve Blocka7e24c12009-10-30 11:49:00 +00002036 // Preserve the attributes of this existing property.
Andrei Popescu402d9372010-02-26 13:31:12 +00002037 attributes = result.GetAttributes();
Steve Blocka7e24c12009-10-30 11:49:00 +00002038 return ConvertDescriptorToField(name, value, attributes);
2039 case CALLBACKS:
2040 case INTERCEPTOR:
2041 // Override callback in clone
2042 return ConvertDescriptorToField(name, value, attributes);
2043 case CONSTANT_TRANSITION:
2044 // Replace with a MAP_TRANSITION to a new map with a FIELD, even
2045 // if the value is a function.
2046 return ConvertDescriptorToFieldAndMapTransition(name, value, attributes);
2047 case NULL_DESCRIPTOR:
2048 return ConvertDescriptorToFieldAndMapTransition(name, value, attributes);
2049 default:
2050 UNREACHABLE();
2051 }
2052 UNREACHABLE();
2053 return value;
2054}
2055
2056
2057PropertyAttributes JSObject::GetPropertyAttributePostInterceptor(
2058 JSObject* receiver,
2059 String* name,
2060 bool continue_search) {
2061 // Check local property, ignore interceptor.
2062 LookupResult result;
2063 LocalLookupRealNamedProperty(name, &result);
2064 if (result.IsProperty()) return result.GetAttributes();
2065
2066 if (continue_search) {
2067 // Continue searching via the prototype chain.
2068 Object* pt = GetPrototype();
2069 if (pt != Heap::null_value()) {
2070 return JSObject::cast(pt)->
2071 GetPropertyAttributeWithReceiver(receiver, name);
2072 }
2073 }
2074 return ABSENT;
2075}
2076
2077
2078PropertyAttributes JSObject::GetPropertyAttributeWithInterceptor(
2079 JSObject* receiver,
2080 String* name,
2081 bool continue_search) {
2082 // Make sure that the top context does not change when doing
2083 // callbacks or interceptor calls.
2084 AssertNoContextChange ncc;
2085
2086 HandleScope scope;
2087 Handle<InterceptorInfo> interceptor(GetNamedInterceptor());
2088 Handle<JSObject> receiver_handle(receiver);
2089 Handle<JSObject> holder_handle(this);
2090 Handle<String> name_handle(name);
2091 CustomArguments args(interceptor->data(), receiver, this);
2092 v8::AccessorInfo info(args.end());
2093 if (!interceptor->query()->IsUndefined()) {
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01002094 v8::NamedPropertyQuery query =
2095 v8::ToCData<v8::NamedPropertyQuery>(interceptor->query());
Steve Blocka7e24c12009-10-30 11:49:00 +00002096 LOG(ApiNamedPropertyAccess("interceptor-named-has", *holder_handle, name));
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01002097 v8::Handle<v8::Integer> result;
Steve Blocka7e24c12009-10-30 11:49:00 +00002098 {
2099 // Leaving JavaScript.
2100 VMState state(EXTERNAL);
2101 result = query(v8::Utils::ToLocal(name_handle), info);
2102 }
2103 if (!result.IsEmpty()) {
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01002104 ASSERT(result->IsInt32());
2105 return static_cast<PropertyAttributes>(result->Int32Value());
Steve Blocka7e24c12009-10-30 11:49:00 +00002106 }
2107 } else if (!interceptor->getter()->IsUndefined()) {
2108 v8::NamedPropertyGetter getter =
2109 v8::ToCData<v8::NamedPropertyGetter>(interceptor->getter());
2110 LOG(ApiNamedPropertyAccess("interceptor-named-get-has", this, name));
2111 v8::Handle<v8::Value> result;
2112 {
2113 // Leaving JavaScript.
2114 VMState state(EXTERNAL);
2115 result = getter(v8::Utils::ToLocal(name_handle), info);
2116 }
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01002117 if (!result.IsEmpty()) return DONT_ENUM;
Steve Blocka7e24c12009-10-30 11:49:00 +00002118 }
2119 return holder_handle->GetPropertyAttributePostInterceptor(*receiver_handle,
2120 *name_handle,
2121 continue_search);
2122}
2123
2124
2125PropertyAttributes JSObject::GetPropertyAttributeWithReceiver(
2126 JSObject* receiver,
2127 String* key) {
2128 uint32_t index = 0;
2129 if (key->AsArrayIndex(&index)) {
2130 if (HasElementWithReceiver(receiver, index)) return NONE;
2131 return ABSENT;
2132 }
2133 // Named property.
2134 LookupResult result;
2135 Lookup(key, &result);
2136 return GetPropertyAttribute(receiver, &result, key, true);
2137}
2138
2139
2140PropertyAttributes JSObject::GetPropertyAttribute(JSObject* receiver,
2141 LookupResult* result,
2142 String* name,
2143 bool continue_search) {
2144 // Check access rights if needed.
2145 if (IsAccessCheckNeeded() &&
2146 !Top::MayNamedAccess(this, name, v8::ACCESS_HAS)) {
2147 return GetPropertyAttributeWithFailedAccessCheck(receiver,
2148 result,
2149 name,
2150 continue_search);
2151 }
Andrei Popescu402d9372010-02-26 13:31:12 +00002152 if (result->IsProperty()) {
Steve Blocka7e24c12009-10-30 11:49:00 +00002153 switch (result->type()) {
2154 case NORMAL: // fall through
2155 case FIELD:
2156 case CONSTANT_FUNCTION:
2157 case CALLBACKS:
2158 return result->GetAttributes();
2159 case INTERCEPTOR:
2160 return result->holder()->
2161 GetPropertyAttributeWithInterceptor(receiver, name, continue_search);
Steve Blocka7e24c12009-10-30 11:49:00 +00002162 default:
2163 UNREACHABLE();
Steve Blocka7e24c12009-10-30 11:49:00 +00002164 }
2165 }
2166 return ABSENT;
2167}
2168
2169
2170PropertyAttributes JSObject::GetLocalPropertyAttribute(String* name) {
2171 // Check whether the name is an array index.
2172 uint32_t index = 0;
2173 if (name->AsArrayIndex(&index)) {
2174 if (HasLocalElement(index)) return NONE;
2175 return ABSENT;
2176 }
2177 // Named property.
2178 LookupResult result;
2179 LocalLookup(name, &result);
2180 return GetPropertyAttribute(this, &result, name, false);
2181}
2182
2183
John Reck59135872010-11-02 12:39:01 -07002184MaybeObject* NormalizedMapCache::Get(JSObject* obj,
2185 PropertyNormalizationMode mode) {
Kristian Monsen80d68ea2010-09-08 11:05:35 +01002186 Map* fast = obj->map();
Kristian Monsen0d5e1162010-09-30 15:31:59 +01002187 int index = Hash(fast) % kEntries;
2188 Object* result = get(index);
2189 if (result->IsMap() && CheckHit(Map::cast(result), fast, mode)) {
Kristian Monsen80d68ea2010-09-08 11:05:35 +01002190#ifdef DEBUG
Kristian Monsen0d5e1162010-09-30 15:31:59 +01002191 if (FLAG_enable_slow_asserts) {
2192 // The cached map should match newly created normalized map bit-by-bit.
John Reck59135872010-11-02 12:39:01 -07002193 Object* fresh;
2194 { MaybeObject* maybe_fresh =
2195 fast->CopyNormalized(mode, SHARED_NORMALIZED_MAP);
2196 if (maybe_fresh->ToObject(&fresh)) {
2197 ASSERT(memcmp(Map::cast(fresh)->address(),
2198 Map::cast(result)->address(),
2199 Map::kSize) == 0);
2200 }
Kristian Monsen80d68ea2010-09-08 11:05:35 +01002201 }
Kristian Monsen80d68ea2010-09-08 11:05:35 +01002202 }
Kristian Monsen0d5e1162010-09-30 15:31:59 +01002203#endif
2204 return result;
Kristian Monsen80d68ea2010-09-08 11:05:35 +01002205 }
Kristian Monsen0d5e1162010-09-30 15:31:59 +01002206
John Reck59135872010-11-02 12:39:01 -07002207 { MaybeObject* maybe_result =
2208 fast->CopyNormalized(mode, SHARED_NORMALIZED_MAP);
2209 if (!maybe_result->ToObject(&result)) return maybe_result;
2210 }
Kristian Monsen0d5e1162010-09-30 15:31:59 +01002211 set(index, result);
Kristian Monsen80d68ea2010-09-08 11:05:35 +01002212 Counters::normalized_maps.Increment();
2213
2214 return result;
2215}
2216
2217
Kristian Monsen80d68ea2010-09-08 11:05:35 +01002218void NormalizedMapCache::Clear() {
2219 int entries = length();
2220 for (int i = 0; i != entries; i++) {
2221 set_undefined(i);
2222 }
2223}
2224
2225
2226int NormalizedMapCache::Hash(Map* fast) {
2227 // For performance reasons we only hash the 3 most variable fields of a map:
2228 // constructor, prototype and bit_field2.
2229
2230 // Shift away the tag.
2231 int hash = (static_cast<uint32_t>(
2232 reinterpret_cast<uintptr_t>(fast->constructor())) >> 2);
2233
2234 // XOR-ing the prototype and constructor directly yields too many zero bits
2235 // when the two pointers are close (which is fairly common).
2236 // To avoid this we shift the prototype 4 bits relatively to the constructor.
2237 hash ^= (static_cast<uint32_t>(
2238 reinterpret_cast<uintptr_t>(fast->prototype())) << 2);
2239
2240 return hash ^ (hash >> 16) ^ fast->bit_field2();
2241}
2242
2243
2244bool NormalizedMapCache::CheckHit(Map* slow,
2245 Map* fast,
2246 PropertyNormalizationMode mode) {
2247#ifdef DEBUG
Kristian Monsen0d5e1162010-09-30 15:31:59 +01002248 slow->SharedMapVerify();
Kristian Monsen80d68ea2010-09-08 11:05:35 +01002249#endif
2250 return
2251 slow->constructor() == fast->constructor() &&
2252 slow->prototype() == fast->prototype() &&
2253 slow->inobject_properties() == ((mode == CLEAR_INOBJECT_PROPERTIES) ?
2254 0 :
2255 fast->inobject_properties()) &&
2256 slow->instance_type() == fast->instance_type() &&
2257 slow->bit_field() == fast->bit_field() &&
Kristian Monsen0d5e1162010-09-30 15:31:59 +01002258 (slow->bit_field2() & ~(1<<Map::kIsShared)) == fast->bit_field2();
Kristian Monsen80d68ea2010-09-08 11:05:35 +01002259}
2260
2261
John Reck59135872010-11-02 12:39:01 -07002262MaybeObject* JSObject::UpdateMapCodeCache(String* name, Code* code) {
Kristian Monsen0d5e1162010-09-30 15:31:59 +01002263 if (map()->is_shared()) {
2264 // Fast case maps are never marked as shared.
2265 ASSERT(!HasFastProperties());
2266 // Replace the map with an identical copy that can be safely modified.
John Reck59135872010-11-02 12:39:01 -07002267 Object* obj;
2268 { MaybeObject* maybe_obj = map()->CopyNormalized(KEEP_INOBJECT_PROPERTIES,
2269 UNIQUE_NORMALIZED_MAP);
2270 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
2271 }
Kristian Monsen80d68ea2010-09-08 11:05:35 +01002272 Counters::normalized_maps.Increment();
2273
2274 set_map(Map::cast(obj));
2275 }
2276 return map()->UpdateCodeCache(name, code);
2277}
2278
2279
John Reck59135872010-11-02 12:39:01 -07002280MaybeObject* JSObject::NormalizeProperties(PropertyNormalizationMode mode,
2281 int expected_additional_properties) {
Steve Blocka7e24c12009-10-30 11:49:00 +00002282 if (!HasFastProperties()) return this;
2283
2284 // The global object is always normalized.
2285 ASSERT(!IsGlobalObject());
2286
2287 // Allocate new content.
2288 int property_count = map()->NumberOfDescribedProperties();
2289 if (expected_additional_properties > 0) {
2290 property_count += expected_additional_properties;
2291 } else {
2292 property_count += 2; // Make space for two more properties.
2293 }
John Reck59135872010-11-02 12:39:01 -07002294 Object* obj;
2295 { MaybeObject* maybe_obj =
2296 StringDictionary::Allocate(property_count);
2297 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
2298 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002299 StringDictionary* dictionary = StringDictionary::cast(obj);
2300
2301 DescriptorArray* descs = map()->instance_descriptors();
2302 for (int i = 0; i < descs->number_of_descriptors(); i++) {
2303 PropertyDetails details = descs->GetDetails(i);
2304 switch (details.type()) {
2305 case CONSTANT_FUNCTION: {
2306 PropertyDetails d =
2307 PropertyDetails(details.attributes(), NORMAL, details.index());
2308 Object* value = descs->GetConstantFunction(i);
John Reck59135872010-11-02 12:39:01 -07002309 Object* result;
2310 { MaybeObject* maybe_result =
2311 dictionary->Add(descs->GetKey(i), value, d);
2312 if (!maybe_result->ToObject(&result)) return maybe_result;
2313 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002314 dictionary = StringDictionary::cast(result);
2315 break;
2316 }
2317 case FIELD: {
2318 PropertyDetails d =
2319 PropertyDetails(details.attributes(), NORMAL, details.index());
2320 Object* value = FastPropertyAt(descs->GetFieldIndex(i));
John Reck59135872010-11-02 12:39:01 -07002321 Object* result;
2322 { MaybeObject* maybe_result =
2323 dictionary->Add(descs->GetKey(i), value, d);
2324 if (!maybe_result->ToObject(&result)) return maybe_result;
2325 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002326 dictionary = StringDictionary::cast(result);
2327 break;
2328 }
2329 case CALLBACKS: {
2330 PropertyDetails d =
2331 PropertyDetails(details.attributes(), CALLBACKS, details.index());
2332 Object* value = descs->GetCallbacksObject(i);
John Reck59135872010-11-02 12:39:01 -07002333 Object* result;
2334 { MaybeObject* maybe_result =
2335 dictionary->Add(descs->GetKey(i), value, d);
2336 if (!maybe_result->ToObject(&result)) return maybe_result;
2337 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002338 dictionary = StringDictionary::cast(result);
2339 break;
2340 }
2341 case MAP_TRANSITION:
2342 case CONSTANT_TRANSITION:
2343 case NULL_DESCRIPTOR:
2344 case INTERCEPTOR:
2345 break;
2346 default:
2347 UNREACHABLE();
2348 }
2349 }
2350
2351 // Copy the next enumeration index from instance descriptor.
2352 int index = map()->instance_descriptors()->NextEnumerationIndex();
2353 dictionary->SetNextEnumerationIndex(index);
2354
John Reck59135872010-11-02 12:39:01 -07002355 { MaybeObject* maybe_obj = Top::context()->global_context()->
2356 normalized_map_cache()->Get(this, mode);
2357 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
2358 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002359 Map* new_map = Map::cast(obj);
2360
Steve Blocka7e24c12009-10-30 11:49:00 +00002361 // We have now successfully allocated all the necessary objects.
2362 // Changes can now be made with the guarantee that all of them take effect.
Kristian Monsen80d68ea2010-09-08 11:05:35 +01002363
2364 // Resize the object in the heap if necessary.
2365 int new_instance_size = new_map->instance_size();
2366 int instance_size_delta = map()->instance_size() - new_instance_size;
2367 ASSERT(instance_size_delta >= 0);
2368 Heap::CreateFillerObjectAt(this->address() + new_instance_size,
2369 instance_size_delta);
2370
Steve Blocka7e24c12009-10-30 11:49:00 +00002371 set_map(new_map);
Steve Blocka7e24c12009-10-30 11:49:00 +00002372
2373 set_properties(dictionary);
2374
2375 Counters::props_to_dictionary.Increment();
2376
2377#ifdef DEBUG
2378 if (FLAG_trace_normalization) {
2379 PrintF("Object properties have been normalized:\n");
2380 Print();
2381 }
2382#endif
2383 return this;
2384}
2385
2386
John Reck59135872010-11-02 12:39:01 -07002387MaybeObject* JSObject::TransformToFastProperties(int unused_property_fields) {
Steve Blocka7e24c12009-10-30 11:49:00 +00002388 if (HasFastProperties()) return this;
2389 ASSERT(!IsGlobalObject());
2390 return property_dictionary()->
2391 TransformPropertiesToFastFor(this, unused_property_fields);
2392}
2393
2394
John Reck59135872010-11-02 12:39:01 -07002395MaybeObject* JSObject::NormalizeElements() {
Steve Block3ce2e202009-11-05 08:53:23 +00002396 ASSERT(!HasPixelElements() && !HasExternalArrayElements());
Steve Blocka7e24c12009-10-30 11:49:00 +00002397 if (HasDictionaryElements()) return this;
Steve Block8defd9f2010-07-08 12:39:36 +01002398 ASSERT(map()->has_fast_elements());
2399
John Reck59135872010-11-02 12:39:01 -07002400 Object* obj;
2401 { MaybeObject* maybe_obj = map()->GetSlowElementsMap();
2402 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
2403 }
Steve Block8defd9f2010-07-08 12:39:36 +01002404 Map* new_map = Map::cast(obj);
Steve Blocka7e24c12009-10-30 11:49:00 +00002405
2406 // Get number of entries.
2407 FixedArray* array = FixedArray::cast(elements());
2408
2409 // Compute the effective length.
2410 int length = IsJSArray() ?
2411 Smi::cast(JSArray::cast(this)->length())->value() :
2412 array->length();
John Reck59135872010-11-02 12:39:01 -07002413 { MaybeObject* maybe_obj = NumberDictionary::Allocate(length);
2414 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
2415 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002416 NumberDictionary* dictionary = NumberDictionary::cast(obj);
2417 // Copy entries.
2418 for (int i = 0; i < length; i++) {
2419 Object* value = array->get(i);
2420 if (!value->IsTheHole()) {
2421 PropertyDetails details = PropertyDetails(NONE, NORMAL);
John Reck59135872010-11-02 12:39:01 -07002422 Object* result;
2423 { MaybeObject* maybe_result =
2424 dictionary->AddNumberEntry(i, array->get(i), details);
2425 if (!maybe_result->ToObject(&result)) return maybe_result;
2426 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002427 dictionary = NumberDictionary::cast(result);
2428 }
2429 }
Steve Block8defd9f2010-07-08 12:39:36 +01002430 // Switch to using the dictionary as the backing storage for
2431 // elements. Set the new map first to satify the elements type
2432 // assert in set_elements().
2433 set_map(new_map);
Steve Blocka7e24c12009-10-30 11:49:00 +00002434 set_elements(dictionary);
2435
2436 Counters::elements_to_dictionary.Increment();
2437
2438#ifdef DEBUG
2439 if (FLAG_trace_normalization) {
2440 PrintF("Object elements have been normalized:\n");
2441 Print();
2442 }
2443#endif
2444
2445 return this;
2446}
2447
2448
John Reck59135872010-11-02 12:39:01 -07002449MaybeObject* JSObject::DeletePropertyPostInterceptor(String* name,
2450 DeleteMode mode) {
Steve Blocka7e24c12009-10-30 11:49:00 +00002451 // Check local property, ignore interceptor.
2452 LookupResult result;
2453 LocalLookupRealNamedProperty(name, &result);
Andrei Popescu402d9372010-02-26 13:31:12 +00002454 if (!result.IsProperty()) return Heap::true_value();
Steve Blocka7e24c12009-10-30 11:49:00 +00002455
2456 // Normalize object if needed.
John Reck59135872010-11-02 12:39:01 -07002457 Object* obj;
2458 { MaybeObject* maybe_obj = NormalizeProperties(CLEAR_INOBJECT_PROPERTIES, 0);
2459 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
2460 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002461
2462 return DeleteNormalizedProperty(name, mode);
2463}
2464
2465
John Reck59135872010-11-02 12:39:01 -07002466MaybeObject* JSObject::DeletePropertyWithInterceptor(String* name) {
Steve Blocka7e24c12009-10-30 11:49:00 +00002467 HandleScope scope;
2468 Handle<InterceptorInfo> interceptor(GetNamedInterceptor());
2469 Handle<String> name_handle(name);
2470 Handle<JSObject> this_handle(this);
2471 if (!interceptor->deleter()->IsUndefined()) {
2472 v8::NamedPropertyDeleter deleter =
2473 v8::ToCData<v8::NamedPropertyDeleter>(interceptor->deleter());
2474 LOG(ApiNamedPropertyAccess("interceptor-named-delete", *this_handle, name));
2475 CustomArguments args(interceptor->data(), this, this);
2476 v8::AccessorInfo info(args.end());
2477 v8::Handle<v8::Boolean> result;
2478 {
2479 // Leaving JavaScript.
2480 VMState state(EXTERNAL);
2481 result = deleter(v8::Utils::ToLocal(name_handle), info);
2482 }
2483 RETURN_IF_SCHEDULED_EXCEPTION();
2484 if (!result.IsEmpty()) {
2485 ASSERT(result->IsBoolean());
2486 return *v8::Utils::OpenHandle(*result);
2487 }
2488 }
John Reck59135872010-11-02 12:39:01 -07002489 MaybeObject* raw_result =
Steve Blocka7e24c12009-10-30 11:49:00 +00002490 this_handle->DeletePropertyPostInterceptor(*name_handle, NORMAL_DELETION);
2491 RETURN_IF_SCHEDULED_EXCEPTION();
2492 return raw_result;
2493}
2494
2495
John Reck59135872010-11-02 12:39:01 -07002496MaybeObject* JSObject::DeleteElementPostInterceptor(uint32_t index,
2497 DeleteMode mode) {
Steve Block3ce2e202009-11-05 08:53:23 +00002498 ASSERT(!HasPixelElements() && !HasExternalArrayElements());
Steve Blocka7e24c12009-10-30 11:49:00 +00002499 switch (GetElementsKind()) {
2500 case FAST_ELEMENTS: {
John Reck59135872010-11-02 12:39:01 -07002501 Object* obj;
2502 { MaybeObject* maybe_obj = EnsureWritableFastElements();
2503 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
2504 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002505 uint32_t length = IsJSArray() ?
2506 static_cast<uint32_t>(Smi::cast(JSArray::cast(this)->length())->value()) :
2507 static_cast<uint32_t>(FixedArray::cast(elements())->length());
2508 if (index < length) {
2509 FixedArray::cast(elements())->set_the_hole(index);
2510 }
2511 break;
2512 }
2513 case DICTIONARY_ELEMENTS: {
2514 NumberDictionary* dictionary = element_dictionary();
2515 int entry = dictionary->FindEntry(index);
2516 if (entry != NumberDictionary::kNotFound) {
2517 return dictionary->DeleteProperty(entry, mode);
2518 }
2519 break;
2520 }
2521 default:
2522 UNREACHABLE();
2523 break;
2524 }
2525 return Heap::true_value();
2526}
2527
2528
John Reck59135872010-11-02 12:39:01 -07002529MaybeObject* JSObject::DeleteElementWithInterceptor(uint32_t index) {
Steve Blocka7e24c12009-10-30 11:49:00 +00002530 // Make sure that the top context does not change when doing
2531 // callbacks or interceptor calls.
2532 AssertNoContextChange ncc;
2533 HandleScope scope;
2534 Handle<InterceptorInfo> interceptor(GetIndexedInterceptor());
2535 if (interceptor->deleter()->IsUndefined()) return Heap::false_value();
2536 v8::IndexedPropertyDeleter deleter =
2537 v8::ToCData<v8::IndexedPropertyDeleter>(interceptor->deleter());
2538 Handle<JSObject> this_handle(this);
2539 LOG(ApiIndexedPropertyAccess("interceptor-indexed-delete", this, index));
2540 CustomArguments args(interceptor->data(), this, this);
2541 v8::AccessorInfo info(args.end());
2542 v8::Handle<v8::Boolean> result;
2543 {
2544 // Leaving JavaScript.
2545 VMState state(EXTERNAL);
2546 result = deleter(index, info);
2547 }
2548 RETURN_IF_SCHEDULED_EXCEPTION();
2549 if (!result.IsEmpty()) {
2550 ASSERT(result->IsBoolean());
2551 return *v8::Utils::OpenHandle(*result);
2552 }
John Reck59135872010-11-02 12:39:01 -07002553 MaybeObject* raw_result =
Steve Blocka7e24c12009-10-30 11:49:00 +00002554 this_handle->DeleteElementPostInterceptor(index, NORMAL_DELETION);
2555 RETURN_IF_SCHEDULED_EXCEPTION();
2556 return raw_result;
2557}
2558
2559
John Reck59135872010-11-02 12:39:01 -07002560MaybeObject* JSObject::DeleteElement(uint32_t index, DeleteMode mode) {
Steve Blocka7e24c12009-10-30 11:49:00 +00002561 // Check access rights if needed.
2562 if (IsAccessCheckNeeded() &&
2563 !Top::MayIndexedAccess(this, index, v8::ACCESS_DELETE)) {
2564 Top::ReportFailedAccessCheck(this, v8::ACCESS_DELETE);
2565 return Heap::false_value();
2566 }
2567
2568 if (IsJSGlobalProxy()) {
2569 Object* proto = GetPrototype();
2570 if (proto->IsNull()) return Heap::false_value();
2571 ASSERT(proto->IsJSGlobalObject());
2572 return JSGlobalObject::cast(proto)->DeleteElement(index, mode);
2573 }
2574
2575 if (HasIndexedInterceptor()) {
2576 // Skip interceptor if forcing deletion.
2577 if (mode == FORCE_DELETION) {
2578 return DeleteElementPostInterceptor(index, mode);
2579 }
2580 return DeleteElementWithInterceptor(index);
2581 }
2582
2583 switch (GetElementsKind()) {
2584 case FAST_ELEMENTS: {
John Reck59135872010-11-02 12:39:01 -07002585 Object* obj;
2586 { MaybeObject* maybe_obj = EnsureWritableFastElements();
2587 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
2588 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002589 uint32_t length = IsJSArray() ?
2590 static_cast<uint32_t>(Smi::cast(JSArray::cast(this)->length())->value()) :
2591 static_cast<uint32_t>(FixedArray::cast(elements())->length());
2592 if (index < length) {
2593 FixedArray::cast(elements())->set_the_hole(index);
2594 }
2595 break;
2596 }
Steve Block3ce2e202009-11-05 08:53:23 +00002597 case PIXEL_ELEMENTS:
2598 case EXTERNAL_BYTE_ELEMENTS:
2599 case EXTERNAL_UNSIGNED_BYTE_ELEMENTS:
2600 case EXTERNAL_SHORT_ELEMENTS:
2601 case EXTERNAL_UNSIGNED_SHORT_ELEMENTS:
2602 case EXTERNAL_INT_ELEMENTS:
2603 case EXTERNAL_UNSIGNED_INT_ELEMENTS:
2604 case EXTERNAL_FLOAT_ELEMENTS:
2605 // Pixel and external array elements cannot be deleted. Just
2606 // silently ignore here.
Steve Blocka7e24c12009-10-30 11:49:00 +00002607 break;
Steve Blocka7e24c12009-10-30 11:49:00 +00002608 case DICTIONARY_ELEMENTS: {
2609 NumberDictionary* dictionary = element_dictionary();
2610 int entry = dictionary->FindEntry(index);
2611 if (entry != NumberDictionary::kNotFound) {
2612 return dictionary->DeleteProperty(entry, mode);
2613 }
2614 break;
2615 }
2616 default:
2617 UNREACHABLE();
2618 break;
2619 }
2620 return Heap::true_value();
2621}
2622
2623
John Reck59135872010-11-02 12:39:01 -07002624MaybeObject* JSObject::DeleteProperty(String* name, DeleteMode mode) {
Steve Blocka7e24c12009-10-30 11:49:00 +00002625 // ECMA-262, 3rd, 8.6.2.5
2626 ASSERT(name->IsString());
2627
2628 // Check access rights if needed.
2629 if (IsAccessCheckNeeded() &&
2630 !Top::MayNamedAccess(this, name, v8::ACCESS_DELETE)) {
2631 Top::ReportFailedAccessCheck(this, v8::ACCESS_DELETE);
2632 return Heap::false_value();
2633 }
2634
2635 if (IsJSGlobalProxy()) {
2636 Object* proto = GetPrototype();
2637 if (proto->IsNull()) return Heap::false_value();
2638 ASSERT(proto->IsJSGlobalObject());
2639 return JSGlobalObject::cast(proto)->DeleteProperty(name, mode);
2640 }
2641
2642 uint32_t index = 0;
2643 if (name->AsArrayIndex(&index)) {
2644 return DeleteElement(index, mode);
2645 } else {
2646 LookupResult result;
2647 LocalLookup(name, &result);
Andrei Popescu402d9372010-02-26 13:31:12 +00002648 if (!result.IsProperty()) return Heap::true_value();
Steve Blocka7e24c12009-10-30 11:49:00 +00002649 // Ignore attributes if forcing a deletion.
2650 if (result.IsDontDelete() && mode != FORCE_DELETION) {
2651 return Heap::false_value();
2652 }
2653 // Check for interceptor.
2654 if (result.type() == INTERCEPTOR) {
2655 // Skip interceptor if forcing a deletion.
2656 if (mode == FORCE_DELETION) {
2657 return DeletePropertyPostInterceptor(name, mode);
2658 }
2659 return DeletePropertyWithInterceptor(name);
2660 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002661 // Normalize object if needed.
John Reck59135872010-11-02 12:39:01 -07002662 Object* obj;
2663 { MaybeObject* maybe_obj =
2664 NormalizeProperties(CLEAR_INOBJECT_PROPERTIES, 0);
2665 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
2666 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002667 // Make sure the properties are normalized before removing the entry.
2668 return DeleteNormalizedProperty(name, mode);
2669 }
2670}
2671
2672
2673// Check whether this object references another object.
2674bool JSObject::ReferencesObject(Object* obj) {
2675 AssertNoAllocation no_alloc;
2676
2677 // Is the object the constructor for this object?
2678 if (map()->constructor() == obj) {
2679 return true;
2680 }
2681
2682 // Is the object the prototype for this object?
2683 if (map()->prototype() == obj) {
2684 return true;
2685 }
2686
2687 // Check if the object is among the named properties.
2688 Object* key = SlowReverseLookup(obj);
2689 if (key != Heap::undefined_value()) {
2690 return true;
2691 }
2692
2693 // Check if the object is among the indexed properties.
2694 switch (GetElementsKind()) {
2695 case PIXEL_ELEMENTS:
Steve Block3ce2e202009-11-05 08:53:23 +00002696 case EXTERNAL_BYTE_ELEMENTS:
2697 case EXTERNAL_UNSIGNED_BYTE_ELEMENTS:
2698 case EXTERNAL_SHORT_ELEMENTS:
2699 case EXTERNAL_UNSIGNED_SHORT_ELEMENTS:
2700 case EXTERNAL_INT_ELEMENTS:
2701 case EXTERNAL_UNSIGNED_INT_ELEMENTS:
2702 case EXTERNAL_FLOAT_ELEMENTS:
2703 // Raw pixels and external arrays do not reference other
2704 // objects.
Steve Blocka7e24c12009-10-30 11:49:00 +00002705 break;
2706 case FAST_ELEMENTS: {
2707 int length = IsJSArray() ?
2708 Smi::cast(JSArray::cast(this)->length())->value() :
2709 FixedArray::cast(elements())->length();
2710 for (int i = 0; i < length; i++) {
2711 Object* element = FixedArray::cast(elements())->get(i);
2712 if (!element->IsTheHole() && element == obj) {
2713 return true;
2714 }
2715 }
2716 break;
2717 }
2718 case DICTIONARY_ELEMENTS: {
2719 key = element_dictionary()->SlowReverseLookup(obj);
2720 if (key != Heap::undefined_value()) {
2721 return true;
2722 }
2723 break;
2724 }
2725 default:
2726 UNREACHABLE();
2727 break;
2728 }
2729
Steve Block6ded16b2010-05-10 14:33:55 +01002730 // For functions check the context.
2731 if (IsJSFunction()) {
Steve Blocka7e24c12009-10-30 11:49:00 +00002732 // Get the constructor function for arguments array.
2733 JSObject* arguments_boilerplate =
2734 Top::context()->global_context()->arguments_boilerplate();
2735 JSFunction* arguments_function =
2736 JSFunction::cast(arguments_boilerplate->map()->constructor());
2737
2738 // Get the context and don't check if it is the global context.
2739 JSFunction* f = JSFunction::cast(this);
2740 Context* context = f->context();
2741 if (context->IsGlobalContext()) {
2742 return false;
2743 }
2744
2745 // Check the non-special context slots.
2746 for (int i = Context::MIN_CONTEXT_SLOTS; i < context->length(); i++) {
2747 // Only check JS objects.
2748 if (context->get(i)->IsJSObject()) {
2749 JSObject* ctxobj = JSObject::cast(context->get(i));
2750 // If it is an arguments array check the content.
2751 if (ctxobj->map()->constructor() == arguments_function) {
2752 if (ctxobj->ReferencesObject(obj)) {
2753 return true;
2754 }
2755 } else if (ctxobj == obj) {
2756 return true;
2757 }
2758 }
2759 }
2760
2761 // Check the context extension if any.
2762 if (context->has_extension()) {
2763 return context->extension()->ReferencesObject(obj);
2764 }
2765 }
2766
2767 // No references to object.
2768 return false;
2769}
2770
2771
John Reck59135872010-11-02 12:39:01 -07002772MaybeObject* JSObject::PreventExtensions() {
Steve Block8defd9f2010-07-08 12:39:36 +01002773 // If there are fast elements we normalize.
2774 if (HasFastElements()) {
John Reck59135872010-11-02 12:39:01 -07002775 Object* ok;
2776 { MaybeObject* maybe_ok = NormalizeElements();
2777 if (!maybe_ok->ToObject(&ok)) return maybe_ok;
2778 }
Steve Block8defd9f2010-07-08 12:39:36 +01002779 }
2780 // Make sure that we never go back to fast case.
2781 element_dictionary()->set_requires_slow_elements();
2782
2783 // Do a map transition, other objects with this map may still
2784 // be extensible.
John Reck59135872010-11-02 12:39:01 -07002785 Object* new_map;
2786 { MaybeObject* maybe_new_map = map()->CopyDropTransitions();
2787 if (!maybe_new_map->ToObject(&new_map)) return maybe_new_map;
2788 }
Steve Block8defd9f2010-07-08 12:39:36 +01002789 Map::cast(new_map)->set_is_extensible(false);
2790 set_map(Map::cast(new_map));
2791 ASSERT(!map()->is_extensible());
2792 return new_map;
2793}
2794
2795
Steve Blocka7e24c12009-10-30 11:49:00 +00002796// Tests for the fast common case for property enumeration:
Steve Blockd0582a62009-12-15 09:54:21 +00002797// - This object and all prototypes has an enum cache (which means that it has
2798// no interceptors and needs no access checks).
2799// - This object has no elements.
2800// - No prototype has enumerable properties/elements.
Steve Blocka7e24c12009-10-30 11:49:00 +00002801bool JSObject::IsSimpleEnum() {
Steve Blocka7e24c12009-10-30 11:49:00 +00002802 for (Object* o = this;
2803 o != Heap::null_value();
2804 o = JSObject::cast(o)->GetPrototype()) {
2805 JSObject* curr = JSObject::cast(o);
Steve Blocka7e24c12009-10-30 11:49:00 +00002806 if (!curr->map()->instance_descriptors()->HasEnumCache()) return false;
Steve Blockd0582a62009-12-15 09:54:21 +00002807 ASSERT(!curr->HasNamedInterceptor());
2808 ASSERT(!curr->HasIndexedInterceptor());
2809 ASSERT(!curr->IsAccessCheckNeeded());
Steve Blocka7e24c12009-10-30 11:49:00 +00002810 if (curr->NumberOfEnumElements() > 0) return false;
Steve Blocka7e24c12009-10-30 11:49:00 +00002811 if (curr != this) {
2812 FixedArray* curr_fixed_array =
2813 FixedArray::cast(curr->map()->instance_descriptors()->GetEnumCache());
Steve Blockd0582a62009-12-15 09:54:21 +00002814 if (curr_fixed_array->length() > 0) return false;
Steve Blocka7e24c12009-10-30 11:49:00 +00002815 }
2816 }
2817 return true;
2818}
2819
2820
2821int Map::NumberOfDescribedProperties() {
2822 int result = 0;
2823 DescriptorArray* descs = instance_descriptors();
2824 for (int i = 0; i < descs->number_of_descriptors(); i++) {
2825 if (descs->IsProperty(i)) result++;
2826 }
2827 return result;
2828}
2829
2830
2831int Map::PropertyIndexFor(String* name) {
2832 DescriptorArray* descs = instance_descriptors();
2833 for (int i = 0; i < descs->number_of_descriptors(); i++) {
2834 if (name->Equals(descs->GetKey(i)) && !descs->IsNullDescriptor(i)) {
2835 return descs->GetFieldIndex(i);
2836 }
2837 }
2838 return -1;
2839}
2840
2841
2842int Map::NextFreePropertyIndex() {
2843 int max_index = -1;
2844 DescriptorArray* descs = instance_descriptors();
2845 for (int i = 0; i < descs->number_of_descriptors(); i++) {
2846 if (descs->GetType(i) == FIELD) {
2847 int current_index = descs->GetFieldIndex(i);
2848 if (current_index > max_index) max_index = current_index;
2849 }
2850 }
2851 return max_index + 1;
2852}
2853
2854
2855AccessorDescriptor* Map::FindAccessor(String* name) {
2856 DescriptorArray* descs = instance_descriptors();
2857 for (int i = 0; i < descs->number_of_descriptors(); i++) {
2858 if (name->Equals(descs->GetKey(i)) && descs->GetType(i) == CALLBACKS) {
2859 return descs->GetCallbacks(i);
2860 }
2861 }
2862 return NULL;
2863}
2864
2865
2866void JSObject::LocalLookup(String* name, LookupResult* result) {
2867 ASSERT(name->IsString());
2868
2869 if (IsJSGlobalProxy()) {
2870 Object* proto = GetPrototype();
2871 if (proto->IsNull()) return result->NotFound();
2872 ASSERT(proto->IsJSGlobalObject());
2873 return JSObject::cast(proto)->LocalLookup(name, result);
2874 }
2875
2876 // Do not use inline caching if the object is a non-global object
2877 // that requires access checks.
2878 if (!IsJSGlobalProxy() && IsAccessCheckNeeded()) {
2879 result->DisallowCaching();
2880 }
2881
2882 // Check __proto__ before interceptor.
2883 if (name->Equals(Heap::Proto_symbol()) && !IsJSContextExtensionObject()) {
2884 result->ConstantResult(this);
2885 return;
2886 }
2887
2888 // Check for lookup interceptor except when bootstrapping.
2889 if (HasNamedInterceptor() && !Bootstrapper::IsActive()) {
2890 result->InterceptorResult(this);
2891 return;
2892 }
2893
2894 LocalLookupRealNamedProperty(name, result);
2895}
2896
2897
2898void JSObject::Lookup(String* name, LookupResult* result) {
2899 // Ecma-262 3rd 8.6.2.4
2900 for (Object* current = this;
2901 current != Heap::null_value();
2902 current = JSObject::cast(current)->GetPrototype()) {
2903 JSObject::cast(current)->LocalLookup(name, result);
Andrei Popescu402d9372010-02-26 13:31:12 +00002904 if (result->IsProperty()) return;
Steve Blocka7e24c12009-10-30 11:49:00 +00002905 }
2906 result->NotFound();
2907}
2908
2909
2910// Search object and it's prototype chain for callback properties.
2911void JSObject::LookupCallback(String* name, LookupResult* result) {
2912 for (Object* current = this;
2913 current != Heap::null_value();
2914 current = JSObject::cast(current)->GetPrototype()) {
2915 JSObject::cast(current)->LocalLookupRealNamedProperty(name, result);
Andrei Popescu402d9372010-02-26 13:31:12 +00002916 if (result->IsProperty() && result->type() == CALLBACKS) return;
Steve Blocka7e24c12009-10-30 11:49:00 +00002917 }
2918 result->NotFound();
2919}
2920
2921
John Reck59135872010-11-02 12:39:01 -07002922MaybeObject* JSObject::DefineGetterSetter(String* name,
2923 PropertyAttributes attributes) {
Steve Blocka7e24c12009-10-30 11:49:00 +00002924 // Make sure that the top context does not change when doing callbacks or
2925 // interceptor calls.
2926 AssertNoContextChange ncc;
2927
Steve Blocka7e24c12009-10-30 11:49:00 +00002928 // Try to flatten before operating on the string.
Steve Block6ded16b2010-05-10 14:33:55 +01002929 name->TryFlatten();
Steve Blocka7e24c12009-10-30 11:49:00 +00002930
Leon Clarkef7060e22010-06-03 12:02:55 +01002931 if (!CanSetCallback(name)) {
2932 return Heap::undefined_value();
Steve Blocka7e24c12009-10-30 11:49:00 +00002933 }
2934
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01002935 uint32_t index = 0;
Steve Blocka7e24c12009-10-30 11:49:00 +00002936 bool is_element = name->AsArrayIndex(&index);
Steve Blocka7e24c12009-10-30 11:49:00 +00002937
2938 if (is_element) {
2939 switch (GetElementsKind()) {
2940 case FAST_ELEMENTS:
2941 break;
2942 case PIXEL_ELEMENTS:
Steve Block3ce2e202009-11-05 08:53:23 +00002943 case EXTERNAL_BYTE_ELEMENTS:
2944 case EXTERNAL_UNSIGNED_BYTE_ELEMENTS:
2945 case EXTERNAL_SHORT_ELEMENTS:
2946 case EXTERNAL_UNSIGNED_SHORT_ELEMENTS:
2947 case EXTERNAL_INT_ELEMENTS:
2948 case EXTERNAL_UNSIGNED_INT_ELEMENTS:
2949 case EXTERNAL_FLOAT_ELEMENTS:
2950 // Ignore getters and setters on pixel and external array
2951 // elements.
Steve Blocka7e24c12009-10-30 11:49:00 +00002952 return Heap::undefined_value();
2953 case DICTIONARY_ELEMENTS: {
2954 // Lookup the index.
2955 NumberDictionary* dictionary = element_dictionary();
2956 int entry = dictionary->FindEntry(index);
2957 if (entry != NumberDictionary::kNotFound) {
2958 Object* result = dictionary->ValueAt(entry);
2959 PropertyDetails details = dictionary->DetailsAt(entry);
2960 if (details.IsReadOnly()) return Heap::undefined_value();
2961 if (details.type() == CALLBACKS) {
Leon Clarkef7060e22010-06-03 12:02:55 +01002962 if (result->IsFixedArray()) {
2963 return result;
2964 }
2965 // Otherwise allow to override it.
Steve Blocka7e24c12009-10-30 11:49:00 +00002966 }
2967 }
2968 break;
2969 }
2970 default:
2971 UNREACHABLE();
2972 break;
2973 }
2974 } else {
2975 // Lookup the name.
2976 LookupResult result;
2977 LocalLookup(name, &result);
Andrei Popescu402d9372010-02-26 13:31:12 +00002978 if (result.IsProperty()) {
Steve Blocka7e24c12009-10-30 11:49:00 +00002979 if (result.IsReadOnly()) return Heap::undefined_value();
2980 if (result.type() == CALLBACKS) {
2981 Object* obj = result.GetCallbackObject();
Leon Clarkef7060e22010-06-03 12:02:55 +01002982 // Need to preserve old getters/setters.
Leon Clarked91b9f72010-01-27 17:25:45 +00002983 if (obj->IsFixedArray()) {
Leon Clarkef7060e22010-06-03 12:02:55 +01002984 // Use set to update attributes.
2985 return SetPropertyCallback(name, obj, attributes);
Leon Clarked91b9f72010-01-27 17:25:45 +00002986 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002987 }
2988 }
2989 }
2990
2991 // Allocate the fixed array to hold getter and setter.
John Reck59135872010-11-02 12:39:01 -07002992 Object* structure;
2993 { MaybeObject* maybe_structure = Heap::AllocateFixedArray(2, TENURED);
2994 if (!maybe_structure->ToObject(&structure)) return maybe_structure;
2995 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002996
2997 if (is_element) {
Leon Clarkef7060e22010-06-03 12:02:55 +01002998 return SetElementCallback(index, structure, attributes);
Steve Blocka7e24c12009-10-30 11:49:00 +00002999 } else {
Leon Clarkef7060e22010-06-03 12:02:55 +01003000 return SetPropertyCallback(name, structure, attributes);
Steve Blocka7e24c12009-10-30 11:49:00 +00003001 }
Leon Clarkef7060e22010-06-03 12:02:55 +01003002}
3003
3004
3005bool JSObject::CanSetCallback(String* name) {
3006 ASSERT(!IsAccessCheckNeeded()
3007 || Top::MayNamedAccess(this, name, v8::ACCESS_SET));
3008
3009 // Check if there is an API defined callback object which prohibits
3010 // callback overwriting in this object or it's prototype chain.
3011 // This mechanism is needed for instance in a browser setting, where
3012 // certain accessors such as window.location should not be allowed
3013 // to be overwritten because allowing overwriting could potentially
3014 // cause security problems.
3015 LookupResult callback_result;
3016 LookupCallback(name, &callback_result);
3017 if (callback_result.IsProperty()) {
3018 Object* obj = callback_result.GetCallbackObject();
3019 if (obj->IsAccessorInfo() &&
3020 AccessorInfo::cast(obj)->prohibits_overwriting()) {
3021 return false;
3022 }
3023 }
3024
3025 return true;
3026}
3027
3028
John Reck59135872010-11-02 12:39:01 -07003029MaybeObject* JSObject::SetElementCallback(uint32_t index,
3030 Object* structure,
3031 PropertyAttributes attributes) {
Leon Clarkef7060e22010-06-03 12:02:55 +01003032 PropertyDetails details = PropertyDetails(attributes, CALLBACKS);
3033
3034 // Normalize elements to make this operation simple.
John Reck59135872010-11-02 12:39:01 -07003035 Object* ok;
3036 { MaybeObject* maybe_ok = NormalizeElements();
3037 if (!maybe_ok->ToObject(&ok)) return maybe_ok;
3038 }
Leon Clarkef7060e22010-06-03 12:02:55 +01003039
3040 // Update the dictionary with the new CALLBACKS property.
John Reck59135872010-11-02 12:39:01 -07003041 Object* dict;
3042 { MaybeObject* maybe_dict =
3043 element_dictionary()->Set(index, structure, details);
3044 if (!maybe_dict->ToObject(&dict)) return maybe_dict;
3045 }
Leon Clarkef7060e22010-06-03 12:02:55 +01003046
3047 NumberDictionary* elements = NumberDictionary::cast(dict);
3048 elements->set_requires_slow_elements();
3049 // Set the potential new dictionary on the object.
3050 set_elements(elements);
Steve Blocka7e24c12009-10-30 11:49:00 +00003051
3052 return structure;
3053}
3054
3055
John Reck59135872010-11-02 12:39:01 -07003056MaybeObject* JSObject::SetPropertyCallback(String* name,
3057 Object* structure,
3058 PropertyAttributes attributes) {
Leon Clarkef7060e22010-06-03 12:02:55 +01003059 PropertyDetails details = PropertyDetails(attributes, CALLBACKS);
3060
3061 bool convert_back_to_fast = HasFastProperties() &&
3062 (map()->instance_descriptors()->number_of_descriptors()
3063 < DescriptorArray::kMaxNumberOfDescriptors);
3064
3065 // Normalize object to make this operation simple.
John Reck59135872010-11-02 12:39:01 -07003066 Object* ok;
3067 { MaybeObject* maybe_ok = NormalizeProperties(CLEAR_INOBJECT_PROPERTIES, 0);
3068 if (!maybe_ok->ToObject(&ok)) return maybe_ok;
3069 }
Leon Clarkef7060e22010-06-03 12:02:55 +01003070
3071 // For the global object allocate a new map to invalidate the global inline
3072 // caches which have a global property cell reference directly in the code.
3073 if (IsGlobalObject()) {
John Reck59135872010-11-02 12:39:01 -07003074 Object* new_map;
3075 { MaybeObject* maybe_new_map = map()->CopyDropDescriptors();
3076 if (!maybe_new_map->ToObject(&new_map)) return maybe_new_map;
3077 }
Leon Clarkef7060e22010-06-03 12:02:55 +01003078 set_map(Map::cast(new_map));
Ben Murdochb0fe1622011-05-05 13:52:32 +01003079 // When running crankshaft, changing the map is not enough. We
3080 // need to deoptimize all functions that rely on this global
3081 // object.
3082 Deoptimizer::DeoptimizeGlobalObject(this);
Leon Clarkef7060e22010-06-03 12:02:55 +01003083 }
3084
3085 // Update the dictionary with the new CALLBACKS property.
John Reck59135872010-11-02 12:39:01 -07003086 Object* result;
3087 { MaybeObject* maybe_result = SetNormalizedProperty(name, structure, details);
3088 if (!maybe_result->ToObject(&result)) return maybe_result;
3089 }
Leon Clarkef7060e22010-06-03 12:02:55 +01003090
3091 if (convert_back_to_fast) {
John Reck59135872010-11-02 12:39:01 -07003092 { MaybeObject* maybe_ok = TransformToFastProperties(0);
3093 if (!maybe_ok->ToObject(&ok)) return maybe_ok;
3094 }
Leon Clarkef7060e22010-06-03 12:02:55 +01003095 }
3096 return result;
3097}
3098
John Reck59135872010-11-02 12:39:01 -07003099MaybeObject* JSObject::DefineAccessor(String* name,
3100 bool is_getter,
Ben Murdochb0fe1622011-05-05 13:52:32 +01003101 Object* fun,
John Reck59135872010-11-02 12:39:01 -07003102 PropertyAttributes attributes) {
Ben Murdochb0fe1622011-05-05 13:52:32 +01003103 ASSERT(fun->IsJSFunction() || fun->IsUndefined());
Steve Blocka7e24c12009-10-30 11:49:00 +00003104 // Check access rights if needed.
3105 if (IsAccessCheckNeeded() &&
Leon Clarkef7060e22010-06-03 12:02:55 +01003106 !Top::MayNamedAccess(this, name, v8::ACCESS_SET)) {
3107 Top::ReportFailedAccessCheck(this, v8::ACCESS_SET);
Steve Blocka7e24c12009-10-30 11:49:00 +00003108 return Heap::undefined_value();
3109 }
3110
3111 if (IsJSGlobalProxy()) {
3112 Object* proto = GetPrototype();
3113 if (proto->IsNull()) return this;
3114 ASSERT(proto->IsJSGlobalObject());
3115 return JSObject::cast(proto)->DefineAccessor(name, is_getter,
3116 fun, attributes);
3117 }
3118
John Reck59135872010-11-02 12:39:01 -07003119 Object* array;
3120 { MaybeObject* maybe_array = DefineGetterSetter(name, attributes);
3121 if (!maybe_array->ToObject(&array)) return maybe_array;
3122 }
3123 if (array->IsUndefined()) return array;
Steve Blocka7e24c12009-10-30 11:49:00 +00003124 FixedArray::cast(array)->set(is_getter ? 0 : 1, fun);
3125 return this;
3126}
3127
3128
John Reck59135872010-11-02 12:39:01 -07003129MaybeObject* JSObject::DefineAccessor(AccessorInfo* info) {
Leon Clarkef7060e22010-06-03 12:02:55 +01003130 String* name = String::cast(info->name());
3131 // Check access rights if needed.
3132 if (IsAccessCheckNeeded() &&
3133 !Top::MayNamedAccess(this, name, v8::ACCESS_SET)) {
3134 Top::ReportFailedAccessCheck(this, v8::ACCESS_SET);
3135 return Heap::undefined_value();
3136 }
3137
3138 if (IsJSGlobalProxy()) {
3139 Object* proto = GetPrototype();
3140 if (proto->IsNull()) return this;
3141 ASSERT(proto->IsJSGlobalObject());
3142 return JSObject::cast(proto)->DefineAccessor(info);
3143 }
3144
3145 // Make sure that the top context does not change when doing callbacks or
3146 // interceptor calls.
3147 AssertNoContextChange ncc;
3148
3149 // Try to flatten before operating on the string.
3150 name->TryFlatten();
3151
3152 if (!CanSetCallback(name)) {
3153 return Heap::undefined_value();
3154 }
3155
3156 uint32_t index = 0;
3157 bool is_element = name->AsArrayIndex(&index);
3158
3159 if (is_element) {
3160 if (IsJSArray()) return Heap::undefined_value();
3161
3162 // Accessors overwrite previous callbacks (cf. with getters/setters).
3163 switch (GetElementsKind()) {
3164 case FAST_ELEMENTS:
3165 break;
3166 case PIXEL_ELEMENTS:
3167 case EXTERNAL_BYTE_ELEMENTS:
3168 case EXTERNAL_UNSIGNED_BYTE_ELEMENTS:
3169 case EXTERNAL_SHORT_ELEMENTS:
3170 case EXTERNAL_UNSIGNED_SHORT_ELEMENTS:
3171 case EXTERNAL_INT_ELEMENTS:
3172 case EXTERNAL_UNSIGNED_INT_ELEMENTS:
3173 case EXTERNAL_FLOAT_ELEMENTS:
3174 // Ignore getters and setters on pixel and external array
3175 // elements.
3176 return Heap::undefined_value();
3177 case DICTIONARY_ELEMENTS:
3178 break;
3179 default:
3180 UNREACHABLE();
3181 break;
3182 }
3183
John Reck59135872010-11-02 12:39:01 -07003184 Object* ok;
3185 { MaybeObject* maybe_ok =
3186 SetElementCallback(index, info, info->property_attributes());
3187 if (!maybe_ok->ToObject(&ok)) return maybe_ok;
3188 }
Leon Clarkef7060e22010-06-03 12:02:55 +01003189 } else {
3190 // Lookup the name.
3191 LookupResult result;
3192 LocalLookup(name, &result);
3193 // ES5 forbids turning a property into an accessor if it's not
3194 // configurable (that is IsDontDelete in ES3 and v8), see 8.6.1 (Table 5).
3195 if (result.IsProperty() && (result.IsReadOnly() || result.IsDontDelete())) {
3196 return Heap::undefined_value();
3197 }
John Reck59135872010-11-02 12:39:01 -07003198 Object* ok;
3199 { MaybeObject* maybe_ok =
3200 SetPropertyCallback(name, info, info->property_attributes());
3201 if (!maybe_ok->ToObject(&ok)) return maybe_ok;
3202 }
Leon Clarkef7060e22010-06-03 12:02:55 +01003203 }
3204
3205 return this;
3206}
3207
3208
Steve Blocka7e24c12009-10-30 11:49:00 +00003209Object* JSObject::LookupAccessor(String* name, bool is_getter) {
3210 // Make sure that the top context does not change when doing callbacks or
3211 // interceptor calls.
3212 AssertNoContextChange ncc;
3213
3214 // Check access rights if needed.
3215 if (IsAccessCheckNeeded() &&
3216 !Top::MayNamedAccess(this, name, v8::ACCESS_HAS)) {
3217 Top::ReportFailedAccessCheck(this, v8::ACCESS_HAS);
3218 return Heap::undefined_value();
3219 }
3220
3221 // Make the lookup and include prototypes.
3222 int accessor_index = is_getter ? kGetterIndex : kSetterIndex;
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01003223 uint32_t index = 0;
Steve Blocka7e24c12009-10-30 11:49:00 +00003224 if (name->AsArrayIndex(&index)) {
3225 for (Object* obj = this;
3226 obj != Heap::null_value();
3227 obj = JSObject::cast(obj)->GetPrototype()) {
3228 JSObject* js_object = JSObject::cast(obj);
3229 if (js_object->HasDictionaryElements()) {
3230 NumberDictionary* dictionary = js_object->element_dictionary();
3231 int entry = dictionary->FindEntry(index);
3232 if (entry != NumberDictionary::kNotFound) {
3233 Object* element = dictionary->ValueAt(entry);
3234 PropertyDetails details = dictionary->DetailsAt(entry);
3235 if (details.type() == CALLBACKS) {
Leon Clarkef7060e22010-06-03 12:02:55 +01003236 if (element->IsFixedArray()) {
3237 return FixedArray::cast(element)->get(accessor_index);
3238 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003239 }
3240 }
3241 }
3242 }
3243 } else {
3244 for (Object* obj = this;
3245 obj != Heap::null_value();
3246 obj = JSObject::cast(obj)->GetPrototype()) {
3247 LookupResult result;
3248 JSObject::cast(obj)->LocalLookup(name, &result);
Andrei Popescu402d9372010-02-26 13:31:12 +00003249 if (result.IsProperty()) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003250 if (result.IsReadOnly()) return Heap::undefined_value();
3251 if (result.type() == CALLBACKS) {
3252 Object* obj = result.GetCallbackObject();
3253 if (obj->IsFixedArray()) {
3254 return FixedArray::cast(obj)->get(accessor_index);
3255 }
3256 }
3257 }
3258 }
3259 }
3260 return Heap::undefined_value();
3261}
3262
3263
3264Object* JSObject::SlowReverseLookup(Object* value) {
3265 if (HasFastProperties()) {
3266 DescriptorArray* descs = map()->instance_descriptors();
3267 for (int i = 0; i < descs->number_of_descriptors(); i++) {
3268 if (descs->GetType(i) == FIELD) {
3269 if (FastPropertyAt(descs->GetFieldIndex(i)) == value) {
3270 return descs->GetKey(i);
3271 }
3272 } else if (descs->GetType(i) == CONSTANT_FUNCTION) {
3273 if (descs->GetConstantFunction(i) == value) {
3274 return descs->GetKey(i);
3275 }
3276 }
3277 }
3278 return Heap::undefined_value();
3279 } else {
3280 return property_dictionary()->SlowReverseLookup(value);
3281 }
3282}
3283
3284
John Reck59135872010-11-02 12:39:01 -07003285MaybeObject* Map::CopyDropDescriptors() {
3286 Object* result;
3287 { MaybeObject* maybe_result =
3288 Heap::AllocateMap(instance_type(), instance_size());
3289 if (!maybe_result->ToObject(&result)) return maybe_result;
3290 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003291 Map::cast(result)->set_prototype(prototype());
3292 Map::cast(result)->set_constructor(constructor());
3293 // Don't copy descriptors, so map transitions always remain a forest.
3294 // If we retained the same descriptors we would have two maps
3295 // pointing to the same transition which is bad because the garbage
3296 // collector relies on being able to reverse pointers from transitions
3297 // to maps. If properties need to be retained use CopyDropTransitions.
3298 Map::cast(result)->set_instance_descriptors(Heap::empty_descriptor_array());
3299 // Please note instance_type and instance_size are set when allocated.
3300 Map::cast(result)->set_inobject_properties(inobject_properties());
3301 Map::cast(result)->set_unused_property_fields(unused_property_fields());
3302
3303 // If the map has pre-allocated properties always start out with a descriptor
3304 // array describing these properties.
3305 if (pre_allocated_property_fields() > 0) {
3306 ASSERT(constructor()->IsJSFunction());
3307 JSFunction* ctor = JSFunction::cast(constructor());
John Reck59135872010-11-02 12:39:01 -07003308 Object* descriptors;
3309 { MaybeObject* maybe_descriptors =
3310 ctor->initial_map()->instance_descriptors()->RemoveTransitions();
3311 if (!maybe_descriptors->ToObject(&descriptors)) return maybe_descriptors;
3312 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003313 Map::cast(result)->set_instance_descriptors(
3314 DescriptorArray::cast(descriptors));
3315 Map::cast(result)->set_pre_allocated_property_fields(
3316 pre_allocated_property_fields());
3317 }
3318 Map::cast(result)->set_bit_field(bit_field());
3319 Map::cast(result)->set_bit_field2(bit_field2());
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003320 Map::cast(result)->set_is_shared(false);
Steve Blocka7e24c12009-10-30 11:49:00 +00003321 Map::cast(result)->ClearCodeCache();
3322 return result;
3323}
3324
3325
John Reck59135872010-11-02 12:39:01 -07003326MaybeObject* Map::CopyNormalized(PropertyNormalizationMode mode,
3327 NormalizedMapSharingMode sharing) {
Kristian Monsen80d68ea2010-09-08 11:05:35 +01003328 int new_instance_size = instance_size();
3329 if (mode == CLEAR_INOBJECT_PROPERTIES) {
3330 new_instance_size -= inobject_properties() * kPointerSize;
3331 }
3332
John Reck59135872010-11-02 12:39:01 -07003333 Object* result;
3334 { MaybeObject* maybe_result =
3335 Heap::AllocateMap(instance_type(), new_instance_size);
3336 if (!maybe_result->ToObject(&result)) return maybe_result;
3337 }
Kristian Monsen80d68ea2010-09-08 11:05:35 +01003338
3339 if (mode != CLEAR_INOBJECT_PROPERTIES) {
3340 Map::cast(result)->set_inobject_properties(inobject_properties());
3341 }
3342
3343 Map::cast(result)->set_prototype(prototype());
3344 Map::cast(result)->set_constructor(constructor());
3345
3346 Map::cast(result)->set_bit_field(bit_field());
3347 Map::cast(result)->set_bit_field2(bit_field2());
3348
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003349 Map::cast(result)->set_is_shared(sharing == SHARED_NORMALIZED_MAP);
3350
Kristian Monsen80d68ea2010-09-08 11:05:35 +01003351#ifdef DEBUG
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003352 if (Map::cast(result)->is_shared()) {
3353 Map::cast(result)->SharedMapVerify();
3354 }
Kristian Monsen80d68ea2010-09-08 11:05:35 +01003355#endif
3356
3357 return result;
3358}
3359
3360
John Reck59135872010-11-02 12:39:01 -07003361MaybeObject* Map::CopyDropTransitions() {
3362 Object* new_map;
3363 { MaybeObject* maybe_new_map = CopyDropDescriptors();
3364 if (!maybe_new_map->ToObject(&new_map)) return maybe_new_map;
3365 }
3366 Object* descriptors;
3367 { MaybeObject* maybe_descriptors =
3368 instance_descriptors()->RemoveTransitions();
3369 if (!maybe_descriptors->ToObject(&descriptors)) return maybe_descriptors;
3370 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003371 cast(new_map)->set_instance_descriptors(DescriptorArray::cast(descriptors));
Steve Block8defd9f2010-07-08 12:39:36 +01003372 return new_map;
Steve Blocka7e24c12009-10-30 11:49:00 +00003373}
3374
3375
John Reck59135872010-11-02 12:39:01 -07003376MaybeObject* Map::UpdateCodeCache(String* name, Code* code) {
Steve Block6ded16b2010-05-10 14:33:55 +01003377 // Allocate the code cache if not present.
3378 if (code_cache()->IsFixedArray()) {
John Reck59135872010-11-02 12:39:01 -07003379 Object* result;
3380 { MaybeObject* maybe_result = Heap::AllocateCodeCache();
3381 if (!maybe_result->ToObject(&result)) return maybe_result;
3382 }
Steve Block6ded16b2010-05-10 14:33:55 +01003383 set_code_cache(result);
3384 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003385
Steve Block6ded16b2010-05-10 14:33:55 +01003386 // Update the code cache.
3387 return CodeCache::cast(code_cache())->Update(name, code);
3388}
3389
3390
3391Object* Map::FindInCodeCache(String* name, Code::Flags flags) {
3392 // Do a lookup if a code cache exists.
3393 if (!code_cache()->IsFixedArray()) {
3394 return CodeCache::cast(code_cache())->Lookup(name, flags);
3395 } else {
3396 return Heap::undefined_value();
3397 }
3398}
3399
3400
3401int Map::IndexInCodeCache(Object* name, Code* code) {
3402 // Get the internal index if a code cache exists.
3403 if (!code_cache()->IsFixedArray()) {
3404 return CodeCache::cast(code_cache())->GetIndex(name, code);
3405 }
3406 return -1;
3407}
3408
3409
3410void Map::RemoveFromCodeCache(String* name, Code* code, int index) {
3411 // No GC is supposed to happen between a call to IndexInCodeCache and
3412 // RemoveFromCodeCache so the code cache must be there.
3413 ASSERT(!code_cache()->IsFixedArray());
3414 CodeCache::cast(code_cache())->RemoveByIndex(name, code, index);
3415}
3416
3417
Kristian Monsen0d5e1162010-09-30 15:31:59 +01003418void Map::TraverseTransitionTree(TraverseCallback callback, void* data) {
3419 Map* current = this;
3420 while (current != Heap::meta_map()) {
3421 DescriptorArray* d = reinterpret_cast<DescriptorArray*>(
3422 *RawField(current, Map::kInstanceDescriptorsOffset));
3423 if (d == Heap::empty_descriptor_array()) {
3424 Map* prev = current->map();
3425 current->set_map(Heap::meta_map());
3426 callback(current, data);
3427 current = prev;
3428 continue;
3429 }
3430
3431 FixedArray* contents = reinterpret_cast<FixedArray*>(
3432 d->get(DescriptorArray::kContentArrayIndex));
3433 Object** map_or_index_field = RawField(contents, HeapObject::kMapOffset);
3434 Object* map_or_index = *map_or_index_field;
3435 bool map_done = true;
3436 for (int i = map_or_index->IsSmi() ? Smi::cast(map_or_index)->value() : 0;
3437 i < contents->length();
3438 i += 2) {
3439 PropertyDetails details(Smi::cast(contents->get(i + 1)));
3440 if (details.IsTransition()) {
3441 Map* next = reinterpret_cast<Map*>(contents->get(i));
3442 next->set_map(current);
3443 *map_or_index_field = Smi::FromInt(i + 2);
3444 current = next;
3445 map_done = false;
3446 break;
3447 }
3448 }
3449 if (!map_done) continue;
3450 *map_or_index_field = Heap::fixed_array_map();
3451 Map* prev = current->map();
3452 current->set_map(Heap::meta_map());
3453 callback(current, data);
3454 current = prev;
3455 }
3456}
3457
3458
John Reck59135872010-11-02 12:39:01 -07003459MaybeObject* CodeCache::Update(String* name, Code* code) {
Steve Block6ded16b2010-05-10 14:33:55 +01003460 ASSERT(code->ic_state() == MONOMORPHIC);
3461
3462 // The number of monomorphic stubs for normal load/store/call IC's can grow to
3463 // a large number and therefore they need to go into a hash table. They are
3464 // used to load global properties from cells.
3465 if (code->type() == NORMAL) {
3466 // Make sure that a hash table is allocated for the normal load code cache.
3467 if (normal_type_cache()->IsUndefined()) {
John Reck59135872010-11-02 12:39:01 -07003468 Object* result;
3469 { MaybeObject* maybe_result =
3470 CodeCacheHashTable::Allocate(CodeCacheHashTable::kInitialSize);
3471 if (!maybe_result->ToObject(&result)) return maybe_result;
3472 }
Steve Block6ded16b2010-05-10 14:33:55 +01003473 set_normal_type_cache(result);
3474 }
3475 return UpdateNormalTypeCache(name, code);
3476 } else {
3477 ASSERT(default_cache()->IsFixedArray());
3478 return UpdateDefaultCache(name, code);
3479 }
3480}
3481
3482
John Reck59135872010-11-02 12:39:01 -07003483MaybeObject* CodeCache::UpdateDefaultCache(String* name, Code* code) {
Steve Block6ded16b2010-05-10 14:33:55 +01003484 // When updating the default code cache we disregard the type encoded in the
Steve Blocka7e24c12009-10-30 11:49:00 +00003485 // flags. This allows call constant stubs to overwrite call field
3486 // stubs, etc.
3487 Code::Flags flags = Code::RemoveTypeFromFlags(code->flags());
3488
3489 // First check whether we can update existing code cache without
3490 // extending it.
Steve Block6ded16b2010-05-10 14:33:55 +01003491 FixedArray* cache = default_cache();
Steve Blocka7e24c12009-10-30 11:49:00 +00003492 int length = cache->length();
3493 int deleted_index = -1;
Steve Block6ded16b2010-05-10 14:33:55 +01003494 for (int i = 0; i < length; i += kCodeCacheEntrySize) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003495 Object* key = cache->get(i);
3496 if (key->IsNull()) {
3497 if (deleted_index < 0) deleted_index = i;
3498 continue;
3499 }
3500 if (key->IsUndefined()) {
3501 if (deleted_index >= 0) i = deleted_index;
Steve Block6ded16b2010-05-10 14:33:55 +01003502 cache->set(i + kCodeCacheEntryNameOffset, name);
3503 cache->set(i + kCodeCacheEntryCodeOffset, code);
Steve Blocka7e24c12009-10-30 11:49:00 +00003504 return this;
3505 }
3506 if (name->Equals(String::cast(key))) {
Steve Block6ded16b2010-05-10 14:33:55 +01003507 Code::Flags found =
3508 Code::cast(cache->get(i + kCodeCacheEntryCodeOffset))->flags();
Steve Blocka7e24c12009-10-30 11:49:00 +00003509 if (Code::RemoveTypeFromFlags(found) == flags) {
Steve Block6ded16b2010-05-10 14:33:55 +01003510 cache->set(i + kCodeCacheEntryCodeOffset, code);
Steve Blocka7e24c12009-10-30 11:49:00 +00003511 return this;
3512 }
3513 }
3514 }
3515
3516 // Reached the end of the code cache. If there were deleted
3517 // elements, reuse the space for the first of them.
3518 if (deleted_index >= 0) {
Steve Block6ded16b2010-05-10 14:33:55 +01003519 cache->set(deleted_index + kCodeCacheEntryNameOffset, name);
3520 cache->set(deleted_index + kCodeCacheEntryCodeOffset, code);
Steve Blocka7e24c12009-10-30 11:49:00 +00003521 return this;
3522 }
3523
Steve Block6ded16b2010-05-10 14:33:55 +01003524 // Extend the code cache with some new entries (at least one). Must be a
3525 // multiple of the entry size.
3526 int new_length = length + ((length >> 1)) + kCodeCacheEntrySize;
3527 new_length = new_length - new_length % kCodeCacheEntrySize;
3528 ASSERT((new_length % kCodeCacheEntrySize) == 0);
John Reck59135872010-11-02 12:39:01 -07003529 Object* result;
3530 { MaybeObject* maybe_result = cache->CopySize(new_length);
3531 if (!maybe_result->ToObject(&result)) return maybe_result;
3532 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003533
3534 // Add the (name, code) pair to the new cache.
3535 cache = FixedArray::cast(result);
Steve Block6ded16b2010-05-10 14:33:55 +01003536 cache->set(length + kCodeCacheEntryNameOffset, name);
3537 cache->set(length + kCodeCacheEntryCodeOffset, code);
3538 set_default_cache(cache);
Steve Blocka7e24c12009-10-30 11:49:00 +00003539 return this;
3540}
3541
3542
John Reck59135872010-11-02 12:39:01 -07003543MaybeObject* CodeCache::UpdateNormalTypeCache(String* name, Code* code) {
Steve Block6ded16b2010-05-10 14:33:55 +01003544 // Adding a new entry can cause a new cache to be allocated.
3545 CodeCacheHashTable* cache = CodeCacheHashTable::cast(normal_type_cache());
John Reck59135872010-11-02 12:39:01 -07003546 Object* new_cache;
3547 { MaybeObject* maybe_new_cache = cache->Put(name, code);
3548 if (!maybe_new_cache->ToObject(&new_cache)) return maybe_new_cache;
3549 }
Steve Block6ded16b2010-05-10 14:33:55 +01003550 set_normal_type_cache(new_cache);
3551 return this;
3552}
3553
3554
3555Object* CodeCache::Lookup(String* name, Code::Flags flags) {
3556 if (Code::ExtractTypeFromFlags(flags) == NORMAL) {
3557 return LookupNormalTypeCache(name, flags);
3558 } else {
3559 return LookupDefaultCache(name, flags);
3560 }
3561}
3562
3563
3564Object* CodeCache::LookupDefaultCache(String* name, Code::Flags flags) {
3565 FixedArray* cache = default_cache();
Steve Blocka7e24c12009-10-30 11:49:00 +00003566 int length = cache->length();
Steve Block6ded16b2010-05-10 14:33:55 +01003567 for (int i = 0; i < length; i += kCodeCacheEntrySize) {
3568 Object* key = cache->get(i + kCodeCacheEntryNameOffset);
Steve Blocka7e24c12009-10-30 11:49:00 +00003569 // Skip deleted elements.
3570 if (key->IsNull()) continue;
3571 if (key->IsUndefined()) return key;
3572 if (name->Equals(String::cast(key))) {
Steve Block6ded16b2010-05-10 14:33:55 +01003573 Code* code = Code::cast(cache->get(i + kCodeCacheEntryCodeOffset));
3574 if (code->flags() == flags) {
3575 return code;
3576 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003577 }
3578 }
3579 return Heap::undefined_value();
3580}
3581
3582
Steve Block6ded16b2010-05-10 14:33:55 +01003583Object* CodeCache::LookupNormalTypeCache(String* name, Code::Flags flags) {
3584 if (!normal_type_cache()->IsUndefined()) {
3585 CodeCacheHashTable* cache = CodeCacheHashTable::cast(normal_type_cache());
3586 return cache->Lookup(name, flags);
3587 } else {
3588 return Heap::undefined_value();
3589 }
3590}
3591
3592
3593int CodeCache::GetIndex(Object* name, Code* code) {
3594 if (code->type() == NORMAL) {
3595 if (normal_type_cache()->IsUndefined()) return -1;
3596 CodeCacheHashTable* cache = CodeCacheHashTable::cast(normal_type_cache());
3597 return cache->GetIndex(String::cast(name), code->flags());
3598 }
3599
3600 FixedArray* array = default_cache();
Steve Blocka7e24c12009-10-30 11:49:00 +00003601 int len = array->length();
Steve Block6ded16b2010-05-10 14:33:55 +01003602 for (int i = 0; i < len; i += kCodeCacheEntrySize) {
3603 if (array->get(i + kCodeCacheEntryCodeOffset) == code) return i + 1;
Steve Blocka7e24c12009-10-30 11:49:00 +00003604 }
3605 return -1;
3606}
3607
3608
Steve Block6ded16b2010-05-10 14:33:55 +01003609void CodeCache::RemoveByIndex(Object* name, Code* code, int index) {
3610 if (code->type() == NORMAL) {
3611 ASSERT(!normal_type_cache()->IsUndefined());
3612 CodeCacheHashTable* cache = CodeCacheHashTable::cast(normal_type_cache());
3613 ASSERT(cache->GetIndex(String::cast(name), code->flags()) == index);
3614 cache->RemoveByIndex(index);
3615 } else {
3616 FixedArray* array = default_cache();
3617 ASSERT(array->length() >= index && array->get(index)->IsCode());
3618 // Use null instead of undefined for deleted elements to distinguish
3619 // deleted elements from unused elements. This distinction is used
3620 // when looking up in the cache and when updating the cache.
3621 ASSERT_EQ(1, kCodeCacheEntryCodeOffset - kCodeCacheEntryNameOffset);
3622 array->set_null(index - 1); // Name.
3623 array->set_null(index); // Code.
3624 }
3625}
3626
3627
3628// The key in the code cache hash table consists of the property name and the
3629// code object. The actual match is on the name and the code flags. If a key
3630// is created using the flags and not a code object it can only be used for
3631// lookup not to create a new entry.
3632class CodeCacheHashTableKey : public HashTableKey {
3633 public:
3634 CodeCacheHashTableKey(String* name, Code::Flags flags)
3635 : name_(name), flags_(flags), code_(NULL) { }
3636
3637 CodeCacheHashTableKey(String* name, Code* code)
3638 : name_(name),
3639 flags_(code->flags()),
3640 code_(code) { }
3641
3642
3643 bool IsMatch(Object* other) {
3644 if (!other->IsFixedArray()) return false;
3645 FixedArray* pair = FixedArray::cast(other);
3646 String* name = String::cast(pair->get(0));
3647 Code::Flags flags = Code::cast(pair->get(1))->flags();
3648 if (flags != flags_) {
3649 return false;
3650 }
3651 return name_->Equals(name);
3652 }
3653
3654 static uint32_t NameFlagsHashHelper(String* name, Code::Flags flags) {
3655 return name->Hash() ^ flags;
3656 }
3657
3658 uint32_t Hash() { return NameFlagsHashHelper(name_, flags_); }
3659
3660 uint32_t HashForObject(Object* obj) {
3661 FixedArray* pair = FixedArray::cast(obj);
3662 String* name = String::cast(pair->get(0));
3663 Code* code = Code::cast(pair->get(1));
3664 return NameFlagsHashHelper(name, code->flags());
3665 }
3666
John Reck59135872010-11-02 12:39:01 -07003667 MUST_USE_RESULT MaybeObject* AsObject() {
Steve Block6ded16b2010-05-10 14:33:55 +01003668 ASSERT(code_ != NULL);
John Reck59135872010-11-02 12:39:01 -07003669 Object* obj;
3670 { MaybeObject* maybe_obj = Heap::AllocateFixedArray(2);
3671 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
3672 }
Steve Block6ded16b2010-05-10 14:33:55 +01003673 FixedArray* pair = FixedArray::cast(obj);
3674 pair->set(0, name_);
3675 pair->set(1, code_);
3676 return pair;
3677 }
3678
3679 private:
3680 String* name_;
3681 Code::Flags flags_;
3682 Code* code_;
3683};
3684
3685
3686Object* CodeCacheHashTable::Lookup(String* name, Code::Flags flags) {
3687 CodeCacheHashTableKey key(name, flags);
3688 int entry = FindEntry(&key);
3689 if (entry == kNotFound) return Heap::undefined_value();
3690 return get(EntryToIndex(entry) + 1);
3691}
3692
3693
John Reck59135872010-11-02 12:39:01 -07003694MaybeObject* CodeCacheHashTable::Put(String* name, Code* code) {
Steve Block6ded16b2010-05-10 14:33:55 +01003695 CodeCacheHashTableKey key(name, code);
John Reck59135872010-11-02 12:39:01 -07003696 Object* obj;
3697 { MaybeObject* maybe_obj = EnsureCapacity(1, &key);
3698 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
3699 }
Steve Block6ded16b2010-05-10 14:33:55 +01003700
3701 // Don't use this, as the table might have grown.
3702 CodeCacheHashTable* cache = reinterpret_cast<CodeCacheHashTable*>(obj);
3703
3704 int entry = cache->FindInsertionEntry(key.Hash());
John Reck59135872010-11-02 12:39:01 -07003705 Object* k;
3706 { MaybeObject* maybe_k = key.AsObject();
3707 if (!maybe_k->ToObject(&k)) return maybe_k;
3708 }
Steve Block6ded16b2010-05-10 14:33:55 +01003709
3710 cache->set(EntryToIndex(entry), k);
3711 cache->set(EntryToIndex(entry) + 1, code);
3712 cache->ElementAdded();
3713 return cache;
3714}
3715
3716
3717int CodeCacheHashTable::GetIndex(String* name, Code::Flags flags) {
3718 CodeCacheHashTableKey key(name, flags);
3719 int entry = FindEntry(&key);
3720 return (entry == kNotFound) ? -1 : entry;
3721}
3722
3723
3724void CodeCacheHashTable::RemoveByIndex(int index) {
3725 ASSERT(index >= 0);
3726 set(EntryToIndex(index), Heap::null_value());
3727 set(EntryToIndex(index) + 1, Heap::null_value());
3728 ElementRemoved();
Steve Blocka7e24c12009-10-30 11:49:00 +00003729}
3730
3731
Steve Blocka7e24c12009-10-30 11:49:00 +00003732static bool HasKey(FixedArray* array, Object* key) {
3733 int len0 = array->length();
3734 for (int i = 0; i < len0; i++) {
3735 Object* element = array->get(i);
3736 if (element->IsSmi() && key->IsSmi() && (element == key)) return true;
3737 if (element->IsString() &&
3738 key->IsString() && String::cast(element)->Equals(String::cast(key))) {
3739 return true;
3740 }
3741 }
3742 return false;
3743}
3744
3745
John Reck59135872010-11-02 12:39:01 -07003746MaybeObject* FixedArray::AddKeysFromJSArray(JSArray* array) {
Steve Block3ce2e202009-11-05 08:53:23 +00003747 ASSERT(!array->HasPixelElements() && !array->HasExternalArrayElements());
Steve Blocka7e24c12009-10-30 11:49:00 +00003748 switch (array->GetElementsKind()) {
3749 case JSObject::FAST_ELEMENTS:
3750 return UnionOfKeys(FixedArray::cast(array->elements()));
3751 case JSObject::DICTIONARY_ELEMENTS: {
3752 NumberDictionary* dict = array->element_dictionary();
3753 int size = dict->NumberOfElements();
3754
3755 // Allocate a temporary fixed array.
John Reck59135872010-11-02 12:39:01 -07003756 Object* object;
3757 { MaybeObject* maybe_object = Heap::AllocateFixedArray(size);
3758 if (!maybe_object->ToObject(&object)) return maybe_object;
3759 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003760 FixedArray* key_array = FixedArray::cast(object);
3761
3762 int capacity = dict->Capacity();
3763 int pos = 0;
3764 // Copy the elements from the JSArray to the temporary fixed array.
3765 for (int i = 0; i < capacity; i++) {
3766 if (dict->IsKey(dict->KeyAt(i))) {
3767 key_array->set(pos++, dict->ValueAt(i));
3768 }
3769 }
3770 // Compute the union of this and the temporary fixed array.
3771 return UnionOfKeys(key_array);
3772 }
3773 default:
3774 UNREACHABLE();
3775 }
3776 UNREACHABLE();
3777 return Heap::null_value(); // Failure case needs to "return" a value.
3778}
3779
3780
John Reck59135872010-11-02 12:39:01 -07003781MaybeObject* FixedArray::UnionOfKeys(FixedArray* other) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003782 int len0 = length();
Ben Murdochf87a2032010-10-22 12:50:53 +01003783#ifdef DEBUG
3784 if (FLAG_enable_slow_asserts) {
3785 for (int i = 0; i < len0; i++) {
3786 ASSERT(get(i)->IsString() || get(i)->IsNumber());
3787 }
3788 }
3789#endif
Steve Blocka7e24c12009-10-30 11:49:00 +00003790 int len1 = other->length();
Ben Murdochf87a2032010-10-22 12:50:53 +01003791 // Optimize if 'other' is empty.
3792 // We cannot optimize if 'this' is empty, as other may have holes
3793 // or non keys.
Steve Blocka7e24c12009-10-30 11:49:00 +00003794 if (len1 == 0) return this;
3795
3796 // Compute how many elements are not in this.
3797 int extra = 0;
3798 for (int y = 0; y < len1; y++) {
3799 Object* value = other->get(y);
3800 if (!value->IsTheHole() && !HasKey(this, value)) extra++;
3801 }
3802
3803 if (extra == 0) return this;
3804
3805 // Allocate the result
John Reck59135872010-11-02 12:39:01 -07003806 Object* obj;
3807 { MaybeObject* maybe_obj = Heap::AllocateFixedArray(len0 + extra);
3808 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
3809 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003810 // Fill in the content
Leon Clarke4515c472010-02-03 11:58:03 +00003811 AssertNoAllocation no_gc;
Steve Blocka7e24c12009-10-30 11:49:00 +00003812 FixedArray* result = FixedArray::cast(obj);
Leon Clarke4515c472010-02-03 11:58:03 +00003813 WriteBarrierMode mode = result->GetWriteBarrierMode(no_gc);
Steve Blocka7e24c12009-10-30 11:49:00 +00003814 for (int i = 0; i < len0; i++) {
Ben Murdochf87a2032010-10-22 12:50:53 +01003815 Object* e = get(i);
3816 ASSERT(e->IsString() || e->IsNumber());
3817 result->set(i, e, mode);
Steve Blocka7e24c12009-10-30 11:49:00 +00003818 }
3819 // Fill in the extra keys.
3820 int index = 0;
3821 for (int y = 0; y < len1; y++) {
3822 Object* value = other->get(y);
3823 if (!value->IsTheHole() && !HasKey(this, value)) {
Ben Murdochf87a2032010-10-22 12:50:53 +01003824 Object* e = other->get(y);
3825 ASSERT(e->IsString() || e->IsNumber());
3826 result->set(len0 + index, e, mode);
Steve Blocka7e24c12009-10-30 11:49:00 +00003827 index++;
3828 }
3829 }
3830 ASSERT(extra == index);
3831 return result;
3832}
3833
3834
John Reck59135872010-11-02 12:39:01 -07003835MaybeObject* FixedArray::CopySize(int new_length) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003836 if (new_length == 0) return Heap::empty_fixed_array();
John Reck59135872010-11-02 12:39:01 -07003837 Object* obj;
3838 { MaybeObject* maybe_obj = Heap::AllocateFixedArray(new_length);
3839 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
3840 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003841 FixedArray* result = FixedArray::cast(obj);
3842 // Copy the content
Leon Clarke4515c472010-02-03 11:58:03 +00003843 AssertNoAllocation no_gc;
Steve Blocka7e24c12009-10-30 11:49:00 +00003844 int len = length();
3845 if (new_length < len) len = new_length;
3846 result->set_map(map());
Leon Clarke4515c472010-02-03 11:58:03 +00003847 WriteBarrierMode mode = result->GetWriteBarrierMode(no_gc);
Steve Blocka7e24c12009-10-30 11:49:00 +00003848 for (int i = 0; i < len; i++) {
3849 result->set(i, get(i), mode);
3850 }
3851 return result;
3852}
3853
3854
3855void FixedArray::CopyTo(int pos, FixedArray* dest, int dest_pos, int len) {
Leon Clarke4515c472010-02-03 11:58:03 +00003856 AssertNoAllocation no_gc;
3857 WriteBarrierMode mode = dest->GetWriteBarrierMode(no_gc);
Steve Blocka7e24c12009-10-30 11:49:00 +00003858 for (int index = 0; index < len; index++) {
3859 dest->set(dest_pos+index, get(pos+index), mode);
3860 }
3861}
3862
3863
3864#ifdef DEBUG
3865bool FixedArray::IsEqualTo(FixedArray* other) {
3866 if (length() != other->length()) return false;
3867 for (int i = 0 ; i < length(); ++i) {
3868 if (get(i) != other->get(i)) return false;
3869 }
3870 return true;
3871}
3872#endif
3873
3874
John Reck59135872010-11-02 12:39:01 -07003875MaybeObject* DescriptorArray::Allocate(int number_of_descriptors) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003876 if (number_of_descriptors == 0) {
3877 return Heap::empty_descriptor_array();
3878 }
3879 // Allocate the array of keys.
John Reck59135872010-11-02 12:39:01 -07003880 Object* array;
3881 { MaybeObject* maybe_array =
3882 Heap::AllocateFixedArray(ToKeyIndex(number_of_descriptors));
3883 if (!maybe_array->ToObject(&array)) return maybe_array;
3884 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003885 // Do not use DescriptorArray::cast on incomplete object.
3886 FixedArray* result = FixedArray::cast(array);
3887
3888 // Allocate the content array and set it in the descriptor array.
John Reck59135872010-11-02 12:39:01 -07003889 { MaybeObject* maybe_array =
3890 Heap::AllocateFixedArray(number_of_descriptors << 1);
3891 if (!maybe_array->ToObject(&array)) return maybe_array;
3892 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003893 result->set(kContentArrayIndex, array);
3894 result->set(kEnumerationIndexIndex,
Leon Clarke4515c472010-02-03 11:58:03 +00003895 Smi::FromInt(PropertyDetails::kInitialIndex));
Steve Blocka7e24c12009-10-30 11:49:00 +00003896 return result;
3897}
3898
3899
3900void DescriptorArray::SetEnumCache(FixedArray* bridge_storage,
3901 FixedArray* new_cache) {
3902 ASSERT(bridge_storage->length() >= kEnumCacheBridgeLength);
3903 if (HasEnumCache()) {
3904 FixedArray::cast(get(kEnumerationIndexIndex))->
3905 set(kEnumCacheBridgeCacheIndex, new_cache);
3906 } else {
3907 if (IsEmpty()) return; // Do nothing for empty descriptor array.
3908 FixedArray::cast(bridge_storage)->
3909 set(kEnumCacheBridgeCacheIndex, new_cache);
3910 fast_set(FixedArray::cast(bridge_storage),
3911 kEnumCacheBridgeEnumIndex,
3912 get(kEnumerationIndexIndex));
3913 set(kEnumerationIndexIndex, bridge_storage);
3914 }
3915}
3916
3917
John Reck59135872010-11-02 12:39:01 -07003918MaybeObject* DescriptorArray::CopyInsert(Descriptor* descriptor,
3919 TransitionFlag transition_flag) {
Steve Blocka7e24c12009-10-30 11:49:00 +00003920 // Transitions are only kept when inserting another transition.
3921 // This precondition is not required by this function's implementation, but
3922 // is currently required by the semantics of maps, so we check it.
3923 // Conversely, we filter after replacing, so replacing a transition and
3924 // removing all other transitions is not supported.
3925 bool remove_transitions = transition_flag == REMOVE_TRANSITIONS;
3926 ASSERT(remove_transitions == !descriptor->GetDetails().IsTransition());
3927 ASSERT(descriptor->GetDetails().type() != NULL_DESCRIPTOR);
3928
3929 // Ensure the key is a symbol.
John Reck59135872010-11-02 12:39:01 -07003930 Object* result;
3931 { MaybeObject* maybe_result = descriptor->KeyToSymbol();
3932 if (!maybe_result->ToObject(&result)) return maybe_result;
3933 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003934
3935 int transitions = 0;
3936 int null_descriptors = 0;
3937 if (remove_transitions) {
3938 for (int i = 0; i < number_of_descriptors(); i++) {
3939 if (IsTransition(i)) transitions++;
3940 if (IsNullDescriptor(i)) null_descriptors++;
3941 }
3942 } else {
3943 for (int i = 0; i < number_of_descriptors(); i++) {
3944 if (IsNullDescriptor(i)) null_descriptors++;
3945 }
3946 }
3947 int new_size = number_of_descriptors() - transitions - null_descriptors;
3948
3949 // If key is in descriptor, we replace it in-place when filtering.
3950 // Count a null descriptor for key as inserted, not replaced.
3951 int index = Search(descriptor->GetKey());
3952 const bool inserting = (index == kNotFound);
3953 const bool replacing = !inserting;
3954 bool keep_enumeration_index = false;
3955 if (inserting) {
3956 ++new_size;
3957 }
3958 if (replacing) {
3959 // We are replacing an existing descriptor. We keep the enumeration
3960 // index of a visible property.
3961 PropertyType t = PropertyDetails(GetDetails(index)).type();
3962 if (t == CONSTANT_FUNCTION ||
3963 t == FIELD ||
3964 t == CALLBACKS ||
3965 t == INTERCEPTOR) {
3966 keep_enumeration_index = true;
3967 } else if (remove_transitions) {
3968 // Replaced descriptor has been counted as removed if it is
3969 // a transition that will be replaced. Adjust count in this case.
3970 ++new_size;
3971 }
3972 }
John Reck59135872010-11-02 12:39:01 -07003973 { MaybeObject* maybe_result = Allocate(new_size);
3974 if (!maybe_result->ToObject(&result)) return maybe_result;
3975 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003976 DescriptorArray* new_descriptors = DescriptorArray::cast(result);
3977 // Set the enumeration index in the descriptors and set the enumeration index
3978 // in the result.
3979 int enumeration_index = NextEnumerationIndex();
3980 if (!descriptor->GetDetails().IsTransition()) {
3981 if (keep_enumeration_index) {
3982 descriptor->SetEnumerationIndex(
3983 PropertyDetails(GetDetails(index)).index());
3984 } else {
3985 descriptor->SetEnumerationIndex(enumeration_index);
3986 ++enumeration_index;
3987 }
3988 }
3989 new_descriptors->SetNextEnumerationIndex(enumeration_index);
3990
3991 // Copy the descriptors, filtering out transitions and null descriptors,
3992 // and inserting or replacing a descriptor.
3993 uint32_t descriptor_hash = descriptor->GetKey()->Hash();
3994 int from_index = 0;
3995 int to_index = 0;
3996
3997 for (; from_index < number_of_descriptors(); from_index++) {
3998 String* key = GetKey(from_index);
3999 if (key->Hash() > descriptor_hash || key == descriptor->GetKey()) {
4000 break;
4001 }
4002 if (IsNullDescriptor(from_index)) continue;
4003 if (remove_transitions && IsTransition(from_index)) continue;
4004 new_descriptors->CopyFrom(to_index++, this, from_index);
4005 }
4006
4007 new_descriptors->Set(to_index++, descriptor);
4008 if (replacing) from_index++;
4009
4010 for (; from_index < number_of_descriptors(); from_index++) {
4011 if (IsNullDescriptor(from_index)) continue;
4012 if (remove_transitions && IsTransition(from_index)) continue;
4013 new_descriptors->CopyFrom(to_index++, this, from_index);
4014 }
4015
4016 ASSERT(to_index == new_descriptors->number_of_descriptors());
4017 SLOW_ASSERT(new_descriptors->IsSortedNoDuplicates());
4018
4019 return new_descriptors;
4020}
4021
4022
John Reck59135872010-11-02 12:39:01 -07004023MaybeObject* DescriptorArray::RemoveTransitions() {
Steve Blocka7e24c12009-10-30 11:49:00 +00004024 // Remove all transitions and null descriptors. Return a copy of the array
4025 // with all transitions removed, or a Failure object if the new array could
4026 // not be allocated.
4027
4028 // Compute the size of the map transition entries to be removed.
4029 int num_removed = 0;
4030 for (int i = 0; i < number_of_descriptors(); i++) {
4031 if (!IsProperty(i)) num_removed++;
4032 }
4033
4034 // Allocate the new descriptor array.
John Reck59135872010-11-02 12:39:01 -07004035 Object* result;
4036 { MaybeObject* maybe_result = Allocate(number_of_descriptors() - num_removed);
4037 if (!maybe_result->ToObject(&result)) return maybe_result;
4038 }
Steve Blocka7e24c12009-10-30 11:49:00 +00004039 DescriptorArray* new_descriptors = DescriptorArray::cast(result);
4040
4041 // Copy the content.
4042 int next_descriptor = 0;
4043 for (int i = 0; i < number_of_descriptors(); i++) {
4044 if (IsProperty(i)) new_descriptors->CopyFrom(next_descriptor++, this, i);
4045 }
4046 ASSERT(next_descriptor == new_descriptors->number_of_descriptors());
4047
4048 return new_descriptors;
4049}
4050
4051
Kristian Monsen0d5e1162010-09-30 15:31:59 +01004052void DescriptorArray::SortUnchecked() {
Steve Blocka7e24c12009-10-30 11:49:00 +00004053 // In-place heap sort.
4054 int len = number_of_descriptors();
4055
4056 // Bottom-up max-heap construction.
Steve Block6ded16b2010-05-10 14:33:55 +01004057 // Index of the last node with children
4058 const int max_parent_index = (len / 2) - 1;
4059 for (int i = max_parent_index; i >= 0; --i) {
4060 int parent_index = i;
4061 const uint32_t parent_hash = GetKey(i)->Hash();
4062 while (parent_index <= max_parent_index) {
4063 int child_index = 2 * parent_index + 1;
Steve Blocka7e24c12009-10-30 11:49:00 +00004064 uint32_t child_hash = GetKey(child_index)->Hash();
Steve Block6ded16b2010-05-10 14:33:55 +01004065 if (child_index + 1 < len) {
4066 uint32_t right_child_hash = GetKey(child_index + 1)->Hash();
4067 if (right_child_hash > child_hash) {
4068 child_index++;
4069 child_hash = right_child_hash;
4070 }
Steve Blocka7e24c12009-10-30 11:49:00 +00004071 }
Steve Block6ded16b2010-05-10 14:33:55 +01004072 if (child_hash <= parent_hash) break;
4073 Swap(parent_index, child_index);
4074 // Now element at child_index could be < its children.
4075 parent_index = child_index; // parent_hash remains correct.
Steve Blocka7e24c12009-10-30 11:49:00 +00004076 }
4077 }
4078
4079 // Extract elements and create sorted array.
4080 for (int i = len - 1; i > 0; --i) {
4081 // Put max element at the back of the array.
4082 Swap(0, i);
4083 // Sift down the new top element.
4084 int parent_index = 0;
Steve Block6ded16b2010-05-10 14:33:55 +01004085 const uint32_t parent_hash = GetKey(parent_index)->Hash();
4086 const int max_parent_index = (i / 2) - 1;
4087 while (parent_index <= max_parent_index) {
4088 int child_index = parent_index * 2 + 1;
4089 uint32_t child_hash = GetKey(child_index)->Hash();
4090 if (child_index + 1 < i) {
4091 uint32_t right_child_hash = GetKey(child_index + 1)->Hash();
4092 if (right_child_hash > child_hash) {
4093 child_index++;
4094 child_hash = right_child_hash;
4095 }
Steve Blocka7e24c12009-10-30 11:49:00 +00004096 }
Steve Block6ded16b2010-05-10 14:33:55 +01004097 if (child_hash <= parent_hash) break;
4098 Swap(parent_index, child_index);
4099 parent_index = child_index;
Steve Blocka7e24c12009-10-30 11:49:00 +00004100 }
4101 }
Kristian Monsen0d5e1162010-09-30 15:31:59 +01004102}
Steve Blocka7e24c12009-10-30 11:49:00 +00004103
Kristian Monsen0d5e1162010-09-30 15:31:59 +01004104
4105void DescriptorArray::Sort() {
4106 SortUnchecked();
Steve Blocka7e24c12009-10-30 11:49:00 +00004107 SLOW_ASSERT(IsSortedNoDuplicates());
4108}
4109
4110
4111int DescriptorArray::BinarySearch(String* name, int low, int high) {
4112 uint32_t hash = name->Hash();
4113
4114 while (low <= high) {
4115 int mid = (low + high) / 2;
4116 String* mid_name = GetKey(mid);
4117 uint32_t mid_hash = mid_name->Hash();
4118
4119 if (mid_hash > hash) {
4120 high = mid - 1;
4121 continue;
4122 }
4123 if (mid_hash < hash) {
4124 low = mid + 1;
4125 continue;
4126 }
4127 // Found an element with the same hash-code.
4128 ASSERT(hash == mid_hash);
4129 // There might be more, so we find the first one and
4130 // check them all to see if we have a match.
4131 if (name == mid_name && !is_null_descriptor(mid)) return mid;
4132 while ((mid > low) && (GetKey(mid - 1)->Hash() == hash)) mid--;
4133 for (; (mid <= high) && (GetKey(mid)->Hash() == hash); mid++) {
4134 if (GetKey(mid)->Equals(name) && !is_null_descriptor(mid)) return mid;
4135 }
4136 break;
4137 }
4138 return kNotFound;
4139}
4140
4141
4142int DescriptorArray::LinearSearch(String* name, int len) {
4143 uint32_t hash = name->Hash();
4144 for (int number = 0; number < len; number++) {
4145 String* entry = GetKey(number);
4146 if ((entry->Hash() == hash) &&
4147 name->Equals(entry) &&
4148 !is_null_descriptor(number)) {
4149 return number;
4150 }
4151 }
4152 return kNotFound;
4153}
4154
4155
Ben Murdochb0fe1622011-05-05 13:52:32 +01004156MaybeObject* DeoptimizationInputData::Allocate(int deopt_entry_count,
4157 PretenureFlag pretenure) {
4158 ASSERT(deopt_entry_count > 0);
4159 return Heap::AllocateFixedArray(LengthFor(deopt_entry_count),
4160 pretenure);
4161}
4162
4163
4164MaybeObject* DeoptimizationOutputData::Allocate(int number_of_deopt_points,
4165 PretenureFlag pretenure) {
4166 if (number_of_deopt_points == 0) return Heap::empty_fixed_array();
4167 return Heap::AllocateFixedArray(LengthOfFixedArray(number_of_deopt_points),
4168 pretenure);
4169}
4170
4171
Steve Blocka7e24c12009-10-30 11:49:00 +00004172#ifdef DEBUG
4173bool DescriptorArray::IsEqualTo(DescriptorArray* other) {
4174 if (IsEmpty()) return other->IsEmpty();
4175 if (other->IsEmpty()) return false;
4176 if (length() != other->length()) return false;
4177 for (int i = 0; i < length(); ++i) {
4178 if (get(i) != other->get(i) && i != kContentArrayIndex) return false;
4179 }
4180 return GetContentArray()->IsEqualTo(other->GetContentArray());
4181}
4182#endif
4183
4184
4185static StaticResource<StringInputBuffer> string_input_buffer;
4186
4187
4188bool String::LooksValid() {
4189 if (!Heap::Contains(this)) return false;
4190 return true;
4191}
4192
4193
4194int String::Utf8Length() {
4195 if (IsAsciiRepresentation()) return length();
4196 // Attempt to flatten before accessing the string. It probably
4197 // doesn't make Utf8Length faster, but it is very likely that
4198 // the string will be accessed later (for example by WriteUtf8)
4199 // so it's still a good idea.
Steve Block6ded16b2010-05-10 14:33:55 +01004200 TryFlatten();
Steve Blocka7e24c12009-10-30 11:49:00 +00004201 Access<StringInputBuffer> buffer(&string_input_buffer);
4202 buffer->Reset(0, this);
4203 int result = 0;
4204 while (buffer->has_more())
4205 result += unibrow::Utf8::Length(buffer->GetNext());
4206 return result;
4207}
4208
4209
4210Vector<const char> String::ToAsciiVector() {
4211 ASSERT(IsAsciiRepresentation());
4212 ASSERT(IsFlat());
4213
4214 int offset = 0;
4215 int length = this->length();
4216 StringRepresentationTag string_tag = StringShape(this).representation_tag();
4217 String* string = this;
Steve Blockd0582a62009-12-15 09:54:21 +00004218 if (string_tag == kConsStringTag) {
Steve Blocka7e24c12009-10-30 11:49:00 +00004219 ConsString* cons = ConsString::cast(string);
4220 ASSERT(cons->second()->length() == 0);
4221 string = cons->first();
4222 string_tag = StringShape(string).representation_tag();
4223 }
4224 if (string_tag == kSeqStringTag) {
4225 SeqAsciiString* seq = SeqAsciiString::cast(string);
4226 char* start = seq->GetChars();
4227 return Vector<const char>(start + offset, length);
4228 }
4229 ASSERT(string_tag == kExternalStringTag);
4230 ExternalAsciiString* ext = ExternalAsciiString::cast(string);
4231 const char* start = ext->resource()->data();
4232 return Vector<const char>(start + offset, length);
4233}
4234
4235
4236Vector<const uc16> String::ToUC16Vector() {
4237 ASSERT(IsTwoByteRepresentation());
4238 ASSERT(IsFlat());
4239
4240 int offset = 0;
4241 int length = this->length();
4242 StringRepresentationTag string_tag = StringShape(this).representation_tag();
4243 String* string = this;
Steve Blockd0582a62009-12-15 09:54:21 +00004244 if (string_tag == kConsStringTag) {
Steve Blocka7e24c12009-10-30 11:49:00 +00004245 ConsString* cons = ConsString::cast(string);
4246 ASSERT(cons->second()->length() == 0);
4247 string = cons->first();
4248 string_tag = StringShape(string).representation_tag();
4249 }
4250 if (string_tag == kSeqStringTag) {
4251 SeqTwoByteString* seq = SeqTwoByteString::cast(string);
4252 return Vector<const uc16>(seq->GetChars() + offset, length);
4253 }
4254 ASSERT(string_tag == kExternalStringTag);
4255 ExternalTwoByteString* ext = ExternalTwoByteString::cast(string);
4256 const uc16* start =
4257 reinterpret_cast<const uc16*>(ext->resource()->data());
4258 return Vector<const uc16>(start + offset, length);
4259}
4260
4261
4262SmartPointer<char> String::ToCString(AllowNullsFlag allow_nulls,
4263 RobustnessFlag robust_flag,
4264 int offset,
4265 int length,
4266 int* length_return) {
4267 ASSERT(NativeAllocationChecker::allocation_allowed());
4268 if (robust_flag == ROBUST_STRING_TRAVERSAL && !LooksValid()) {
4269 return SmartPointer<char>(NULL);
4270 }
4271
4272 // Negative length means the to the end of the string.
4273 if (length < 0) length = kMaxInt - offset;
4274
4275 // Compute the size of the UTF-8 string. Start at the specified offset.
4276 Access<StringInputBuffer> buffer(&string_input_buffer);
4277 buffer->Reset(offset, this);
4278 int character_position = offset;
4279 int utf8_bytes = 0;
4280 while (buffer->has_more()) {
4281 uint16_t character = buffer->GetNext();
4282 if (character_position < offset + length) {
4283 utf8_bytes += unibrow::Utf8::Length(character);
4284 }
4285 character_position++;
4286 }
4287
4288 if (length_return) {
4289 *length_return = utf8_bytes;
4290 }
4291
4292 char* result = NewArray<char>(utf8_bytes + 1);
4293
4294 // Convert the UTF-16 string to a UTF-8 buffer. Start at the specified offset.
4295 buffer->Rewind();
4296 buffer->Seek(offset);
4297 character_position = offset;
4298 int utf8_byte_position = 0;
4299 while (buffer->has_more()) {
4300 uint16_t character = buffer->GetNext();
4301 if (character_position < offset + length) {
4302 if (allow_nulls == DISALLOW_NULLS && character == 0) {
4303 character = ' ';
4304 }
4305 utf8_byte_position +=
4306 unibrow::Utf8::Encode(result + utf8_byte_position, character);
4307 }
4308 character_position++;
4309 }
4310 result[utf8_byte_position] = 0;
4311 return SmartPointer<char>(result);
4312}
4313
4314
4315SmartPointer<char> String::ToCString(AllowNullsFlag allow_nulls,
4316 RobustnessFlag robust_flag,
4317 int* length_return) {
4318 return ToCString(allow_nulls, robust_flag, 0, -1, length_return);
4319}
4320
4321
4322const uc16* String::GetTwoByteData() {
4323 return GetTwoByteData(0);
4324}
4325
4326
4327const uc16* String::GetTwoByteData(unsigned start) {
4328 ASSERT(!IsAsciiRepresentation());
4329 switch (StringShape(this).representation_tag()) {
4330 case kSeqStringTag:
4331 return SeqTwoByteString::cast(this)->SeqTwoByteStringGetData(start);
4332 case kExternalStringTag:
4333 return ExternalTwoByteString::cast(this)->
4334 ExternalTwoByteStringGetData(start);
Steve Blocka7e24c12009-10-30 11:49:00 +00004335 case kConsStringTag:
4336 UNREACHABLE();
4337 return NULL;
4338 }
4339 UNREACHABLE();
4340 return NULL;
4341}
4342
4343
4344SmartPointer<uc16> String::ToWideCString(RobustnessFlag robust_flag) {
4345 ASSERT(NativeAllocationChecker::allocation_allowed());
4346
4347 if (robust_flag == ROBUST_STRING_TRAVERSAL && !LooksValid()) {
4348 return SmartPointer<uc16>();
4349 }
4350
4351 Access<StringInputBuffer> buffer(&string_input_buffer);
4352 buffer->Reset(this);
4353
4354 uc16* result = NewArray<uc16>(length() + 1);
4355
4356 int i = 0;
4357 while (buffer->has_more()) {
4358 uint16_t character = buffer->GetNext();
4359 result[i++] = character;
4360 }
4361 result[i] = 0;
4362 return SmartPointer<uc16>(result);
4363}
4364
4365
4366const uc16* SeqTwoByteString::SeqTwoByteStringGetData(unsigned start) {
4367 return reinterpret_cast<uc16*>(
4368 reinterpret_cast<char*>(this) - kHeapObjectTag + kHeaderSize) + start;
4369}
4370
4371
4372void SeqTwoByteString::SeqTwoByteStringReadBlockIntoBuffer(ReadBlockBuffer* rbb,
4373 unsigned* offset_ptr,
4374 unsigned max_chars) {
4375 unsigned chars_read = 0;
4376 unsigned offset = *offset_ptr;
4377 while (chars_read < max_chars) {
4378 uint16_t c = *reinterpret_cast<uint16_t*>(
4379 reinterpret_cast<char*>(this) -
4380 kHeapObjectTag + kHeaderSize + offset * kShortSize);
4381 if (c <= kMaxAsciiCharCode) {
4382 // Fast case for ASCII characters. Cursor is an input output argument.
4383 if (!unibrow::CharacterStream::EncodeAsciiCharacter(c,
4384 rbb->util_buffer,
4385 rbb->capacity,
4386 rbb->cursor)) {
4387 break;
4388 }
4389 } else {
4390 if (!unibrow::CharacterStream::EncodeNonAsciiCharacter(c,
4391 rbb->util_buffer,
4392 rbb->capacity,
4393 rbb->cursor)) {
4394 break;
4395 }
4396 }
4397 offset++;
4398 chars_read++;
4399 }
4400 *offset_ptr = offset;
4401 rbb->remaining += chars_read;
4402}
4403
4404
4405const unibrow::byte* SeqAsciiString::SeqAsciiStringReadBlock(
4406 unsigned* remaining,
4407 unsigned* offset_ptr,
4408 unsigned max_chars) {
4409 const unibrow::byte* b = reinterpret_cast<unibrow::byte*>(this) -
4410 kHeapObjectTag + kHeaderSize + *offset_ptr * kCharSize;
4411 *remaining = max_chars;
4412 *offset_ptr += max_chars;
4413 return b;
4414}
4415
4416
4417// This will iterate unless the block of string data spans two 'halves' of
4418// a ConsString, in which case it will recurse. Since the block of string
4419// data to be read has a maximum size this limits the maximum recursion
4420// depth to something sane. Since C++ does not have tail call recursion
4421// elimination, the iteration must be explicit. Since this is not an
4422// -IntoBuffer method it can delegate to one of the efficient
4423// *AsciiStringReadBlock routines.
4424const unibrow::byte* ConsString::ConsStringReadBlock(ReadBlockBuffer* rbb,
4425 unsigned* offset_ptr,
4426 unsigned max_chars) {
4427 ConsString* current = this;
4428 unsigned offset = *offset_ptr;
4429 int offset_correction = 0;
4430
4431 while (true) {
4432 String* left = current->first();
4433 unsigned left_length = (unsigned)left->length();
4434 if (left_length > offset &&
4435 (max_chars <= left_length - offset ||
4436 (rbb->capacity <= left_length - offset &&
4437 (max_chars = left_length - offset, true)))) { // comma operator!
4438 // Left hand side only - iterate unless we have reached the bottom of
4439 // the cons tree. The assignment on the left of the comma operator is
4440 // in order to make use of the fact that the -IntoBuffer routines can
4441 // produce at most 'capacity' characters. This enables us to postpone
4442 // the point where we switch to the -IntoBuffer routines (below) in order
4443 // to maximize the chances of delegating a big chunk of work to the
4444 // efficient *AsciiStringReadBlock routines.
4445 if (StringShape(left).IsCons()) {
4446 current = ConsString::cast(left);
4447 continue;
4448 } else {
4449 const unibrow::byte* answer =
4450 String::ReadBlock(left, rbb, &offset, max_chars);
4451 *offset_ptr = offset + offset_correction;
4452 return answer;
4453 }
4454 } else if (left_length <= offset) {
4455 // Right hand side only - iterate unless we have reached the bottom of
4456 // the cons tree.
4457 String* right = current->second();
4458 offset -= left_length;
4459 offset_correction += left_length;
4460 if (StringShape(right).IsCons()) {
4461 current = ConsString::cast(right);
4462 continue;
4463 } else {
4464 const unibrow::byte* answer =
4465 String::ReadBlock(right, rbb, &offset, max_chars);
4466 *offset_ptr = offset + offset_correction;
4467 return answer;
4468 }
4469 } else {
4470 // The block to be read spans two sides of the ConsString, so we call the
4471 // -IntoBuffer version, which will recurse. The -IntoBuffer methods
4472 // are able to assemble data from several part strings because they use
4473 // the util_buffer to store their data and never return direct pointers
4474 // to their storage. We don't try to read more than the buffer capacity
4475 // here or we can get too much recursion.
4476 ASSERT(rbb->remaining == 0);
4477 ASSERT(rbb->cursor == 0);
4478 current->ConsStringReadBlockIntoBuffer(
4479 rbb,
4480 &offset,
4481 max_chars > rbb->capacity ? rbb->capacity : max_chars);
4482 *offset_ptr = offset + offset_correction;
4483 return rbb->util_buffer;
4484 }
4485 }
4486}
4487
4488
Steve Blocka7e24c12009-10-30 11:49:00 +00004489uint16_t ExternalAsciiString::ExternalAsciiStringGet(int index) {
4490 ASSERT(index >= 0 && index < length());
4491 return resource()->data()[index];
4492}
4493
4494
4495const unibrow::byte* ExternalAsciiString::ExternalAsciiStringReadBlock(
4496 unsigned* remaining,
4497 unsigned* offset_ptr,
4498 unsigned max_chars) {
4499 // Cast const char* to unibrow::byte* (signedness difference).
4500 const unibrow::byte* b =
4501 reinterpret_cast<const unibrow::byte*>(resource()->data()) + *offset_ptr;
4502 *remaining = max_chars;
4503 *offset_ptr += max_chars;
4504 return b;
4505}
4506
4507
4508const uc16* ExternalTwoByteString::ExternalTwoByteStringGetData(
4509 unsigned start) {
4510 return resource()->data() + start;
4511}
4512
4513
4514uint16_t ExternalTwoByteString::ExternalTwoByteStringGet(int index) {
4515 ASSERT(index >= 0 && index < length());
4516 return resource()->data()[index];
4517}
4518
4519
4520void ExternalTwoByteString::ExternalTwoByteStringReadBlockIntoBuffer(
4521 ReadBlockBuffer* rbb,
4522 unsigned* offset_ptr,
4523 unsigned max_chars) {
4524 unsigned chars_read = 0;
4525 unsigned offset = *offset_ptr;
4526 const uint16_t* data = resource()->data();
4527 while (chars_read < max_chars) {
4528 uint16_t c = data[offset];
4529 if (c <= kMaxAsciiCharCode) {
4530 // Fast case for ASCII characters. Cursor is an input output argument.
4531 if (!unibrow::CharacterStream::EncodeAsciiCharacter(c,
4532 rbb->util_buffer,
4533 rbb->capacity,
4534 rbb->cursor))
4535 break;
4536 } else {
4537 if (!unibrow::CharacterStream::EncodeNonAsciiCharacter(c,
4538 rbb->util_buffer,
4539 rbb->capacity,
4540 rbb->cursor))
4541 break;
4542 }
4543 offset++;
4544 chars_read++;
4545 }
4546 *offset_ptr = offset;
4547 rbb->remaining += chars_read;
4548}
4549
4550
4551void SeqAsciiString::SeqAsciiStringReadBlockIntoBuffer(ReadBlockBuffer* rbb,
4552 unsigned* offset_ptr,
4553 unsigned max_chars) {
4554 unsigned capacity = rbb->capacity - rbb->cursor;
4555 if (max_chars > capacity) max_chars = capacity;
4556 memcpy(rbb->util_buffer + rbb->cursor,
4557 reinterpret_cast<char*>(this) - kHeapObjectTag + kHeaderSize +
4558 *offset_ptr * kCharSize,
4559 max_chars);
4560 rbb->remaining += max_chars;
4561 *offset_ptr += max_chars;
4562 rbb->cursor += max_chars;
4563}
4564
4565
4566void ExternalAsciiString::ExternalAsciiStringReadBlockIntoBuffer(
4567 ReadBlockBuffer* rbb,
4568 unsigned* offset_ptr,
4569 unsigned max_chars) {
4570 unsigned capacity = rbb->capacity - rbb->cursor;
4571 if (max_chars > capacity) max_chars = capacity;
4572 memcpy(rbb->util_buffer + rbb->cursor,
4573 resource()->data() + *offset_ptr,
4574 max_chars);
4575 rbb->remaining += max_chars;
4576 *offset_ptr += max_chars;
4577 rbb->cursor += max_chars;
4578}
4579
4580
4581// This method determines the type of string involved and then copies
4582// a whole chunk of characters into a buffer, or returns a pointer to a buffer
4583// where they can be found. The pointer is not necessarily valid across a GC
4584// (see AsciiStringReadBlock).
4585const unibrow::byte* String::ReadBlock(String* input,
4586 ReadBlockBuffer* rbb,
4587 unsigned* offset_ptr,
4588 unsigned max_chars) {
4589 ASSERT(*offset_ptr <= static_cast<unsigned>(input->length()));
4590 if (max_chars == 0) {
4591 rbb->remaining = 0;
4592 return NULL;
4593 }
4594 switch (StringShape(input).representation_tag()) {
4595 case kSeqStringTag:
4596 if (input->IsAsciiRepresentation()) {
4597 SeqAsciiString* str = SeqAsciiString::cast(input);
4598 return str->SeqAsciiStringReadBlock(&rbb->remaining,
4599 offset_ptr,
4600 max_chars);
4601 } else {
4602 SeqTwoByteString* str = SeqTwoByteString::cast(input);
4603 str->SeqTwoByteStringReadBlockIntoBuffer(rbb,
4604 offset_ptr,
4605 max_chars);
4606 return rbb->util_buffer;
4607 }
4608 case kConsStringTag:
4609 return ConsString::cast(input)->ConsStringReadBlock(rbb,
4610 offset_ptr,
4611 max_chars);
Steve Blocka7e24c12009-10-30 11:49:00 +00004612 case kExternalStringTag:
4613 if (input->IsAsciiRepresentation()) {
4614 return ExternalAsciiString::cast(input)->ExternalAsciiStringReadBlock(
4615 &rbb->remaining,
4616 offset_ptr,
4617 max_chars);
4618 } else {
4619 ExternalTwoByteString::cast(input)->
4620 ExternalTwoByteStringReadBlockIntoBuffer(rbb,
4621 offset_ptr,
4622 max_chars);
4623 return rbb->util_buffer;
4624 }
4625 default:
4626 break;
4627 }
4628
4629 UNREACHABLE();
4630 return 0;
4631}
4632
4633
4634Relocatable* Relocatable::top_ = NULL;
4635
4636
4637void Relocatable::PostGarbageCollectionProcessing() {
4638 Relocatable* current = top_;
4639 while (current != NULL) {
4640 current->PostGarbageCollection();
4641 current = current->prev_;
4642 }
4643}
4644
4645
4646// Reserve space for statics needing saving and restoring.
4647int Relocatable::ArchiveSpacePerThread() {
4648 return sizeof(top_);
4649}
4650
4651
4652// Archive statics that are thread local.
4653char* Relocatable::ArchiveState(char* to) {
4654 *reinterpret_cast<Relocatable**>(to) = top_;
4655 top_ = NULL;
4656 return to + ArchiveSpacePerThread();
4657}
4658
4659
4660// Restore statics that are thread local.
4661char* Relocatable::RestoreState(char* from) {
4662 top_ = *reinterpret_cast<Relocatable**>(from);
4663 return from + ArchiveSpacePerThread();
4664}
4665
4666
4667char* Relocatable::Iterate(ObjectVisitor* v, char* thread_storage) {
4668 Relocatable* top = *reinterpret_cast<Relocatable**>(thread_storage);
4669 Iterate(v, top);
4670 return thread_storage + ArchiveSpacePerThread();
4671}
4672
4673
4674void Relocatable::Iterate(ObjectVisitor* v) {
4675 Iterate(v, top_);
4676}
4677
4678
4679void Relocatable::Iterate(ObjectVisitor* v, Relocatable* top) {
4680 Relocatable* current = top;
4681 while (current != NULL) {
4682 current->IterateInstance(v);
4683 current = current->prev_;
4684 }
4685}
4686
4687
4688FlatStringReader::FlatStringReader(Handle<String> str)
4689 : str_(str.location()),
4690 length_(str->length()) {
4691 PostGarbageCollection();
4692}
4693
4694
4695FlatStringReader::FlatStringReader(Vector<const char> input)
4696 : str_(0),
4697 is_ascii_(true),
4698 length_(input.length()),
4699 start_(input.start()) { }
4700
4701
4702void FlatStringReader::PostGarbageCollection() {
4703 if (str_ == NULL) return;
4704 Handle<String> str(str_);
4705 ASSERT(str->IsFlat());
4706 is_ascii_ = str->IsAsciiRepresentation();
4707 if (is_ascii_) {
4708 start_ = str->ToAsciiVector().start();
4709 } else {
4710 start_ = str->ToUC16Vector().start();
4711 }
4712}
4713
4714
4715void StringInputBuffer::Seek(unsigned pos) {
4716 Reset(pos, input_);
4717}
4718
4719
4720void SafeStringInputBuffer::Seek(unsigned pos) {
4721 Reset(pos, input_);
4722}
4723
4724
4725// This method determines the type of string involved and then copies
4726// a whole chunk of characters into a buffer. It can be used with strings
4727// that have been glued together to form a ConsString and which must cooperate
4728// to fill up a buffer.
4729void String::ReadBlockIntoBuffer(String* input,
4730 ReadBlockBuffer* rbb,
4731 unsigned* offset_ptr,
4732 unsigned max_chars) {
4733 ASSERT(*offset_ptr <= (unsigned)input->length());
4734 if (max_chars == 0) return;
4735
4736 switch (StringShape(input).representation_tag()) {
4737 case kSeqStringTag:
4738 if (input->IsAsciiRepresentation()) {
4739 SeqAsciiString::cast(input)->SeqAsciiStringReadBlockIntoBuffer(rbb,
4740 offset_ptr,
4741 max_chars);
4742 return;
4743 } else {
4744 SeqTwoByteString::cast(input)->SeqTwoByteStringReadBlockIntoBuffer(rbb,
4745 offset_ptr,
4746 max_chars);
4747 return;
4748 }
4749 case kConsStringTag:
4750 ConsString::cast(input)->ConsStringReadBlockIntoBuffer(rbb,
4751 offset_ptr,
4752 max_chars);
4753 return;
Steve Blocka7e24c12009-10-30 11:49:00 +00004754 case kExternalStringTag:
4755 if (input->IsAsciiRepresentation()) {
Steve Blockd0582a62009-12-15 09:54:21 +00004756 ExternalAsciiString::cast(input)->
4757 ExternalAsciiStringReadBlockIntoBuffer(rbb, offset_ptr, max_chars);
4758 } else {
4759 ExternalTwoByteString::cast(input)->
4760 ExternalTwoByteStringReadBlockIntoBuffer(rbb,
4761 offset_ptr,
4762 max_chars);
Steve Blocka7e24c12009-10-30 11:49:00 +00004763 }
4764 return;
4765 default:
4766 break;
4767 }
4768
4769 UNREACHABLE();
4770 return;
4771}
4772
4773
4774const unibrow::byte* String::ReadBlock(String* input,
4775 unibrow::byte* util_buffer,
4776 unsigned capacity,
4777 unsigned* remaining,
4778 unsigned* offset_ptr) {
4779 ASSERT(*offset_ptr <= (unsigned)input->length());
4780 unsigned chars = input->length() - *offset_ptr;
4781 ReadBlockBuffer rbb(util_buffer, 0, capacity, 0);
4782 const unibrow::byte* answer = ReadBlock(input, &rbb, offset_ptr, chars);
4783 ASSERT(rbb.remaining <= static_cast<unsigned>(input->length()));
4784 *remaining = rbb.remaining;
4785 return answer;
4786}
4787
4788
4789const unibrow::byte* String::ReadBlock(String** raw_input,
4790 unibrow::byte* util_buffer,
4791 unsigned capacity,
4792 unsigned* remaining,
4793 unsigned* offset_ptr) {
4794 Handle<String> input(raw_input);
4795 ASSERT(*offset_ptr <= (unsigned)input->length());
4796 unsigned chars = input->length() - *offset_ptr;
4797 if (chars > capacity) chars = capacity;
4798 ReadBlockBuffer rbb(util_buffer, 0, capacity, 0);
4799 ReadBlockIntoBuffer(*input, &rbb, offset_ptr, chars);
4800 ASSERT(rbb.remaining <= static_cast<unsigned>(input->length()));
4801 *remaining = rbb.remaining;
4802 return rbb.util_buffer;
4803}
4804
4805
4806// This will iterate unless the block of string data spans two 'halves' of
4807// a ConsString, in which case it will recurse. Since the block of string
4808// data to be read has a maximum size this limits the maximum recursion
4809// depth to something sane. Since C++ does not have tail call recursion
4810// elimination, the iteration must be explicit.
4811void ConsString::ConsStringReadBlockIntoBuffer(ReadBlockBuffer* rbb,
4812 unsigned* offset_ptr,
4813 unsigned max_chars) {
4814 ConsString* current = this;
4815 unsigned offset = *offset_ptr;
4816 int offset_correction = 0;
4817
4818 while (true) {
4819 String* left = current->first();
4820 unsigned left_length = (unsigned)left->length();
4821 if (left_length > offset &&
4822 max_chars <= left_length - offset) {
4823 // Left hand side only - iterate unless we have reached the bottom of
4824 // the cons tree.
4825 if (StringShape(left).IsCons()) {
4826 current = ConsString::cast(left);
4827 continue;
4828 } else {
4829 String::ReadBlockIntoBuffer(left, rbb, &offset, max_chars);
4830 *offset_ptr = offset + offset_correction;
4831 return;
4832 }
4833 } else if (left_length <= offset) {
4834 // Right hand side only - iterate unless we have reached the bottom of
4835 // the cons tree.
4836 offset -= left_length;
4837 offset_correction += left_length;
4838 String* right = current->second();
4839 if (StringShape(right).IsCons()) {
4840 current = ConsString::cast(right);
4841 continue;
4842 } else {
4843 String::ReadBlockIntoBuffer(right, rbb, &offset, max_chars);
4844 *offset_ptr = offset + offset_correction;
4845 return;
4846 }
4847 } else {
4848 // The block to be read spans two sides of the ConsString, so we recurse.
4849 // First recurse on the left.
4850 max_chars -= left_length - offset;
4851 String::ReadBlockIntoBuffer(left, rbb, &offset, left_length - offset);
4852 // We may have reached the max or there may not have been enough space
4853 // in the buffer for the characters in the left hand side.
4854 if (offset == left_length) {
4855 // Recurse on the right.
4856 String* right = String::cast(current->second());
4857 offset -= left_length;
4858 offset_correction += left_length;
4859 String::ReadBlockIntoBuffer(right, rbb, &offset, max_chars);
4860 }
4861 *offset_ptr = offset + offset_correction;
4862 return;
4863 }
4864 }
4865}
4866
4867
Steve Blocka7e24c12009-10-30 11:49:00 +00004868uint16_t ConsString::ConsStringGet(int index) {
4869 ASSERT(index >= 0 && index < this->length());
4870
4871 // Check for a flattened cons string
4872 if (second()->length() == 0) {
4873 String* left = first();
4874 return left->Get(index);
4875 }
4876
4877 String* string = String::cast(this);
4878
4879 while (true) {
4880 if (StringShape(string).IsCons()) {
4881 ConsString* cons_string = ConsString::cast(string);
4882 String* left = cons_string->first();
4883 if (left->length() > index) {
4884 string = left;
4885 } else {
4886 index -= left->length();
4887 string = cons_string->second();
4888 }
4889 } else {
4890 return string->Get(index);
4891 }
4892 }
4893
4894 UNREACHABLE();
4895 return 0;
4896}
4897
4898
4899template <typename sinkchar>
4900void String::WriteToFlat(String* src,
4901 sinkchar* sink,
4902 int f,
4903 int t) {
4904 String* source = src;
4905 int from = f;
4906 int to = t;
4907 while (true) {
4908 ASSERT(0 <= from && from <= to && to <= source->length());
4909 switch (StringShape(source).full_representation_tag()) {
4910 case kAsciiStringTag | kExternalStringTag: {
4911 CopyChars(sink,
4912 ExternalAsciiString::cast(source)->resource()->data() + from,
4913 to - from);
4914 return;
4915 }
4916 case kTwoByteStringTag | kExternalStringTag: {
4917 const uc16* data =
4918 ExternalTwoByteString::cast(source)->resource()->data();
4919 CopyChars(sink,
4920 data + from,
4921 to - from);
4922 return;
4923 }
4924 case kAsciiStringTag | kSeqStringTag: {
4925 CopyChars(sink,
4926 SeqAsciiString::cast(source)->GetChars() + from,
4927 to - from);
4928 return;
4929 }
4930 case kTwoByteStringTag | kSeqStringTag: {
4931 CopyChars(sink,
4932 SeqTwoByteString::cast(source)->GetChars() + from,
4933 to - from);
4934 return;
4935 }
Steve Blocka7e24c12009-10-30 11:49:00 +00004936 case kAsciiStringTag | kConsStringTag:
4937 case kTwoByteStringTag | kConsStringTag: {
4938 ConsString* cons_string = ConsString::cast(source);
4939 String* first = cons_string->first();
4940 int boundary = first->length();
4941 if (to - boundary >= boundary - from) {
4942 // Right hand side is longer. Recurse over left.
4943 if (from < boundary) {
4944 WriteToFlat(first, sink, from, boundary);
4945 sink += boundary - from;
4946 from = 0;
4947 } else {
4948 from -= boundary;
4949 }
4950 to -= boundary;
4951 source = cons_string->second();
4952 } else {
4953 // Left hand side is longer. Recurse over right.
4954 if (to > boundary) {
4955 String* second = cons_string->second();
4956 WriteToFlat(second,
4957 sink + boundary - from,
4958 0,
4959 to - boundary);
4960 to = boundary;
4961 }
4962 source = first;
4963 }
4964 break;
4965 }
4966 }
4967 }
4968}
4969
4970
Steve Blocka7e24c12009-10-30 11:49:00 +00004971template <typename IteratorA, typename IteratorB>
4972static inline bool CompareStringContents(IteratorA* ia, IteratorB* ib) {
4973 // General slow case check. We know that the ia and ib iterators
4974 // have the same length.
4975 while (ia->has_more()) {
4976 uc32 ca = ia->GetNext();
4977 uc32 cb = ib->GetNext();
4978 if (ca != cb)
4979 return false;
4980 }
4981 return true;
4982}
4983
4984
4985// Compares the contents of two strings by reading and comparing
4986// int-sized blocks of characters.
4987template <typename Char>
4988static inline bool CompareRawStringContents(Vector<Char> a, Vector<Char> b) {
4989 int length = a.length();
4990 ASSERT_EQ(length, b.length());
4991 const Char* pa = a.start();
4992 const Char* pb = b.start();
4993 int i = 0;
4994#ifndef V8_HOST_CAN_READ_UNALIGNED
4995 // If this architecture isn't comfortable reading unaligned ints
4996 // then we have to check that the strings are aligned before
4997 // comparing them blockwise.
4998 const int kAlignmentMask = sizeof(uint32_t) - 1; // NOLINT
4999 uint32_t pa_addr = reinterpret_cast<uint32_t>(pa);
5000 uint32_t pb_addr = reinterpret_cast<uint32_t>(pb);
5001 if (((pa_addr & kAlignmentMask) | (pb_addr & kAlignmentMask)) == 0) {
5002#endif
5003 const int kStepSize = sizeof(int) / sizeof(Char); // NOLINT
5004 int endpoint = length - kStepSize;
5005 // Compare blocks until we reach near the end of the string.
5006 for (; i <= endpoint; i += kStepSize) {
5007 uint32_t wa = *reinterpret_cast<const uint32_t*>(pa + i);
5008 uint32_t wb = *reinterpret_cast<const uint32_t*>(pb + i);
5009 if (wa != wb) {
5010 return false;
5011 }
5012 }
5013#ifndef V8_HOST_CAN_READ_UNALIGNED
5014 }
5015#endif
5016 // Compare the remaining characters that didn't fit into a block.
5017 for (; i < length; i++) {
5018 if (a[i] != b[i]) {
5019 return false;
5020 }
5021 }
5022 return true;
5023}
5024
5025
5026static StringInputBuffer string_compare_buffer_b;
5027
5028
5029template <typename IteratorA>
5030static inline bool CompareStringContentsPartial(IteratorA* ia, String* b) {
5031 if (b->IsFlat()) {
5032 if (b->IsAsciiRepresentation()) {
5033 VectorIterator<char> ib(b->ToAsciiVector());
5034 return CompareStringContents(ia, &ib);
5035 } else {
5036 VectorIterator<uc16> ib(b->ToUC16Vector());
5037 return CompareStringContents(ia, &ib);
5038 }
5039 } else {
5040 string_compare_buffer_b.Reset(0, b);
5041 return CompareStringContents(ia, &string_compare_buffer_b);
5042 }
5043}
5044
5045
5046static StringInputBuffer string_compare_buffer_a;
5047
5048
5049bool String::SlowEquals(String* other) {
5050 // Fast check: negative check with lengths.
5051 int len = length();
5052 if (len != other->length()) return false;
5053 if (len == 0) return true;
5054
5055 // Fast check: if hash code is computed for both strings
5056 // a fast negative check can be performed.
5057 if (HasHashCode() && other->HasHashCode()) {
5058 if (Hash() != other->Hash()) return false;
5059 }
5060
Leon Clarkef7060e22010-06-03 12:02:55 +01005061 // We know the strings are both non-empty. Compare the first chars
5062 // before we try to flatten the strings.
5063 if (this->Get(0) != other->Get(0)) return false;
5064
5065 String* lhs = this->TryFlattenGetString();
5066 String* rhs = other->TryFlattenGetString();
5067
5068 if (StringShape(lhs).IsSequentialAscii() &&
5069 StringShape(rhs).IsSequentialAscii()) {
5070 const char* str1 = SeqAsciiString::cast(lhs)->GetChars();
5071 const char* str2 = SeqAsciiString::cast(rhs)->GetChars();
Steve Blocka7e24c12009-10-30 11:49:00 +00005072 return CompareRawStringContents(Vector<const char>(str1, len),
5073 Vector<const char>(str2, len));
5074 }
5075
Leon Clarkef7060e22010-06-03 12:02:55 +01005076 if (lhs->IsFlat()) {
Ben Murdochbb769b22010-08-11 14:56:33 +01005077 if (lhs->IsAsciiRepresentation()) {
Leon Clarkef7060e22010-06-03 12:02:55 +01005078 Vector<const char> vec1 = lhs->ToAsciiVector();
5079 if (rhs->IsFlat()) {
5080 if (rhs->IsAsciiRepresentation()) {
5081 Vector<const char> vec2 = rhs->ToAsciiVector();
Steve Blocka7e24c12009-10-30 11:49:00 +00005082 return CompareRawStringContents(vec1, vec2);
5083 } else {
5084 VectorIterator<char> buf1(vec1);
Leon Clarkef7060e22010-06-03 12:02:55 +01005085 VectorIterator<uc16> ib(rhs->ToUC16Vector());
Steve Blocka7e24c12009-10-30 11:49:00 +00005086 return CompareStringContents(&buf1, &ib);
5087 }
5088 } else {
5089 VectorIterator<char> buf1(vec1);
Leon Clarkef7060e22010-06-03 12:02:55 +01005090 string_compare_buffer_b.Reset(0, rhs);
Steve Blocka7e24c12009-10-30 11:49:00 +00005091 return CompareStringContents(&buf1, &string_compare_buffer_b);
5092 }
5093 } else {
Leon Clarkef7060e22010-06-03 12:02:55 +01005094 Vector<const uc16> vec1 = lhs->ToUC16Vector();
5095 if (rhs->IsFlat()) {
5096 if (rhs->IsAsciiRepresentation()) {
Steve Blocka7e24c12009-10-30 11:49:00 +00005097 VectorIterator<uc16> buf1(vec1);
Leon Clarkef7060e22010-06-03 12:02:55 +01005098 VectorIterator<char> ib(rhs->ToAsciiVector());
Steve Blocka7e24c12009-10-30 11:49:00 +00005099 return CompareStringContents(&buf1, &ib);
5100 } else {
Leon Clarkef7060e22010-06-03 12:02:55 +01005101 Vector<const uc16> vec2(rhs->ToUC16Vector());
Steve Blocka7e24c12009-10-30 11:49:00 +00005102 return CompareRawStringContents(vec1, vec2);
5103 }
5104 } else {
5105 VectorIterator<uc16> buf1(vec1);
Leon Clarkef7060e22010-06-03 12:02:55 +01005106 string_compare_buffer_b.Reset(0, rhs);
Steve Blocka7e24c12009-10-30 11:49:00 +00005107 return CompareStringContents(&buf1, &string_compare_buffer_b);
5108 }
5109 }
5110 } else {
Leon Clarkef7060e22010-06-03 12:02:55 +01005111 string_compare_buffer_a.Reset(0, lhs);
5112 return CompareStringContentsPartial(&string_compare_buffer_a, rhs);
Steve Blocka7e24c12009-10-30 11:49:00 +00005113 }
5114}
5115
5116
5117bool String::MarkAsUndetectable() {
5118 if (StringShape(this).IsSymbol()) return false;
5119
5120 Map* map = this->map();
Steve Blockd0582a62009-12-15 09:54:21 +00005121 if (map == Heap::string_map()) {
5122 this->set_map(Heap::undetectable_string_map());
Steve Blocka7e24c12009-10-30 11:49:00 +00005123 return true;
Steve Blockd0582a62009-12-15 09:54:21 +00005124 } else if (map == Heap::ascii_string_map()) {
5125 this->set_map(Heap::undetectable_ascii_string_map());
Steve Blocka7e24c12009-10-30 11:49:00 +00005126 return true;
5127 }
5128 // Rest cannot be marked as undetectable
5129 return false;
5130}
5131
5132
5133bool String::IsEqualTo(Vector<const char> str) {
5134 int slen = length();
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -08005135 Access<ScannerConstants::Utf8Decoder>
5136 decoder(ScannerConstants::utf8_decoder());
Steve Blocka7e24c12009-10-30 11:49:00 +00005137 decoder->Reset(str.start(), str.length());
5138 int i;
5139 for (i = 0; i < slen && decoder->has_more(); i++) {
5140 uc32 r = decoder->GetNext();
5141 if (Get(i) != r) return false;
5142 }
5143 return i == slen && !decoder->has_more();
5144}
5145
5146
Steve Block9fac8402011-05-12 15:51:54 +01005147bool String::IsAsciiEqualTo(Vector<const char> str) {
5148 int slen = length();
5149 if (str.length() != slen) return false;
5150 for (int i = 0; i < slen; i++) {
5151 if (Get(i) != static_cast<uint16_t>(str[i])) return false;
5152 }
5153 return true;
5154}
5155
5156
5157bool String::IsTwoByteEqualTo(Vector<const uc16> str) {
5158 int slen = length();
5159 if (str.length() != slen) return false;
5160 for (int i = 0; i < slen; i++) {
5161 if (Get(i) != str[i]) return false;
5162 }
5163 return true;
5164}
5165
5166
Steve Block6ded16b2010-05-10 14:33:55 +01005167template <typename schar>
5168static inline uint32_t HashSequentialString(const schar* chars, int length) {
5169 StringHasher hasher(length);
5170 if (!hasher.has_trivial_hash()) {
5171 int i;
5172 for (i = 0; hasher.is_array_index() && (i < length); i++) {
5173 hasher.AddCharacter(chars[i]);
5174 }
5175 for (; i < length; i++) {
5176 hasher.AddCharacterNoIndex(chars[i]);
5177 }
5178 }
5179 return hasher.GetHashField();
5180}
5181
5182
Steve Blocka7e24c12009-10-30 11:49:00 +00005183uint32_t String::ComputeAndSetHash() {
5184 // Should only be called if hash code has not yet been computed.
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01005185 ASSERT(!HasHashCode());
Steve Blocka7e24c12009-10-30 11:49:00 +00005186
Steve Block6ded16b2010-05-10 14:33:55 +01005187 const int len = length();
5188
Steve Blocka7e24c12009-10-30 11:49:00 +00005189 // Compute the hash code.
Steve Block6ded16b2010-05-10 14:33:55 +01005190 uint32_t field = 0;
5191 if (StringShape(this).IsSequentialAscii()) {
5192 field = HashSequentialString(SeqAsciiString::cast(this)->GetChars(), len);
5193 } else if (StringShape(this).IsSequentialTwoByte()) {
5194 field = HashSequentialString(SeqTwoByteString::cast(this)->GetChars(), len);
5195 } else {
5196 StringInputBuffer buffer(this);
5197 field = ComputeHashField(&buffer, len);
5198 }
Steve Blocka7e24c12009-10-30 11:49:00 +00005199
5200 // Store the hash code in the object.
Steve Blockd0582a62009-12-15 09:54:21 +00005201 set_hash_field(field);
Steve Blocka7e24c12009-10-30 11:49:00 +00005202
5203 // Check the hash code is there.
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01005204 ASSERT(HasHashCode());
Steve Blocka7e24c12009-10-30 11:49:00 +00005205 uint32_t result = field >> kHashShift;
5206 ASSERT(result != 0); // Ensure that the hash value of 0 is never computed.
5207 return result;
5208}
5209
5210
5211bool String::ComputeArrayIndex(unibrow::CharacterStream* buffer,
5212 uint32_t* index,
5213 int length) {
5214 if (length == 0 || length > kMaxArrayIndexSize) return false;
5215 uc32 ch = buffer->GetNext();
5216
5217 // If the string begins with a '0' character, it must only consist
5218 // of it to be a legal array index.
5219 if (ch == '0') {
5220 *index = 0;
5221 return length == 1;
5222 }
5223
5224 // Convert string to uint32 array index; character by character.
5225 int d = ch - '0';
5226 if (d < 0 || d > 9) return false;
5227 uint32_t result = d;
5228 while (buffer->has_more()) {
5229 d = buffer->GetNext() - '0';
5230 if (d < 0 || d > 9) return false;
5231 // Check that the new result is below the 32 bit limit.
5232 if (result > 429496729U - ((d > 5) ? 1 : 0)) return false;
5233 result = (result * 10) + d;
5234 }
5235
5236 *index = result;
5237 return true;
5238}
5239
5240
5241bool String::SlowAsArrayIndex(uint32_t* index) {
5242 if (length() <= kMaxCachedArrayIndexLength) {
5243 Hash(); // force computation of hash code
Steve Blockd0582a62009-12-15 09:54:21 +00005244 uint32_t field = hash_field();
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01005245 if ((field & kIsNotArrayIndexMask) != 0) return false;
Steve Blockd0582a62009-12-15 09:54:21 +00005246 // Isolate the array index form the full hash field.
5247 *index = (kArrayIndexHashMask & field) >> kHashShift;
Steve Blocka7e24c12009-10-30 11:49:00 +00005248 return true;
5249 } else {
5250 StringInputBuffer buffer(this);
5251 return ComputeArrayIndex(&buffer, index, length());
5252 }
5253}
5254
5255
Iain Merrick9ac36c92010-09-13 15:29:50 +01005256uint32_t StringHasher::MakeArrayIndexHash(uint32_t value, int length) {
Kristian Monsen80d68ea2010-09-08 11:05:35 +01005257 // For array indexes mix the length into the hash as an array index could
5258 // be zero.
5259 ASSERT(length > 0);
5260 ASSERT(length <= String::kMaxArrayIndexSize);
5261 ASSERT(TenToThe(String::kMaxCachedArrayIndexLength) <
5262 (1 << String::kArrayIndexValueBits));
Iain Merrick9ac36c92010-09-13 15:29:50 +01005263
5264 value <<= String::kHashShift;
Kristian Monsen80d68ea2010-09-08 11:05:35 +01005265 value |= length << String::kArrayIndexHashLengthShift;
Iain Merrick9ac36c92010-09-13 15:29:50 +01005266
5267 ASSERT((value & String::kIsNotArrayIndexMask) == 0);
5268 ASSERT((length > String::kMaxCachedArrayIndexLength) ||
5269 (value & String::kContainsCachedArrayIndexMask) == 0);
Kristian Monsen80d68ea2010-09-08 11:05:35 +01005270 return value;
Steve Blocka7e24c12009-10-30 11:49:00 +00005271}
5272
5273
5274uint32_t StringHasher::GetHashField() {
5275 ASSERT(is_valid());
Steve Blockd0582a62009-12-15 09:54:21 +00005276 if (length_ <= String::kMaxHashCalcLength) {
Steve Blocka7e24c12009-10-30 11:49:00 +00005277 if (is_array_index()) {
Iain Merrick9ac36c92010-09-13 15:29:50 +01005278 return MakeArrayIndexHash(array_index(), length_);
Steve Blocka7e24c12009-10-30 11:49:00 +00005279 }
Kristian Monsen80d68ea2010-09-08 11:05:35 +01005280 return (GetHash() << String::kHashShift) | String::kIsNotArrayIndexMask;
Steve Blocka7e24c12009-10-30 11:49:00 +00005281 } else {
Kristian Monsen80d68ea2010-09-08 11:05:35 +01005282 return (length_ << String::kHashShift) | String::kIsNotArrayIndexMask;
Steve Blocka7e24c12009-10-30 11:49:00 +00005283 }
5284}
5285
5286
Steve Blockd0582a62009-12-15 09:54:21 +00005287uint32_t String::ComputeHashField(unibrow::CharacterStream* buffer,
5288 int length) {
Steve Blocka7e24c12009-10-30 11:49:00 +00005289 StringHasher hasher(length);
5290
5291 // Very long strings have a trivial hash that doesn't inspect the
5292 // string contents.
5293 if (hasher.has_trivial_hash()) {
5294 return hasher.GetHashField();
5295 }
5296
5297 // Do the iterative array index computation as long as there is a
5298 // chance this is an array index.
5299 while (buffer->has_more() && hasher.is_array_index()) {
5300 hasher.AddCharacter(buffer->GetNext());
5301 }
5302
5303 // Process the remaining characters without updating the array
5304 // index.
5305 while (buffer->has_more()) {
5306 hasher.AddCharacterNoIndex(buffer->GetNext());
5307 }
5308
5309 return hasher.GetHashField();
5310}
5311
5312
John Reck59135872010-11-02 12:39:01 -07005313MaybeObject* String::SubString(int start, int end, PretenureFlag pretenure) {
Steve Blocka7e24c12009-10-30 11:49:00 +00005314 if (start == 0 && end == length()) return this;
John Reck59135872010-11-02 12:39:01 -07005315 MaybeObject* result = Heap::AllocateSubString(this, start, end, pretenure);
Steve Blockd0582a62009-12-15 09:54:21 +00005316 return result;
Steve Blocka7e24c12009-10-30 11:49:00 +00005317}
5318
5319
5320void String::PrintOn(FILE* file) {
5321 int length = this->length();
5322 for (int i = 0; i < length; i++) {
5323 fprintf(file, "%c", Get(i));
5324 }
5325}
5326
5327
5328void Map::CreateBackPointers() {
5329 DescriptorArray* descriptors = instance_descriptors();
5330 for (int i = 0; i < descriptors->number_of_descriptors(); i++) {
Iain Merrick75681382010-08-19 15:07:18 +01005331 if (descriptors->GetType(i) == MAP_TRANSITION ||
5332 descriptors->GetType(i) == CONSTANT_TRANSITION) {
Steve Blocka7e24c12009-10-30 11:49:00 +00005333 // Get target.
5334 Map* target = Map::cast(descriptors->GetValue(i));
5335#ifdef DEBUG
5336 // Verify target.
5337 Object* source_prototype = prototype();
5338 Object* target_prototype = target->prototype();
5339 ASSERT(source_prototype->IsJSObject() ||
5340 source_prototype->IsMap() ||
5341 source_prototype->IsNull());
5342 ASSERT(target_prototype->IsJSObject() ||
5343 target_prototype->IsNull());
5344 ASSERT(source_prototype->IsMap() ||
5345 source_prototype == target_prototype);
5346#endif
5347 // Point target back to source. set_prototype() will not let us set
5348 // the prototype to a map, as we do here.
5349 *RawField(target, kPrototypeOffset) = this;
5350 }
5351 }
5352}
5353
5354
5355void Map::ClearNonLiveTransitions(Object* real_prototype) {
5356 // Live DescriptorArray objects will be marked, so we must use
5357 // low-level accessors to get and modify their data.
5358 DescriptorArray* d = reinterpret_cast<DescriptorArray*>(
5359 *RawField(this, Map::kInstanceDescriptorsOffset));
5360 if (d == Heap::raw_unchecked_empty_descriptor_array()) return;
5361 Smi* NullDescriptorDetails =
5362 PropertyDetails(NONE, NULL_DESCRIPTOR).AsSmi();
5363 FixedArray* contents = reinterpret_cast<FixedArray*>(
5364 d->get(DescriptorArray::kContentArrayIndex));
5365 ASSERT(contents->length() >= 2);
5366 for (int i = 0; i < contents->length(); i += 2) {
5367 // If the pair (value, details) is a map transition,
5368 // check if the target is live. If not, null the descriptor.
5369 // Also drop the back pointer for that map transition, so that this
5370 // map is not reached again by following a back pointer from a
5371 // non-live object.
5372 PropertyDetails details(Smi::cast(contents->get(i + 1)));
Iain Merrick75681382010-08-19 15:07:18 +01005373 if (details.type() == MAP_TRANSITION ||
5374 details.type() == CONSTANT_TRANSITION) {
Steve Blocka7e24c12009-10-30 11:49:00 +00005375 Map* target = reinterpret_cast<Map*>(contents->get(i));
5376 ASSERT(target->IsHeapObject());
5377 if (!target->IsMarked()) {
5378 ASSERT(target->IsMap());
Iain Merrick75681382010-08-19 15:07:18 +01005379 contents->set_unchecked(i + 1, NullDescriptorDetails);
5380 contents->set_null_unchecked(i);
Steve Blocka7e24c12009-10-30 11:49:00 +00005381 ASSERT(target->prototype() == this ||
5382 target->prototype() == real_prototype);
5383 // Getter prototype() is read-only, set_prototype() has side effects.
5384 *RawField(target, Map::kPrototypeOffset) = real_prototype;
5385 }
5386 }
5387 }
5388}
5389
5390
Steve Block791712a2010-08-27 10:21:07 +01005391void JSFunction::JSFunctionIterateBody(int object_size, ObjectVisitor* v) {
5392 // Iterate over all fields in the body but take care in dealing with
5393 // the code entry.
5394 IteratePointers(v, kPropertiesOffset, kCodeEntryOffset);
5395 v->VisitCodeEntry(this->address() + kCodeEntryOffset);
5396 IteratePointers(v, kCodeEntryOffset + kPointerSize, object_size);
5397}
5398
5399
Ben Murdochb0fe1622011-05-05 13:52:32 +01005400void JSFunction::MarkForLazyRecompilation() {
5401 ASSERT(is_compiled() && !IsOptimized());
Ben Murdochb8e0da22011-05-16 14:20:40 +01005402 ASSERT(shared()->allows_lazy_compilation() ||
5403 code()->optimizable());
Ben Murdochb0fe1622011-05-05 13:52:32 +01005404 ReplaceCode(Builtins::builtin(Builtins::LazyRecompile));
5405}
5406
5407
5408uint32_t JSFunction::SourceHash() {
5409 uint32_t hash = 0;
5410 Object* script = shared()->script();
5411 if (!script->IsUndefined()) {
5412 Object* source = Script::cast(script)->source();
5413 if (source->IsUndefined()) hash = String::cast(source)->Hash();
5414 }
5415 hash ^= ComputeIntegerHash(shared()->start_position_and_type());
5416 hash += ComputeIntegerHash(shared()->end_position());
5417 return hash;
5418}
5419
5420
5421bool JSFunction::IsInlineable() {
5422 if (IsBuiltin()) return false;
5423 // Check that the function has a script associated with it.
5424 if (!shared()->script()->IsScript()) return false;
5425 Code* code = shared()->code();
5426 if (code->kind() == Code::OPTIMIZED_FUNCTION) return true;
5427 // If we never ran this (unlikely) then lets try to optimize it.
5428 if (code->kind() != Code::FUNCTION) return true;
5429 return code->optimizable();
5430}
5431
5432
Steve Blocka7e24c12009-10-30 11:49:00 +00005433Object* JSFunction::SetInstancePrototype(Object* value) {
5434 ASSERT(value->IsJSObject());
5435
5436 if (has_initial_map()) {
5437 initial_map()->set_prototype(value);
5438 } else {
5439 // Put the value in the initial map field until an initial map is
5440 // needed. At that point, a new initial map is created and the
5441 // prototype is put into the initial map where it belongs.
5442 set_prototype_or_initial_map(value);
5443 }
Kristian Monsen25f61362010-05-21 11:50:48 +01005444 Heap::ClearInstanceofCache();
Steve Blocka7e24c12009-10-30 11:49:00 +00005445 return value;
5446}
5447
5448
John Reck59135872010-11-02 12:39:01 -07005449MaybeObject* JSFunction::SetPrototype(Object* value) {
Steve Block6ded16b2010-05-10 14:33:55 +01005450 ASSERT(should_have_prototype());
Steve Blocka7e24c12009-10-30 11:49:00 +00005451 Object* construct_prototype = value;
5452
5453 // If the value is not a JSObject, store the value in the map's
5454 // constructor field so it can be accessed. Also, set the prototype
5455 // used for constructing objects to the original object prototype.
5456 // See ECMA-262 13.2.2.
5457 if (!value->IsJSObject()) {
5458 // Copy the map so this does not affect unrelated functions.
5459 // Remove map transitions because they point to maps with a
5460 // different prototype.
John Reck59135872010-11-02 12:39:01 -07005461 Object* new_map;
5462 { MaybeObject* maybe_new_map = map()->CopyDropTransitions();
5463 if (!maybe_new_map->ToObject(&new_map)) return maybe_new_map;
5464 }
Steve Blocka7e24c12009-10-30 11:49:00 +00005465 set_map(Map::cast(new_map));
5466 map()->set_constructor(value);
5467 map()->set_non_instance_prototype(true);
5468 construct_prototype =
5469 Top::context()->global_context()->initial_object_prototype();
5470 } else {
5471 map()->set_non_instance_prototype(false);
5472 }
5473
5474 return SetInstancePrototype(construct_prototype);
5475}
5476
5477
Steve Block6ded16b2010-05-10 14:33:55 +01005478Object* JSFunction::RemovePrototype() {
5479 ASSERT(map() == context()->global_context()->function_map());
5480 set_map(context()->global_context()->function_without_prototype_map());
5481 set_prototype_or_initial_map(Heap::the_hole_value());
5482 return this;
5483}
5484
5485
Steve Blocka7e24c12009-10-30 11:49:00 +00005486Object* JSFunction::SetInstanceClassName(String* name) {
5487 shared()->set_instance_class_name(name);
5488 return this;
5489}
5490
5491
Ben Murdochb0fe1622011-05-05 13:52:32 +01005492void JSFunction::PrintName(FILE* out) {
5493 SmartPointer<char> name = shared()->DebugName()->ToCString();
5494 PrintF(out, "%s", *name);
5495}
5496
5497
Steve Blocka7e24c12009-10-30 11:49:00 +00005498Context* JSFunction::GlobalContextFromLiterals(FixedArray* literals) {
5499 return Context::cast(literals->get(JSFunction::kLiteralGlobalContextIndex));
5500}
5501
5502
John Reck59135872010-11-02 12:39:01 -07005503MaybeObject* Oddball::Initialize(const char* to_string, Object* to_number) {
5504 Object* symbol;
5505 { MaybeObject* maybe_symbol = Heap::LookupAsciiSymbol(to_string);
5506 if (!maybe_symbol->ToObject(&symbol)) return maybe_symbol;
5507 }
Steve Blocka7e24c12009-10-30 11:49:00 +00005508 set_to_string(String::cast(symbol));
5509 set_to_number(to_number);
5510 return this;
5511}
5512
5513
Ben Murdochf87a2032010-10-22 12:50:53 +01005514String* SharedFunctionInfo::DebugName() {
5515 Object* n = name();
5516 if (!n->IsString() || String::cast(n)->length() == 0) return inferred_name();
5517 return String::cast(n);
5518}
5519
5520
Steve Blocka7e24c12009-10-30 11:49:00 +00005521bool SharedFunctionInfo::HasSourceCode() {
5522 return !script()->IsUndefined() &&
Iain Merrick75681382010-08-19 15:07:18 +01005523 !reinterpret_cast<Script*>(script())->source()->IsUndefined();
Steve Blocka7e24c12009-10-30 11:49:00 +00005524}
5525
5526
5527Object* SharedFunctionInfo::GetSourceCode() {
Ben Murdochb0fe1622011-05-05 13:52:32 +01005528 if (!HasSourceCode()) return Heap::undefined_value();
Steve Blocka7e24c12009-10-30 11:49:00 +00005529 HandleScope scope;
Steve Blocka7e24c12009-10-30 11:49:00 +00005530 Object* source = Script::cast(script())->source();
Steve Blocka7e24c12009-10-30 11:49:00 +00005531 return *SubString(Handle<String>(String::cast(source)),
5532 start_position(), end_position());
5533}
5534
5535
Ben Murdochb0fe1622011-05-05 13:52:32 +01005536int SharedFunctionInfo::SourceSize() {
5537 return end_position() - start_position();
5538}
5539
5540
Steve Blocka7e24c12009-10-30 11:49:00 +00005541int SharedFunctionInfo::CalculateInstanceSize() {
5542 int instance_size =
5543 JSObject::kHeaderSize +
5544 expected_nof_properties() * kPointerSize;
5545 if (instance_size > JSObject::kMaxInstanceSize) {
5546 instance_size = JSObject::kMaxInstanceSize;
5547 }
5548 return instance_size;
5549}
5550
5551
5552int SharedFunctionInfo::CalculateInObjectProperties() {
5553 return (CalculateInstanceSize() - JSObject::kHeaderSize) / kPointerSize;
5554}
5555
5556
Andrei Popescu402d9372010-02-26 13:31:12 +00005557bool SharedFunctionInfo::CanGenerateInlineConstructor(Object* prototype) {
5558 // Check the basic conditions for generating inline constructor code.
5559 if (!FLAG_inline_new
5560 || !has_only_simple_this_property_assignments()
5561 || this_property_assignments_count() == 0) {
5562 return false;
5563 }
5564
5565 // If the prototype is null inline constructors cause no problems.
5566 if (!prototype->IsJSObject()) {
5567 ASSERT(prototype->IsNull());
5568 return true;
5569 }
5570
5571 // Traverse the proposed prototype chain looking for setters for properties of
5572 // the same names as are set by the inline constructor.
5573 for (Object* obj = prototype;
5574 obj != Heap::null_value();
5575 obj = obj->GetPrototype()) {
5576 JSObject* js_object = JSObject::cast(obj);
5577 for (int i = 0; i < this_property_assignments_count(); i++) {
5578 LookupResult result;
5579 String* name = GetThisPropertyAssignmentName(i);
5580 js_object->LocalLookupRealNamedProperty(name, &result);
5581 if (result.IsProperty() && result.type() == CALLBACKS) {
5582 return false;
5583 }
5584 }
5585 }
5586
5587 return true;
5588}
5589
5590
Kristian Monsen0d5e1162010-09-30 15:31:59 +01005591void SharedFunctionInfo::ForbidInlineConstructor() {
5592 set_compiler_hints(BooleanBit::set(compiler_hints(),
5593 kHasOnlySimpleThisPropertyAssignments,
5594 false));
5595}
5596
5597
Steve Blocka7e24c12009-10-30 11:49:00 +00005598void SharedFunctionInfo::SetThisPropertyAssignmentsInfo(
Steve Blocka7e24c12009-10-30 11:49:00 +00005599 bool only_simple_this_property_assignments,
5600 FixedArray* assignments) {
5601 set_compiler_hints(BooleanBit::set(compiler_hints(),
Steve Blocka7e24c12009-10-30 11:49:00 +00005602 kHasOnlySimpleThisPropertyAssignments,
5603 only_simple_this_property_assignments));
5604 set_this_property_assignments(assignments);
5605 set_this_property_assignments_count(assignments->length() / 3);
5606}
5607
5608
5609void SharedFunctionInfo::ClearThisPropertyAssignmentsInfo() {
5610 set_compiler_hints(BooleanBit::set(compiler_hints(),
Steve Blocka7e24c12009-10-30 11:49:00 +00005611 kHasOnlySimpleThisPropertyAssignments,
5612 false));
5613 set_this_property_assignments(Heap::undefined_value());
5614 set_this_property_assignments_count(0);
5615}
5616
5617
5618String* SharedFunctionInfo::GetThisPropertyAssignmentName(int index) {
5619 Object* obj = this_property_assignments();
5620 ASSERT(obj->IsFixedArray());
5621 ASSERT(index < this_property_assignments_count());
5622 obj = FixedArray::cast(obj)->get(index * 3);
5623 ASSERT(obj->IsString());
5624 return String::cast(obj);
5625}
5626
5627
5628bool SharedFunctionInfo::IsThisPropertyAssignmentArgument(int index) {
5629 Object* obj = this_property_assignments();
5630 ASSERT(obj->IsFixedArray());
5631 ASSERT(index < this_property_assignments_count());
5632 obj = FixedArray::cast(obj)->get(index * 3 + 1);
5633 return Smi::cast(obj)->value() != -1;
5634}
5635
5636
5637int SharedFunctionInfo::GetThisPropertyAssignmentArgument(int index) {
5638 ASSERT(IsThisPropertyAssignmentArgument(index));
5639 Object* obj =
5640 FixedArray::cast(this_property_assignments())->get(index * 3 + 1);
5641 return Smi::cast(obj)->value();
5642}
5643
5644
5645Object* SharedFunctionInfo::GetThisPropertyAssignmentConstant(int index) {
5646 ASSERT(!IsThisPropertyAssignmentArgument(index));
5647 Object* obj =
5648 FixedArray::cast(this_property_assignments())->get(index * 3 + 2);
5649 return obj;
5650}
5651
5652
Steve Blocka7e24c12009-10-30 11:49:00 +00005653// Support function for printing the source code to a StringStream
5654// without any allocation in the heap.
5655void SharedFunctionInfo::SourceCodePrint(StringStream* accumulator,
5656 int max_length) {
5657 // For some native functions there is no source.
Ben Murdochb0fe1622011-05-05 13:52:32 +01005658 if (!HasSourceCode()) {
Steve Blocka7e24c12009-10-30 11:49:00 +00005659 accumulator->Add("<No Source>");
5660 return;
5661 }
5662
Steve Blockd0582a62009-12-15 09:54:21 +00005663 // Get the source for the script which this function came from.
Steve Blocka7e24c12009-10-30 11:49:00 +00005664 // Don't use String::cast because we don't want more assertion errors while
5665 // we are already creating a stack dump.
5666 String* script_source =
5667 reinterpret_cast<String*>(Script::cast(script())->source());
5668
5669 if (!script_source->LooksValid()) {
5670 accumulator->Add("<Invalid Source>");
5671 return;
5672 }
5673
5674 if (!is_toplevel()) {
5675 accumulator->Add("function ");
5676 Object* name = this->name();
5677 if (name->IsString() && String::cast(name)->length() > 0) {
5678 accumulator->PrintName(name);
5679 }
5680 }
5681
5682 int len = end_position() - start_position();
Ben Murdochb0fe1622011-05-05 13:52:32 +01005683 if (len <= max_length || max_length < 0) {
5684 accumulator->Put(script_source, start_position(), end_position());
5685 } else {
Steve Blocka7e24c12009-10-30 11:49:00 +00005686 accumulator->Put(script_source,
5687 start_position(),
5688 start_position() + max_length);
5689 accumulator->Add("...\n");
Steve Blocka7e24c12009-10-30 11:49:00 +00005690 }
5691}
5692
5693
Ben Murdochb0fe1622011-05-05 13:52:32 +01005694static bool IsCodeEquivalent(Code* code, Code* recompiled) {
5695 if (code->instruction_size() != recompiled->instruction_size()) return false;
5696 ByteArray* code_relocation = code->relocation_info();
5697 ByteArray* recompiled_relocation = recompiled->relocation_info();
5698 int length = code_relocation->length();
5699 if (length != recompiled_relocation->length()) return false;
5700 int compare = memcmp(code_relocation->GetDataStartAddress(),
5701 recompiled_relocation->GetDataStartAddress(),
5702 length);
5703 return compare == 0;
5704}
5705
5706
5707void SharedFunctionInfo::EnableDeoptimizationSupport(Code* recompiled) {
5708 ASSERT(!has_deoptimization_support());
5709 AssertNoAllocation no_allocation;
5710 Code* code = this->code();
5711 if (IsCodeEquivalent(code, recompiled)) {
5712 // Copy the deoptimization data from the recompiled code.
5713 code->set_deoptimization_data(recompiled->deoptimization_data());
5714 code->set_has_deoptimization_support(true);
5715 } else {
5716 // TODO(3025757): In case the recompiled isn't equivalent to the
5717 // old code, we have to replace it. We should try to avoid this
5718 // altogether because it flushes valuable type feedback by
5719 // effectively resetting all IC state.
5720 set_code(recompiled);
5721 }
5722 ASSERT(has_deoptimization_support());
5723}
5724
5725
5726bool SharedFunctionInfo::VerifyBailoutId(int id) {
5727 // TODO(srdjan): debugging ARM crashes in hydrogen. OK to disable while
5728 // we are always bailing out on ARM.
5729
5730 ASSERT(id != AstNode::kNoNumber);
5731 Code* unoptimized = code();
5732 DeoptimizationOutputData* data =
5733 DeoptimizationOutputData::cast(unoptimized->deoptimization_data());
5734 unsigned ignore = Deoptimizer::GetOutputInfo(data, id, this);
5735 USE(ignore);
5736 return true; // Return true if there was no ASSERT.
5737}
5738
5739
Kristian Monsen0d5e1162010-09-30 15:31:59 +01005740void SharedFunctionInfo::StartInobjectSlackTracking(Map* map) {
5741 ASSERT(!IsInobjectSlackTrackingInProgress());
5742
5743 // Only initiate the tracking the first time.
5744 if (live_objects_may_exist()) return;
5745 set_live_objects_may_exist(true);
5746
5747 // No tracking during the snapshot construction phase.
5748 if (Serializer::enabled()) return;
5749
5750 if (map->unused_property_fields() == 0) return;
5751
5752 // Nonzero counter is a leftover from the previous attempt interrupted
5753 // by GC, keep it.
5754 if (construction_count() == 0) {
5755 set_construction_count(kGenerousAllocationCount);
5756 }
5757 set_initial_map(map);
5758 ASSERT_EQ(Builtins::builtin(Builtins::JSConstructStubGeneric),
5759 construct_stub());
5760 set_construct_stub(Builtins::builtin(Builtins::JSConstructStubCountdown));
5761}
5762
5763
5764// Called from GC, hence reinterpret_cast and unchecked accessors.
5765void SharedFunctionInfo::DetachInitialMap() {
5766 Map* map = reinterpret_cast<Map*>(initial_map());
5767
5768 // Make the map remember to restore the link if it survives the GC.
5769 map->set_bit_field2(
5770 map->bit_field2() | (1 << Map::kAttachedToSharedFunctionInfo));
5771
5772 // Undo state changes made by StartInobjectTracking (except the
5773 // construction_count). This way if the initial map does not survive the GC
5774 // then StartInobjectTracking will be called again the next time the
5775 // constructor is called. The countdown will continue and (possibly after
5776 // several more GCs) CompleteInobjectSlackTracking will eventually be called.
5777 set_initial_map(Heap::raw_unchecked_undefined_value());
5778 ASSERT_EQ(Builtins::builtin(Builtins::JSConstructStubCountdown),
5779 *RawField(this, kConstructStubOffset));
5780 set_construct_stub(Builtins::builtin(Builtins::JSConstructStubGeneric));
5781 // It is safe to clear the flag: it will be set again if the map is live.
5782 set_live_objects_may_exist(false);
5783}
5784
5785
5786// Called from GC, hence reinterpret_cast and unchecked accessors.
5787void SharedFunctionInfo::AttachInitialMap(Map* map) {
5788 map->set_bit_field2(
5789 map->bit_field2() & ~(1 << Map::kAttachedToSharedFunctionInfo));
5790
5791 // Resume inobject slack tracking.
5792 set_initial_map(map);
5793 ASSERT_EQ(Builtins::builtin(Builtins::JSConstructStubGeneric),
5794 *RawField(this, kConstructStubOffset));
5795 set_construct_stub(Builtins::builtin(Builtins::JSConstructStubCountdown));
5796 // The map survived the gc, so there may be objects referencing it.
5797 set_live_objects_may_exist(true);
5798}
5799
5800
5801static void GetMinInobjectSlack(Map* map, void* data) {
5802 int slack = map->unused_property_fields();
5803 if (*reinterpret_cast<int*>(data) > slack) {
5804 *reinterpret_cast<int*>(data) = slack;
5805 }
5806}
5807
5808
5809static void ShrinkInstanceSize(Map* map, void* data) {
5810 int slack = *reinterpret_cast<int*>(data);
5811 map->set_inobject_properties(map->inobject_properties() - slack);
5812 map->set_unused_property_fields(map->unused_property_fields() - slack);
5813 map->set_instance_size(map->instance_size() - slack * kPointerSize);
5814
5815 // Visitor id might depend on the instance size, recalculate it.
5816 map->set_visitor_id(StaticVisitorBase::GetVisitorId(map));
5817}
5818
5819
5820void SharedFunctionInfo::CompleteInobjectSlackTracking() {
5821 ASSERT(live_objects_may_exist() && IsInobjectSlackTrackingInProgress());
5822 Map* map = Map::cast(initial_map());
5823
5824 set_initial_map(Heap::undefined_value());
5825 ASSERT_EQ(Builtins::builtin(Builtins::JSConstructStubCountdown),
5826 construct_stub());
5827 set_construct_stub(Builtins::builtin(Builtins::JSConstructStubGeneric));
5828
5829 int slack = map->unused_property_fields();
5830 map->TraverseTransitionTree(&GetMinInobjectSlack, &slack);
5831 if (slack != 0) {
5832 // Resize the initial map and all maps in its transition tree.
5833 map->TraverseTransitionTree(&ShrinkInstanceSize, &slack);
5834 // Give the correct expected_nof_properties to initial maps created later.
5835 ASSERT(expected_nof_properties() >= slack);
5836 set_expected_nof_properties(expected_nof_properties() - slack);
5837 }
5838}
5839
5840
Steve Blocka7e24c12009-10-30 11:49:00 +00005841void ObjectVisitor::VisitCodeTarget(RelocInfo* rinfo) {
5842 ASSERT(RelocInfo::IsCodeTarget(rinfo->rmode()));
5843 Object* target = Code::GetCodeFromTargetAddress(rinfo->target_address());
5844 Object* old_target = target;
5845 VisitPointer(&target);
5846 CHECK_EQ(target, old_target); // VisitPointer doesn't change Code* *target.
5847}
5848
5849
Steve Block791712a2010-08-27 10:21:07 +01005850void ObjectVisitor::VisitCodeEntry(Address entry_address) {
5851 Object* code = Code::GetObjectFromEntryAddress(entry_address);
5852 Object* old_code = code;
5853 VisitPointer(&code);
5854 if (code != old_code) {
5855 Memory::Address_at(entry_address) = reinterpret_cast<Code*>(code)->entry();
5856 }
5857}
5858
5859
Ben Murdochb0fe1622011-05-05 13:52:32 +01005860void ObjectVisitor::VisitGlobalPropertyCell(RelocInfo* rinfo) {
5861 ASSERT(rinfo->rmode() == RelocInfo::GLOBAL_PROPERTY_CELL);
5862 Object* cell = rinfo->target_cell();
5863 Object* old_cell = cell;
5864 VisitPointer(&cell);
5865 if (cell != old_cell) {
5866 rinfo->set_target_cell(reinterpret_cast<JSGlobalPropertyCell*>(cell));
5867 }
5868}
5869
5870
Steve Blocka7e24c12009-10-30 11:49:00 +00005871void ObjectVisitor::VisitDebugTarget(RelocInfo* rinfo) {
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01005872 ASSERT((RelocInfo::IsJSReturn(rinfo->rmode()) &&
5873 rinfo->IsPatchedReturnSequence()) ||
5874 (RelocInfo::IsDebugBreakSlot(rinfo->rmode()) &&
5875 rinfo->IsPatchedDebugBreakSlotSequence()));
Steve Blocka7e24c12009-10-30 11:49:00 +00005876 Object* target = Code::GetCodeFromTargetAddress(rinfo->call_address());
5877 Object* old_target = target;
5878 VisitPointer(&target);
5879 CHECK_EQ(target, old_target); // VisitPointer doesn't change Code* *target.
5880}
5881
5882
Ben Murdochb0fe1622011-05-05 13:52:32 +01005883void Code::InvalidateRelocation() {
5884 HandleScope scope;
5885 set_relocation_info(Heap::empty_byte_array());
5886}
5887
5888
Steve Blockd0582a62009-12-15 09:54:21 +00005889void Code::Relocate(intptr_t delta) {
Steve Blocka7e24c12009-10-30 11:49:00 +00005890 for (RelocIterator it(this, RelocInfo::kApplyMask); !it.done(); it.next()) {
5891 it.rinfo()->apply(delta);
5892 }
5893 CPU::FlushICache(instruction_start(), instruction_size());
5894}
5895
5896
5897void Code::CopyFrom(const CodeDesc& desc) {
5898 // copy code
5899 memmove(instruction_start(), desc.buffer, desc.instr_size);
5900
Steve Blocka7e24c12009-10-30 11:49:00 +00005901 // copy reloc info
5902 memmove(relocation_start(),
5903 desc.buffer + desc.buffer_size - desc.reloc_size,
5904 desc.reloc_size);
5905
5906 // unbox handles and relocate
Steve Block3ce2e202009-11-05 08:53:23 +00005907 intptr_t delta = instruction_start() - desc.buffer;
Steve Blocka7e24c12009-10-30 11:49:00 +00005908 int mode_mask = RelocInfo::kCodeTargetMask |
5909 RelocInfo::ModeMask(RelocInfo::EMBEDDED_OBJECT) |
Ben Murdochb0fe1622011-05-05 13:52:32 +01005910 RelocInfo::ModeMask(RelocInfo::GLOBAL_PROPERTY_CELL) |
Steve Blocka7e24c12009-10-30 11:49:00 +00005911 RelocInfo::kApplyMask;
Steve Block3ce2e202009-11-05 08:53:23 +00005912 Assembler* origin = desc.origin; // Needed to find target_object on X64.
Steve Blocka7e24c12009-10-30 11:49:00 +00005913 for (RelocIterator it(this, mode_mask); !it.done(); it.next()) {
5914 RelocInfo::Mode mode = it.rinfo()->rmode();
5915 if (mode == RelocInfo::EMBEDDED_OBJECT) {
Steve Block3ce2e202009-11-05 08:53:23 +00005916 Handle<Object> p = it.rinfo()->target_object_handle(origin);
Steve Blocka7e24c12009-10-30 11:49:00 +00005917 it.rinfo()->set_target_object(*p);
Ben Murdochb0fe1622011-05-05 13:52:32 +01005918 } else if (mode == RelocInfo::GLOBAL_PROPERTY_CELL) {
5919 Handle<JSGlobalPropertyCell> cell = it.rinfo()->target_cell_handle();
5920 it.rinfo()->set_target_cell(*cell);
Steve Blocka7e24c12009-10-30 11:49:00 +00005921 } else if (RelocInfo::IsCodeTarget(mode)) {
5922 // rewrite code handles in inline cache targets to direct
5923 // pointers to the first instruction in the code object
Steve Block3ce2e202009-11-05 08:53:23 +00005924 Handle<Object> p = it.rinfo()->target_object_handle(origin);
Steve Blocka7e24c12009-10-30 11:49:00 +00005925 Code* code = Code::cast(*p);
5926 it.rinfo()->set_target_address(code->instruction_start());
5927 } else {
5928 it.rinfo()->apply(delta);
5929 }
5930 }
5931 CPU::FlushICache(instruction_start(), instruction_size());
5932}
5933
5934
5935// Locate the source position which is closest to the address in the code. This
5936// is using the source position information embedded in the relocation info.
5937// The position returned is relative to the beginning of the script where the
5938// source for this function is found.
5939int Code::SourcePosition(Address pc) {
5940 int distance = kMaxInt;
5941 int position = RelocInfo::kNoPosition; // Initially no position found.
5942 // Run through all the relocation info to find the best matching source
5943 // position. All the code needs to be considered as the sequence of the
5944 // instructions in the code does not necessarily follow the same order as the
5945 // source.
5946 RelocIterator it(this, RelocInfo::kPositionMask);
5947 while (!it.done()) {
5948 // Only look at positions after the current pc.
5949 if (it.rinfo()->pc() < pc) {
5950 // Get position and distance.
Steve Blockd0582a62009-12-15 09:54:21 +00005951
5952 int dist = static_cast<int>(pc - it.rinfo()->pc());
5953 int pos = static_cast<int>(it.rinfo()->data());
Steve Blocka7e24c12009-10-30 11:49:00 +00005954 // If this position is closer than the current candidate or if it has the
5955 // same distance as the current candidate and the position is higher then
5956 // this position is the new candidate.
5957 if ((dist < distance) ||
5958 (dist == distance && pos > position)) {
5959 position = pos;
5960 distance = dist;
5961 }
5962 }
5963 it.next();
5964 }
5965 return position;
5966}
5967
5968
5969// Same as Code::SourcePosition above except it only looks for statement
5970// positions.
5971int Code::SourceStatementPosition(Address pc) {
5972 // First find the position as close as possible using all position
5973 // information.
5974 int position = SourcePosition(pc);
5975 // Now find the closest statement position before the position.
5976 int statement_position = 0;
5977 RelocIterator it(this, RelocInfo::kPositionMask);
5978 while (!it.done()) {
5979 if (RelocInfo::IsStatementPosition(it.rinfo()->rmode())) {
Steve Blockd0582a62009-12-15 09:54:21 +00005980 int p = static_cast<int>(it.rinfo()->data());
Steve Blocka7e24c12009-10-30 11:49:00 +00005981 if (statement_position < p && p <= position) {
5982 statement_position = p;
5983 }
5984 }
5985 it.next();
5986 }
5987 return statement_position;
5988}
5989
5990
Ben Murdochb8e0da22011-05-16 14:20:40 +01005991SafepointEntry Code::GetSafepointEntry(Address pc) {
Ben Murdochb0fe1622011-05-05 13:52:32 +01005992 SafepointTable table(this);
Ben Murdochb8e0da22011-05-16 14:20:40 +01005993 return table.FindEntry(pc);
Ben Murdochb0fe1622011-05-05 13:52:32 +01005994}
5995
5996
5997void Code::SetNoStackCheckTable() {
5998 // Indicate the absence of a stack-check table by a table start after the
5999 // end of the instructions. Table start must be aligned, so round up.
6000 set_stack_check_table_start(RoundUp(instruction_size(), kIntSize));
6001}
6002
6003
6004Map* Code::FindFirstMap() {
6005 ASSERT(is_inline_cache_stub());
6006 AssertNoAllocation no_allocation;
6007 int mask = RelocInfo::ModeMask(RelocInfo::EMBEDDED_OBJECT);
6008 for (RelocIterator it(this, mask); !it.done(); it.next()) {
6009 RelocInfo* info = it.rinfo();
6010 Object* object = info->target_object();
6011 if (object->IsMap()) return Map::cast(object);
6012 }
6013 return NULL;
6014}
6015
6016
Steve Blocka7e24c12009-10-30 11:49:00 +00006017#ifdef ENABLE_DISASSEMBLER
Ben Murdochb0fe1622011-05-05 13:52:32 +01006018
6019#ifdef OBJECT_PRINT
6020
6021void DeoptimizationInputData::DeoptimizationInputDataPrint(FILE* out) {
6022 disasm::NameConverter converter;
6023 int deopt_count = DeoptCount();
6024 PrintF(out, "Deoptimization Input Data (deopt points = %d)\n", deopt_count);
6025 if (0 == deopt_count) return;
6026
6027 PrintF(out, "%6s %6s %6s %12s\n", "index", "ast id", "argc", "commands");
6028 for (int i = 0; i < deopt_count; i++) {
6029 int command_count = 0;
6030 PrintF(out, "%6d %6d %6d",
6031 i, AstId(i)->value(), ArgumentsStackHeight(i)->value());
6032 int translation_index = TranslationIndex(i)->value();
6033 TranslationIterator iterator(TranslationByteArray(), translation_index);
6034 Translation::Opcode opcode =
6035 static_cast<Translation::Opcode>(iterator.Next());
6036 ASSERT(Translation::BEGIN == opcode);
6037 int frame_count = iterator.Next();
6038 if (FLAG_print_code_verbose) {
6039 PrintF(out, " %s {count=%d}\n", Translation::StringFor(opcode),
6040 frame_count);
6041 }
6042
6043 for (int i = 0; i < frame_count; ++i) {
6044 opcode = static_cast<Translation::Opcode>(iterator.Next());
6045 ASSERT(Translation::FRAME == opcode);
6046 int ast_id = iterator.Next();
6047 int function_id = iterator.Next();
6048 JSFunction* function =
6049 JSFunction::cast(LiteralArray()->get(function_id));
6050 unsigned height = iterator.Next();
6051 if (FLAG_print_code_verbose) {
6052 PrintF(out, "%24s %s {ast_id=%d, function=",
6053 "", Translation::StringFor(opcode), ast_id);
6054 function->PrintName(out);
6055 PrintF(out, ", height=%u}\n", height);
6056 }
6057
6058 // Size of translation is height plus all incoming arguments including
6059 // receiver.
6060 int size = height + function->shared()->formal_parameter_count() + 1;
6061 command_count += size;
6062 for (int j = 0; j < size; ++j) {
6063 opcode = static_cast<Translation::Opcode>(iterator.Next());
6064 if (FLAG_print_code_verbose) {
6065 PrintF(out, "%24s %s ", "", Translation::StringFor(opcode));
6066 }
6067
6068 if (opcode == Translation::DUPLICATE) {
6069 opcode = static_cast<Translation::Opcode>(iterator.Next());
6070 if (FLAG_print_code_verbose) {
6071 PrintF(out, "%s ", Translation::StringFor(opcode));
6072 }
6073 --j; // Two commands share the same frame index.
6074 }
6075
6076 switch (opcode) {
6077 case Translation::BEGIN:
6078 case Translation::FRAME:
6079 case Translation::DUPLICATE:
6080 UNREACHABLE();
6081 break;
6082
6083 case Translation::REGISTER: {
6084 int reg_code = iterator.Next();
6085 if (FLAG_print_code_verbose) {
6086 PrintF(out, "{input=%s}", converter.NameOfCPURegister(reg_code));
6087 }
6088 break;
6089 }
6090
6091 case Translation::INT32_REGISTER: {
6092 int reg_code = iterator.Next();
6093 if (FLAG_print_code_verbose) {
6094 PrintF(out, "{input=%s}", converter.NameOfCPURegister(reg_code));
6095 }
6096 break;
6097 }
6098
6099 case Translation::DOUBLE_REGISTER: {
6100 int reg_code = iterator.Next();
6101 if (FLAG_print_code_verbose) {
6102 PrintF(out, "{input=%s}",
6103 DoubleRegister::AllocationIndexToString(reg_code));
6104 }
6105 break;
6106 }
6107
6108 case Translation::STACK_SLOT: {
6109 int input_slot_index = iterator.Next();
6110 if (FLAG_print_code_verbose) {
6111 PrintF(out, "{input=%d}", input_slot_index);
6112 }
6113 break;
6114 }
6115
6116 case Translation::INT32_STACK_SLOT: {
6117 int input_slot_index = iterator.Next();
6118 if (FLAG_print_code_verbose) {
6119 PrintF(out, "{input=%d}", input_slot_index);
6120 }
6121 break;
6122 }
6123
6124 case Translation::DOUBLE_STACK_SLOT: {
6125 int input_slot_index = iterator.Next();
6126 if (FLAG_print_code_verbose) {
6127 PrintF(out, "{input=%d}", input_slot_index);
6128 }
6129 break;
6130 }
6131
6132 case Translation::LITERAL: {
6133 unsigned literal_index = iterator.Next();
6134 if (FLAG_print_code_verbose) {
6135 PrintF(out, "{literal_id=%u}", literal_index);
6136 }
6137 break;
6138 }
6139
6140 case Translation::ARGUMENTS_OBJECT:
6141 break;
6142 }
6143 if (FLAG_print_code_verbose) PrintF(out, "\n");
6144 }
6145 }
6146 if (!FLAG_print_code_verbose) PrintF(out, " %12d\n", command_count);
6147 }
6148}
6149
6150
6151void DeoptimizationOutputData::DeoptimizationOutputDataPrint(FILE* out) {
6152 PrintF(out, "Deoptimization Output Data (deopt points = %d)\n",
6153 this->DeoptPoints());
6154 if (this->DeoptPoints() == 0) return;
6155
6156 PrintF("%6s %8s %s\n", "ast id", "pc", "state");
6157 for (int i = 0; i < this->DeoptPoints(); i++) {
6158 int pc_and_state = this->PcAndState(i)->value();
6159 PrintF("%6d %8d %s\n",
6160 this->AstId(i)->value(),
6161 FullCodeGenerator::PcField::decode(pc_and_state),
6162 FullCodeGenerator::State2String(
6163 FullCodeGenerator::StateField::decode(pc_and_state)));
6164 }
6165}
6166
6167#endif
6168
6169
Steve Blocka7e24c12009-10-30 11:49:00 +00006170// Identify kind of code.
6171const char* Code::Kind2String(Kind kind) {
6172 switch (kind) {
6173 case FUNCTION: return "FUNCTION";
Ben Murdochb0fe1622011-05-05 13:52:32 +01006174 case OPTIMIZED_FUNCTION: return "OPTIMIZED_FUNCTION";
Steve Blocka7e24c12009-10-30 11:49:00 +00006175 case STUB: return "STUB";
6176 case BUILTIN: return "BUILTIN";
6177 case LOAD_IC: return "LOAD_IC";
6178 case KEYED_LOAD_IC: return "KEYED_LOAD_IC";
6179 case STORE_IC: return "STORE_IC";
6180 case KEYED_STORE_IC: return "KEYED_STORE_IC";
6181 case CALL_IC: return "CALL_IC";
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01006182 case KEYED_CALL_IC: return "KEYED_CALL_IC";
Steve Block6ded16b2010-05-10 14:33:55 +01006183 case BINARY_OP_IC: return "BINARY_OP_IC";
Ben Murdochb0fe1622011-05-05 13:52:32 +01006184 case TYPE_RECORDING_BINARY_OP_IC: return "TYPE_RECORDING_BINARY_OP_IC";
6185 case COMPARE_IC: return "COMPARE_IC";
Steve Blocka7e24c12009-10-30 11:49:00 +00006186 }
6187 UNREACHABLE();
6188 return NULL;
6189}
6190
6191
6192const char* Code::ICState2String(InlineCacheState state) {
6193 switch (state) {
6194 case UNINITIALIZED: return "UNINITIALIZED";
6195 case PREMONOMORPHIC: return "PREMONOMORPHIC";
6196 case MONOMORPHIC: return "MONOMORPHIC";
6197 case MONOMORPHIC_PROTOTYPE_FAILURE: return "MONOMORPHIC_PROTOTYPE_FAILURE";
6198 case MEGAMORPHIC: return "MEGAMORPHIC";
6199 case DEBUG_BREAK: return "DEBUG_BREAK";
6200 case DEBUG_PREPARE_STEP_IN: return "DEBUG_PREPARE_STEP_IN";
6201 }
6202 UNREACHABLE();
6203 return NULL;
6204}
6205
6206
6207const char* Code::PropertyType2String(PropertyType type) {
6208 switch (type) {
6209 case NORMAL: return "NORMAL";
6210 case FIELD: return "FIELD";
6211 case CONSTANT_FUNCTION: return "CONSTANT_FUNCTION";
6212 case CALLBACKS: return "CALLBACKS";
6213 case INTERCEPTOR: return "INTERCEPTOR";
6214 case MAP_TRANSITION: return "MAP_TRANSITION";
6215 case CONSTANT_TRANSITION: return "CONSTANT_TRANSITION";
6216 case NULL_DESCRIPTOR: return "NULL_DESCRIPTOR";
6217 }
6218 UNREACHABLE();
6219 return NULL;
6220}
6221
Ben Murdochb0fe1622011-05-05 13:52:32 +01006222
6223void Code::Disassemble(const char* name, FILE* out) {
6224 PrintF(out, "kind = %s\n", Kind2String(kind()));
Steve Blocka7e24c12009-10-30 11:49:00 +00006225 if (is_inline_cache_stub()) {
Ben Murdochb0fe1622011-05-05 13:52:32 +01006226 PrintF(out, "ic_state = %s\n", ICState2String(ic_state()));
6227 PrintF(out, "ic_in_loop = %d\n", ic_in_loop() == IN_LOOP);
Steve Blocka7e24c12009-10-30 11:49:00 +00006228 if (ic_state() == MONOMORPHIC) {
Ben Murdochb0fe1622011-05-05 13:52:32 +01006229 PrintF(out, "type = %s\n", PropertyType2String(type()));
Steve Blocka7e24c12009-10-30 11:49:00 +00006230 }
6231 }
6232 if ((name != NULL) && (name[0] != '\0')) {
Ben Murdochb0fe1622011-05-05 13:52:32 +01006233 PrintF(out, "name = %s\n", name);
6234 }
6235 if (kind() == OPTIMIZED_FUNCTION) {
6236 PrintF(out, "stack_slots = %d\n", stack_slots());
Steve Blocka7e24c12009-10-30 11:49:00 +00006237 }
6238
Ben Murdochb0fe1622011-05-05 13:52:32 +01006239 PrintF(out, "Instructions (size = %d)\n", instruction_size());
6240 Disassembler::Decode(out, this);
6241 PrintF(out, "\n");
6242
6243#ifdef DEBUG
6244 if (kind() == FUNCTION) {
6245 DeoptimizationOutputData* data =
6246 DeoptimizationOutputData::cast(this->deoptimization_data());
6247 data->DeoptimizationOutputDataPrint(out);
6248 } else if (kind() == OPTIMIZED_FUNCTION) {
6249 DeoptimizationInputData* data =
6250 DeoptimizationInputData::cast(this->deoptimization_data());
6251 data->DeoptimizationInputDataPrint(out);
6252 }
Steve Blocka7e24c12009-10-30 11:49:00 +00006253 PrintF("\n");
Ben Murdochb0fe1622011-05-05 13:52:32 +01006254#endif
6255
6256 if (kind() == OPTIMIZED_FUNCTION) {
6257 SafepointTable table(this);
6258 PrintF(out, "Safepoints (size = %u)\n", table.size());
6259 for (unsigned i = 0; i < table.length(); i++) {
6260 unsigned pc_offset = table.GetPcOffset(i);
6261 PrintF(out, "%p %4d ", (instruction_start() + pc_offset), pc_offset);
6262 table.PrintEntry(i);
6263 PrintF(out, " (sp -> fp)");
Ben Murdochb8e0da22011-05-16 14:20:40 +01006264 SafepointEntry entry = table.GetEntry(i);
6265 if (entry.deoptimization_index() != Safepoint::kNoDeoptimizationIndex) {
6266 PrintF(out, " %6d", entry.deoptimization_index());
Ben Murdochb0fe1622011-05-05 13:52:32 +01006267 } else {
6268 PrintF(out, " <none>");
6269 }
Ben Murdochb8e0da22011-05-16 14:20:40 +01006270 if (entry.argument_count() > 0) {
6271 PrintF(out, " argc: %d", entry.argument_count());
6272 }
Ben Murdochb0fe1622011-05-05 13:52:32 +01006273 PrintF(out, "\n");
6274 }
6275 PrintF(out, "\n");
6276 } else if (kind() == FUNCTION) {
6277 unsigned offset = stack_check_table_start();
6278 // If there is no stack check table, the "table start" will at or after
6279 // (due to alignment) the end of the instruction stream.
6280 if (static_cast<int>(offset) < instruction_size()) {
6281 unsigned* address =
6282 reinterpret_cast<unsigned*>(instruction_start() + offset);
6283 unsigned length = address[0];
6284 PrintF(out, "Stack checks (size = %u)\n", length);
6285 PrintF(out, "ast_id pc_offset\n");
6286 for (unsigned i = 0; i < length; ++i) {
6287 unsigned index = (2 * i) + 1;
6288 PrintF(out, "%6u %9u\n", address[index], address[index + 1]);
6289 }
6290 PrintF(out, "\n");
6291 }
6292 }
Steve Blocka7e24c12009-10-30 11:49:00 +00006293
6294 PrintF("RelocInfo (size = %d)\n", relocation_size());
Ben Murdochb0fe1622011-05-05 13:52:32 +01006295 for (RelocIterator it(this); !it.done(); it.next()) it.rinfo()->Print(out);
6296 PrintF(out, "\n");
Steve Blocka7e24c12009-10-30 11:49:00 +00006297}
6298#endif // ENABLE_DISASSEMBLER
6299
6300
John Reck59135872010-11-02 12:39:01 -07006301MaybeObject* JSObject::SetFastElementsCapacityAndLength(int capacity,
6302 int length) {
Steve Block3ce2e202009-11-05 08:53:23 +00006303 // We should never end in here with a pixel or external array.
6304 ASSERT(!HasPixelElements() && !HasExternalArrayElements());
Steve Block8defd9f2010-07-08 12:39:36 +01006305
John Reck59135872010-11-02 12:39:01 -07006306 Object* obj;
6307 { MaybeObject* maybe_obj = Heap::AllocateFixedArrayWithHoles(capacity);
6308 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
6309 }
Steve Block8defd9f2010-07-08 12:39:36 +01006310 FixedArray* elems = FixedArray::cast(obj);
6311
John Reck59135872010-11-02 12:39:01 -07006312 { MaybeObject* maybe_obj = map()->GetFastElementsMap();
6313 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
6314 }
Steve Block8defd9f2010-07-08 12:39:36 +01006315 Map* new_map = Map::cast(obj);
6316
Leon Clarke4515c472010-02-03 11:58:03 +00006317 AssertNoAllocation no_gc;
6318 WriteBarrierMode mode = elems->GetWriteBarrierMode(no_gc);
Steve Blocka7e24c12009-10-30 11:49:00 +00006319 switch (GetElementsKind()) {
6320 case FAST_ELEMENTS: {
6321 FixedArray* old_elements = FixedArray::cast(elements());
6322 uint32_t old_length = static_cast<uint32_t>(old_elements->length());
6323 // Fill out the new array with this content and array holes.
6324 for (uint32_t i = 0; i < old_length; i++) {
6325 elems->set(i, old_elements->get(i), mode);
6326 }
6327 break;
6328 }
6329 case DICTIONARY_ELEMENTS: {
6330 NumberDictionary* dictionary = NumberDictionary::cast(elements());
6331 for (int i = 0; i < dictionary->Capacity(); i++) {
6332 Object* key = dictionary->KeyAt(i);
6333 if (key->IsNumber()) {
6334 uint32_t entry = static_cast<uint32_t>(key->Number());
6335 elems->set(entry, dictionary->ValueAt(i), mode);
6336 }
6337 }
6338 break;
6339 }
6340 default:
6341 UNREACHABLE();
6342 break;
6343 }
Steve Block8defd9f2010-07-08 12:39:36 +01006344
6345 set_map(new_map);
Steve Blocka7e24c12009-10-30 11:49:00 +00006346 set_elements(elems);
Steve Block8defd9f2010-07-08 12:39:36 +01006347
6348 if (IsJSArray()) {
6349 JSArray::cast(this)->set_length(Smi::FromInt(length));
6350 }
6351
6352 return this;
Steve Blocka7e24c12009-10-30 11:49:00 +00006353}
6354
6355
John Reck59135872010-11-02 12:39:01 -07006356MaybeObject* JSObject::SetSlowElements(Object* len) {
Steve Block3ce2e202009-11-05 08:53:23 +00006357 // We should never end in here with a pixel or external array.
6358 ASSERT(!HasPixelElements() && !HasExternalArrayElements());
Steve Blocka7e24c12009-10-30 11:49:00 +00006359
6360 uint32_t new_length = static_cast<uint32_t>(len->Number());
6361
6362 switch (GetElementsKind()) {
6363 case FAST_ELEMENTS: {
6364 // Make sure we never try to shrink dense arrays into sparse arrays.
6365 ASSERT(static_cast<uint32_t>(FixedArray::cast(elements())->length()) <=
6366 new_length);
John Reck59135872010-11-02 12:39:01 -07006367 Object* obj;
6368 { MaybeObject* maybe_obj = NormalizeElements();
6369 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
6370 }
Steve Blocka7e24c12009-10-30 11:49:00 +00006371
6372 // Update length for JSArrays.
6373 if (IsJSArray()) JSArray::cast(this)->set_length(len);
6374 break;
6375 }
6376 case DICTIONARY_ELEMENTS: {
6377 if (IsJSArray()) {
6378 uint32_t old_length =
Steve Block6ded16b2010-05-10 14:33:55 +01006379 static_cast<uint32_t>(JSArray::cast(this)->length()->Number());
Steve Blocka7e24c12009-10-30 11:49:00 +00006380 element_dictionary()->RemoveNumberEntries(new_length, old_length),
6381 JSArray::cast(this)->set_length(len);
6382 }
6383 break;
6384 }
6385 default:
6386 UNREACHABLE();
6387 break;
6388 }
6389 return this;
6390}
6391
6392
John Reck59135872010-11-02 12:39:01 -07006393MaybeObject* JSArray::Initialize(int capacity) {
Steve Blocka7e24c12009-10-30 11:49:00 +00006394 ASSERT(capacity >= 0);
Leon Clarke4515c472010-02-03 11:58:03 +00006395 set_length(Smi::FromInt(0));
Steve Blocka7e24c12009-10-30 11:49:00 +00006396 FixedArray* new_elements;
6397 if (capacity == 0) {
6398 new_elements = Heap::empty_fixed_array();
6399 } else {
John Reck59135872010-11-02 12:39:01 -07006400 Object* obj;
6401 { MaybeObject* maybe_obj = Heap::AllocateFixedArrayWithHoles(capacity);
6402 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
6403 }
Steve Blocka7e24c12009-10-30 11:49:00 +00006404 new_elements = FixedArray::cast(obj);
6405 }
6406 set_elements(new_elements);
6407 return this;
6408}
6409
6410
6411void JSArray::Expand(int required_size) {
6412 Handle<JSArray> self(this);
6413 Handle<FixedArray> old_backing(FixedArray::cast(elements()));
6414 int old_size = old_backing->length();
Steve Blockd0582a62009-12-15 09:54:21 +00006415 int new_size = required_size > old_size ? required_size : old_size;
Steve Blocka7e24c12009-10-30 11:49:00 +00006416 Handle<FixedArray> new_backing = Factory::NewFixedArray(new_size);
6417 // Can't use this any more now because we may have had a GC!
6418 for (int i = 0; i < old_size; i++) new_backing->set(i, old_backing->get(i));
6419 self->SetContent(*new_backing);
6420}
6421
6422
6423// Computes the new capacity when expanding the elements of a JSObject.
6424static int NewElementsCapacity(int old_capacity) {
6425 // (old_capacity + 50%) + 16
6426 return old_capacity + (old_capacity >> 1) + 16;
6427}
6428
6429
John Reck59135872010-11-02 12:39:01 -07006430static Failure* ArrayLengthRangeError() {
Steve Blocka7e24c12009-10-30 11:49:00 +00006431 HandleScope scope;
6432 return Top::Throw(*Factory::NewRangeError("invalid_array_length",
6433 HandleVector<Object>(NULL, 0)));
6434}
6435
6436
John Reck59135872010-11-02 12:39:01 -07006437MaybeObject* JSObject::SetElementsLength(Object* len) {
Steve Block3ce2e202009-11-05 08:53:23 +00006438 // We should never end in here with a pixel or external array.
Steve Block6ded16b2010-05-10 14:33:55 +01006439 ASSERT(AllowsSetElementsLength());
Steve Blocka7e24c12009-10-30 11:49:00 +00006440
John Reck59135872010-11-02 12:39:01 -07006441 MaybeObject* maybe_smi_length = len->ToSmi();
6442 Object* smi_length = Smi::FromInt(0);
6443 if (maybe_smi_length->ToObject(&smi_length) && smi_length->IsSmi()) {
Steve Block8defd9f2010-07-08 12:39:36 +01006444 const int value = Smi::cast(smi_length)->value();
Steve Blocka7e24c12009-10-30 11:49:00 +00006445 if (value < 0) return ArrayLengthRangeError();
6446 switch (GetElementsKind()) {
6447 case FAST_ELEMENTS: {
6448 int old_capacity = FixedArray::cast(elements())->length();
6449 if (value <= old_capacity) {
6450 if (IsJSArray()) {
John Reck59135872010-11-02 12:39:01 -07006451 Object* obj;
6452 { MaybeObject* maybe_obj = EnsureWritableFastElements();
6453 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
6454 }
Steve Blocka7e24c12009-10-30 11:49:00 +00006455 int old_length = FastD2I(JSArray::cast(this)->length()->Number());
6456 // NOTE: We may be able to optimize this by removing the
6457 // last part of the elements backing storage array and
6458 // setting the capacity to the new size.
6459 for (int i = value; i < old_length; i++) {
6460 FixedArray::cast(elements())->set_the_hole(i);
6461 }
Leon Clarke4515c472010-02-03 11:58:03 +00006462 JSArray::cast(this)->set_length(Smi::cast(smi_length));
Steve Blocka7e24c12009-10-30 11:49:00 +00006463 }
6464 return this;
6465 }
6466 int min = NewElementsCapacity(old_capacity);
6467 int new_capacity = value > min ? value : min;
6468 if (new_capacity <= kMaxFastElementsLength ||
6469 !ShouldConvertToSlowElements(new_capacity)) {
John Reck59135872010-11-02 12:39:01 -07006470 Object* obj;
6471 { MaybeObject* maybe_obj =
6472 SetFastElementsCapacityAndLength(new_capacity, value);
6473 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
6474 }
Steve Blocka7e24c12009-10-30 11:49:00 +00006475 return this;
6476 }
6477 break;
6478 }
6479 case DICTIONARY_ELEMENTS: {
6480 if (IsJSArray()) {
6481 if (value == 0) {
6482 // If the length of a slow array is reset to zero, we clear
6483 // the array and flush backing storage. This has the added
6484 // benefit that the array returns to fast mode.
John Reck59135872010-11-02 12:39:01 -07006485 Object* obj;
6486 { MaybeObject* maybe_obj = ResetElements();
6487 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
6488 }
Steve Blocka7e24c12009-10-30 11:49:00 +00006489 } else {
6490 // Remove deleted elements.
6491 uint32_t old_length =
6492 static_cast<uint32_t>(JSArray::cast(this)->length()->Number());
6493 element_dictionary()->RemoveNumberEntries(value, old_length);
6494 }
Leon Clarke4515c472010-02-03 11:58:03 +00006495 JSArray::cast(this)->set_length(Smi::cast(smi_length));
Steve Blocka7e24c12009-10-30 11:49:00 +00006496 }
6497 return this;
6498 }
6499 default:
6500 UNREACHABLE();
6501 break;
6502 }
6503 }
6504
6505 // General slow case.
6506 if (len->IsNumber()) {
6507 uint32_t length;
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01006508 if (len->ToArrayIndex(&length)) {
Steve Blocka7e24c12009-10-30 11:49:00 +00006509 return SetSlowElements(len);
6510 } else {
6511 return ArrayLengthRangeError();
6512 }
6513 }
6514
6515 // len is not a number so make the array size one and
6516 // set only element to len.
John Reck59135872010-11-02 12:39:01 -07006517 Object* obj;
6518 { MaybeObject* maybe_obj = Heap::AllocateFixedArray(1);
6519 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
6520 }
Steve Blocka7e24c12009-10-30 11:49:00 +00006521 FixedArray::cast(obj)->set(0, len);
Leon Clarke4515c472010-02-03 11:58:03 +00006522 if (IsJSArray()) JSArray::cast(this)->set_length(Smi::FromInt(1));
Steve Blocka7e24c12009-10-30 11:49:00 +00006523 set_elements(FixedArray::cast(obj));
6524 return this;
6525}
6526
6527
John Reck59135872010-11-02 12:39:01 -07006528MaybeObject* JSObject::SetPrototype(Object* value,
6529 bool skip_hidden_prototypes) {
Andrei Popescu402d9372010-02-26 13:31:12 +00006530 // Silently ignore the change if value is not a JSObject or null.
6531 // SpiderMonkey behaves this way.
6532 if (!value->IsJSObject() && !value->IsNull()) return value;
6533
6534 // Before we can set the prototype we need to be sure
6535 // prototype cycles are prevented.
6536 // It is sufficient to validate that the receiver is not in the new prototype
6537 // chain.
6538 for (Object* pt = value; pt != Heap::null_value(); pt = pt->GetPrototype()) {
6539 if (JSObject::cast(pt) == this) {
6540 // Cycle detected.
6541 HandleScope scope;
6542 return Top::Throw(*Factory::NewError("cyclic_proto",
6543 HandleVector<Object>(NULL, 0)));
6544 }
6545 }
6546
6547 JSObject* real_receiver = this;
6548
6549 if (skip_hidden_prototypes) {
6550 // Find the first object in the chain whose prototype object is not
6551 // hidden and set the new prototype on that object.
6552 Object* current_proto = real_receiver->GetPrototype();
6553 while (current_proto->IsJSObject() &&
6554 JSObject::cast(current_proto)->map()->is_hidden_prototype()) {
6555 real_receiver = JSObject::cast(current_proto);
6556 current_proto = current_proto->GetPrototype();
6557 }
6558 }
6559
6560 // Set the new prototype of the object.
John Reck59135872010-11-02 12:39:01 -07006561 Object* new_map;
6562 { MaybeObject* maybe_new_map = real_receiver->map()->CopyDropTransitions();
6563 if (!maybe_new_map->ToObject(&new_map)) return maybe_new_map;
6564 }
Andrei Popescu402d9372010-02-26 13:31:12 +00006565 Map::cast(new_map)->set_prototype(value);
6566 real_receiver->set_map(Map::cast(new_map));
6567
Kristian Monsen25f61362010-05-21 11:50:48 +01006568 Heap::ClearInstanceofCache();
6569
Andrei Popescu402d9372010-02-26 13:31:12 +00006570 return value;
6571}
6572
6573
Steve Blocka7e24c12009-10-30 11:49:00 +00006574bool JSObject::HasElementPostInterceptor(JSObject* receiver, uint32_t index) {
6575 switch (GetElementsKind()) {
6576 case FAST_ELEMENTS: {
6577 uint32_t length = IsJSArray() ?
6578 static_cast<uint32_t>
6579 (Smi::cast(JSArray::cast(this)->length())->value()) :
6580 static_cast<uint32_t>(FixedArray::cast(elements())->length());
6581 if ((index < length) &&
6582 !FixedArray::cast(elements())->get(index)->IsTheHole()) {
6583 return true;
6584 }
6585 break;
6586 }
6587 case PIXEL_ELEMENTS: {
6588 // TODO(iposva): Add testcase.
6589 PixelArray* pixels = PixelArray::cast(elements());
6590 if (index < static_cast<uint32_t>(pixels->length())) {
6591 return true;
6592 }
6593 break;
6594 }
Steve Block3ce2e202009-11-05 08:53:23 +00006595 case EXTERNAL_BYTE_ELEMENTS:
6596 case EXTERNAL_UNSIGNED_BYTE_ELEMENTS:
6597 case EXTERNAL_SHORT_ELEMENTS:
6598 case EXTERNAL_UNSIGNED_SHORT_ELEMENTS:
6599 case EXTERNAL_INT_ELEMENTS:
6600 case EXTERNAL_UNSIGNED_INT_ELEMENTS:
6601 case EXTERNAL_FLOAT_ELEMENTS: {
6602 // TODO(kbr): Add testcase.
6603 ExternalArray* array = ExternalArray::cast(elements());
6604 if (index < static_cast<uint32_t>(array->length())) {
6605 return true;
6606 }
6607 break;
6608 }
Steve Blocka7e24c12009-10-30 11:49:00 +00006609 case DICTIONARY_ELEMENTS: {
6610 if (element_dictionary()->FindEntry(index)
6611 != NumberDictionary::kNotFound) {
6612 return true;
6613 }
6614 break;
6615 }
6616 default:
6617 UNREACHABLE();
6618 break;
6619 }
6620
6621 // Handle [] on String objects.
6622 if (this->IsStringObjectWithCharacterAt(index)) return true;
6623
6624 Object* pt = GetPrototype();
6625 if (pt == Heap::null_value()) return false;
6626 return JSObject::cast(pt)->HasElementWithReceiver(receiver, index);
6627}
6628
6629
6630bool JSObject::HasElementWithInterceptor(JSObject* receiver, uint32_t index) {
6631 // Make sure that the top context does not change when doing
6632 // callbacks or interceptor calls.
6633 AssertNoContextChange ncc;
6634 HandleScope scope;
6635 Handle<InterceptorInfo> interceptor(GetIndexedInterceptor());
6636 Handle<JSObject> receiver_handle(receiver);
6637 Handle<JSObject> holder_handle(this);
6638 CustomArguments args(interceptor->data(), receiver, this);
6639 v8::AccessorInfo info(args.end());
6640 if (!interceptor->query()->IsUndefined()) {
6641 v8::IndexedPropertyQuery query =
6642 v8::ToCData<v8::IndexedPropertyQuery>(interceptor->query());
6643 LOG(ApiIndexedPropertyAccess("interceptor-indexed-has", this, index));
Iain Merrick75681382010-08-19 15:07:18 +01006644 v8::Handle<v8::Integer> result;
Steve Blocka7e24c12009-10-30 11:49:00 +00006645 {
6646 // Leaving JavaScript.
6647 VMState state(EXTERNAL);
6648 result = query(index, info);
6649 }
Iain Merrick75681382010-08-19 15:07:18 +01006650 if (!result.IsEmpty()) {
6651 ASSERT(result->IsInt32());
6652 return true; // absence of property is signaled by empty handle.
6653 }
Steve Blocka7e24c12009-10-30 11:49:00 +00006654 } else if (!interceptor->getter()->IsUndefined()) {
6655 v8::IndexedPropertyGetter getter =
6656 v8::ToCData<v8::IndexedPropertyGetter>(interceptor->getter());
6657 LOG(ApiIndexedPropertyAccess("interceptor-indexed-has-get", this, index));
6658 v8::Handle<v8::Value> result;
6659 {
6660 // Leaving JavaScript.
6661 VMState state(EXTERNAL);
6662 result = getter(index, info);
6663 }
6664 if (!result.IsEmpty()) return true;
6665 }
6666 return holder_handle->HasElementPostInterceptor(*receiver_handle, index);
6667}
6668
6669
Kristian Monsen0d5e1162010-09-30 15:31:59 +01006670JSObject::LocalElementType JSObject::HasLocalElement(uint32_t index) {
Steve Blocka7e24c12009-10-30 11:49:00 +00006671 // Check access rights if needed.
6672 if (IsAccessCheckNeeded() &&
6673 !Top::MayIndexedAccess(this, index, v8::ACCESS_HAS)) {
6674 Top::ReportFailedAccessCheck(this, v8::ACCESS_HAS);
Kristian Monsen0d5e1162010-09-30 15:31:59 +01006675 return UNDEFINED_ELEMENT;
Steve Blocka7e24c12009-10-30 11:49:00 +00006676 }
6677
6678 // Check for lookup interceptor
6679 if (HasIndexedInterceptor()) {
Kristian Monsen0d5e1162010-09-30 15:31:59 +01006680 return HasElementWithInterceptor(this, index) ? INTERCEPTED_ELEMENT
6681 : UNDEFINED_ELEMENT;
Steve Blocka7e24c12009-10-30 11:49:00 +00006682 }
6683
6684 // Handle [] on String objects.
Kristian Monsen0d5e1162010-09-30 15:31:59 +01006685 if (this->IsStringObjectWithCharacterAt(index)) {
6686 return STRING_CHARACTER_ELEMENT;
6687 }
Steve Blocka7e24c12009-10-30 11:49:00 +00006688
6689 switch (GetElementsKind()) {
6690 case FAST_ELEMENTS: {
6691 uint32_t length = IsJSArray() ?
6692 static_cast<uint32_t>
6693 (Smi::cast(JSArray::cast(this)->length())->value()) :
6694 static_cast<uint32_t>(FixedArray::cast(elements())->length());
Kristian Monsen0d5e1162010-09-30 15:31:59 +01006695 if ((index < length) &&
6696 !FixedArray::cast(elements())->get(index)->IsTheHole()) {
6697 return FAST_ELEMENT;
6698 }
6699 break;
Steve Blocka7e24c12009-10-30 11:49:00 +00006700 }
6701 case PIXEL_ELEMENTS: {
6702 PixelArray* pixels = PixelArray::cast(elements());
Kristian Monsen0d5e1162010-09-30 15:31:59 +01006703 if (index < static_cast<uint32_t>(pixels->length())) return FAST_ELEMENT;
6704 break;
Steve Blocka7e24c12009-10-30 11:49:00 +00006705 }
Steve Block3ce2e202009-11-05 08:53:23 +00006706 case EXTERNAL_BYTE_ELEMENTS:
6707 case EXTERNAL_UNSIGNED_BYTE_ELEMENTS:
6708 case EXTERNAL_SHORT_ELEMENTS:
6709 case EXTERNAL_UNSIGNED_SHORT_ELEMENTS:
6710 case EXTERNAL_INT_ELEMENTS:
6711 case EXTERNAL_UNSIGNED_INT_ELEMENTS:
6712 case EXTERNAL_FLOAT_ELEMENTS: {
6713 ExternalArray* array = ExternalArray::cast(elements());
Kristian Monsen0d5e1162010-09-30 15:31:59 +01006714 if (index < static_cast<uint32_t>(array->length())) return FAST_ELEMENT;
6715 break;
Steve Block3ce2e202009-11-05 08:53:23 +00006716 }
Steve Blocka7e24c12009-10-30 11:49:00 +00006717 case DICTIONARY_ELEMENTS: {
Kristian Monsen0d5e1162010-09-30 15:31:59 +01006718 if (element_dictionary()->FindEntry(index) !=
6719 NumberDictionary::kNotFound) {
6720 return DICTIONARY_ELEMENT;
6721 }
6722 break;
Steve Blocka7e24c12009-10-30 11:49:00 +00006723 }
6724 default:
6725 UNREACHABLE();
6726 break;
6727 }
Kristian Monsen0d5e1162010-09-30 15:31:59 +01006728
6729 return UNDEFINED_ELEMENT;
Steve Blocka7e24c12009-10-30 11:49:00 +00006730}
6731
6732
6733bool JSObject::HasElementWithReceiver(JSObject* receiver, uint32_t index) {
6734 // Check access rights if needed.
6735 if (IsAccessCheckNeeded() &&
6736 !Top::MayIndexedAccess(this, index, v8::ACCESS_HAS)) {
6737 Top::ReportFailedAccessCheck(this, v8::ACCESS_HAS);
6738 return false;
6739 }
6740
6741 // Check for lookup interceptor
6742 if (HasIndexedInterceptor()) {
6743 return HasElementWithInterceptor(receiver, index);
6744 }
6745
6746 switch (GetElementsKind()) {
6747 case FAST_ELEMENTS: {
6748 uint32_t length = IsJSArray() ?
6749 static_cast<uint32_t>
6750 (Smi::cast(JSArray::cast(this)->length())->value()) :
6751 static_cast<uint32_t>(FixedArray::cast(elements())->length());
6752 if ((index < length) &&
6753 !FixedArray::cast(elements())->get(index)->IsTheHole()) return true;
6754 break;
6755 }
6756 case PIXEL_ELEMENTS: {
6757 PixelArray* pixels = PixelArray::cast(elements());
6758 if (index < static_cast<uint32_t>(pixels->length())) {
6759 return true;
6760 }
6761 break;
6762 }
Steve Block3ce2e202009-11-05 08:53:23 +00006763 case EXTERNAL_BYTE_ELEMENTS:
6764 case EXTERNAL_UNSIGNED_BYTE_ELEMENTS:
6765 case EXTERNAL_SHORT_ELEMENTS:
6766 case EXTERNAL_UNSIGNED_SHORT_ELEMENTS:
6767 case EXTERNAL_INT_ELEMENTS:
6768 case EXTERNAL_UNSIGNED_INT_ELEMENTS:
6769 case EXTERNAL_FLOAT_ELEMENTS: {
6770 ExternalArray* array = ExternalArray::cast(elements());
6771 if (index < static_cast<uint32_t>(array->length())) {
6772 return true;
6773 }
6774 break;
6775 }
Steve Blocka7e24c12009-10-30 11:49:00 +00006776 case DICTIONARY_ELEMENTS: {
6777 if (element_dictionary()->FindEntry(index)
6778 != NumberDictionary::kNotFound) {
6779 return true;
6780 }
6781 break;
6782 }
6783 default:
6784 UNREACHABLE();
6785 break;
6786 }
6787
6788 // Handle [] on String objects.
6789 if (this->IsStringObjectWithCharacterAt(index)) return true;
6790
6791 Object* pt = GetPrototype();
6792 if (pt == Heap::null_value()) return false;
6793 return JSObject::cast(pt)->HasElementWithReceiver(receiver, index);
6794}
6795
6796
John Reck59135872010-11-02 12:39:01 -07006797MaybeObject* JSObject::SetElementWithInterceptor(uint32_t index,
Steve Block9fac8402011-05-12 15:51:54 +01006798 Object* value,
6799 bool check_prototype) {
Steve Blocka7e24c12009-10-30 11:49:00 +00006800 // Make sure that the top context does not change when doing
6801 // callbacks or interceptor calls.
6802 AssertNoContextChange ncc;
6803 HandleScope scope;
6804 Handle<InterceptorInfo> interceptor(GetIndexedInterceptor());
6805 Handle<JSObject> this_handle(this);
6806 Handle<Object> value_handle(value);
6807 if (!interceptor->setter()->IsUndefined()) {
6808 v8::IndexedPropertySetter setter =
6809 v8::ToCData<v8::IndexedPropertySetter>(interceptor->setter());
6810 LOG(ApiIndexedPropertyAccess("interceptor-indexed-set", this, index));
6811 CustomArguments args(interceptor->data(), this, this);
6812 v8::AccessorInfo info(args.end());
6813 v8::Handle<v8::Value> result;
6814 {
6815 // Leaving JavaScript.
6816 VMState state(EXTERNAL);
6817 result = setter(index, v8::Utils::ToLocal(value_handle), info);
6818 }
6819 RETURN_IF_SCHEDULED_EXCEPTION();
6820 if (!result.IsEmpty()) return *value_handle;
6821 }
John Reck59135872010-11-02 12:39:01 -07006822 MaybeObject* raw_result =
Steve Block9fac8402011-05-12 15:51:54 +01006823 this_handle->SetElementWithoutInterceptor(index,
6824 *value_handle,
6825 check_prototype);
Steve Blocka7e24c12009-10-30 11:49:00 +00006826 RETURN_IF_SCHEDULED_EXCEPTION();
6827 return raw_result;
6828}
6829
6830
John Reck59135872010-11-02 12:39:01 -07006831MaybeObject* JSObject::GetElementWithCallback(Object* receiver,
6832 Object* structure,
6833 uint32_t index,
6834 Object* holder) {
Leon Clarkef7060e22010-06-03 12:02:55 +01006835 ASSERT(!structure->IsProxy());
6836
6837 // api style callbacks.
6838 if (structure->IsAccessorInfo()) {
6839 AccessorInfo* data = AccessorInfo::cast(structure);
6840 Object* fun_obj = data->getter();
6841 v8::AccessorGetter call_fun = v8::ToCData<v8::AccessorGetter>(fun_obj);
6842 HandleScope scope;
6843 Handle<JSObject> self(JSObject::cast(receiver));
6844 Handle<JSObject> holder_handle(JSObject::cast(holder));
6845 Handle<Object> number = Factory::NewNumberFromUint(index);
6846 Handle<String> key(Factory::NumberToString(number));
6847 LOG(ApiNamedPropertyAccess("load", *self, *key));
6848 CustomArguments args(data->data(), *self, *holder_handle);
6849 v8::AccessorInfo info(args.end());
6850 v8::Handle<v8::Value> result;
6851 {
6852 // Leaving JavaScript.
6853 VMState state(EXTERNAL);
6854 result = call_fun(v8::Utils::ToLocal(key), info);
6855 }
6856 RETURN_IF_SCHEDULED_EXCEPTION();
6857 if (result.IsEmpty()) return Heap::undefined_value();
6858 return *v8::Utils::OpenHandle(*result);
6859 }
6860
6861 // __defineGetter__ callback
6862 if (structure->IsFixedArray()) {
6863 Object* getter = FixedArray::cast(structure)->get(kGetterIndex);
6864 if (getter->IsJSFunction()) {
6865 return Object::GetPropertyWithDefinedGetter(receiver,
6866 JSFunction::cast(getter));
6867 }
6868 // Getter is not a function.
6869 return Heap::undefined_value();
6870 }
6871
6872 UNREACHABLE();
6873 return NULL;
6874}
6875
6876
John Reck59135872010-11-02 12:39:01 -07006877MaybeObject* JSObject::SetElementWithCallback(Object* structure,
6878 uint32_t index,
6879 Object* value,
6880 JSObject* holder) {
Leon Clarkef7060e22010-06-03 12:02:55 +01006881 HandleScope scope;
6882
6883 // We should never get here to initialize a const with the hole
6884 // value since a const declaration would conflict with the setter.
6885 ASSERT(!value->IsTheHole());
6886 Handle<Object> value_handle(value);
6887
6888 // To accommodate both the old and the new api we switch on the
6889 // data structure used to store the callbacks. Eventually proxy
6890 // callbacks should be phased out.
6891 ASSERT(!structure->IsProxy());
6892
6893 if (structure->IsAccessorInfo()) {
6894 // api style callbacks
6895 AccessorInfo* data = AccessorInfo::cast(structure);
6896 Object* call_obj = data->setter();
6897 v8::AccessorSetter call_fun = v8::ToCData<v8::AccessorSetter>(call_obj);
6898 if (call_fun == NULL) return value;
6899 Handle<Object> number = Factory::NewNumberFromUint(index);
6900 Handle<String> key(Factory::NumberToString(number));
6901 LOG(ApiNamedPropertyAccess("store", this, *key));
6902 CustomArguments args(data->data(), this, JSObject::cast(holder));
6903 v8::AccessorInfo info(args.end());
6904 {
6905 // Leaving JavaScript.
6906 VMState state(EXTERNAL);
6907 call_fun(v8::Utils::ToLocal(key),
6908 v8::Utils::ToLocal(value_handle),
6909 info);
6910 }
6911 RETURN_IF_SCHEDULED_EXCEPTION();
6912 return *value_handle;
6913 }
6914
6915 if (structure->IsFixedArray()) {
6916 Object* setter = FixedArray::cast(structure)->get(kSetterIndex);
6917 if (setter->IsJSFunction()) {
6918 return SetPropertyWithDefinedSetter(JSFunction::cast(setter), value);
6919 } else {
6920 Handle<Object> holder_handle(holder);
6921 Handle<Object> key(Factory::NewNumberFromUint(index));
6922 Handle<Object> args[2] = { key, holder_handle };
6923 return Top::Throw(*Factory::NewTypeError("no_setter_in_callback",
6924 HandleVector(args, 2)));
6925 }
6926 }
6927
6928 UNREACHABLE();
6929 return NULL;
6930}
6931
6932
Steve Blocka7e24c12009-10-30 11:49:00 +00006933// Adding n elements in fast case is O(n*n).
6934// Note: revisit design to have dual undefined values to capture absent
6935// elements.
Steve Block9fac8402011-05-12 15:51:54 +01006936MaybeObject* JSObject::SetFastElement(uint32_t index,
6937 Object* value,
6938 bool check_prototype) {
Steve Blocka7e24c12009-10-30 11:49:00 +00006939 ASSERT(HasFastElements());
6940
John Reck59135872010-11-02 12:39:01 -07006941 Object* elms_obj;
6942 { MaybeObject* maybe_elms_obj = EnsureWritableFastElements();
6943 if (!maybe_elms_obj->ToObject(&elms_obj)) return maybe_elms_obj;
6944 }
Iain Merrick75681382010-08-19 15:07:18 +01006945 FixedArray* elms = FixedArray::cast(elms_obj);
Steve Blocka7e24c12009-10-30 11:49:00 +00006946 uint32_t elms_length = static_cast<uint32_t>(elms->length());
6947
Steve Block9fac8402011-05-12 15:51:54 +01006948 if (check_prototype &&
6949 (index >= elms_length || elms->get(index)->IsTheHole()) &&
6950 SetElementWithCallbackSetterInPrototypes(index, value)) {
6951 return value;
Steve Blocka7e24c12009-10-30 11:49:00 +00006952 }
6953
Steve Block9fac8402011-05-12 15:51:54 +01006954
Steve Blocka7e24c12009-10-30 11:49:00 +00006955 // Check whether there is extra space in fixed array..
6956 if (index < elms_length) {
6957 elms->set(index, value);
6958 if (IsJSArray()) {
6959 // Update the length of the array if needed.
6960 uint32_t array_length = 0;
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01006961 CHECK(JSArray::cast(this)->length()->ToArrayIndex(&array_length));
Steve Blocka7e24c12009-10-30 11:49:00 +00006962 if (index >= array_length) {
Leon Clarke4515c472010-02-03 11:58:03 +00006963 JSArray::cast(this)->set_length(Smi::FromInt(index + 1));
Steve Blocka7e24c12009-10-30 11:49:00 +00006964 }
6965 }
6966 return value;
6967 }
6968
6969 // Allow gap in fast case.
6970 if ((index - elms_length) < kMaxGap) {
6971 // Try allocating extra space.
6972 int new_capacity = NewElementsCapacity(index+1);
6973 if (new_capacity <= kMaxFastElementsLength ||
6974 !ShouldConvertToSlowElements(new_capacity)) {
6975 ASSERT(static_cast<uint32_t>(new_capacity) > index);
John Reck59135872010-11-02 12:39:01 -07006976 Object* obj;
6977 { MaybeObject* maybe_obj =
6978 SetFastElementsCapacityAndLength(new_capacity, index + 1);
6979 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
6980 }
Steve Blocka7e24c12009-10-30 11:49:00 +00006981 FixedArray::cast(elements())->set(index, value);
6982 return value;
6983 }
6984 }
6985
6986 // Otherwise default to slow case.
John Reck59135872010-11-02 12:39:01 -07006987 Object* obj;
6988 { MaybeObject* maybe_obj = NormalizeElements();
6989 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
6990 }
Steve Blocka7e24c12009-10-30 11:49:00 +00006991 ASSERT(HasDictionaryElements());
Steve Block9fac8402011-05-12 15:51:54 +01006992 return SetElement(index, value, check_prototype);
Steve Blocka7e24c12009-10-30 11:49:00 +00006993}
6994
Iain Merrick75681382010-08-19 15:07:18 +01006995
Steve Block9fac8402011-05-12 15:51:54 +01006996MaybeObject* JSObject::SetElement(uint32_t index,
6997 Object* value,
6998 bool check_prototype) {
Steve Blocka7e24c12009-10-30 11:49:00 +00006999 // Check access rights if needed.
7000 if (IsAccessCheckNeeded() &&
7001 !Top::MayIndexedAccess(this, index, v8::ACCESS_SET)) {
Iain Merrick75681382010-08-19 15:07:18 +01007002 HandleScope scope;
7003 Handle<Object> value_handle(value);
Steve Blocka7e24c12009-10-30 11:49:00 +00007004 Top::ReportFailedAccessCheck(this, v8::ACCESS_SET);
Iain Merrick75681382010-08-19 15:07:18 +01007005 return *value_handle;
Steve Blocka7e24c12009-10-30 11:49:00 +00007006 }
7007
7008 if (IsJSGlobalProxy()) {
7009 Object* proto = GetPrototype();
7010 if (proto->IsNull()) return value;
7011 ASSERT(proto->IsJSGlobalObject());
Steve Block9fac8402011-05-12 15:51:54 +01007012 return JSObject::cast(proto)->SetElement(index, value, check_prototype);
Steve Blocka7e24c12009-10-30 11:49:00 +00007013 }
7014
7015 // Check for lookup interceptor
7016 if (HasIndexedInterceptor()) {
Steve Block9fac8402011-05-12 15:51:54 +01007017 return SetElementWithInterceptor(index, value, check_prototype);
Steve Blocka7e24c12009-10-30 11:49:00 +00007018 }
7019
Steve Block9fac8402011-05-12 15:51:54 +01007020 return SetElementWithoutInterceptor(index, value, check_prototype);
Steve Blocka7e24c12009-10-30 11:49:00 +00007021}
7022
7023
John Reck59135872010-11-02 12:39:01 -07007024MaybeObject* JSObject::SetElementWithoutInterceptor(uint32_t index,
Steve Block9fac8402011-05-12 15:51:54 +01007025 Object* value,
7026 bool check_prototype) {
Steve Blocka7e24c12009-10-30 11:49:00 +00007027 switch (GetElementsKind()) {
7028 case FAST_ELEMENTS:
7029 // Fast case.
Steve Block9fac8402011-05-12 15:51:54 +01007030 return SetFastElement(index, value, check_prototype);
Steve Blocka7e24c12009-10-30 11:49:00 +00007031 case PIXEL_ELEMENTS: {
7032 PixelArray* pixels = PixelArray::cast(elements());
7033 return pixels->SetValue(index, value);
7034 }
Steve Block3ce2e202009-11-05 08:53:23 +00007035 case EXTERNAL_BYTE_ELEMENTS: {
7036 ExternalByteArray* array = ExternalByteArray::cast(elements());
7037 return array->SetValue(index, value);
7038 }
7039 case EXTERNAL_UNSIGNED_BYTE_ELEMENTS: {
7040 ExternalUnsignedByteArray* array =
7041 ExternalUnsignedByteArray::cast(elements());
7042 return array->SetValue(index, value);
7043 }
7044 case EXTERNAL_SHORT_ELEMENTS: {
7045 ExternalShortArray* array = ExternalShortArray::cast(elements());
7046 return array->SetValue(index, value);
7047 }
7048 case EXTERNAL_UNSIGNED_SHORT_ELEMENTS: {
7049 ExternalUnsignedShortArray* array =
7050 ExternalUnsignedShortArray::cast(elements());
7051 return array->SetValue(index, value);
7052 }
7053 case EXTERNAL_INT_ELEMENTS: {
7054 ExternalIntArray* array = ExternalIntArray::cast(elements());
7055 return array->SetValue(index, value);
7056 }
7057 case EXTERNAL_UNSIGNED_INT_ELEMENTS: {
7058 ExternalUnsignedIntArray* array =
7059 ExternalUnsignedIntArray::cast(elements());
7060 return array->SetValue(index, value);
7061 }
7062 case EXTERNAL_FLOAT_ELEMENTS: {
7063 ExternalFloatArray* array = ExternalFloatArray::cast(elements());
7064 return array->SetValue(index, value);
7065 }
Steve Blocka7e24c12009-10-30 11:49:00 +00007066 case DICTIONARY_ELEMENTS: {
7067 // Insert element in the dictionary.
7068 FixedArray* elms = FixedArray::cast(elements());
7069 NumberDictionary* dictionary = NumberDictionary::cast(elms);
7070
7071 int entry = dictionary->FindEntry(index);
7072 if (entry != NumberDictionary::kNotFound) {
7073 Object* element = dictionary->ValueAt(entry);
7074 PropertyDetails details = dictionary->DetailsAt(entry);
7075 if (details.type() == CALLBACKS) {
Leon Clarkef7060e22010-06-03 12:02:55 +01007076 return SetElementWithCallback(element, index, value, this);
Steve Blocka7e24c12009-10-30 11:49:00 +00007077 } else {
7078 dictionary->UpdateMaxNumberKey(index);
7079 dictionary->ValueAtPut(entry, value);
7080 }
7081 } else {
7082 // Index not already used. Look for an accessor in the prototype chain.
Steve Block9fac8402011-05-12 15:51:54 +01007083 if (check_prototype &&
7084 SetElementWithCallbackSetterInPrototypes(index, value)) {
7085 return value;
Steve Blocka7e24c12009-10-30 11:49:00 +00007086 }
Steve Block8defd9f2010-07-08 12:39:36 +01007087 // When we set the is_extensible flag to false we always force
7088 // the element into dictionary mode (and force them to stay there).
7089 if (!map()->is_extensible()) {
Ben Murdochf87a2032010-10-22 12:50:53 +01007090 Handle<Object> number(Factory::NewNumberFromUint(index));
Steve Block8defd9f2010-07-08 12:39:36 +01007091 Handle<String> index_string(Factory::NumberToString(number));
7092 Handle<Object> args[1] = { index_string };
7093 return Top::Throw(*Factory::NewTypeError("object_not_extensible",
7094 HandleVector(args, 1)));
7095 }
John Reck59135872010-11-02 12:39:01 -07007096 Object* result;
7097 { MaybeObject* maybe_result = dictionary->AtNumberPut(index, value);
7098 if (!maybe_result->ToObject(&result)) return maybe_result;
7099 }
Steve Blocka7e24c12009-10-30 11:49:00 +00007100 if (elms != FixedArray::cast(result)) {
7101 set_elements(FixedArray::cast(result));
7102 }
7103 }
7104
7105 // Update the array length if this JSObject is an array.
7106 if (IsJSArray()) {
7107 JSArray* array = JSArray::cast(this);
John Reck59135872010-11-02 12:39:01 -07007108 Object* return_value;
7109 { MaybeObject* maybe_return_value =
7110 array->JSArrayUpdateLengthFromIndex(index, value);
7111 if (!maybe_return_value->ToObject(&return_value)) {
7112 return maybe_return_value;
7113 }
7114 }
Steve Blocka7e24c12009-10-30 11:49:00 +00007115 }
7116
7117 // Attempt to put this object back in fast case.
7118 if (ShouldConvertToFastElements()) {
7119 uint32_t new_length = 0;
7120 if (IsJSArray()) {
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01007121 CHECK(JSArray::cast(this)->length()->ToArrayIndex(&new_length));
Steve Blocka7e24c12009-10-30 11:49:00 +00007122 } else {
7123 new_length = NumberDictionary::cast(elements())->max_number_key() + 1;
7124 }
John Reck59135872010-11-02 12:39:01 -07007125 Object* obj;
7126 { MaybeObject* maybe_obj =
7127 SetFastElementsCapacityAndLength(new_length, new_length);
7128 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
7129 }
Steve Blocka7e24c12009-10-30 11:49:00 +00007130#ifdef DEBUG
7131 if (FLAG_trace_normalization) {
7132 PrintF("Object elements are fast case again:\n");
7133 Print();
7134 }
7135#endif
7136 }
7137
7138 return value;
7139 }
7140 default:
7141 UNREACHABLE();
7142 break;
7143 }
7144 // All possible cases have been handled above. Add a return to avoid the
7145 // complaints from the compiler.
7146 UNREACHABLE();
7147 return Heap::null_value();
7148}
7149
7150
John Reck59135872010-11-02 12:39:01 -07007151MaybeObject* JSArray::JSArrayUpdateLengthFromIndex(uint32_t index,
7152 Object* value) {
Steve Blocka7e24c12009-10-30 11:49:00 +00007153 uint32_t old_len = 0;
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01007154 CHECK(length()->ToArrayIndex(&old_len));
Steve Blocka7e24c12009-10-30 11:49:00 +00007155 // Check to see if we need to update the length. For now, we make
7156 // sure that the length stays within 32-bits (unsigned).
7157 if (index >= old_len && index != 0xffffffff) {
John Reck59135872010-11-02 12:39:01 -07007158 Object* len;
7159 { MaybeObject* maybe_len =
7160 Heap::NumberFromDouble(static_cast<double>(index) + 1);
7161 if (!maybe_len->ToObject(&len)) return maybe_len;
7162 }
Steve Blocka7e24c12009-10-30 11:49:00 +00007163 set_length(len);
7164 }
7165 return value;
7166}
7167
7168
John Reck59135872010-11-02 12:39:01 -07007169MaybeObject* JSObject::GetElementPostInterceptor(JSObject* receiver,
7170 uint32_t index) {
Steve Blocka7e24c12009-10-30 11:49:00 +00007171 // Get element works for both JSObject and JSArray since
7172 // JSArray::length cannot change.
7173 switch (GetElementsKind()) {
7174 case FAST_ELEMENTS: {
7175 FixedArray* elms = FixedArray::cast(elements());
7176 if (index < static_cast<uint32_t>(elms->length())) {
7177 Object* value = elms->get(index);
7178 if (!value->IsTheHole()) return value;
7179 }
7180 break;
7181 }
7182 case PIXEL_ELEMENTS: {
7183 // TODO(iposva): Add testcase and implement.
7184 UNIMPLEMENTED();
7185 break;
7186 }
Steve Block3ce2e202009-11-05 08:53:23 +00007187 case EXTERNAL_BYTE_ELEMENTS:
7188 case EXTERNAL_UNSIGNED_BYTE_ELEMENTS:
7189 case EXTERNAL_SHORT_ELEMENTS:
7190 case EXTERNAL_UNSIGNED_SHORT_ELEMENTS:
7191 case EXTERNAL_INT_ELEMENTS:
7192 case EXTERNAL_UNSIGNED_INT_ELEMENTS:
7193 case EXTERNAL_FLOAT_ELEMENTS: {
7194 // TODO(kbr): Add testcase and implement.
7195 UNIMPLEMENTED();
7196 break;
7197 }
Steve Blocka7e24c12009-10-30 11:49:00 +00007198 case DICTIONARY_ELEMENTS: {
7199 NumberDictionary* dictionary = element_dictionary();
7200 int entry = dictionary->FindEntry(index);
7201 if (entry != NumberDictionary::kNotFound) {
7202 Object* element = dictionary->ValueAt(entry);
7203 PropertyDetails details = dictionary->DetailsAt(entry);
7204 if (details.type() == CALLBACKS) {
Leon Clarkef7060e22010-06-03 12:02:55 +01007205 return GetElementWithCallback(receiver,
7206 element,
7207 index,
7208 this);
Steve Blocka7e24c12009-10-30 11:49:00 +00007209 }
7210 return element;
7211 }
7212 break;
7213 }
7214 default:
7215 UNREACHABLE();
7216 break;
7217 }
7218
7219 // Continue searching via the prototype chain.
7220 Object* pt = GetPrototype();
7221 if (pt == Heap::null_value()) return Heap::undefined_value();
7222 return pt->GetElementWithReceiver(receiver, index);
7223}
7224
7225
John Reck59135872010-11-02 12:39:01 -07007226MaybeObject* JSObject::GetElementWithInterceptor(JSObject* receiver,
7227 uint32_t index) {
Steve Blocka7e24c12009-10-30 11:49:00 +00007228 // Make sure that the top context does not change when doing
7229 // callbacks or interceptor calls.
7230 AssertNoContextChange ncc;
7231 HandleScope scope;
7232 Handle<InterceptorInfo> interceptor(GetIndexedInterceptor());
7233 Handle<JSObject> this_handle(receiver);
7234 Handle<JSObject> holder_handle(this);
7235
7236 if (!interceptor->getter()->IsUndefined()) {
7237 v8::IndexedPropertyGetter getter =
7238 v8::ToCData<v8::IndexedPropertyGetter>(interceptor->getter());
7239 LOG(ApiIndexedPropertyAccess("interceptor-indexed-get", this, index));
7240 CustomArguments args(interceptor->data(), receiver, this);
7241 v8::AccessorInfo info(args.end());
7242 v8::Handle<v8::Value> result;
7243 {
7244 // Leaving JavaScript.
7245 VMState state(EXTERNAL);
7246 result = getter(index, info);
7247 }
7248 RETURN_IF_SCHEDULED_EXCEPTION();
7249 if (!result.IsEmpty()) return *v8::Utils::OpenHandle(*result);
7250 }
7251
John Reck59135872010-11-02 12:39:01 -07007252 MaybeObject* raw_result =
Steve Blocka7e24c12009-10-30 11:49:00 +00007253 holder_handle->GetElementPostInterceptor(*this_handle, index);
7254 RETURN_IF_SCHEDULED_EXCEPTION();
7255 return raw_result;
7256}
7257
7258
John Reck59135872010-11-02 12:39:01 -07007259MaybeObject* JSObject::GetElementWithReceiver(JSObject* receiver,
7260 uint32_t index) {
Steve Blocka7e24c12009-10-30 11:49:00 +00007261 // Check access rights if needed.
7262 if (IsAccessCheckNeeded() &&
7263 !Top::MayIndexedAccess(this, index, v8::ACCESS_GET)) {
7264 Top::ReportFailedAccessCheck(this, v8::ACCESS_GET);
7265 return Heap::undefined_value();
7266 }
7267
7268 if (HasIndexedInterceptor()) {
7269 return GetElementWithInterceptor(receiver, index);
7270 }
7271
7272 // Get element works for both JSObject and JSArray since
7273 // JSArray::length cannot change.
7274 switch (GetElementsKind()) {
7275 case FAST_ELEMENTS: {
7276 FixedArray* elms = FixedArray::cast(elements());
7277 if (index < static_cast<uint32_t>(elms->length())) {
7278 Object* value = elms->get(index);
7279 if (!value->IsTheHole()) return value;
7280 }
7281 break;
7282 }
7283 case PIXEL_ELEMENTS: {
7284 PixelArray* pixels = PixelArray::cast(elements());
7285 if (index < static_cast<uint32_t>(pixels->length())) {
7286 uint8_t value = pixels->get(index);
7287 return Smi::FromInt(value);
7288 }
7289 break;
7290 }
Steve Block3ce2e202009-11-05 08:53:23 +00007291 case EXTERNAL_BYTE_ELEMENTS: {
7292 ExternalByteArray* array = ExternalByteArray::cast(elements());
7293 if (index < static_cast<uint32_t>(array->length())) {
7294 int8_t value = array->get(index);
7295 return Smi::FromInt(value);
7296 }
7297 break;
7298 }
7299 case EXTERNAL_UNSIGNED_BYTE_ELEMENTS: {
7300 ExternalUnsignedByteArray* array =
7301 ExternalUnsignedByteArray::cast(elements());
7302 if (index < static_cast<uint32_t>(array->length())) {
7303 uint8_t value = array->get(index);
7304 return Smi::FromInt(value);
7305 }
7306 break;
7307 }
7308 case EXTERNAL_SHORT_ELEMENTS: {
7309 ExternalShortArray* array = ExternalShortArray::cast(elements());
7310 if (index < static_cast<uint32_t>(array->length())) {
7311 int16_t value = array->get(index);
7312 return Smi::FromInt(value);
7313 }
7314 break;
7315 }
7316 case EXTERNAL_UNSIGNED_SHORT_ELEMENTS: {
7317 ExternalUnsignedShortArray* array =
7318 ExternalUnsignedShortArray::cast(elements());
7319 if (index < static_cast<uint32_t>(array->length())) {
7320 uint16_t value = array->get(index);
7321 return Smi::FromInt(value);
7322 }
7323 break;
7324 }
7325 case EXTERNAL_INT_ELEMENTS: {
7326 ExternalIntArray* array = ExternalIntArray::cast(elements());
7327 if (index < static_cast<uint32_t>(array->length())) {
7328 int32_t value = array->get(index);
7329 return Heap::NumberFromInt32(value);
7330 }
7331 break;
7332 }
7333 case EXTERNAL_UNSIGNED_INT_ELEMENTS: {
7334 ExternalUnsignedIntArray* array =
7335 ExternalUnsignedIntArray::cast(elements());
7336 if (index < static_cast<uint32_t>(array->length())) {
7337 uint32_t value = array->get(index);
7338 return Heap::NumberFromUint32(value);
7339 }
7340 break;
7341 }
7342 case EXTERNAL_FLOAT_ELEMENTS: {
7343 ExternalFloatArray* array = ExternalFloatArray::cast(elements());
7344 if (index < static_cast<uint32_t>(array->length())) {
7345 float value = array->get(index);
7346 return Heap::AllocateHeapNumber(value);
7347 }
7348 break;
7349 }
Steve Blocka7e24c12009-10-30 11:49:00 +00007350 case DICTIONARY_ELEMENTS: {
7351 NumberDictionary* dictionary = element_dictionary();
7352 int entry = dictionary->FindEntry(index);
7353 if (entry != NumberDictionary::kNotFound) {
7354 Object* element = dictionary->ValueAt(entry);
7355 PropertyDetails details = dictionary->DetailsAt(entry);
7356 if (details.type() == CALLBACKS) {
Leon Clarkef7060e22010-06-03 12:02:55 +01007357 return GetElementWithCallback(receiver,
7358 element,
7359 index,
7360 this);
Steve Blocka7e24c12009-10-30 11:49:00 +00007361 }
7362 return element;
7363 }
7364 break;
7365 }
7366 }
7367
7368 Object* pt = GetPrototype();
7369 if (pt == Heap::null_value()) return Heap::undefined_value();
7370 return pt->GetElementWithReceiver(receiver, index);
7371}
7372
7373
7374bool JSObject::HasDenseElements() {
7375 int capacity = 0;
7376 int number_of_elements = 0;
7377
7378 switch (GetElementsKind()) {
7379 case FAST_ELEMENTS: {
7380 FixedArray* elms = FixedArray::cast(elements());
7381 capacity = elms->length();
7382 for (int i = 0; i < capacity; i++) {
7383 if (!elms->get(i)->IsTheHole()) number_of_elements++;
7384 }
7385 break;
7386 }
Steve Block3ce2e202009-11-05 08:53:23 +00007387 case PIXEL_ELEMENTS:
7388 case EXTERNAL_BYTE_ELEMENTS:
7389 case EXTERNAL_UNSIGNED_BYTE_ELEMENTS:
7390 case EXTERNAL_SHORT_ELEMENTS:
7391 case EXTERNAL_UNSIGNED_SHORT_ELEMENTS:
7392 case EXTERNAL_INT_ELEMENTS:
7393 case EXTERNAL_UNSIGNED_INT_ELEMENTS:
7394 case EXTERNAL_FLOAT_ELEMENTS: {
Steve Blocka7e24c12009-10-30 11:49:00 +00007395 return true;
7396 }
7397 case DICTIONARY_ELEMENTS: {
7398 NumberDictionary* dictionary = NumberDictionary::cast(elements());
7399 capacity = dictionary->Capacity();
7400 number_of_elements = dictionary->NumberOfElements();
7401 break;
7402 }
7403 default:
7404 UNREACHABLE();
7405 break;
7406 }
7407
7408 if (capacity == 0) return true;
7409 return (number_of_elements > (capacity / 2));
7410}
7411
7412
7413bool JSObject::ShouldConvertToSlowElements(int new_capacity) {
7414 ASSERT(HasFastElements());
7415 // Keep the array in fast case if the current backing storage is
7416 // almost filled and if the new capacity is no more than twice the
7417 // old capacity.
7418 int elements_length = FixedArray::cast(elements())->length();
7419 return !HasDenseElements() || ((new_capacity / 2) > elements_length);
7420}
7421
7422
7423bool JSObject::ShouldConvertToFastElements() {
7424 ASSERT(HasDictionaryElements());
7425 NumberDictionary* dictionary = NumberDictionary::cast(elements());
7426 // If the elements are sparse, we should not go back to fast case.
7427 if (!HasDenseElements()) return false;
7428 // If an element has been added at a very high index in the elements
7429 // dictionary, we cannot go back to fast case.
7430 if (dictionary->requires_slow_elements()) return false;
7431 // An object requiring access checks is never allowed to have fast
7432 // elements. If it had fast elements we would skip security checks.
7433 if (IsAccessCheckNeeded()) return false;
7434 // If the dictionary backing storage takes up roughly half as much
7435 // space as a fast-case backing storage would the array should have
7436 // fast elements.
7437 uint32_t length = 0;
7438 if (IsJSArray()) {
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01007439 CHECK(JSArray::cast(this)->length()->ToArrayIndex(&length));
Steve Blocka7e24c12009-10-30 11:49:00 +00007440 } else {
7441 length = dictionary->max_number_key();
7442 }
7443 return static_cast<uint32_t>(dictionary->Capacity()) >=
7444 (length / (2 * NumberDictionary::kEntrySize));
7445}
7446
7447
7448// Certain compilers request function template instantiation when they
7449// see the definition of the other template functions in the
7450// class. This requires us to have the template functions put
7451// together, so even though this function belongs in objects-debug.cc,
7452// we keep it here instead to satisfy certain compilers.
Ben Murdochb0fe1622011-05-05 13:52:32 +01007453#ifdef OBJECT_PRINT
Steve Blocka7e24c12009-10-30 11:49:00 +00007454template<typename Shape, typename Key>
Ben Murdochb0fe1622011-05-05 13:52:32 +01007455void Dictionary<Shape, Key>::Print(FILE* out) {
Steve Blocka7e24c12009-10-30 11:49:00 +00007456 int capacity = HashTable<Shape, Key>::Capacity();
7457 for (int i = 0; i < capacity; i++) {
7458 Object* k = HashTable<Shape, Key>::KeyAt(i);
7459 if (HashTable<Shape, Key>::IsKey(k)) {
Ben Murdochb0fe1622011-05-05 13:52:32 +01007460 PrintF(out, " ");
Steve Blocka7e24c12009-10-30 11:49:00 +00007461 if (k->IsString()) {
Ben Murdochb0fe1622011-05-05 13:52:32 +01007462 String::cast(k)->StringPrint(out);
Steve Blocka7e24c12009-10-30 11:49:00 +00007463 } else {
Ben Murdochb0fe1622011-05-05 13:52:32 +01007464 k->ShortPrint(out);
Steve Blocka7e24c12009-10-30 11:49:00 +00007465 }
Ben Murdochb0fe1622011-05-05 13:52:32 +01007466 PrintF(out, ": ");
7467 ValueAt(i)->ShortPrint(out);
7468 PrintF(out, "\n");
Steve Blocka7e24c12009-10-30 11:49:00 +00007469 }
7470 }
7471}
7472#endif
7473
7474
7475template<typename Shape, typename Key>
7476void Dictionary<Shape, Key>::CopyValuesTo(FixedArray* elements) {
7477 int pos = 0;
7478 int capacity = HashTable<Shape, Key>::Capacity();
Leon Clarke4515c472010-02-03 11:58:03 +00007479 AssertNoAllocation no_gc;
7480 WriteBarrierMode mode = elements->GetWriteBarrierMode(no_gc);
Steve Blocka7e24c12009-10-30 11:49:00 +00007481 for (int i = 0; i < capacity; i++) {
7482 Object* k = Dictionary<Shape, Key>::KeyAt(i);
7483 if (Dictionary<Shape, Key>::IsKey(k)) {
7484 elements->set(pos++, ValueAt(i), mode);
7485 }
7486 }
7487 ASSERT(pos == elements->length());
7488}
7489
7490
7491InterceptorInfo* JSObject::GetNamedInterceptor() {
7492 ASSERT(map()->has_named_interceptor());
7493 JSFunction* constructor = JSFunction::cast(map()->constructor());
Steve Block6ded16b2010-05-10 14:33:55 +01007494 ASSERT(constructor->shared()->IsApiFunction());
Steve Blocka7e24c12009-10-30 11:49:00 +00007495 Object* result =
Steve Block6ded16b2010-05-10 14:33:55 +01007496 constructor->shared()->get_api_func_data()->named_property_handler();
Steve Blocka7e24c12009-10-30 11:49:00 +00007497 return InterceptorInfo::cast(result);
7498}
7499
7500
7501InterceptorInfo* JSObject::GetIndexedInterceptor() {
7502 ASSERT(map()->has_indexed_interceptor());
7503 JSFunction* constructor = JSFunction::cast(map()->constructor());
Steve Block6ded16b2010-05-10 14:33:55 +01007504 ASSERT(constructor->shared()->IsApiFunction());
Steve Blocka7e24c12009-10-30 11:49:00 +00007505 Object* result =
Steve Block6ded16b2010-05-10 14:33:55 +01007506 constructor->shared()->get_api_func_data()->indexed_property_handler();
Steve Blocka7e24c12009-10-30 11:49:00 +00007507 return InterceptorInfo::cast(result);
7508}
7509
7510
John Reck59135872010-11-02 12:39:01 -07007511MaybeObject* JSObject::GetPropertyPostInterceptor(
7512 JSObject* receiver,
7513 String* name,
7514 PropertyAttributes* attributes) {
Steve Blocka7e24c12009-10-30 11:49:00 +00007515 // Check local property in holder, ignore interceptor.
7516 LookupResult result;
7517 LocalLookupRealNamedProperty(name, &result);
Andrei Popescu402d9372010-02-26 13:31:12 +00007518 if (result.IsProperty()) {
7519 return GetProperty(receiver, &result, name, attributes);
7520 }
Steve Blocka7e24c12009-10-30 11:49:00 +00007521 // Continue searching via the prototype chain.
7522 Object* pt = GetPrototype();
7523 *attributes = ABSENT;
7524 if (pt == Heap::null_value()) return Heap::undefined_value();
7525 return pt->GetPropertyWithReceiver(receiver, name, attributes);
7526}
7527
7528
John Reck59135872010-11-02 12:39:01 -07007529MaybeObject* JSObject::GetLocalPropertyPostInterceptor(
Steve Blockd0582a62009-12-15 09:54:21 +00007530 JSObject* receiver,
7531 String* name,
7532 PropertyAttributes* attributes) {
7533 // Check local property in holder, ignore interceptor.
7534 LookupResult result;
7535 LocalLookupRealNamedProperty(name, &result);
Andrei Popescu402d9372010-02-26 13:31:12 +00007536 if (result.IsProperty()) {
7537 return GetProperty(receiver, &result, name, attributes);
7538 }
7539 return Heap::undefined_value();
Steve Blockd0582a62009-12-15 09:54:21 +00007540}
7541
7542
John Reck59135872010-11-02 12:39:01 -07007543MaybeObject* JSObject::GetPropertyWithInterceptor(
Steve Blocka7e24c12009-10-30 11:49:00 +00007544 JSObject* receiver,
7545 String* name,
7546 PropertyAttributes* attributes) {
7547 InterceptorInfo* interceptor = GetNamedInterceptor();
7548 HandleScope scope;
7549 Handle<JSObject> receiver_handle(receiver);
7550 Handle<JSObject> holder_handle(this);
7551 Handle<String> name_handle(name);
7552
7553 if (!interceptor->getter()->IsUndefined()) {
7554 v8::NamedPropertyGetter getter =
7555 v8::ToCData<v8::NamedPropertyGetter>(interceptor->getter());
7556 LOG(ApiNamedPropertyAccess("interceptor-named-get", *holder_handle, name));
7557 CustomArguments args(interceptor->data(), receiver, this);
7558 v8::AccessorInfo info(args.end());
7559 v8::Handle<v8::Value> result;
7560 {
7561 // Leaving JavaScript.
7562 VMState state(EXTERNAL);
7563 result = getter(v8::Utils::ToLocal(name_handle), info);
7564 }
7565 RETURN_IF_SCHEDULED_EXCEPTION();
7566 if (!result.IsEmpty()) {
7567 *attributes = NONE;
7568 return *v8::Utils::OpenHandle(*result);
7569 }
7570 }
7571
John Reck59135872010-11-02 12:39:01 -07007572 MaybeObject* result = holder_handle->GetPropertyPostInterceptor(
Steve Blocka7e24c12009-10-30 11:49:00 +00007573 *receiver_handle,
7574 *name_handle,
7575 attributes);
7576 RETURN_IF_SCHEDULED_EXCEPTION();
7577 return result;
7578}
7579
7580
7581bool JSObject::HasRealNamedProperty(String* key) {
7582 // Check access rights if needed.
7583 if (IsAccessCheckNeeded() &&
7584 !Top::MayNamedAccess(this, key, v8::ACCESS_HAS)) {
7585 Top::ReportFailedAccessCheck(this, v8::ACCESS_HAS);
7586 return false;
7587 }
7588
7589 LookupResult result;
7590 LocalLookupRealNamedProperty(key, &result);
Andrei Popescu402d9372010-02-26 13:31:12 +00007591 return result.IsProperty() && (result.type() != INTERCEPTOR);
Steve Blocka7e24c12009-10-30 11:49:00 +00007592}
7593
7594
7595bool JSObject::HasRealElementProperty(uint32_t index) {
7596 // Check access rights if needed.
7597 if (IsAccessCheckNeeded() &&
7598 !Top::MayIndexedAccess(this, index, v8::ACCESS_HAS)) {
7599 Top::ReportFailedAccessCheck(this, v8::ACCESS_HAS);
7600 return false;
7601 }
7602
7603 // Handle [] on String objects.
7604 if (this->IsStringObjectWithCharacterAt(index)) return true;
7605
7606 switch (GetElementsKind()) {
7607 case FAST_ELEMENTS: {
7608 uint32_t length = IsJSArray() ?
7609 static_cast<uint32_t>(
7610 Smi::cast(JSArray::cast(this)->length())->value()) :
7611 static_cast<uint32_t>(FixedArray::cast(elements())->length());
7612 return (index < length) &&
7613 !FixedArray::cast(elements())->get(index)->IsTheHole();
7614 }
7615 case PIXEL_ELEMENTS: {
7616 PixelArray* pixels = PixelArray::cast(elements());
7617 return index < static_cast<uint32_t>(pixels->length());
7618 }
Steve Block3ce2e202009-11-05 08:53:23 +00007619 case EXTERNAL_BYTE_ELEMENTS:
7620 case EXTERNAL_UNSIGNED_BYTE_ELEMENTS:
7621 case EXTERNAL_SHORT_ELEMENTS:
7622 case EXTERNAL_UNSIGNED_SHORT_ELEMENTS:
7623 case EXTERNAL_INT_ELEMENTS:
7624 case EXTERNAL_UNSIGNED_INT_ELEMENTS:
7625 case EXTERNAL_FLOAT_ELEMENTS: {
7626 ExternalArray* array = ExternalArray::cast(elements());
7627 return index < static_cast<uint32_t>(array->length());
7628 }
Steve Blocka7e24c12009-10-30 11:49:00 +00007629 case DICTIONARY_ELEMENTS: {
7630 return element_dictionary()->FindEntry(index)
7631 != NumberDictionary::kNotFound;
7632 }
7633 default:
7634 UNREACHABLE();
7635 break;
7636 }
7637 // All possibilities have been handled above already.
7638 UNREACHABLE();
7639 return Heap::null_value();
7640}
7641
7642
7643bool JSObject::HasRealNamedCallbackProperty(String* key) {
7644 // Check access rights if needed.
7645 if (IsAccessCheckNeeded() &&
7646 !Top::MayNamedAccess(this, key, v8::ACCESS_HAS)) {
7647 Top::ReportFailedAccessCheck(this, v8::ACCESS_HAS);
7648 return false;
7649 }
7650
7651 LookupResult result;
7652 LocalLookupRealNamedProperty(key, &result);
Andrei Popescu402d9372010-02-26 13:31:12 +00007653 return result.IsProperty() && (result.type() == CALLBACKS);
Steve Blocka7e24c12009-10-30 11:49:00 +00007654}
7655
7656
7657int JSObject::NumberOfLocalProperties(PropertyAttributes filter) {
7658 if (HasFastProperties()) {
7659 DescriptorArray* descs = map()->instance_descriptors();
7660 int result = 0;
7661 for (int i = 0; i < descs->number_of_descriptors(); i++) {
7662 PropertyDetails details = descs->GetDetails(i);
7663 if (details.IsProperty() && (details.attributes() & filter) == 0) {
7664 result++;
7665 }
7666 }
7667 return result;
7668 } else {
7669 return property_dictionary()->NumberOfElementsFilterAttributes(filter);
7670 }
7671}
7672
7673
7674int JSObject::NumberOfEnumProperties() {
7675 return NumberOfLocalProperties(static_cast<PropertyAttributes>(DONT_ENUM));
7676}
7677
7678
7679void FixedArray::SwapPairs(FixedArray* numbers, int i, int j) {
7680 Object* temp = get(i);
7681 set(i, get(j));
7682 set(j, temp);
7683 if (this != numbers) {
7684 temp = numbers->get(i);
7685 numbers->set(i, numbers->get(j));
7686 numbers->set(j, temp);
7687 }
7688}
7689
7690
7691static void InsertionSortPairs(FixedArray* content,
7692 FixedArray* numbers,
7693 int len) {
7694 for (int i = 1; i < len; i++) {
7695 int j = i;
7696 while (j > 0 &&
7697 (NumberToUint32(numbers->get(j - 1)) >
7698 NumberToUint32(numbers->get(j)))) {
7699 content->SwapPairs(numbers, j - 1, j);
7700 j--;
7701 }
7702 }
7703}
7704
7705
7706void HeapSortPairs(FixedArray* content, FixedArray* numbers, int len) {
7707 // In-place heap sort.
7708 ASSERT(content->length() == numbers->length());
7709
7710 // Bottom-up max-heap construction.
7711 for (int i = 1; i < len; ++i) {
7712 int child_index = i;
7713 while (child_index > 0) {
7714 int parent_index = ((child_index + 1) >> 1) - 1;
7715 uint32_t parent_value = NumberToUint32(numbers->get(parent_index));
7716 uint32_t child_value = NumberToUint32(numbers->get(child_index));
7717 if (parent_value < child_value) {
7718 content->SwapPairs(numbers, parent_index, child_index);
7719 } else {
7720 break;
7721 }
7722 child_index = parent_index;
7723 }
7724 }
7725
7726 // Extract elements and create sorted array.
7727 for (int i = len - 1; i > 0; --i) {
7728 // Put max element at the back of the array.
7729 content->SwapPairs(numbers, 0, i);
7730 // Sift down the new top element.
7731 int parent_index = 0;
7732 while (true) {
7733 int child_index = ((parent_index + 1) << 1) - 1;
7734 if (child_index >= i) break;
7735 uint32_t child1_value = NumberToUint32(numbers->get(child_index));
7736 uint32_t child2_value = NumberToUint32(numbers->get(child_index + 1));
7737 uint32_t parent_value = NumberToUint32(numbers->get(parent_index));
7738 if (child_index + 1 >= i || child1_value > child2_value) {
7739 if (parent_value > child1_value) break;
7740 content->SwapPairs(numbers, parent_index, child_index);
7741 parent_index = child_index;
7742 } else {
7743 if (parent_value > child2_value) break;
7744 content->SwapPairs(numbers, parent_index, child_index + 1);
7745 parent_index = child_index + 1;
7746 }
7747 }
7748 }
7749}
7750
7751
7752// Sort this array and the numbers as pairs wrt. the (distinct) numbers.
7753void FixedArray::SortPairs(FixedArray* numbers, uint32_t len) {
7754 ASSERT(this->length() == numbers->length());
7755 // For small arrays, simply use insertion sort.
7756 if (len <= 10) {
7757 InsertionSortPairs(this, numbers, len);
7758 return;
7759 }
7760 // Check the range of indices.
7761 uint32_t min_index = NumberToUint32(numbers->get(0));
7762 uint32_t max_index = min_index;
7763 uint32_t i;
7764 for (i = 1; i < len; i++) {
7765 if (NumberToUint32(numbers->get(i)) < min_index) {
7766 min_index = NumberToUint32(numbers->get(i));
7767 } else if (NumberToUint32(numbers->get(i)) > max_index) {
7768 max_index = NumberToUint32(numbers->get(i));
7769 }
7770 }
7771 if (max_index - min_index + 1 == len) {
7772 // Indices form a contiguous range, unless there are duplicates.
7773 // Do an in-place linear time sort assuming distinct numbers, but
7774 // avoid hanging in case they are not.
7775 for (i = 0; i < len; i++) {
7776 uint32_t p;
7777 uint32_t j = 0;
7778 // While the current element at i is not at its correct position p,
7779 // swap the elements at these two positions.
7780 while ((p = NumberToUint32(numbers->get(i)) - min_index) != i &&
7781 j++ < len) {
7782 SwapPairs(numbers, i, p);
7783 }
7784 }
7785 } else {
7786 HeapSortPairs(this, numbers, len);
7787 return;
7788 }
7789}
7790
7791
7792// Fill in the names of local properties into the supplied storage. The main
7793// purpose of this function is to provide reflection information for the object
7794// mirrors.
7795void JSObject::GetLocalPropertyNames(FixedArray* storage, int index) {
7796 ASSERT(storage->length() >= (NumberOfLocalProperties(NONE) - index));
7797 if (HasFastProperties()) {
7798 DescriptorArray* descs = map()->instance_descriptors();
7799 for (int i = 0; i < descs->number_of_descriptors(); i++) {
7800 if (descs->IsProperty(i)) storage->set(index++, descs->GetKey(i));
7801 }
7802 ASSERT(storage->length() >= index);
7803 } else {
7804 property_dictionary()->CopyKeysTo(storage);
7805 }
7806}
7807
7808
7809int JSObject::NumberOfLocalElements(PropertyAttributes filter) {
7810 return GetLocalElementKeys(NULL, filter);
7811}
7812
7813
7814int JSObject::NumberOfEnumElements() {
Steve Blockd0582a62009-12-15 09:54:21 +00007815 // Fast case for objects with no elements.
7816 if (!IsJSValue() && HasFastElements()) {
7817 uint32_t length = IsJSArray() ?
7818 static_cast<uint32_t>(
7819 Smi::cast(JSArray::cast(this)->length())->value()) :
7820 static_cast<uint32_t>(FixedArray::cast(elements())->length());
7821 if (length == 0) return 0;
7822 }
7823 // Compute the number of enumerable elements.
Steve Blocka7e24c12009-10-30 11:49:00 +00007824 return NumberOfLocalElements(static_cast<PropertyAttributes>(DONT_ENUM));
7825}
7826
7827
7828int JSObject::GetLocalElementKeys(FixedArray* storage,
7829 PropertyAttributes filter) {
7830 int counter = 0;
7831 switch (GetElementsKind()) {
7832 case FAST_ELEMENTS: {
7833 int length = IsJSArray() ?
7834 Smi::cast(JSArray::cast(this)->length())->value() :
7835 FixedArray::cast(elements())->length();
7836 for (int i = 0; i < length; i++) {
7837 if (!FixedArray::cast(elements())->get(i)->IsTheHole()) {
7838 if (storage != NULL) {
Leon Clarke4515c472010-02-03 11:58:03 +00007839 storage->set(counter, Smi::FromInt(i));
Steve Blocka7e24c12009-10-30 11:49:00 +00007840 }
7841 counter++;
7842 }
7843 }
7844 ASSERT(!storage || storage->length() >= counter);
7845 break;
7846 }
7847 case PIXEL_ELEMENTS: {
7848 int length = PixelArray::cast(elements())->length();
7849 while (counter < length) {
7850 if (storage != NULL) {
Leon Clarke4515c472010-02-03 11:58:03 +00007851 storage->set(counter, Smi::FromInt(counter));
Steve Blocka7e24c12009-10-30 11:49:00 +00007852 }
7853 counter++;
7854 }
7855 ASSERT(!storage || storage->length() >= counter);
7856 break;
7857 }
Steve Block3ce2e202009-11-05 08:53:23 +00007858 case EXTERNAL_BYTE_ELEMENTS:
7859 case EXTERNAL_UNSIGNED_BYTE_ELEMENTS:
7860 case EXTERNAL_SHORT_ELEMENTS:
7861 case EXTERNAL_UNSIGNED_SHORT_ELEMENTS:
7862 case EXTERNAL_INT_ELEMENTS:
7863 case EXTERNAL_UNSIGNED_INT_ELEMENTS:
7864 case EXTERNAL_FLOAT_ELEMENTS: {
7865 int length = ExternalArray::cast(elements())->length();
7866 while (counter < length) {
7867 if (storage != NULL) {
Leon Clarke4515c472010-02-03 11:58:03 +00007868 storage->set(counter, Smi::FromInt(counter));
Steve Block3ce2e202009-11-05 08:53:23 +00007869 }
7870 counter++;
7871 }
7872 ASSERT(!storage || storage->length() >= counter);
7873 break;
7874 }
Steve Blocka7e24c12009-10-30 11:49:00 +00007875 case DICTIONARY_ELEMENTS: {
7876 if (storage != NULL) {
7877 element_dictionary()->CopyKeysTo(storage, filter);
7878 }
7879 counter = element_dictionary()->NumberOfElementsFilterAttributes(filter);
7880 break;
7881 }
7882 default:
7883 UNREACHABLE();
7884 break;
7885 }
7886
7887 if (this->IsJSValue()) {
7888 Object* val = JSValue::cast(this)->value();
7889 if (val->IsString()) {
7890 String* str = String::cast(val);
7891 if (storage) {
7892 for (int i = 0; i < str->length(); i++) {
Leon Clarke4515c472010-02-03 11:58:03 +00007893 storage->set(counter + i, Smi::FromInt(i));
Steve Blocka7e24c12009-10-30 11:49:00 +00007894 }
7895 }
7896 counter += str->length();
7897 }
7898 }
7899 ASSERT(!storage || storage->length() == counter);
7900 return counter;
7901}
7902
7903
7904int JSObject::GetEnumElementKeys(FixedArray* storage) {
7905 return GetLocalElementKeys(storage,
7906 static_cast<PropertyAttributes>(DONT_ENUM));
7907}
7908
7909
7910bool NumberDictionaryShape::IsMatch(uint32_t key, Object* other) {
7911 ASSERT(other->IsNumber());
7912 return key == static_cast<uint32_t>(other->Number());
7913}
7914
7915
7916uint32_t NumberDictionaryShape::Hash(uint32_t key) {
7917 return ComputeIntegerHash(key);
7918}
7919
7920
7921uint32_t NumberDictionaryShape::HashForObject(uint32_t key, Object* other) {
7922 ASSERT(other->IsNumber());
7923 return ComputeIntegerHash(static_cast<uint32_t>(other->Number()));
7924}
7925
7926
John Reck59135872010-11-02 12:39:01 -07007927MaybeObject* NumberDictionaryShape::AsObject(uint32_t key) {
Steve Blocka7e24c12009-10-30 11:49:00 +00007928 return Heap::NumberFromUint32(key);
7929}
7930
7931
7932bool StringDictionaryShape::IsMatch(String* key, Object* other) {
7933 // We know that all entries in a hash table had their hash keys created.
7934 // Use that knowledge to have fast failure.
7935 if (key->Hash() != String::cast(other)->Hash()) return false;
7936 return key->Equals(String::cast(other));
7937}
7938
7939
7940uint32_t StringDictionaryShape::Hash(String* key) {
7941 return key->Hash();
7942}
7943
7944
7945uint32_t StringDictionaryShape::HashForObject(String* key, Object* other) {
7946 return String::cast(other)->Hash();
7947}
7948
7949
John Reck59135872010-11-02 12:39:01 -07007950MaybeObject* StringDictionaryShape::AsObject(String* key) {
Steve Blocka7e24c12009-10-30 11:49:00 +00007951 return key;
7952}
7953
7954
7955// StringKey simply carries a string object as key.
7956class StringKey : public HashTableKey {
7957 public:
7958 explicit StringKey(String* string) :
7959 string_(string),
7960 hash_(HashForObject(string)) { }
7961
7962 bool IsMatch(Object* string) {
7963 // We know that all entries in a hash table had their hash keys created.
7964 // Use that knowledge to have fast failure.
7965 if (hash_ != HashForObject(string)) {
7966 return false;
7967 }
7968 return string_->Equals(String::cast(string));
7969 }
7970
7971 uint32_t Hash() { return hash_; }
7972
7973 uint32_t HashForObject(Object* other) { return String::cast(other)->Hash(); }
7974
7975 Object* AsObject() { return string_; }
7976
7977 String* string_;
7978 uint32_t hash_;
7979};
7980
7981
7982// StringSharedKeys are used as keys in the eval cache.
7983class StringSharedKey : public HashTableKey {
7984 public:
7985 StringSharedKey(String* source, SharedFunctionInfo* shared)
7986 : source_(source), shared_(shared) { }
7987
7988 bool IsMatch(Object* other) {
7989 if (!other->IsFixedArray()) return false;
7990 FixedArray* pair = FixedArray::cast(other);
7991 SharedFunctionInfo* shared = SharedFunctionInfo::cast(pair->get(0));
7992 if (shared != shared_) return false;
7993 String* source = String::cast(pair->get(1));
7994 return source->Equals(source_);
7995 }
7996
7997 static uint32_t StringSharedHashHelper(String* source,
7998 SharedFunctionInfo* shared) {
7999 uint32_t hash = source->Hash();
8000 if (shared->HasSourceCode()) {
8001 // Instead of using the SharedFunctionInfo pointer in the hash
8002 // code computation, we use a combination of the hash of the
8003 // script source code and the start and end positions. We do
8004 // this to ensure that the cache entries can survive garbage
8005 // collection.
8006 Script* script = Script::cast(shared->script());
8007 hash ^= String::cast(script->source())->Hash();
8008 hash += shared->start_position();
8009 }
8010 return hash;
8011 }
8012
8013 uint32_t Hash() {
8014 return StringSharedHashHelper(source_, shared_);
8015 }
8016
8017 uint32_t HashForObject(Object* obj) {
8018 FixedArray* pair = FixedArray::cast(obj);
8019 SharedFunctionInfo* shared = SharedFunctionInfo::cast(pair->get(0));
8020 String* source = String::cast(pair->get(1));
8021 return StringSharedHashHelper(source, shared);
8022 }
8023
John Reck59135872010-11-02 12:39:01 -07008024 MUST_USE_RESULT MaybeObject* AsObject() {
8025 Object* obj;
8026 { MaybeObject* maybe_obj = Heap::AllocateFixedArray(2);
8027 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
8028 }
Steve Blocka7e24c12009-10-30 11:49:00 +00008029 FixedArray* pair = FixedArray::cast(obj);
8030 pair->set(0, shared_);
8031 pair->set(1, source_);
8032 return pair;
8033 }
8034
8035 private:
8036 String* source_;
8037 SharedFunctionInfo* shared_;
8038};
8039
8040
8041// RegExpKey carries the source and flags of a regular expression as key.
8042class RegExpKey : public HashTableKey {
8043 public:
8044 RegExpKey(String* string, JSRegExp::Flags flags)
8045 : string_(string),
8046 flags_(Smi::FromInt(flags.value())) { }
8047
Steve Block3ce2e202009-11-05 08:53:23 +00008048 // Rather than storing the key in the hash table, a pointer to the
8049 // stored value is stored where the key should be. IsMatch then
8050 // compares the search key to the found object, rather than comparing
8051 // a key to a key.
Steve Blocka7e24c12009-10-30 11:49:00 +00008052 bool IsMatch(Object* obj) {
8053 FixedArray* val = FixedArray::cast(obj);
8054 return string_->Equals(String::cast(val->get(JSRegExp::kSourceIndex)))
8055 && (flags_ == val->get(JSRegExp::kFlagsIndex));
8056 }
8057
8058 uint32_t Hash() { return RegExpHash(string_, flags_); }
8059
8060 Object* AsObject() {
8061 // Plain hash maps, which is where regexp keys are used, don't
8062 // use this function.
8063 UNREACHABLE();
8064 return NULL;
8065 }
8066
8067 uint32_t HashForObject(Object* obj) {
8068 FixedArray* val = FixedArray::cast(obj);
8069 return RegExpHash(String::cast(val->get(JSRegExp::kSourceIndex)),
8070 Smi::cast(val->get(JSRegExp::kFlagsIndex)));
8071 }
8072
8073 static uint32_t RegExpHash(String* string, Smi* flags) {
8074 return string->Hash() + flags->value();
8075 }
8076
8077 String* string_;
8078 Smi* flags_;
8079};
8080
8081// Utf8SymbolKey carries a vector of chars as key.
8082class Utf8SymbolKey : public HashTableKey {
8083 public:
8084 explicit Utf8SymbolKey(Vector<const char> string)
Steve Blockd0582a62009-12-15 09:54:21 +00008085 : string_(string), hash_field_(0) { }
Steve Blocka7e24c12009-10-30 11:49:00 +00008086
8087 bool IsMatch(Object* string) {
8088 return String::cast(string)->IsEqualTo(string_);
8089 }
8090
8091 uint32_t Hash() {
Steve Blockd0582a62009-12-15 09:54:21 +00008092 if (hash_field_ != 0) return hash_field_ >> String::kHashShift;
Steve Blocka7e24c12009-10-30 11:49:00 +00008093 unibrow::Utf8InputBuffer<> buffer(string_.start(),
8094 static_cast<unsigned>(string_.length()));
8095 chars_ = buffer.Length();
Steve Blockd0582a62009-12-15 09:54:21 +00008096 hash_field_ = String::ComputeHashField(&buffer, chars_);
8097 uint32_t result = hash_field_ >> String::kHashShift;
Steve Blocka7e24c12009-10-30 11:49:00 +00008098 ASSERT(result != 0); // Ensure that the hash value of 0 is never computed.
8099 return result;
8100 }
8101
8102 uint32_t HashForObject(Object* other) {
8103 return String::cast(other)->Hash();
8104 }
8105
John Reck59135872010-11-02 12:39:01 -07008106 MaybeObject* AsObject() {
Steve Blockd0582a62009-12-15 09:54:21 +00008107 if (hash_field_ == 0) Hash();
8108 return Heap::AllocateSymbol(string_, chars_, hash_field_);
Steve Blocka7e24c12009-10-30 11:49:00 +00008109 }
8110
8111 Vector<const char> string_;
Steve Blockd0582a62009-12-15 09:54:21 +00008112 uint32_t hash_field_;
Steve Blocka7e24c12009-10-30 11:49:00 +00008113 int chars_; // Caches the number of characters when computing the hash code.
8114};
8115
8116
Steve Block9fac8402011-05-12 15:51:54 +01008117template <typename Char>
8118class SequentialSymbolKey : public HashTableKey {
8119 public:
8120 explicit SequentialSymbolKey(Vector<const Char> string)
8121 : string_(string), hash_field_(0) { }
8122
8123 uint32_t Hash() {
8124 StringHasher hasher(string_.length());
8125
8126 // Very long strings have a trivial hash that doesn't inspect the
8127 // string contents.
8128 if (hasher.has_trivial_hash()) {
8129 hash_field_ = hasher.GetHashField();
8130 } else {
8131 int i = 0;
8132 // Do the iterative array index computation as long as there is a
8133 // chance this is an array index.
8134 while (i < string_.length() && hasher.is_array_index()) {
8135 hasher.AddCharacter(static_cast<uc32>(string_[i]));
8136 i++;
8137 }
8138
8139 // Process the remaining characters without updating the array
8140 // index.
8141 while (i < string_.length()) {
8142 hasher.AddCharacterNoIndex(static_cast<uc32>(string_[i]));
8143 i++;
8144 }
8145 hash_field_ = hasher.GetHashField();
8146 }
8147
8148 uint32_t result = hash_field_ >> String::kHashShift;
8149 ASSERT(result != 0); // Ensure that the hash value of 0 is never computed.
8150 return result;
8151 }
8152
8153
8154 uint32_t HashForObject(Object* other) {
8155 return String::cast(other)->Hash();
8156 }
8157
8158 Vector<const Char> string_;
8159 uint32_t hash_field_;
8160};
8161
8162
8163
8164class AsciiSymbolKey : public SequentialSymbolKey<char> {
8165 public:
8166 explicit AsciiSymbolKey(Vector<const char> str)
8167 : SequentialSymbolKey<char>(str) { }
8168
8169 bool IsMatch(Object* string) {
8170 return String::cast(string)->IsAsciiEqualTo(string_);
8171 }
8172
8173 MaybeObject* AsObject() {
8174 if (hash_field_ == 0) Hash();
8175 return Heap::AllocateAsciiSymbol(string_, hash_field_);
8176 }
8177};
8178
8179
8180class TwoByteSymbolKey : public SequentialSymbolKey<uc16> {
8181 public:
8182 explicit TwoByteSymbolKey(Vector<const uc16> str)
8183 : SequentialSymbolKey<uc16>(str) { }
8184
8185 bool IsMatch(Object* string) {
8186 return String::cast(string)->IsTwoByteEqualTo(string_);
8187 }
8188
8189 MaybeObject* AsObject() {
8190 if (hash_field_ == 0) Hash();
8191 return Heap::AllocateTwoByteSymbol(string_, hash_field_);
8192 }
8193};
8194
8195
Steve Blocka7e24c12009-10-30 11:49:00 +00008196// SymbolKey carries a string/symbol object as key.
8197class SymbolKey : public HashTableKey {
8198 public:
8199 explicit SymbolKey(String* string) : string_(string) { }
8200
8201 bool IsMatch(Object* string) {
8202 return String::cast(string)->Equals(string_);
8203 }
8204
8205 uint32_t Hash() { return string_->Hash(); }
8206
8207 uint32_t HashForObject(Object* other) {
8208 return String::cast(other)->Hash();
8209 }
8210
John Reck59135872010-11-02 12:39:01 -07008211 MaybeObject* AsObject() {
Leon Clarkef7060e22010-06-03 12:02:55 +01008212 // Attempt to flatten the string, so that symbols will most often
8213 // be flat strings.
8214 string_ = string_->TryFlattenGetString();
Steve Blocka7e24c12009-10-30 11:49:00 +00008215 // Transform string to symbol if possible.
8216 Map* map = Heap::SymbolMapForString(string_);
8217 if (map != NULL) {
8218 string_->set_map(map);
8219 ASSERT(string_->IsSymbol());
8220 return string_;
8221 }
8222 // Otherwise allocate a new symbol.
8223 StringInputBuffer buffer(string_);
8224 return Heap::AllocateInternalSymbol(&buffer,
8225 string_->length(),
Steve Blockd0582a62009-12-15 09:54:21 +00008226 string_->hash_field());
Steve Blocka7e24c12009-10-30 11:49:00 +00008227 }
8228
8229 static uint32_t StringHash(Object* obj) {
8230 return String::cast(obj)->Hash();
8231 }
8232
8233 String* string_;
8234};
8235
8236
8237template<typename Shape, typename Key>
8238void HashTable<Shape, Key>::IteratePrefix(ObjectVisitor* v) {
8239 IteratePointers(v, 0, kElementsStartOffset);
8240}
8241
8242
8243template<typename Shape, typename Key>
8244void HashTable<Shape, Key>::IterateElements(ObjectVisitor* v) {
8245 IteratePointers(v,
8246 kElementsStartOffset,
8247 kHeaderSize + length() * kPointerSize);
8248}
8249
8250
8251template<typename Shape, typename Key>
John Reck59135872010-11-02 12:39:01 -07008252MaybeObject* HashTable<Shape, Key>::Allocate(int at_least_space_for,
8253 PretenureFlag pretenure) {
Steve Block6ded16b2010-05-10 14:33:55 +01008254 const int kMinCapacity = 32;
8255 int capacity = RoundUpToPowerOf2(at_least_space_for * 2);
8256 if (capacity < kMinCapacity) {
8257 capacity = kMinCapacity; // Guarantee min capacity.
Leon Clarkee46be812010-01-19 14:06:41 +00008258 } else if (capacity > HashTable::kMaxCapacity) {
8259 return Failure::OutOfMemoryException();
8260 }
8261
John Reck59135872010-11-02 12:39:01 -07008262 Object* obj;
8263 { MaybeObject* maybe_obj =
8264 Heap::AllocateHashTable(EntryToIndex(capacity), pretenure);
8265 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
Steve Blocka7e24c12009-10-30 11:49:00 +00008266 }
John Reck59135872010-11-02 12:39:01 -07008267 HashTable::cast(obj)->SetNumberOfElements(0);
8268 HashTable::cast(obj)->SetNumberOfDeletedElements(0);
8269 HashTable::cast(obj)->SetCapacity(capacity);
Steve Blocka7e24c12009-10-30 11:49:00 +00008270 return obj;
8271}
8272
8273
Leon Clarkee46be812010-01-19 14:06:41 +00008274// Find entry for key otherwise return kNotFound.
Steve Blocka7e24c12009-10-30 11:49:00 +00008275template<typename Shape, typename Key>
8276int HashTable<Shape, Key>::FindEntry(Key key) {
Steve Blocka7e24c12009-10-30 11:49:00 +00008277 uint32_t capacity = Capacity();
Leon Clarkee46be812010-01-19 14:06:41 +00008278 uint32_t entry = FirstProbe(Shape::Hash(key), 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()) break; // Empty entry.
8284 if (!element->IsNull() && Shape::IsMatch(key, element)) return entry;
8285 entry = NextProbe(entry, count++, capacity);
Steve Blocka7e24c12009-10-30 11:49:00 +00008286 }
8287 return kNotFound;
8288}
8289
8290
Ben Murdoch3bec4d22010-07-22 14:51:16 +01008291// Find entry for key otherwise return kNotFound.
8292int StringDictionary::FindEntry(String* key) {
8293 if (!key->IsSymbol()) {
8294 return HashTable<StringDictionaryShape, String*>::FindEntry(key);
8295 }
8296
8297 // Optimized for symbol key. Knowledge of the key type allows:
8298 // 1. Move the check if the key is a symbol out of the loop.
8299 // 2. Avoid comparing hash codes in symbol to symbol comparision.
8300 // 3. Detect a case when a dictionary key is not a symbol but the key is.
8301 // In case of positive result the dictionary key may be replaced by
8302 // the symbol with minimal performance penalty. It gives a chance to
8303 // perform further lookups in code stubs (and significant performance boost
8304 // a certain style of code).
8305
8306 // EnsureCapacity will guarantee the hash table is never full.
8307 uint32_t capacity = Capacity();
8308 uint32_t entry = FirstProbe(key->Hash(), capacity);
8309 uint32_t count = 1;
8310
8311 while (true) {
8312 int index = EntryToIndex(entry);
8313 Object* element = get(index);
8314 if (element->IsUndefined()) break; // Empty entry.
8315 if (key == element) return entry;
8316 if (!element->IsSymbol() &&
8317 !element->IsNull() &&
8318 String::cast(element)->Equals(key)) {
8319 // Replace a non-symbol key by the equivalent symbol for faster further
8320 // lookups.
8321 set(index, key);
8322 return entry;
8323 }
8324 ASSERT(element->IsNull() || !String::cast(element)->Equals(key));
8325 entry = NextProbe(entry, count++, capacity);
8326 }
8327 return kNotFound;
8328}
8329
8330
Steve Blocka7e24c12009-10-30 11:49:00 +00008331template<typename Shape, typename Key>
John Reck59135872010-11-02 12:39:01 -07008332MaybeObject* HashTable<Shape, Key>::EnsureCapacity(int n, Key key) {
Steve Blocka7e24c12009-10-30 11:49:00 +00008333 int capacity = Capacity();
8334 int nof = NumberOfElements() + n;
Leon Clarkee46be812010-01-19 14:06:41 +00008335 int nod = NumberOfDeletedElements();
8336 // Return if:
8337 // 50% is still free after adding n elements and
8338 // at most 50% of the free elements are deleted elements.
Steve Block6ded16b2010-05-10 14:33:55 +01008339 if (nod <= (capacity - nof) >> 1) {
8340 int needed_free = nof >> 1;
8341 if (nof + needed_free <= capacity) return this;
8342 }
Steve Blocka7e24c12009-10-30 11:49:00 +00008343
Steve Block6ded16b2010-05-10 14:33:55 +01008344 const int kMinCapacityForPretenure = 256;
8345 bool pretenure =
8346 (capacity > kMinCapacityForPretenure) && !Heap::InNewSpace(this);
John Reck59135872010-11-02 12:39:01 -07008347 Object* obj;
8348 { MaybeObject* maybe_obj =
8349 Allocate(nof * 2, pretenure ? TENURED : NOT_TENURED);
8350 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
8351 }
Leon Clarke4515c472010-02-03 11:58:03 +00008352
8353 AssertNoAllocation no_gc;
Steve Blocka7e24c12009-10-30 11:49:00 +00008354 HashTable* table = HashTable::cast(obj);
Leon Clarke4515c472010-02-03 11:58:03 +00008355 WriteBarrierMode mode = table->GetWriteBarrierMode(no_gc);
Steve Blocka7e24c12009-10-30 11:49:00 +00008356
8357 // Copy prefix to new array.
8358 for (int i = kPrefixStartIndex;
8359 i < kPrefixStartIndex + Shape::kPrefixSize;
8360 i++) {
8361 table->set(i, get(i), mode);
8362 }
8363 // Rehash the elements.
8364 for (int i = 0; i < capacity; i++) {
8365 uint32_t from_index = EntryToIndex(i);
8366 Object* k = get(from_index);
8367 if (IsKey(k)) {
8368 uint32_t hash = Shape::HashForObject(key, k);
8369 uint32_t insertion_index =
8370 EntryToIndex(table->FindInsertionEntry(hash));
8371 for (int j = 0; j < Shape::kEntrySize; j++) {
8372 table->set(insertion_index + j, get(from_index + j), mode);
8373 }
8374 }
8375 }
8376 table->SetNumberOfElements(NumberOfElements());
Leon Clarkee46be812010-01-19 14:06:41 +00008377 table->SetNumberOfDeletedElements(0);
Steve Blocka7e24c12009-10-30 11:49:00 +00008378 return table;
8379}
8380
8381
8382template<typename Shape, typename Key>
8383uint32_t HashTable<Shape, Key>::FindInsertionEntry(uint32_t hash) {
8384 uint32_t capacity = Capacity();
Leon Clarkee46be812010-01-19 14:06:41 +00008385 uint32_t entry = FirstProbe(hash, capacity);
8386 uint32_t count = 1;
8387 // EnsureCapacity will guarantee the hash table is never full.
8388 while (true) {
8389 Object* element = KeyAt(entry);
8390 if (element->IsUndefined() || element->IsNull()) break;
8391 entry = NextProbe(entry, count++, capacity);
Steve Blocka7e24c12009-10-30 11:49:00 +00008392 }
Steve Blocka7e24c12009-10-30 11:49:00 +00008393 return entry;
8394}
8395
8396// Force instantiation of template instances class.
8397// Please note this list is compiler dependent.
8398
8399template class HashTable<SymbolTableShape, HashTableKey*>;
8400
8401template class HashTable<CompilationCacheShape, HashTableKey*>;
8402
8403template class HashTable<MapCacheShape, HashTableKey*>;
8404
8405template class Dictionary<StringDictionaryShape, String*>;
8406
8407template class Dictionary<NumberDictionaryShape, uint32_t>;
8408
John Reck59135872010-11-02 12:39:01 -07008409template MaybeObject* Dictionary<NumberDictionaryShape, uint32_t>::Allocate(
Steve Blocka7e24c12009-10-30 11:49:00 +00008410 int);
8411
John Reck59135872010-11-02 12:39:01 -07008412template MaybeObject* Dictionary<StringDictionaryShape, String*>::Allocate(
Steve Blocka7e24c12009-10-30 11:49:00 +00008413 int);
8414
John Reck59135872010-11-02 12:39:01 -07008415template MaybeObject* Dictionary<NumberDictionaryShape, uint32_t>::AtPut(
Steve Blocka7e24c12009-10-30 11:49:00 +00008416 uint32_t, Object*);
8417
8418template Object* Dictionary<NumberDictionaryShape, uint32_t>::SlowReverseLookup(
8419 Object*);
8420
8421template Object* Dictionary<StringDictionaryShape, String*>::SlowReverseLookup(
8422 Object*);
8423
8424template void Dictionary<NumberDictionaryShape, uint32_t>::CopyKeysTo(
8425 FixedArray*, PropertyAttributes);
8426
8427template Object* Dictionary<StringDictionaryShape, String*>::DeleteProperty(
8428 int, JSObject::DeleteMode);
8429
8430template Object* Dictionary<NumberDictionaryShape, uint32_t>::DeleteProperty(
8431 int, JSObject::DeleteMode);
8432
8433template void Dictionary<StringDictionaryShape, String*>::CopyKeysTo(
8434 FixedArray*);
8435
8436template int
8437Dictionary<StringDictionaryShape, String*>::NumberOfElementsFilterAttributes(
8438 PropertyAttributes);
8439
John Reck59135872010-11-02 12:39:01 -07008440template MaybeObject* Dictionary<StringDictionaryShape, String*>::Add(
Steve Blocka7e24c12009-10-30 11:49:00 +00008441 String*, Object*, PropertyDetails);
8442
John Reck59135872010-11-02 12:39:01 -07008443template MaybeObject*
Steve Blocka7e24c12009-10-30 11:49:00 +00008444Dictionary<StringDictionaryShape, String*>::GenerateNewEnumerationIndices();
8445
8446template int
8447Dictionary<NumberDictionaryShape, uint32_t>::NumberOfElementsFilterAttributes(
8448 PropertyAttributes);
8449
John Reck59135872010-11-02 12:39:01 -07008450template MaybeObject* Dictionary<NumberDictionaryShape, uint32_t>::Add(
Steve Blocka7e24c12009-10-30 11:49:00 +00008451 uint32_t, Object*, PropertyDetails);
8452
John Reck59135872010-11-02 12:39:01 -07008453template MaybeObject* Dictionary<NumberDictionaryShape, uint32_t>::
8454 EnsureCapacity(int, uint32_t);
Steve Blocka7e24c12009-10-30 11:49:00 +00008455
John Reck59135872010-11-02 12:39:01 -07008456template MaybeObject* Dictionary<StringDictionaryShape, String*>::
8457 EnsureCapacity(int, String*);
Steve Blocka7e24c12009-10-30 11:49:00 +00008458
John Reck59135872010-11-02 12:39:01 -07008459template MaybeObject* Dictionary<NumberDictionaryShape, uint32_t>::AddEntry(
Steve Blocka7e24c12009-10-30 11:49:00 +00008460 uint32_t, Object*, PropertyDetails, uint32_t);
8461
John Reck59135872010-11-02 12:39:01 -07008462template MaybeObject* Dictionary<StringDictionaryShape, String*>::AddEntry(
Steve Blocka7e24c12009-10-30 11:49:00 +00008463 String*, Object*, PropertyDetails, uint32_t);
8464
8465template
8466int Dictionary<NumberDictionaryShape, uint32_t>::NumberOfEnumElements();
8467
8468template
8469int Dictionary<StringDictionaryShape, String*>::NumberOfEnumElements();
8470
Leon Clarkee46be812010-01-19 14:06:41 +00008471template
8472int HashTable<NumberDictionaryShape, uint32_t>::FindEntry(uint32_t);
8473
8474
Steve Blocka7e24c12009-10-30 11:49:00 +00008475// Collates undefined and unexisting elements below limit from position
8476// zero of the elements. The object stays in Dictionary mode.
John Reck59135872010-11-02 12:39:01 -07008477MaybeObject* JSObject::PrepareSlowElementsForSort(uint32_t limit) {
Steve Blocka7e24c12009-10-30 11:49:00 +00008478 ASSERT(HasDictionaryElements());
8479 // Must stay in dictionary mode, either because of requires_slow_elements,
8480 // or because we are not going to sort (and therefore compact) all of the
8481 // elements.
8482 NumberDictionary* dict = element_dictionary();
8483 HeapNumber* result_double = NULL;
8484 if (limit > static_cast<uint32_t>(Smi::kMaxValue)) {
8485 // Allocate space for result before we start mutating the object.
John Reck59135872010-11-02 12:39:01 -07008486 Object* new_double;
8487 { MaybeObject* maybe_new_double = Heap::AllocateHeapNumber(0.0);
8488 if (!maybe_new_double->ToObject(&new_double)) return maybe_new_double;
8489 }
Steve Blocka7e24c12009-10-30 11:49:00 +00008490 result_double = HeapNumber::cast(new_double);
8491 }
8492
John Reck59135872010-11-02 12:39:01 -07008493 Object* obj;
8494 { MaybeObject* maybe_obj =
8495 NumberDictionary::Allocate(dict->NumberOfElements());
8496 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
8497 }
Steve Blocka7e24c12009-10-30 11:49:00 +00008498 NumberDictionary* new_dict = NumberDictionary::cast(obj);
8499
8500 AssertNoAllocation no_alloc;
8501
8502 uint32_t pos = 0;
8503 uint32_t undefs = 0;
Steve Block6ded16b2010-05-10 14:33:55 +01008504 int capacity = dict->Capacity();
Steve Blocka7e24c12009-10-30 11:49:00 +00008505 for (int i = 0; i < capacity; i++) {
8506 Object* k = dict->KeyAt(i);
8507 if (dict->IsKey(k)) {
8508 ASSERT(k->IsNumber());
8509 ASSERT(!k->IsSmi() || Smi::cast(k)->value() >= 0);
8510 ASSERT(!k->IsHeapNumber() || HeapNumber::cast(k)->value() >= 0);
8511 ASSERT(!k->IsHeapNumber() || HeapNumber::cast(k)->value() <= kMaxUInt32);
8512 Object* value = dict->ValueAt(i);
8513 PropertyDetails details = dict->DetailsAt(i);
8514 if (details.type() == CALLBACKS) {
8515 // Bail out and do the sorting of undefineds and array holes in JS.
8516 return Smi::FromInt(-1);
8517 }
8518 uint32_t key = NumberToUint32(k);
John Reck59135872010-11-02 12:39:01 -07008519 // In the following we assert that adding the entry to the new dictionary
8520 // does not cause GC. This is the case because we made sure to allocate
8521 // the dictionary big enough above, so it need not grow.
Steve Blocka7e24c12009-10-30 11:49:00 +00008522 if (key < limit) {
8523 if (value->IsUndefined()) {
8524 undefs++;
8525 } else {
John Reck59135872010-11-02 12:39:01 -07008526 new_dict->AddNumberEntry(pos, value, details)->ToObjectUnchecked();
Steve Blocka7e24c12009-10-30 11:49:00 +00008527 pos++;
8528 }
8529 } else {
John Reck59135872010-11-02 12:39:01 -07008530 new_dict->AddNumberEntry(key, value, details)->ToObjectUnchecked();
Steve Blocka7e24c12009-10-30 11:49:00 +00008531 }
8532 }
8533 }
8534
8535 uint32_t result = pos;
8536 PropertyDetails no_details = PropertyDetails(NONE, NORMAL);
8537 while (undefs > 0) {
John Reck59135872010-11-02 12:39:01 -07008538 new_dict->AddNumberEntry(pos, Heap::undefined_value(), no_details)->
8539 ToObjectUnchecked();
Steve Blocka7e24c12009-10-30 11:49:00 +00008540 pos++;
8541 undefs--;
8542 }
8543
8544 set_elements(new_dict);
8545
8546 if (result <= static_cast<uint32_t>(Smi::kMaxValue)) {
8547 return Smi::FromInt(static_cast<int>(result));
8548 }
8549
8550 ASSERT_NE(NULL, result_double);
8551 result_double->set_value(static_cast<double>(result));
8552 return result_double;
8553}
8554
8555
8556// Collects all defined (non-hole) and non-undefined (array) elements at
8557// the start of the elements array.
8558// If the object is in dictionary mode, it is converted to fast elements
8559// mode.
John Reck59135872010-11-02 12:39:01 -07008560MaybeObject* JSObject::PrepareElementsForSort(uint32_t limit) {
Steve Block3ce2e202009-11-05 08:53:23 +00008561 ASSERT(!HasPixelElements() && !HasExternalArrayElements());
Steve Blocka7e24c12009-10-30 11:49:00 +00008562
8563 if (HasDictionaryElements()) {
8564 // Convert to fast elements containing only the existing properties.
8565 // Ordering is irrelevant, since we are going to sort anyway.
8566 NumberDictionary* dict = element_dictionary();
8567 if (IsJSArray() || dict->requires_slow_elements() ||
8568 dict->max_number_key() >= limit) {
8569 return PrepareSlowElementsForSort(limit);
8570 }
8571 // Convert to fast elements.
8572
John Reck59135872010-11-02 12:39:01 -07008573 Object* obj;
8574 { MaybeObject* maybe_obj = map()->GetFastElementsMap();
8575 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
8576 }
Steve Block8defd9f2010-07-08 12:39:36 +01008577 Map* new_map = Map::cast(obj);
8578
Steve Blocka7e24c12009-10-30 11:49:00 +00008579 PretenureFlag tenure = Heap::InNewSpace(this) ? NOT_TENURED: TENURED;
John Reck59135872010-11-02 12:39:01 -07008580 Object* new_array;
8581 { MaybeObject* maybe_new_array =
8582 Heap::AllocateFixedArray(dict->NumberOfElements(), tenure);
8583 if (!maybe_new_array->ToObject(&new_array)) return maybe_new_array;
8584 }
Steve Blocka7e24c12009-10-30 11:49:00 +00008585 FixedArray* fast_elements = FixedArray::cast(new_array);
8586 dict->CopyValuesTo(fast_elements);
Steve Block8defd9f2010-07-08 12:39:36 +01008587
8588 set_map(new_map);
Steve Blocka7e24c12009-10-30 11:49:00 +00008589 set_elements(fast_elements);
Iain Merrick75681382010-08-19 15:07:18 +01008590 } else {
John Reck59135872010-11-02 12:39:01 -07008591 Object* obj;
8592 { MaybeObject* maybe_obj = EnsureWritableFastElements();
8593 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
8594 }
Steve Blocka7e24c12009-10-30 11:49:00 +00008595 }
8596 ASSERT(HasFastElements());
8597
8598 // Collect holes at the end, undefined before that and the rest at the
8599 // start, and return the number of non-hole, non-undefined values.
8600
8601 FixedArray* elements = FixedArray::cast(this->elements());
8602 uint32_t elements_length = static_cast<uint32_t>(elements->length());
8603 if (limit > elements_length) {
8604 limit = elements_length ;
8605 }
8606 if (limit == 0) {
8607 return Smi::FromInt(0);
8608 }
8609
8610 HeapNumber* result_double = NULL;
8611 if (limit > static_cast<uint32_t>(Smi::kMaxValue)) {
8612 // Pessimistically allocate space for return value before
8613 // we start mutating the array.
John Reck59135872010-11-02 12:39:01 -07008614 Object* new_double;
8615 { MaybeObject* maybe_new_double = Heap::AllocateHeapNumber(0.0);
8616 if (!maybe_new_double->ToObject(&new_double)) return maybe_new_double;
8617 }
Steve Blocka7e24c12009-10-30 11:49:00 +00008618 result_double = HeapNumber::cast(new_double);
8619 }
8620
8621 AssertNoAllocation no_alloc;
8622
8623 // Split elements into defined, undefined and the_hole, in that order.
8624 // Only count locations for undefined and the hole, and fill them afterwards.
Leon Clarke4515c472010-02-03 11:58:03 +00008625 WriteBarrierMode write_barrier = elements->GetWriteBarrierMode(no_alloc);
Steve Blocka7e24c12009-10-30 11:49:00 +00008626 unsigned int undefs = limit;
8627 unsigned int holes = limit;
8628 // Assume most arrays contain no holes and undefined values, so minimize the
8629 // number of stores of non-undefined, non-the-hole values.
8630 for (unsigned int i = 0; i < undefs; i++) {
8631 Object* current = elements->get(i);
8632 if (current->IsTheHole()) {
8633 holes--;
8634 undefs--;
8635 } else if (current->IsUndefined()) {
8636 undefs--;
8637 } else {
8638 continue;
8639 }
8640 // Position i needs to be filled.
8641 while (undefs > i) {
8642 current = elements->get(undefs);
8643 if (current->IsTheHole()) {
8644 holes--;
8645 undefs--;
8646 } else if (current->IsUndefined()) {
8647 undefs--;
8648 } else {
8649 elements->set(i, current, write_barrier);
8650 break;
8651 }
8652 }
8653 }
8654 uint32_t result = undefs;
8655 while (undefs < holes) {
8656 elements->set_undefined(undefs);
8657 undefs++;
8658 }
8659 while (holes < limit) {
8660 elements->set_the_hole(holes);
8661 holes++;
8662 }
8663
8664 if (result <= static_cast<uint32_t>(Smi::kMaxValue)) {
8665 return Smi::FromInt(static_cast<int>(result));
8666 }
8667 ASSERT_NE(NULL, result_double);
8668 result_double->set_value(static_cast<double>(result));
8669 return result_double;
8670}
8671
8672
8673Object* PixelArray::SetValue(uint32_t index, Object* value) {
8674 uint8_t clamped_value = 0;
8675 if (index < static_cast<uint32_t>(length())) {
8676 if (value->IsSmi()) {
8677 int int_value = Smi::cast(value)->value();
8678 if (int_value < 0) {
8679 clamped_value = 0;
8680 } else if (int_value > 255) {
8681 clamped_value = 255;
8682 } else {
8683 clamped_value = static_cast<uint8_t>(int_value);
8684 }
8685 } else if (value->IsHeapNumber()) {
8686 double double_value = HeapNumber::cast(value)->value();
8687 if (!(double_value > 0)) {
8688 // NaN and less than zero clamp to zero.
8689 clamped_value = 0;
8690 } else if (double_value > 255) {
8691 // Greater than 255 clamp to 255.
8692 clamped_value = 255;
8693 } else {
8694 // Other doubles are rounded to the nearest integer.
8695 clamped_value = static_cast<uint8_t>(double_value + 0.5);
8696 }
8697 } else {
8698 // Clamp undefined to zero (default). All other types have been
8699 // converted to a number type further up in the call chain.
8700 ASSERT(value->IsUndefined());
8701 }
8702 set(index, clamped_value);
8703 }
8704 return Smi::FromInt(clamped_value);
8705}
8706
8707
Steve Block3ce2e202009-11-05 08:53:23 +00008708template<typename ExternalArrayClass, typename ValueType>
John Reck59135872010-11-02 12:39:01 -07008709static MaybeObject* ExternalArrayIntSetter(ExternalArrayClass* receiver,
8710 uint32_t index,
8711 Object* value) {
Steve Block3ce2e202009-11-05 08:53:23 +00008712 ValueType cast_value = 0;
8713 if (index < static_cast<uint32_t>(receiver->length())) {
8714 if (value->IsSmi()) {
8715 int int_value = Smi::cast(value)->value();
8716 cast_value = static_cast<ValueType>(int_value);
8717 } else if (value->IsHeapNumber()) {
8718 double double_value = HeapNumber::cast(value)->value();
8719 cast_value = static_cast<ValueType>(DoubleToInt32(double_value));
8720 } else {
8721 // Clamp undefined to zero (default). All other types have been
8722 // converted to a number type further up in the call chain.
8723 ASSERT(value->IsUndefined());
8724 }
8725 receiver->set(index, cast_value);
8726 }
8727 return Heap::NumberFromInt32(cast_value);
8728}
8729
8730
John Reck59135872010-11-02 12:39:01 -07008731MaybeObject* ExternalByteArray::SetValue(uint32_t index, Object* value) {
Steve Block3ce2e202009-11-05 08:53:23 +00008732 return ExternalArrayIntSetter<ExternalByteArray, int8_t>
8733 (this, index, value);
8734}
8735
8736
John Reck59135872010-11-02 12:39:01 -07008737MaybeObject* ExternalUnsignedByteArray::SetValue(uint32_t index,
8738 Object* value) {
Steve Block3ce2e202009-11-05 08:53:23 +00008739 return ExternalArrayIntSetter<ExternalUnsignedByteArray, uint8_t>
8740 (this, index, value);
8741}
8742
8743
John Reck59135872010-11-02 12:39:01 -07008744MaybeObject* ExternalShortArray::SetValue(uint32_t index,
8745 Object* value) {
Steve Block3ce2e202009-11-05 08:53:23 +00008746 return ExternalArrayIntSetter<ExternalShortArray, int16_t>
8747 (this, index, value);
8748}
8749
8750
John Reck59135872010-11-02 12:39:01 -07008751MaybeObject* ExternalUnsignedShortArray::SetValue(uint32_t index,
8752 Object* value) {
Steve Block3ce2e202009-11-05 08:53:23 +00008753 return ExternalArrayIntSetter<ExternalUnsignedShortArray, uint16_t>
8754 (this, index, value);
8755}
8756
8757
John Reck59135872010-11-02 12:39:01 -07008758MaybeObject* ExternalIntArray::SetValue(uint32_t index, Object* value) {
Steve Block3ce2e202009-11-05 08:53:23 +00008759 return ExternalArrayIntSetter<ExternalIntArray, int32_t>
8760 (this, index, value);
8761}
8762
8763
John Reck59135872010-11-02 12:39:01 -07008764MaybeObject* ExternalUnsignedIntArray::SetValue(uint32_t index, Object* value) {
Steve Block3ce2e202009-11-05 08:53:23 +00008765 uint32_t cast_value = 0;
8766 if (index < static_cast<uint32_t>(length())) {
8767 if (value->IsSmi()) {
8768 int int_value = Smi::cast(value)->value();
8769 cast_value = static_cast<uint32_t>(int_value);
8770 } else if (value->IsHeapNumber()) {
8771 double double_value = HeapNumber::cast(value)->value();
8772 cast_value = static_cast<uint32_t>(DoubleToUint32(double_value));
8773 } else {
8774 // Clamp undefined to zero (default). All other types have been
8775 // converted to a number type further up in the call chain.
8776 ASSERT(value->IsUndefined());
8777 }
8778 set(index, cast_value);
8779 }
8780 return Heap::NumberFromUint32(cast_value);
8781}
8782
8783
John Reck59135872010-11-02 12:39:01 -07008784MaybeObject* ExternalFloatArray::SetValue(uint32_t index, Object* value) {
Steve Block3ce2e202009-11-05 08:53:23 +00008785 float cast_value = 0;
8786 if (index < static_cast<uint32_t>(length())) {
8787 if (value->IsSmi()) {
8788 int int_value = Smi::cast(value)->value();
8789 cast_value = static_cast<float>(int_value);
8790 } else if (value->IsHeapNumber()) {
8791 double double_value = HeapNumber::cast(value)->value();
8792 cast_value = static_cast<float>(double_value);
8793 } else {
8794 // Clamp undefined to zero (default). All other types have been
8795 // converted to a number type further up in the call chain.
8796 ASSERT(value->IsUndefined());
8797 }
8798 set(index, cast_value);
8799 }
8800 return Heap::AllocateHeapNumber(cast_value);
8801}
8802
8803
Ben Murdochb0fe1622011-05-05 13:52:32 +01008804JSGlobalPropertyCell* GlobalObject::GetPropertyCell(LookupResult* result) {
Steve Blocka7e24c12009-10-30 11:49:00 +00008805 ASSERT(!HasFastProperties());
8806 Object* value = property_dictionary()->ValueAt(result->GetDictionaryEntry());
Ben Murdochb0fe1622011-05-05 13:52:32 +01008807 return JSGlobalPropertyCell::cast(value);
Steve Blocka7e24c12009-10-30 11:49:00 +00008808}
8809
8810
John Reck59135872010-11-02 12:39:01 -07008811MaybeObject* GlobalObject::EnsurePropertyCell(String* name) {
Steve Blocka7e24c12009-10-30 11:49:00 +00008812 ASSERT(!HasFastProperties());
8813 int entry = property_dictionary()->FindEntry(name);
8814 if (entry == StringDictionary::kNotFound) {
John Reck59135872010-11-02 12:39:01 -07008815 Object* cell;
8816 { MaybeObject* maybe_cell =
8817 Heap::AllocateJSGlobalPropertyCell(Heap::the_hole_value());
8818 if (!maybe_cell->ToObject(&cell)) return maybe_cell;
8819 }
Steve Blocka7e24c12009-10-30 11:49:00 +00008820 PropertyDetails details(NONE, NORMAL);
8821 details = details.AsDeleted();
John Reck59135872010-11-02 12:39:01 -07008822 Object* dictionary;
8823 { MaybeObject* maybe_dictionary =
8824 property_dictionary()->Add(name, cell, details);
8825 if (!maybe_dictionary->ToObject(&dictionary)) return maybe_dictionary;
8826 }
Steve Blocka7e24c12009-10-30 11:49:00 +00008827 set_properties(StringDictionary::cast(dictionary));
8828 return cell;
8829 } else {
8830 Object* value = property_dictionary()->ValueAt(entry);
8831 ASSERT(value->IsJSGlobalPropertyCell());
8832 return value;
8833 }
8834}
8835
8836
John Reck59135872010-11-02 12:39:01 -07008837MaybeObject* SymbolTable::LookupString(String* string, Object** s) {
Steve Blocka7e24c12009-10-30 11:49:00 +00008838 SymbolKey key(string);
8839 return LookupKey(&key, s);
8840}
8841
8842
Steve Blockd0582a62009-12-15 09:54:21 +00008843// This class is used for looking up two character strings in the symbol table.
8844// If we don't have a hit we don't want to waste much time so we unroll the
8845// string hash calculation loop here for speed. Doesn't work if the two
8846// characters form a decimal integer, since such strings have a different hash
8847// algorithm.
8848class TwoCharHashTableKey : public HashTableKey {
8849 public:
8850 TwoCharHashTableKey(uint32_t c1, uint32_t c2)
8851 : c1_(c1), c2_(c2) {
8852 // Char 1.
8853 uint32_t hash = c1 + (c1 << 10);
8854 hash ^= hash >> 6;
8855 // Char 2.
8856 hash += c2;
8857 hash += hash << 10;
8858 hash ^= hash >> 6;
8859 // GetHash.
8860 hash += hash << 3;
8861 hash ^= hash >> 11;
8862 hash += hash << 15;
8863 if (hash == 0) hash = 27;
8864#ifdef DEBUG
8865 StringHasher hasher(2);
8866 hasher.AddCharacter(c1);
8867 hasher.AddCharacter(c2);
8868 // If this assert fails then we failed to reproduce the two-character
8869 // version of the string hashing algorithm above. One reason could be
8870 // that we were passed two digits as characters, since the hash
8871 // algorithm is different in that case.
8872 ASSERT_EQ(static_cast<int>(hasher.GetHash()), static_cast<int>(hash));
8873#endif
8874 hash_ = hash;
8875 }
8876
8877 bool IsMatch(Object* o) {
8878 if (!o->IsString()) return false;
8879 String* other = String::cast(o);
8880 if (other->length() != 2) return false;
8881 if (other->Get(0) != c1_) return false;
8882 return other->Get(1) == c2_;
8883 }
8884
8885 uint32_t Hash() { return hash_; }
8886 uint32_t HashForObject(Object* key) {
8887 if (!key->IsString()) return 0;
8888 return String::cast(key)->Hash();
8889 }
8890
8891 Object* AsObject() {
8892 // The TwoCharHashTableKey is only used for looking in the symbol
8893 // table, not for adding to it.
8894 UNREACHABLE();
8895 return NULL;
8896 }
8897 private:
8898 uint32_t c1_;
8899 uint32_t c2_;
8900 uint32_t hash_;
8901};
8902
8903
Steve Blocka7e24c12009-10-30 11:49:00 +00008904bool SymbolTable::LookupSymbolIfExists(String* string, String** symbol) {
8905 SymbolKey key(string);
8906 int entry = FindEntry(&key);
8907 if (entry == kNotFound) {
8908 return false;
8909 } else {
8910 String* result = String::cast(KeyAt(entry));
8911 ASSERT(StringShape(result).IsSymbol());
8912 *symbol = result;
8913 return true;
8914 }
8915}
8916
8917
Steve Blockd0582a62009-12-15 09:54:21 +00008918bool SymbolTable::LookupTwoCharsSymbolIfExists(uint32_t c1,
8919 uint32_t c2,
8920 String** symbol) {
8921 TwoCharHashTableKey key(c1, c2);
8922 int entry = FindEntry(&key);
8923 if (entry == kNotFound) {
8924 return false;
8925 } else {
8926 String* result = String::cast(KeyAt(entry));
8927 ASSERT(StringShape(result).IsSymbol());
8928 *symbol = result;
8929 return true;
8930 }
8931}
8932
8933
John Reck59135872010-11-02 12:39:01 -07008934MaybeObject* SymbolTable::LookupSymbol(Vector<const char> str, Object** s) {
Steve Blocka7e24c12009-10-30 11:49:00 +00008935 Utf8SymbolKey key(str);
8936 return LookupKey(&key, s);
8937}
8938
8939
Steve Block9fac8402011-05-12 15:51:54 +01008940MaybeObject* SymbolTable::LookupAsciiSymbol(Vector<const char> str,
8941 Object** s) {
8942 AsciiSymbolKey key(str);
8943 return LookupKey(&key, s);
8944}
8945
8946
8947MaybeObject* SymbolTable::LookupTwoByteSymbol(Vector<const uc16> str,
8948 Object** s) {
8949 TwoByteSymbolKey key(str);
8950 return LookupKey(&key, s);
8951}
8952
John Reck59135872010-11-02 12:39:01 -07008953MaybeObject* SymbolTable::LookupKey(HashTableKey* key, Object** s) {
Steve Blocka7e24c12009-10-30 11:49:00 +00008954 int entry = FindEntry(key);
8955
8956 // Symbol already in table.
8957 if (entry != kNotFound) {
8958 *s = KeyAt(entry);
8959 return this;
8960 }
8961
8962 // Adding new symbol. Grow table if needed.
John Reck59135872010-11-02 12:39:01 -07008963 Object* obj;
8964 { MaybeObject* maybe_obj = EnsureCapacity(1, key);
8965 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
8966 }
Steve Blocka7e24c12009-10-30 11:49:00 +00008967
8968 // Create symbol object.
John Reck59135872010-11-02 12:39:01 -07008969 Object* symbol;
8970 { MaybeObject* maybe_symbol = key->AsObject();
8971 if (!maybe_symbol->ToObject(&symbol)) return maybe_symbol;
8972 }
Steve Blocka7e24c12009-10-30 11:49:00 +00008973
8974 // If the symbol table grew as part of EnsureCapacity, obj is not
8975 // the current symbol table and therefore we cannot use
8976 // SymbolTable::cast here.
8977 SymbolTable* table = reinterpret_cast<SymbolTable*>(obj);
8978
8979 // Add the new symbol and return it along with the symbol table.
8980 entry = table->FindInsertionEntry(key->Hash());
8981 table->set(EntryToIndex(entry), symbol);
8982 table->ElementAdded();
8983 *s = symbol;
8984 return table;
8985}
8986
8987
8988Object* CompilationCacheTable::Lookup(String* src) {
8989 StringKey key(src);
8990 int entry = FindEntry(&key);
8991 if (entry == kNotFound) return Heap::undefined_value();
8992 return get(EntryToIndex(entry) + 1);
8993}
8994
8995
8996Object* CompilationCacheTable::LookupEval(String* src, Context* context) {
8997 StringSharedKey key(src, context->closure()->shared());
8998 int entry = FindEntry(&key);
8999 if (entry == kNotFound) return Heap::undefined_value();
9000 return get(EntryToIndex(entry) + 1);
9001}
9002
9003
9004Object* CompilationCacheTable::LookupRegExp(String* src,
9005 JSRegExp::Flags flags) {
9006 RegExpKey key(src, flags);
9007 int entry = FindEntry(&key);
9008 if (entry == kNotFound) return Heap::undefined_value();
9009 return get(EntryToIndex(entry) + 1);
9010}
9011
9012
John Reck59135872010-11-02 12:39:01 -07009013MaybeObject* CompilationCacheTable::Put(String* src, Object* value) {
Steve Blocka7e24c12009-10-30 11:49:00 +00009014 StringKey key(src);
John Reck59135872010-11-02 12:39:01 -07009015 Object* obj;
9016 { MaybeObject* maybe_obj = EnsureCapacity(1, &key);
9017 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
9018 }
Steve Blocka7e24c12009-10-30 11:49:00 +00009019
9020 CompilationCacheTable* cache =
9021 reinterpret_cast<CompilationCacheTable*>(obj);
9022 int entry = cache->FindInsertionEntry(key.Hash());
9023 cache->set(EntryToIndex(entry), src);
9024 cache->set(EntryToIndex(entry) + 1, value);
9025 cache->ElementAdded();
9026 return cache;
9027}
9028
9029
John Reck59135872010-11-02 12:39:01 -07009030MaybeObject* CompilationCacheTable::PutEval(String* src,
9031 Context* context,
9032 Object* value) {
Steve Blocka7e24c12009-10-30 11:49:00 +00009033 StringSharedKey key(src, context->closure()->shared());
John Reck59135872010-11-02 12:39:01 -07009034 Object* obj;
9035 { MaybeObject* maybe_obj = EnsureCapacity(1, &key);
9036 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
9037 }
Steve Blocka7e24c12009-10-30 11:49:00 +00009038
9039 CompilationCacheTable* cache =
9040 reinterpret_cast<CompilationCacheTable*>(obj);
9041 int entry = cache->FindInsertionEntry(key.Hash());
9042
John Reck59135872010-11-02 12:39:01 -07009043 Object* k;
9044 { MaybeObject* maybe_k = key.AsObject();
9045 if (!maybe_k->ToObject(&k)) return maybe_k;
9046 }
Steve Blocka7e24c12009-10-30 11:49:00 +00009047
9048 cache->set(EntryToIndex(entry), k);
9049 cache->set(EntryToIndex(entry) + 1, value);
9050 cache->ElementAdded();
9051 return cache;
9052}
9053
9054
John Reck59135872010-11-02 12:39:01 -07009055MaybeObject* CompilationCacheTable::PutRegExp(String* src,
9056 JSRegExp::Flags flags,
9057 FixedArray* value) {
Steve Blocka7e24c12009-10-30 11:49:00 +00009058 RegExpKey key(src, flags);
John Reck59135872010-11-02 12:39:01 -07009059 Object* obj;
9060 { MaybeObject* maybe_obj = EnsureCapacity(1, &key);
9061 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
9062 }
Steve Blocka7e24c12009-10-30 11:49:00 +00009063
9064 CompilationCacheTable* cache =
9065 reinterpret_cast<CompilationCacheTable*>(obj);
9066 int entry = cache->FindInsertionEntry(key.Hash());
Steve Block3ce2e202009-11-05 08:53:23 +00009067 // We store the value in the key slot, and compare the search key
9068 // to the stored value with a custon IsMatch function during lookups.
Steve Blocka7e24c12009-10-30 11:49:00 +00009069 cache->set(EntryToIndex(entry), value);
9070 cache->set(EntryToIndex(entry) + 1, value);
9071 cache->ElementAdded();
9072 return cache;
9073}
9074
9075
Ben Murdochb0fe1622011-05-05 13:52:32 +01009076void CompilationCacheTable::Remove(Object* value) {
9077 for (int entry = 0, size = Capacity(); entry < size; entry++) {
9078 int entry_index = EntryToIndex(entry);
9079 int value_index = entry_index + 1;
9080 if (get(value_index) == value) {
9081 fast_set(this, entry_index, Heap::null_value());
9082 fast_set(this, value_index, Heap::null_value());
9083 ElementRemoved();
9084 }
9085 }
9086 return;
9087}
9088
9089
Steve Blocka7e24c12009-10-30 11:49:00 +00009090// SymbolsKey used for HashTable where key is array of symbols.
9091class SymbolsKey : public HashTableKey {
9092 public:
9093 explicit SymbolsKey(FixedArray* symbols) : symbols_(symbols) { }
9094
9095 bool IsMatch(Object* symbols) {
9096 FixedArray* o = FixedArray::cast(symbols);
9097 int len = symbols_->length();
9098 if (o->length() != len) return false;
9099 for (int i = 0; i < len; i++) {
9100 if (o->get(i) != symbols_->get(i)) return false;
9101 }
9102 return true;
9103 }
9104
9105 uint32_t Hash() { return HashForObject(symbols_); }
9106
9107 uint32_t HashForObject(Object* obj) {
9108 FixedArray* symbols = FixedArray::cast(obj);
9109 int len = symbols->length();
9110 uint32_t hash = 0;
9111 for (int i = 0; i < len; i++) {
9112 hash ^= String::cast(symbols->get(i))->Hash();
9113 }
9114 return hash;
9115 }
9116
9117 Object* AsObject() { return symbols_; }
9118
9119 private:
9120 FixedArray* symbols_;
9121};
9122
9123
9124Object* MapCache::Lookup(FixedArray* array) {
9125 SymbolsKey key(array);
9126 int entry = FindEntry(&key);
9127 if (entry == kNotFound) return Heap::undefined_value();
9128 return get(EntryToIndex(entry) + 1);
9129}
9130
9131
John Reck59135872010-11-02 12:39:01 -07009132MaybeObject* MapCache::Put(FixedArray* array, Map* value) {
Steve Blocka7e24c12009-10-30 11:49:00 +00009133 SymbolsKey key(array);
John Reck59135872010-11-02 12:39:01 -07009134 Object* obj;
9135 { MaybeObject* maybe_obj = EnsureCapacity(1, &key);
9136 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
9137 }
Steve Blocka7e24c12009-10-30 11:49:00 +00009138
9139 MapCache* cache = reinterpret_cast<MapCache*>(obj);
9140 int entry = cache->FindInsertionEntry(key.Hash());
9141 cache->set(EntryToIndex(entry), array);
9142 cache->set(EntryToIndex(entry) + 1, value);
9143 cache->ElementAdded();
9144 return cache;
9145}
9146
9147
9148template<typename Shape, typename Key>
John Reck59135872010-11-02 12:39:01 -07009149MaybeObject* Dictionary<Shape, Key>::Allocate(int at_least_space_for) {
9150 Object* obj;
9151 { MaybeObject* maybe_obj =
9152 HashTable<Shape, Key>::Allocate(at_least_space_for);
9153 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
Steve Blocka7e24c12009-10-30 11:49:00 +00009154 }
John Reck59135872010-11-02 12:39:01 -07009155 // Initialize the next enumeration index.
9156 Dictionary<Shape, Key>::cast(obj)->
9157 SetNextEnumerationIndex(PropertyDetails::kInitialIndex);
Steve Blocka7e24c12009-10-30 11:49:00 +00009158 return obj;
9159}
9160
9161
9162template<typename Shape, typename Key>
John Reck59135872010-11-02 12:39:01 -07009163MaybeObject* Dictionary<Shape, Key>::GenerateNewEnumerationIndices() {
Steve Blocka7e24c12009-10-30 11:49:00 +00009164 int length = HashTable<Shape, Key>::NumberOfElements();
9165
9166 // Allocate and initialize iteration order array.
John Reck59135872010-11-02 12:39:01 -07009167 Object* obj;
9168 { MaybeObject* maybe_obj = Heap::AllocateFixedArray(length);
9169 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
9170 }
Steve Blocka7e24c12009-10-30 11:49:00 +00009171 FixedArray* iteration_order = FixedArray::cast(obj);
9172 for (int i = 0; i < length; i++) {
Leon Clarke4515c472010-02-03 11:58:03 +00009173 iteration_order->set(i, Smi::FromInt(i));
Steve Blocka7e24c12009-10-30 11:49:00 +00009174 }
9175
9176 // Allocate array with enumeration order.
John Reck59135872010-11-02 12:39:01 -07009177 { MaybeObject* maybe_obj = Heap::AllocateFixedArray(length);
9178 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
9179 }
Steve Blocka7e24c12009-10-30 11:49:00 +00009180 FixedArray* enumeration_order = FixedArray::cast(obj);
9181
9182 // Fill the enumeration order array with property details.
9183 int capacity = HashTable<Shape, Key>::Capacity();
9184 int pos = 0;
9185 for (int i = 0; i < capacity; i++) {
9186 if (Dictionary<Shape, Key>::IsKey(Dictionary<Shape, Key>::KeyAt(i))) {
Leon Clarke4515c472010-02-03 11:58:03 +00009187 enumeration_order->set(pos++, Smi::FromInt(DetailsAt(i).index()));
Steve Blocka7e24c12009-10-30 11:49:00 +00009188 }
9189 }
9190
9191 // Sort the arrays wrt. enumeration order.
9192 iteration_order->SortPairs(enumeration_order, enumeration_order->length());
9193
9194 // Overwrite the enumeration_order with the enumeration indices.
9195 for (int i = 0; i < length; i++) {
9196 int index = Smi::cast(iteration_order->get(i))->value();
9197 int enum_index = PropertyDetails::kInitialIndex + i;
Leon Clarke4515c472010-02-03 11:58:03 +00009198 enumeration_order->set(index, Smi::FromInt(enum_index));
Steve Blocka7e24c12009-10-30 11:49:00 +00009199 }
9200
9201 // Update the dictionary with new indices.
9202 capacity = HashTable<Shape, Key>::Capacity();
9203 pos = 0;
9204 for (int i = 0; i < capacity; i++) {
9205 if (Dictionary<Shape, Key>::IsKey(Dictionary<Shape, Key>::KeyAt(i))) {
9206 int enum_index = Smi::cast(enumeration_order->get(pos++))->value();
9207 PropertyDetails details = DetailsAt(i);
9208 PropertyDetails new_details =
9209 PropertyDetails(details.attributes(), details.type(), enum_index);
9210 DetailsAtPut(i, new_details);
9211 }
9212 }
9213
9214 // Set the next enumeration index.
9215 SetNextEnumerationIndex(PropertyDetails::kInitialIndex+length);
9216 return this;
9217}
9218
9219template<typename Shape, typename Key>
John Reck59135872010-11-02 12:39:01 -07009220MaybeObject* Dictionary<Shape, Key>::EnsureCapacity(int n, Key key) {
Steve Blocka7e24c12009-10-30 11:49:00 +00009221 // Check whether there are enough enumeration indices to add n elements.
9222 if (Shape::kIsEnumerable &&
9223 !PropertyDetails::IsValidIndex(NextEnumerationIndex() + n)) {
9224 // If not, we generate new indices for the properties.
John Reck59135872010-11-02 12:39:01 -07009225 Object* result;
9226 { MaybeObject* maybe_result = GenerateNewEnumerationIndices();
9227 if (!maybe_result->ToObject(&result)) return maybe_result;
9228 }
Steve Blocka7e24c12009-10-30 11:49:00 +00009229 }
9230 return HashTable<Shape, Key>::EnsureCapacity(n, key);
9231}
9232
9233
9234void NumberDictionary::RemoveNumberEntries(uint32_t from, uint32_t to) {
9235 // Do nothing if the interval [from, to) is empty.
9236 if (from >= to) return;
9237
9238 int removed_entries = 0;
9239 Object* sentinel = Heap::null_value();
9240 int capacity = Capacity();
9241 for (int i = 0; i < capacity; i++) {
9242 Object* key = KeyAt(i);
9243 if (key->IsNumber()) {
9244 uint32_t number = static_cast<uint32_t>(key->Number());
9245 if (from <= number && number < to) {
9246 SetEntry(i, sentinel, sentinel, Smi::FromInt(0));
9247 removed_entries++;
9248 }
9249 }
9250 }
9251
9252 // Update the number of elements.
Leon Clarkee46be812010-01-19 14:06:41 +00009253 ElementsRemoved(removed_entries);
Steve Blocka7e24c12009-10-30 11:49:00 +00009254}
9255
9256
9257template<typename Shape, typename Key>
9258Object* Dictionary<Shape, Key>::DeleteProperty(int entry,
9259 JSObject::DeleteMode mode) {
9260 PropertyDetails details = DetailsAt(entry);
9261 // Ignore attributes if forcing a deletion.
9262 if (details.IsDontDelete() && mode == JSObject::NORMAL_DELETION) {
9263 return Heap::false_value();
9264 }
9265 SetEntry(entry, Heap::null_value(), Heap::null_value(), Smi::FromInt(0));
9266 HashTable<Shape, Key>::ElementRemoved();
9267 return Heap::true_value();
9268}
9269
9270
9271template<typename Shape, typename Key>
John Reck59135872010-11-02 12:39:01 -07009272MaybeObject* Dictionary<Shape, Key>::AtPut(Key key, Object* value) {
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01009273 int entry = this->FindEntry(key);
Steve Blocka7e24c12009-10-30 11:49:00 +00009274
9275 // If the entry is present set the value;
9276 if (entry != Dictionary<Shape, Key>::kNotFound) {
9277 ValueAtPut(entry, value);
9278 return this;
9279 }
9280
9281 // Check whether the dictionary should be extended.
John Reck59135872010-11-02 12:39:01 -07009282 Object* obj;
9283 { MaybeObject* maybe_obj = EnsureCapacity(1, key);
9284 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
9285 }
Steve Blocka7e24c12009-10-30 11:49:00 +00009286
John Reck59135872010-11-02 12:39:01 -07009287 Object* k;
9288 { MaybeObject* maybe_k = Shape::AsObject(key);
9289 if (!maybe_k->ToObject(&k)) return maybe_k;
9290 }
Steve Blocka7e24c12009-10-30 11:49:00 +00009291 PropertyDetails details = PropertyDetails(NONE, NORMAL);
9292 return Dictionary<Shape, Key>::cast(obj)->
9293 AddEntry(key, value, details, Shape::Hash(key));
9294}
9295
9296
9297template<typename Shape, typename Key>
John Reck59135872010-11-02 12:39:01 -07009298MaybeObject* Dictionary<Shape, Key>::Add(Key key,
9299 Object* value,
9300 PropertyDetails details) {
Steve Blocka7e24c12009-10-30 11:49:00 +00009301 // Valdate key is absent.
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01009302 SLOW_ASSERT((this->FindEntry(key) == Dictionary<Shape, Key>::kNotFound));
Steve Blocka7e24c12009-10-30 11:49:00 +00009303 // Check whether the dictionary should be extended.
John Reck59135872010-11-02 12:39:01 -07009304 Object* obj;
9305 { MaybeObject* maybe_obj = EnsureCapacity(1, key);
9306 if (!maybe_obj->ToObject(&obj)) return maybe_obj;
9307 }
Steve Blocka7e24c12009-10-30 11:49:00 +00009308 return Dictionary<Shape, Key>::cast(obj)->
9309 AddEntry(key, value, details, Shape::Hash(key));
9310}
9311
9312
9313// Add a key, value pair to the dictionary.
9314template<typename Shape, typename Key>
John Reck59135872010-11-02 12:39:01 -07009315MaybeObject* Dictionary<Shape, Key>::AddEntry(Key key,
9316 Object* value,
9317 PropertyDetails details,
9318 uint32_t hash) {
Steve Blocka7e24c12009-10-30 11:49:00 +00009319 // Compute the key object.
John Reck59135872010-11-02 12:39:01 -07009320 Object* k;
9321 { MaybeObject* maybe_k = Shape::AsObject(key);
9322 if (!maybe_k->ToObject(&k)) return maybe_k;
9323 }
Steve Blocka7e24c12009-10-30 11:49:00 +00009324
9325 uint32_t entry = Dictionary<Shape, Key>::FindInsertionEntry(hash);
9326 // Insert element at empty or deleted entry
9327 if (!details.IsDeleted() && details.index() == 0 && Shape::kIsEnumerable) {
9328 // Assign an enumeration index to the property and update
9329 // SetNextEnumerationIndex.
9330 int index = NextEnumerationIndex();
9331 details = PropertyDetails(details.attributes(), details.type(), index);
9332 SetNextEnumerationIndex(index + 1);
9333 }
9334 SetEntry(entry, k, value, details);
9335 ASSERT((Dictionary<Shape, Key>::KeyAt(entry)->IsNumber()
9336 || Dictionary<Shape, Key>::KeyAt(entry)->IsString()));
9337 HashTable<Shape, Key>::ElementAdded();
9338 return this;
9339}
9340
9341
9342void NumberDictionary::UpdateMaxNumberKey(uint32_t key) {
9343 // If the dictionary requires slow elements an element has already
9344 // been added at a high index.
9345 if (requires_slow_elements()) return;
9346 // Check if this index is high enough that we should require slow
9347 // elements.
9348 if (key > kRequiresSlowElementsLimit) {
9349 set_requires_slow_elements();
9350 return;
9351 }
9352 // Update max key value.
9353 Object* max_index_object = get(kMaxNumberKeyIndex);
9354 if (!max_index_object->IsSmi() || max_number_key() < key) {
9355 FixedArray::set(kMaxNumberKeyIndex,
Leon Clarke4515c472010-02-03 11:58:03 +00009356 Smi::FromInt(key << kRequiresSlowElementsTagSize));
Steve Blocka7e24c12009-10-30 11:49:00 +00009357 }
9358}
9359
9360
John Reck59135872010-11-02 12:39:01 -07009361MaybeObject* NumberDictionary::AddNumberEntry(uint32_t key,
9362 Object* value,
9363 PropertyDetails details) {
Steve Blocka7e24c12009-10-30 11:49:00 +00009364 UpdateMaxNumberKey(key);
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01009365 SLOW_ASSERT(this->FindEntry(key) == kNotFound);
Steve Blocka7e24c12009-10-30 11:49:00 +00009366 return Add(key, value, details);
9367}
9368
9369
John Reck59135872010-11-02 12:39:01 -07009370MaybeObject* NumberDictionary::AtNumberPut(uint32_t key, Object* value) {
Steve Blocka7e24c12009-10-30 11:49:00 +00009371 UpdateMaxNumberKey(key);
9372 return AtPut(key, value);
9373}
9374
9375
John Reck59135872010-11-02 12:39:01 -07009376MaybeObject* NumberDictionary::Set(uint32_t key,
9377 Object* value,
9378 PropertyDetails details) {
Steve Blocka7e24c12009-10-30 11:49:00 +00009379 int entry = FindEntry(key);
9380 if (entry == kNotFound) return AddNumberEntry(key, value, details);
9381 // Preserve enumeration index.
9382 details = PropertyDetails(details.attributes(),
9383 details.type(),
9384 DetailsAt(entry).index());
John Reck59135872010-11-02 12:39:01 -07009385 MaybeObject* maybe_object_key = NumberDictionaryShape::AsObject(key);
9386 Object* object_key;
9387 if (!maybe_object_key->ToObject(&object_key)) return maybe_object_key;
Ben Murdochf87a2032010-10-22 12:50:53 +01009388 SetEntry(entry, object_key, value, details);
Steve Blocka7e24c12009-10-30 11:49:00 +00009389 return this;
9390}
9391
9392
9393
9394template<typename Shape, typename Key>
9395int Dictionary<Shape, Key>::NumberOfElementsFilterAttributes(
9396 PropertyAttributes filter) {
9397 int capacity = HashTable<Shape, Key>::Capacity();
9398 int result = 0;
9399 for (int i = 0; i < capacity; i++) {
9400 Object* k = HashTable<Shape, Key>::KeyAt(i);
9401 if (HashTable<Shape, Key>::IsKey(k)) {
9402 PropertyDetails details = DetailsAt(i);
9403 if (details.IsDeleted()) continue;
9404 PropertyAttributes attr = details.attributes();
9405 if ((attr & filter) == 0) result++;
9406 }
9407 }
9408 return result;
9409}
9410
9411
9412template<typename Shape, typename Key>
9413int Dictionary<Shape, Key>::NumberOfEnumElements() {
9414 return NumberOfElementsFilterAttributes(
9415 static_cast<PropertyAttributes>(DONT_ENUM));
9416}
9417
9418
9419template<typename Shape, typename Key>
9420void Dictionary<Shape, Key>::CopyKeysTo(FixedArray* storage,
9421 PropertyAttributes filter) {
9422 ASSERT(storage->length() >= NumberOfEnumElements());
9423 int capacity = HashTable<Shape, Key>::Capacity();
9424 int index = 0;
9425 for (int i = 0; i < capacity; i++) {
9426 Object* k = HashTable<Shape, Key>::KeyAt(i);
9427 if (HashTable<Shape, Key>::IsKey(k)) {
9428 PropertyDetails details = DetailsAt(i);
9429 if (details.IsDeleted()) continue;
9430 PropertyAttributes attr = details.attributes();
9431 if ((attr & filter) == 0) storage->set(index++, k);
9432 }
9433 }
9434 storage->SortPairs(storage, index);
9435 ASSERT(storage->length() >= index);
9436}
9437
9438
9439void StringDictionary::CopyEnumKeysTo(FixedArray* storage,
9440 FixedArray* sort_array) {
9441 ASSERT(storage->length() >= NumberOfEnumElements());
9442 int capacity = Capacity();
9443 int index = 0;
9444 for (int i = 0; i < capacity; i++) {
9445 Object* k = KeyAt(i);
9446 if (IsKey(k)) {
9447 PropertyDetails details = DetailsAt(i);
9448 if (details.IsDeleted() || details.IsDontEnum()) continue;
9449 storage->set(index, k);
Leon Clarke4515c472010-02-03 11:58:03 +00009450 sort_array->set(index, Smi::FromInt(details.index()));
Steve Blocka7e24c12009-10-30 11:49:00 +00009451 index++;
9452 }
9453 }
9454 storage->SortPairs(sort_array, sort_array->length());
9455 ASSERT(storage->length() >= index);
9456}
9457
9458
9459template<typename Shape, typename Key>
9460void Dictionary<Shape, Key>::CopyKeysTo(FixedArray* storage) {
9461 ASSERT(storage->length() >= NumberOfElementsFilterAttributes(
9462 static_cast<PropertyAttributes>(NONE)));
9463 int capacity = HashTable<Shape, Key>::Capacity();
9464 int index = 0;
9465 for (int i = 0; i < capacity; i++) {
9466 Object* k = HashTable<Shape, Key>::KeyAt(i);
9467 if (HashTable<Shape, Key>::IsKey(k)) {
9468 PropertyDetails details = DetailsAt(i);
9469 if (details.IsDeleted()) continue;
9470 storage->set(index++, k);
9471 }
9472 }
9473 ASSERT(storage->length() >= index);
9474}
9475
9476
9477// Backwards lookup (slow).
9478template<typename Shape, typename Key>
9479Object* Dictionary<Shape, Key>::SlowReverseLookup(Object* value) {
9480 int capacity = HashTable<Shape, Key>::Capacity();
9481 for (int i = 0; i < capacity; i++) {
9482 Object* k = HashTable<Shape, Key>::KeyAt(i);
9483 if (Dictionary<Shape, Key>::IsKey(k)) {
9484 Object* e = ValueAt(i);
9485 if (e->IsJSGlobalPropertyCell()) {
9486 e = JSGlobalPropertyCell::cast(e)->value();
9487 }
9488 if (e == value) return k;
9489 }
9490 }
9491 return Heap::undefined_value();
9492}
9493
9494
John Reck59135872010-11-02 12:39:01 -07009495MaybeObject* StringDictionary::TransformPropertiesToFastFor(
Steve Blocka7e24c12009-10-30 11:49:00 +00009496 JSObject* obj, int unused_property_fields) {
9497 // Make sure we preserve dictionary representation if there are too many
9498 // descriptors.
9499 if (NumberOfElements() > DescriptorArray::kMaxNumberOfDescriptors) return obj;
9500
9501 // Figure out if it is necessary to generate new enumeration indices.
9502 int max_enumeration_index =
9503 NextEnumerationIndex() +
9504 (DescriptorArray::kMaxNumberOfDescriptors -
9505 NumberOfElements());
9506 if (!PropertyDetails::IsValidIndex(max_enumeration_index)) {
John Reck59135872010-11-02 12:39:01 -07009507 Object* result;
9508 { MaybeObject* maybe_result = GenerateNewEnumerationIndices();
9509 if (!maybe_result->ToObject(&result)) return maybe_result;
9510 }
Steve Blocka7e24c12009-10-30 11:49:00 +00009511 }
9512
9513 int instance_descriptor_length = 0;
9514 int number_of_fields = 0;
9515
9516 // Compute the length of the instance descriptor.
9517 int capacity = Capacity();
9518 for (int i = 0; i < capacity; i++) {
9519 Object* k = KeyAt(i);
9520 if (IsKey(k)) {
9521 Object* value = ValueAt(i);
9522 PropertyType type = DetailsAt(i).type();
9523 ASSERT(type != FIELD);
9524 instance_descriptor_length++;
Leon Clarkee46be812010-01-19 14:06:41 +00009525 if (type == NORMAL &&
9526 (!value->IsJSFunction() || Heap::InNewSpace(value))) {
9527 number_of_fields += 1;
9528 }
Steve Blocka7e24c12009-10-30 11:49:00 +00009529 }
9530 }
9531
9532 // Allocate the instance descriptor.
John Reck59135872010-11-02 12:39:01 -07009533 Object* descriptors_unchecked;
9534 { MaybeObject* maybe_descriptors_unchecked =
9535 DescriptorArray::Allocate(instance_descriptor_length);
9536 if (!maybe_descriptors_unchecked->ToObject(&descriptors_unchecked)) {
9537 return maybe_descriptors_unchecked;
9538 }
9539 }
Steve Blocka7e24c12009-10-30 11:49:00 +00009540 DescriptorArray* descriptors = DescriptorArray::cast(descriptors_unchecked);
9541
9542 int inobject_props = obj->map()->inobject_properties();
9543 int number_of_allocated_fields =
9544 number_of_fields + unused_property_fields - inobject_props;
Ben Murdochf87a2032010-10-22 12:50:53 +01009545 if (number_of_allocated_fields < 0) {
9546 // There is enough inobject space for all fields (including unused).
9547 number_of_allocated_fields = 0;
9548 unused_property_fields = inobject_props - number_of_fields;
9549 }
Steve Blocka7e24c12009-10-30 11:49:00 +00009550
9551 // Allocate the fixed array for the fields.
John Reck59135872010-11-02 12:39:01 -07009552 Object* fields;
9553 { MaybeObject* maybe_fields =
9554 Heap::AllocateFixedArray(number_of_allocated_fields);
9555 if (!maybe_fields->ToObject(&fields)) return maybe_fields;
9556 }
Steve Blocka7e24c12009-10-30 11:49:00 +00009557
9558 // Fill in the instance descriptor and the fields.
9559 int next_descriptor = 0;
9560 int current_offset = 0;
9561 for (int i = 0; i < capacity; i++) {
9562 Object* k = KeyAt(i);
9563 if (IsKey(k)) {
9564 Object* value = ValueAt(i);
9565 // Ensure the key is a symbol before writing into the instance descriptor.
John Reck59135872010-11-02 12:39:01 -07009566 Object* key;
9567 { MaybeObject* maybe_key = Heap::LookupSymbol(String::cast(k));
9568 if (!maybe_key->ToObject(&key)) return maybe_key;
9569 }
Steve Blocka7e24c12009-10-30 11:49:00 +00009570 PropertyDetails details = DetailsAt(i);
9571 PropertyType type = details.type();
9572
Leon Clarkee46be812010-01-19 14:06:41 +00009573 if (value->IsJSFunction() && !Heap::InNewSpace(value)) {
Steve Blocka7e24c12009-10-30 11:49:00 +00009574 ConstantFunctionDescriptor d(String::cast(key),
9575 JSFunction::cast(value),
9576 details.attributes(),
9577 details.index());
9578 descriptors->Set(next_descriptor++, &d);
9579 } else if (type == NORMAL) {
9580 if (current_offset < inobject_props) {
9581 obj->InObjectPropertyAtPut(current_offset,
9582 value,
9583 UPDATE_WRITE_BARRIER);
9584 } else {
9585 int offset = current_offset - inobject_props;
9586 FixedArray::cast(fields)->set(offset, value);
9587 }
9588 FieldDescriptor d(String::cast(key),
9589 current_offset++,
9590 details.attributes(),
9591 details.index());
9592 descriptors->Set(next_descriptor++, &d);
9593 } else if (type == CALLBACKS) {
9594 CallbacksDescriptor d(String::cast(key),
9595 value,
9596 details.attributes(),
9597 details.index());
9598 descriptors->Set(next_descriptor++, &d);
9599 } else {
9600 UNREACHABLE();
9601 }
9602 }
9603 }
9604 ASSERT(current_offset == number_of_fields);
9605
9606 descriptors->Sort();
9607 // Allocate new map.
John Reck59135872010-11-02 12:39:01 -07009608 Object* new_map;
9609 { MaybeObject* maybe_new_map = obj->map()->CopyDropDescriptors();
9610 if (!maybe_new_map->ToObject(&new_map)) return maybe_new_map;
9611 }
Steve Blocka7e24c12009-10-30 11:49:00 +00009612
9613 // Transform the object.
9614 obj->set_map(Map::cast(new_map));
9615 obj->map()->set_instance_descriptors(descriptors);
9616 obj->map()->set_unused_property_fields(unused_property_fields);
9617
9618 obj->set_properties(FixedArray::cast(fields));
9619 ASSERT(obj->IsJSObject());
9620
9621 descriptors->SetNextEnumerationIndex(NextEnumerationIndex());
9622 // Check that it really works.
9623 ASSERT(obj->HasFastProperties());
9624
9625 return obj;
9626}
9627
9628
9629#ifdef ENABLE_DEBUGGER_SUPPORT
9630// Check if there is a break point at this code position.
9631bool DebugInfo::HasBreakPoint(int code_position) {
9632 // Get the break point info object for this code position.
9633 Object* break_point_info = GetBreakPointInfo(code_position);
9634
9635 // If there is no break point info object or no break points in the break
9636 // point info object there is no break point at this code position.
9637 if (break_point_info->IsUndefined()) return false;
9638 return BreakPointInfo::cast(break_point_info)->GetBreakPointCount() > 0;
9639}
9640
9641
9642// Get the break point info object for this code position.
9643Object* DebugInfo::GetBreakPointInfo(int code_position) {
9644 // Find the index of the break point info object for this code position.
9645 int index = GetBreakPointInfoIndex(code_position);
9646
9647 // Return the break point info object if any.
9648 if (index == kNoBreakPointInfo) return Heap::undefined_value();
9649 return BreakPointInfo::cast(break_points()->get(index));
9650}
9651
9652
9653// Clear a break point at the specified code position.
9654void DebugInfo::ClearBreakPoint(Handle<DebugInfo> debug_info,
9655 int code_position,
9656 Handle<Object> break_point_object) {
9657 Handle<Object> break_point_info(debug_info->GetBreakPointInfo(code_position));
9658 if (break_point_info->IsUndefined()) return;
9659 BreakPointInfo::ClearBreakPoint(
9660 Handle<BreakPointInfo>::cast(break_point_info),
9661 break_point_object);
9662}
9663
9664
9665void DebugInfo::SetBreakPoint(Handle<DebugInfo> debug_info,
9666 int code_position,
9667 int source_position,
9668 int statement_position,
9669 Handle<Object> break_point_object) {
9670 Handle<Object> break_point_info(debug_info->GetBreakPointInfo(code_position));
9671 if (!break_point_info->IsUndefined()) {
9672 BreakPointInfo::SetBreakPoint(
9673 Handle<BreakPointInfo>::cast(break_point_info),
9674 break_point_object);
9675 return;
9676 }
9677
9678 // Adding a new break point for a code position which did not have any
9679 // break points before. Try to find a free slot.
9680 int index = kNoBreakPointInfo;
9681 for (int i = 0; i < debug_info->break_points()->length(); i++) {
9682 if (debug_info->break_points()->get(i)->IsUndefined()) {
9683 index = i;
9684 break;
9685 }
9686 }
9687 if (index == kNoBreakPointInfo) {
9688 // No free slot - extend break point info array.
9689 Handle<FixedArray> old_break_points =
9690 Handle<FixedArray>(FixedArray::cast(debug_info->break_points()));
Steve Blocka7e24c12009-10-30 11:49:00 +00009691 Handle<FixedArray> new_break_points =
Kristian Monsen0d5e1162010-09-30 15:31:59 +01009692 Factory::NewFixedArray(old_break_points->length() +
9693 Debug::kEstimatedNofBreakPointsInFunction);
9694
9695 debug_info->set_break_points(*new_break_points);
Steve Blocka7e24c12009-10-30 11:49:00 +00009696 for (int i = 0; i < old_break_points->length(); i++) {
9697 new_break_points->set(i, old_break_points->get(i));
9698 }
9699 index = old_break_points->length();
9700 }
9701 ASSERT(index != kNoBreakPointInfo);
9702
9703 // Allocate new BreakPointInfo object and set the break point.
9704 Handle<BreakPointInfo> new_break_point_info =
9705 Handle<BreakPointInfo>::cast(Factory::NewStruct(BREAK_POINT_INFO_TYPE));
9706 new_break_point_info->set_code_position(Smi::FromInt(code_position));
9707 new_break_point_info->set_source_position(Smi::FromInt(source_position));
9708 new_break_point_info->
9709 set_statement_position(Smi::FromInt(statement_position));
9710 new_break_point_info->set_break_point_objects(Heap::undefined_value());
9711 BreakPointInfo::SetBreakPoint(new_break_point_info, break_point_object);
9712 debug_info->break_points()->set(index, *new_break_point_info);
9713}
9714
9715
9716// Get the break point objects for a code position.
9717Object* DebugInfo::GetBreakPointObjects(int code_position) {
9718 Object* break_point_info = GetBreakPointInfo(code_position);
9719 if (break_point_info->IsUndefined()) {
9720 return Heap::undefined_value();
9721 }
9722 return BreakPointInfo::cast(break_point_info)->break_point_objects();
9723}
9724
9725
9726// Get the total number of break points.
9727int DebugInfo::GetBreakPointCount() {
9728 if (break_points()->IsUndefined()) return 0;
9729 int count = 0;
9730 for (int i = 0; i < break_points()->length(); i++) {
9731 if (!break_points()->get(i)->IsUndefined()) {
9732 BreakPointInfo* break_point_info =
9733 BreakPointInfo::cast(break_points()->get(i));
9734 count += break_point_info->GetBreakPointCount();
9735 }
9736 }
9737 return count;
9738}
9739
9740
9741Object* DebugInfo::FindBreakPointInfo(Handle<DebugInfo> debug_info,
9742 Handle<Object> break_point_object) {
9743 if (debug_info->break_points()->IsUndefined()) return Heap::undefined_value();
9744 for (int i = 0; i < debug_info->break_points()->length(); i++) {
9745 if (!debug_info->break_points()->get(i)->IsUndefined()) {
9746 Handle<BreakPointInfo> break_point_info =
9747 Handle<BreakPointInfo>(BreakPointInfo::cast(
9748 debug_info->break_points()->get(i)));
9749 if (BreakPointInfo::HasBreakPointObject(break_point_info,
9750 break_point_object)) {
9751 return *break_point_info;
9752 }
9753 }
9754 }
9755 return Heap::undefined_value();
9756}
9757
9758
9759// Find the index of the break point info object for the specified code
9760// position.
9761int DebugInfo::GetBreakPointInfoIndex(int code_position) {
9762 if (break_points()->IsUndefined()) return kNoBreakPointInfo;
9763 for (int i = 0; i < break_points()->length(); i++) {
9764 if (!break_points()->get(i)->IsUndefined()) {
9765 BreakPointInfo* break_point_info =
9766 BreakPointInfo::cast(break_points()->get(i));
9767 if (break_point_info->code_position()->value() == code_position) {
9768 return i;
9769 }
9770 }
9771 }
9772 return kNoBreakPointInfo;
9773}
9774
9775
9776// Remove the specified break point object.
9777void BreakPointInfo::ClearBreakPoint(Handle<BreakPointInfo> break_point_info,
9778 Handle<Object> break_point_object) {
9779 // If there are no break points just ignore.
9780 if (break_point_info->break_point_objects()->IsUndefined()) return;
9781 // If there is a single break point clear it if it is the same.
9782 if (!break_point_info->break_point_objects()->IsFixedArray()) {
9783 if (break_point_info->break_point_objects() == *break_point_object) {
9784 break_point_info->set_break_point_objects(Heap::undefined_value());
9785 }
9786 return;
9787 }
9788 // If there are multiple break points shrink the array
9789 ASSERT(break_point_info->break_point_objects()->IsFixedArray());
9790 Handle<FixedArray> old_array =
9791 Handle<FixedArray>(
9792 FixedArray::cast(break_point_info->break_point_objects()));
9793 Handle<FixedArray> new_array =
9794 Factory::NewFixedArray(old_array->length() - 1);
9795 int found_count = 0;
9796 for (int i = 0; i < old_array->length(); i++) {
9797 if (old_array->get(i) == *break_point_object) {
9798 ASSERT(found_count == 0);
9799 found_count++;
9800 } else {
9801 new_array->set(i - found_count, old_array->get(i));
9802 }
9803 }
9804 // If the break point was found in the list change it.
9805 if (found_count > 0) break_point_info->set_break_point_objects(*new_array);
9806}
9807
9808
9809// Add the specified break point object.
9810void BreakPointInfo::SetBreakPoint(Handle<BreakPointInfo> break_point_info,
9811 Handle<Object> break_point_object) {
9812 // If there was no break point objects before just set it.
9813 if (break_point_info->break_point_objects()->IsUndefined()) {
9814 break_point_info->set_break_point_objects(*break_point_object);
9815 return;
9816 }
9817 // If the break point object is the same as before just ignore.
9818 if (break_point_info->break_point_objects() == *break_point_object) return;
9819 // If there was one break point object before replace with array.
9820 if (!break_point_info->break_point_objects()->IsFixedArray()) {
9821 Handle<FixedArray> array = Factory::NewFixedArray(2);
9822 array->set(0, break_point_info->break_point_objects());
9823 array->set(1, *break_point_object);
9824 break_point_info->set_break_point_objects(*array);
9825 return;
9826 }
9827 // If there was more than one break point before extend array.
9828 Handle<FixedArray> old_array =
9829 Handle<FixedArray>(
9830 FixedArray::cast(break_point_info->break_point_objects()));
9831 Handle<FixedArray> new_array =
9832 Factory::NewFixedArray(old_array->length() + 1);
9833 for (int i = 0; i < old_array->length(); i++) {
9834 // If the break point was there before just ignore.
9835 if (old_array->get(i) == *break_point_object) return;
9836 new_array->set(i, old_array->get(i));
9837 }
9838 // Add the new break point.
9839 new_array->set(old_array->length(), *break_point_object);
9840 break_point_info->set_break_point_objects(*new_array);
9841}
9842
9843
9844bool BreakPointInfo::HasBreakPointObject(
9845 Handle<BreakPointInfo> break_point_info,
9846 Handle<Object> break_point_object) {
9847 // No break point.
9848 if (break_point_info->break_point_objects()->IsUndefined()) return false;
9849 // Single beak point.
9850 if (!break_point_info->break_point_objects()->IsFixedArray()) {
9851 return break_point_info->break_point_objects() == *break_point_object;
9852 }
9853 // Multiple break points.
9854 FixedArray* array = FixedArray::cast(break_point_info->break_point_objects());
9855 for (int i = 0; i < array->length(); i++) {
9856 if (array->get(i) == *break_point_object) {
9857 return true;
9858 }
9859 }
9860 return false;
9861}
9862
9863
9864// Get the number of break points.
9865int BreakPointInfo::GetBreakPointCount() {
9866 // No break point.
9867 if (break_point_objects()->IsUndefined()) return 0;
9868 // Single beak point.
9869 if (!break_point_objects()->IsFixedArray()) return 1;
9870 // Multiple break points.
9871 return FixedArray::cast(break_point_objects())->length();
9872}
9873#endif
9874
9875
9876} } // namespace v8::internal