blob: c90365c31acd8795e1ba3d025e299a3f9cc97cd1 [file] [log] [blame]
Steve Blocka7e24c12009-10-30 11:49:00 +00001// Copyright 2009 the V8 project authors. All rights reserved.
2// Redistribution and use in source and binary forms, with or without
3// modification, are permitted provided that the following conditions are
4// met:
5//
6// * Redistributions of source code must retain the above copyright
7// notice, this list of conditions and the following disclaimer.
8// * Redistributions in binary form must reproduce the above
9// copyright notice, this list of conditions and the following
10// disclaimer in the documentation and/or other materials provided
11// with the distribution.
12// * Neither the name of Google Inc. nor the names of its
13// contributors may be used to endorse or promote products derived
14// from this software without specific prior written permission.
15//
16// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27
28#include "v8.h"
29
30#include "accessors.h"
31#include "api.h"
32#include "arguments.h"
33#include "bootstrapper.h"
Leon Clarke4515c472010-02-03 11:58:03 +000034#include "codegen.h"
Steve Blocka7e24c12009-10-30 11:49:00 +000035#include "compiler.h"
36#include "debug.h"
37#include "execution.h"
38#include "global-handles.h"
39#include "natives.h"
40#include "runtime.h"
Steve Blockd0582a62009-12-15 09:54:21 +000041#include "stub-cache.h"
Steve Blocka7e24c12009-10-30 11:49:00 +000042
43namespace v8 {
44namespace internal {
45
46
47v8::ImplementationUtilities::HandleScopeData HandleScope::current_ =
48 { -1, NULL, NULL };
49
50
51int HandleScope::NumberOfHandles() {
52 int n = HandleScopeImplementer::instance()->blocks()->length();
53 if (n == 0) return 0;
Steve Blockd0582a62009-12-15 09:54:21 +000054 return ((n - 1) * kHandleBlockSize) + static_cast<int>(
55 (current_.next - HandleScopeImplementer::instance()->blocks()->last()));
Steve Blocka7e24c12009-10-30 11:49:00 +000056}
57
58
59Object** HandleScope::Extend() {
60 Object** result = current_.next;
61
62 ASSERT(result == current_.limit);
63 // Make sure there's at least one scope on the stack and that the
64 // top of the scope stack isn't a barrier.
65 if (current_.extensions < 0) {
66 Utils::ReportApiFailure("v8::HandleScope::CreateHandle()",
67 "Cannot create a handle without a HandleScope");
68 return NULL;
69 }
70 HandleScopeImplementer* impl = HandleScopeImplementer::instance();
71 // If there's more room in the last block, we use that. This is used
72 // for fast creation of scopes after scope barriers.
73 if (!impl->blocks()->is_empty()) {
74 Object** limit = &impl->blocks()->last()[kHandleBlockSize];
75 if (current_.limit != limit) {
76 current_.limit = limit;
77 }
78 }
79
80 // If we still haven't found a slot for the handle, we extend the
81 // current handle scope by allocating a new handle block.
82 if (result == current_.limit) {
83 // If there's a spare block, use it for growing the current scope.
84 result = impl->GetSpareOrNewBlock();
85 // Add the extension to the global list of blocks, but count the
86 // extension as part of the current scope.
87 impl->blocks()->Add(result);
88 current_.extensions++;
89 current_.limit = &result[kHandleBlockSize];
90 }
91
92 return result;
93}
94
95
96void HandleScope::DeleteExtensions() {
97 ASSERT(current_.extensions != 0);
98 HandleScopeImplementer::instance()->DeleteExtensions(current_.extensions);
99}
100
101
102void HandleScope::ZapRange(Object** start, Object** end) {
103 if (start == NULL) return;
104 for (Object** p = start; p < end; p++) {
105 *reinterpret_cast<Address*>(p) = v8::internal::kHandleZapValue;
106 }
107}
108
109
Steve Blockd0582a62009-12-15 09:54:21 +0000110Address HandleScope::current_extensions_address() {
111 return reinterpret_cast<Address>(&current_.extensions);
112}
113
114
115Address HandleScope::current_next_address() {
116 return reinterpret_cast<Address>(&current_.next);
117}
118
119
120Address HandleScope::current_limit_address() {
121 return reinterpret_cast<Address>(&current_.limit);
122}
123
124
Steve Blocka7e24c12009-10-30 11:49:00 +0000125Handle<FixedArray> AddKeysFromJSArray(Handle<FixedArray> content,
126 Handle<JSArray> array) {
127 CALL_HEAP_FUNCTION(content->AddKeysFromJSArray(*array), FixedArray);
128}
129
130
131Handle<FixedArray> UnionOfKeys(Handle<FixedArray> first,
132 Handle<FixedArray> second) {
133 CALL_HEAP_FUNCTION(first->UnionOfKeys(*second), FixedArray);
134}
135
136
137Handle<JSGlobalProxy> ReinitializeJSGlobalProxy(
138 Handle<JSFunction> constructor,
139 Handle<JSGlobalProxy> global) {
140 CALL_HEAP_FUNCTION(Heap::ReinitializeJSGlobalProxy(*constructor, *global),
141 JSGlobalProxy);
142}
143
144
145void SetExpectedNofProperties(Handle<JSFunction> func, int nof) {
146 func->shared()->set_expected_nof_properties(nof);
147 if (func->has_initial_map()) {
148 Handle<Map> new_initial_map =
149 Factory::CopyMapDropTransitions(Handle<Map>(func->initial_map()));
150 new_initial_map->set_unused_property_fields(nof);
151 func->set_initial_map(*new_initial_map);
152 }
153}
154
155
156void SetPrototypeProperty(Handle<JSFunction> func, Handle<JSObject> value) {
157 CALL_HEAP_FUNCTION_VOID(func->SetPrototype(*value));
158}
159
160
161static int ExpectedNofPropertiesFromEstimate(int estimate) {
162 // TODO(1231235): We need dynamic feedback to estimate the number
163 // of expected properties in an object. The static hack below
164 // is barely a solution.
165 if (estimate == 0) return 4;
166 return estimate + 2;
167}
168
169
170void SetExpectedNofPropertiesFromEstimate(Handle<SharedFunctionInfo> shared,
171 int estimate) {
172 shared->set_expected_nof_properties(
173 ExpectedNofPropertiesFromEstimate(estimate));
174}
175
176
Steve Blocka7e24c12009-10-30 11:49:00 +0000177void NormalizeProperties(Handle<JSObject> object,
178 PropertyNormalizationMode mode,
179 int expected_additional_properties) {
180 CALL_HEAP_FUNCTION_VOID(object->NormalizeProperties(
181 mode,
182 expected_additional_properties));
183}
184
185
186void NormalizeElements(Handle<JSObject> object) {
187 CALL_HEAP_FUNCTION_VOID(object->NormalizeElements());
188}
189
190
191void TransformToFastProperties(Handle<JSObject> object,
192 int unused_property_fields) {
193 CALL_HEAP_FUNCTION_VOID(
194 object->TransformToFastProperties(unused_property_fields));
195}
196
197
198void FlattenString(Handle<String> string) {
Steve Block6ded16b2010-05-10 14:33:55 +0100199 CALL_HEAP_FUNCTION_VOID(string->TryFlatten());
Steve Blocka7e24c12009-10-30 11:49:00 +0000200 ASSERT(string->IsFlat());
201}
202
203
204Handle<Object> SetPrototype(Handle<JSFunction> function,
205 Handle<Object> prototype) {
Steve Block6ded16b2010-05-10 14:33:55 +0100206 ASSERT(function->should_have_prototype());
Steve Blocka7e24c12009-10-30 11:49:00 +0000207 CALL_HEAP_FUNCTION(Accessors::FunctionSetPrototype(*function,
208 *prototype,
209 NULL),
210 Object);
211}
212
213
214Handle<Object> SetProperty(Handle<JSObject> object,
215 Handle<String> key,
216 Handle<Object> value,
217 PropertyAttributes attributes) {
218 CALL_HEAP_FUNCTION(object->SetProperty(*key, *value, attributes), Object);
219}
220
221
222Handle<Object> SetProperty(Handle<Object> object,
223 Handle<Object> key,
224 Handle<Object> value,
225 PropertyAttributes attributes) {
226 CALL_HEAP_FUNCTION(
227 Runtime::SetObjectProperty(object, key, value, attributes), Object);
228}
229
230
231Handle<Object> ForceSetProperty(Handle<JSObject> object,
232 Handle<Object> key,
233 Handle<Object> value,
234 PropertyAttributes attributes) {
235 CALL_HEAP_FUNCTION(
236 Runtime::ForceSetObjectProperty(object, key, value, attributes), Object);
237}
238
239
Andrei Popescu31002712010-02-23 13:46:05 +0000240Handle<Object> SetNormalizedProperty(Handle<JSObject> object,
241 Handle<String> key,
242 Handle<Object> value,
243 PropertyDetails details) {
244 CALL_HEAP_FUNCTION(object->SetNormalizedProperty(*key, *value, details),
245 Object);
246}
247
248
Steve Blocka7e24c12009-10-30 11:49:00 +0000249Handle<Object> ForceDeleteProperty(Handle<JSObject> object,
250 Handle<Object> key) {
251 CALL_HEAP_FUNCTION(Runtime::ForceDeleteObjectProperty(object, key), Object);
252}
253
254
255Handle<Object> IgnoreAttributesAndSetLocalProperty(
256 Handle<JSObject> object,
257 Handle<String> key,
258 Handle<Object> value,
259 PropertyAttributes attributes) {
260 CALL_HEAP_FUNCTION(object->
261 IgnoreAttributesAndSetLocalProperty(*key, *value, attributes), Object);
262}
263
264
265Handle<Object> SetPropertyWithInterceptor(Handle<JSObject> object,
266 Handle<String> key,
267 Handle<Object> value,
268 PropertyAttributes attributes) {
269 CALL_HEAP_FUNCTION(object->SetPropertyWithInterceptor(*key,
270 *value,
271 attributes),
272 Object);
273}
274
275
276Handle<Object> GetProperty(Handle<JSObject> obj,
277 const char* name) {
278 Handle<String> str = Factory::LookupAsciiSymbol(name);
279 CALL_HEAP_FUNCTION(obj->GetProperty(*str), Object);
280}
281
282
283Handle<Object> GetProperty(Handle<Object> obj,
284 Handle<Object> key) {
285 CALL_HEAP_FUNCTION(Runtime::GetObjectProperty(obj, key), Object);
286}
287
288
Steve Block6ded16b2010-05-10 14:33:55 +0100289Handle<Object> GetElement(Handle<Object> obj,
290 uint32_t index) {
291 CALL_HEAP_FUNCTION(Runtime::GetElement(obj, index), Object);
292}
293
294
Steve Blocka7e24c12009-10-30 11:49:00 +0000295Handle<Object> GetPropertyWithInterceptor(Handle<JSObject> receiver,
296 Handle<JSObject> holder,
297 Handle<String> name,
298 PropertyAttributes* attributes) {
299 CALL_HEAP_FUNCTION(holder->GetPropertyWithInterceptor(*receiver,
300 *name,
301 attributes),
302 Object);
303}
304
305
306Handle<Object> GetPrototype(Handle<Object> obj) {
307 Handle<Object> result(obj->GetPrototype());
308 return result;
309}
310
311
Andrei Popescu402d9372010-02-26 13:31:12 +0000312Handle<Object> SetPrototype(Handle<JSObject> obj, Handle<Object> value) {
313 const bool skip_hidden_prototypes = false;
314 CALL_HEAP_FUNCTION(obj->SetPrototype(*value, skip_hidden_prototypes), Object);
315}
316
317
Steve Blocka7e24c12009-10-30 11:49:00 +0000318Handle<Object> GetHiddenProperties(Handle<JSObject> obj,
319 bool create_if_needed) {
Steve Blockd0582a62009-12-15 09:54:21 +0000320 Object* holder = obj->BypassGlobalProxy();
321 if (holder->IsUndefined()) return Factory::undefined_value();
322 obj = Handle<JSObject>(JSObject::cast(holder));
Steve Blocka7e24c12009-10-30 11:49:00 +0000323
324 if (obj->HasFastProperties()) {
325 // If the object has fast properties, check whether the first slot
326 // in the descriptor array matches the hidden symbol. Since the
327 // hidden symbols hash code is zero (and no other string has hash
328 // code zero) it will always occupy the first entry if present.
329 DescriptorArray* descriptors = obj->map()->instance_descriptors();
330 if ((descriptors->number_of_descriptors() > 0) &&
Steve Blockd0582a62009-12-15 09:54:21 +0000331 (descriptors->GetKey(0) == Heap::hidden_symbol()) &&
Steve Blocka7e24c12009-10-30 11:49:00 +0000332 descriptors->IsProperty(0)) {
333 ASSERT(descriptors->GetType(0) == FIELD);
334 return Handle<Object>(obj->FastPropertyAt(descriptors->GetFieldIndex(0)));
335 }
336 }
337
338 // Only attempt to find the hidden properties in the local object and not
339 // in the prototype chain. Note that HasLocalProperty() can cause a GC in
340 // the general case in the presence of interceptors.
Steve Blockd0582a62009-12-15 09:54:21 +0000341 if (!obj->HasHiddenPropertiesObject()) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000342 // Hidden properties object not found. Allocate a new hidden properties
343 // object if requested. Otherwise return the undefined value.
344 if (create_if_needed) {
345 Handle<Object> hidden_obj = Factory::NewJSObject(Top::object_function());
Steve Blockd0582a62009-12-15 09:54:21 +0000346 CALL_HEAP_FUNCTION(obj->SetHiddenPropertiesObject(*hidden_obj), Object);
Steve Blocka7e24c12009-10-30 11:49:00 +0000347 } else {
348 return Factory::undefined_value();
349 }
350 }
Steve Blockd0582a62009-12-15 09:54:21 +0000351 return Handle<Object>(obj->GetHiddenPropertiesObject());
Steve Blocka7e24c12009-10-30 11:49:00 +0000352}
353
354
355Handle<Object> DeleteElement(Handle<JSObject> obj,
356 uint32_t index) {
357 CALL_HEAP_FUNCTION(obj->DeleteElement(index, JSObject::NORMAL_DELETION),
358 Object);
359}
360
361
362Handle<Object> DeleteProperty(Handle<JSObject> obj,
363 Handle<String> prop) {
364 CALL_HEAP_FUNCTION(obj->DeleteProperty(*prop, JSObject::NORMAL_DELETION),
365 Object);
366}
367
368
369Handle<Object> LookupSingleCharacterStringFromCode(uint32_t index) {
370 CALL_HEAP_FUNCTION(Heap::LookupSingleCharacterStringFromCode(index), Object);
371}
372
373
Steve Block6ded16b2010-05-10 14:33:55 +0100374Handle<String> SubString(Handle<String> str,
375 int start,
376 int end,
377 PretenureFlag pretenure) {
378 CALL_HEAP_FUNCTION(str->SubString(start, end, pretenure), String);
Steve Blocka7e24c12009-10-30 11:49:00 +0000379}
380
381
382Handle<Object> SetElement(Handle<JSObject> object,
383 uint32_t index,
384 Handle<Object> value) {
Steve Block3ce2e202009-11-05 08:53:23 +0000385 if (object->HasPixelElements() || object->HasExternalArrayElements()) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000386 if (!value->IsSmi() && !value->IsHeapNumber() && !value->IsUndefined()) {
387 bool has_exception;
388 Handle<Object> number = Execution::ToNumber(value, &has_exception);
389 if (has_exception) return Handle<Object>();
390 value = number;
391 }
392 }
393 CALL_HEAP_FUNCTION(object->SetElement(index, *value), Object);
394}
395
396
397Handle<JSObject> Copy(Handle<JSObject> obj) {
398 CALL_HEAP_FUNCTION(Heap::CopyJSObject(*obj), JSObject);
399}
400
401
Leon Clarkef7060e22010-06-03 12:02:55 +0100402Handle<Object> SetAccessor(Handle<JSObject> obj, Handle<AccessorInfo> info) {
403 CALL_HEAP_FUNCTION(obj->DefineAccessor(*info), Object);
404}
405
406
Steve Blocka7e24c12009-10-30 11:49:00 +0000407// Wrappers for scripts are kept alive and cached in weak global
408// handles referred from proxy objects held by the scripts as long as
409// they are used. When they are not used anymore, the garbage
410// collector will call the weak callback on the global handle
411// associated with the wrapper and get rid of both the wrapper and the
412// handle.
413static void ClearWrapperCache(Persistent<v8::Value> handle, void*) {
414#ifdef ENABLE_HEAP_PROTECTION
415 // Weak reference callbacks are called as if from outside V8. We
416 // need to reeenter to unprotect the heap.
417 VMState state(OTHER);
418#endif
419 Handle<Object> cache = Utils::OpenHandle(*handle);
420 JSValue* wrapper = JSValue::cast(*cache);
421 Proxy* proxy = Script::cast(wrapper->value())->wrapper();
422 ASSERT(proxy->proxy() == reinterpret_cast<Address>(cache.location()));
423 proxy->set_proxy(0);
424 GlobalHandles::Destroy(cache.location());
425 Counters::script_wrappers.Decrement();
426}
427
428
429Handle<JSValue> GetScriptWrapper(Handle<Script> script) {
430 if (script->wrapper()->proxy() != NULL) {
431 // Return the script wrapper directly from the cache.
432 return Handle<JSValue>(
433 reinterpret_cast<JSValue**>(script->wrapper()->proxy()));
434 }
435
436 // Construct a new script wrapper.
437 Counters::script_wrappers.Increment();
438 Handle<JSFunction> constructor = Top::script_function();
439 Handle<JSValue> result =
440 Handle<JSValue>::cast(Factory::NewJSObject(constructor));
441 result->set_value(*script);
442
443 // Create a new weak global handle and use it to cache the wrapper
444 // for future use. The cache will automatically be cleared by the
445 // garbage collector when it is not used anymore.
446 Handle<Object> handle = GlobalHandles::Create(*result);
447 GlobalHandles::MakeWeak(handle.location(), NULL, &ClearWrapperCache);
448 script->wrapper()->set_proxy(reinterpret_cast<Address>(handle.location()));
449 return result;
450}
451
452
453// Init line_ends array with code positions of line ends inside script
454// source.
455void InitScriptLineEnds(Handle<Script> script) {
456 if (!script->line_ends()->IsUndefined()) return;
457
458 if (!script->source()->IsString()) {
459 ASSERT(script->source()->IsUndefined());
Steve Blockd0582a62009-12-15 09:54:21 +0000460 script->set_line_ends(*(Factory::NewFixedArray(0)));
461 ASSERT(script->line_ends()->IsFixedArray());
Steve Blocka7e24c12009-10-30 11:49:00 +0000462 return;
463 }
464
465 Handle<String> src(String::cast(script->source()));
Steve Block6ded16b2010-05-10 14:33:55 +0100466
467 Handle<FixedArray> array = CalculateLineEnds(src, true);
468
469 script->set_line_ends(*array);
470 ASSERT(script->line_ends()->IsFixedArray());
471}
472
473
474Handle<FixedArray> CalculateLineEnds(Handle<String> src,
475 bool with_imaginary_last_new_line) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000476 const int src_len = src->length();
477 Handle<String> new_line = Factory::NewStringFromAscii(CStrVector("\n"));
478
479 // Pass 1: Identify line count.
480 int line_count = 0;
481 int position = 0;
482 while (position != -1 && position < src_len) {
483 position = Runtime::StringMatch(src, new_line, position);
484 if (position != -1) {
485 position++;
486 }
Steve Block6ded16b2010-05-10 14:33:55 +0100487 if (position != -1) {
488 line_count++;
489 } else if (with_imaginary_last_new_line) {
490 // Even if the last line misses a line end, it is counted.
491 line_count++;
492 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000493 }
494
495 // Pass 2: Fill in line ends positions
496 Handle<FixedArray> array = Factory::NewFixedArray(line_count);
497 int array_index = 0;
498 position = 0;
499 while (position != -1 && position < src_len) {
500 position = Runtime::StringMatch(src, new_line, position);
Steve Block6ded16b2010-05-10 14:33:55 +0100501 if (position != -1) {
502 array->set(array_index++, Smi::FromInt(position++));
503 } else if (with_imaginary_last_new_line) {
504 // If the script does not end with a line ending add the final end
505 // position as just past the last line ending.
506 array->set(array_index++, Smi::FromInt(src_len));
507 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000508 }
509 ASSERT(array_index == line_count);
510
Steve Block6ded16b2010-05-10 14:33:55 +0100511 return array;
Steve Blocka7e24c12009-10-30 11:49:00 +0000512}
513
514
515// Convert code position into line number.
516int GetScriptLineNumber(Handle<Script> script, int code_pos) {
517 InitScriptLineEnds(script);
518 AssertNoAllocation no_allocation;
Andrei Popescu402d9372010-02-26 13:31:12 +0000519 FixedArray* line_ends_array = FixedArray::cast(script->line_ends());
Steve Blockd0582a62009-12-15 09:54:21 +0000520 const int line_ends_len = line_ends_array->length();
Steve Blocka7e24c12009-10-30 11:49:00 +0000521
Andrei Popescu402d9372010-02-26 13:31:12 +0000522 if (!line_ends_len)
523 return -1;
524
525 if ((Smi::cast(line_ends_array->get(0)))->value() >= code_pos)
526 return script->line_offset()->value();
527
528 int left = 0;
529 int right = line_ends_len;
530 while (int half = (right - left) / 2) {
531 if ((Smi::cast(line_ends_array->get(left + half)))->value() > code_pos) {
532 right -= half;
533 } else {
534 left += half;
Steve Blocka7e24c12009-10-30 11:49:00 +0000535 }
536 }
Andrei Popescu402d9372010-02-26 13:31:12 +0000537 return right + script->line_offset()->value();
Steve Blocka7e24c12009-10-30 11:49:00 +0000538}
539
540
Steve Block6ded16b2010-05-10 14:33:55 +0100541int GetScriptLineNumberSafe(Handle<Script> script, int code_pos) {
542 AssertNoAllocation no_allocation;
543 if (!script->line_ends()->IsUndefined()) {
544 return GetScriptLineNumber(script, code_pos);
545 }
546 // Slow mode: we do not have line_ends. We have to iterate through source.
547 if (!script->source()->IsString()) {
548 return -1;
549 }
550 String* source = String::cast(script->source());
551 int line = 0;
552 int len = source->length();
553 for (int pos = 0; pos < len; pos++) {
554 if (pos == code_pos) {
555 break;
556 }
557 if (source->Get(pos) == '\n') {
558 line++;
559 }
560 }
561 return line;
562}
563
564
Steve Blocka7e24c12009-10-30 11:49:00 +0000565void CustomArguments::IterateInstance(ObjectVisitor* v) {
Steve Block6ded16b2010-05-10 14:33:55 +0100566 v->VisitPointers(values_, values_ + ARRAY_SIZE(values_));
Steve Blocka7e24c12009-10-30 11:49:00 +0000567}
568
569
570// Compute the property keys from the interceptor.
571v8::Handle<v8::Array> GetKeysForNamedInterceptor(Handle<JSObject> receiver,
572 Handle<JSObject> object) {
573 Handle<InterceptorInfo> interceptor(object->GetNamedInterceptor());
574 CustomArguments args(interceptor->data(), *receiver, *object);
575 v8::AccessorInfo info(args.end());
576 v8::Handle<v8::Array> result;
577 if (!interceptor->enumerator()->IsUndefined()) {
578 v8::NamedPropertyEnumerator enum_fun =
579 v8::ToCData<v8::NamedPropertyEnumerator>(interceptor->enumerator());
580 LOG(ApiObjectAccess("interceptor-named-enum", *object));
581 {
582 // Leaving JavaScript.
583 VMState state(EXTERNAL);
584 result = enum_fun(info);
585 }
586 }
587 return result;
588}
589
590
591// Compute the element keys from the interceptor.
592v8::Handle<v8::Array> GetKeysForIndexedInterceptor(Handle<JSObject> receiver,
593 Handle<JSObject> object) {
594 Handle<InterceptorInfo> interceptor(object->GetIndexedInterceptor());
595 CustomArguments args(interceptor->data(), *receiver, *object);
596 v8::AccessorInfo info(args.end());
597 v8::Handle<v8::Array> result;
598 if (!interceptor->enumerator()->IsUndefined()) {
599 v8::IndexedPropertyEnumerator enum_fun =
600 v8::ToCData<v8::IndexedPropertyEnumerator>(interceptor->enumerator());
601 LOG(ApiObjectAccess("interceptor-indexed-enum", *object));
602 {
603 // Leaving JavaScript.
604 VMState state(EXTERNAL);
605 result = enum_fun(info);
606 }
607 }
608 return result;
609}
610
611
612Handle<FixedArray> GetKeysInFixedArrayFor(Handle<JSObject> object,
613 KeyCollectionType type) {
614 Handle<FixedArray> content = Factory::empty_fixed_array();
Steve Blockd0582a62009-12-15 09:54:21 +0000615 Handle<JSObject> arguments_boilerplate =
616 Handle<JSObject>(
617 Top::context()->global_context()->arguments_boilerplate());
618 Handle<JSFunction> arguments_function =
619 Handle<JSFunction>(
620 JSFunction::cast(arguments_boilerplate->map()->constructor()));
Steve Blocka7e24c12009-10-30 11:49:00 +0000621
622 // Only collect keys if access is permitted.
623 for (Handle<Object> p = object;
624 *p != Heap::null_value();
625 p = Handle<Object>(p->GetPrototype())) {
626 Handle<JSObject> current(JSObject::cast(*p));
627
628 // Check access rights if required.
629 if (current->IsAccessCheckNeeded() &&
630 !Top::MayNamedAccess(*current, Heap::undefined_value(),
631 v8::ACCESS_KEYS)) {
632 Top::ReportFailedAccessCheck(*current, v8::ACCESS_KEYS);
633 break;
634 }
635
636 // Compute the element keys.
637 Handle<FixedArray> element_keys =
638 Factory::NewFixedArray(current->NumberOfEnumElements());
639 current->GetEnumElementKeys(*element_keys);
640 content = UnionOfKeys(content, element_keys);
641
642 // Add the element keys from the interceptor.
643 if (current->HasIndexedInterceptor()) {
644 v8::Handle<v8::Array> result =
645 GetKeysForIndexedInterceptor(object, current);
646 if (!result.IsEmpty())
647 content = AddKeysFromJSArray(content, v8::Utils::OpenHandle(*result));
648 }
649
Steve Blockd0582a62009-12-15 09:54:21 +0000650 // We can cache the computed property keys if access checks are
651 // not needed and no interceptors are involved.
652 //
653 // We do not use the cache if the object has elements and
654 // therefore it does not make sense to cache the property names
655 // for arguments objects. Arguments objects will always have
656 // elements.
657 bool cache_enum_keys =
658 ((current->map()->constructor() != *arguments_function) &&
659 !current->IsAccessCheckNeeded() &&
660 !current->HasNamedInterceptor() &&
661 !current->HasIndexedInterceptor());
662 // Compute the property keys and cache them if possible.
663 content =
664 UnionOfKeys(content, GetEnumPropertyKeys(current, cache_enum_keys));
Steve Blocka7e24c12009-10-30 11:49:00 +0000665
666 // Add the property keys from the interceptor.
667 if (current->HasNamedInterceptor()) {
668 v8::Handle<v8::Array> result =
669 GetKeysForNamedInterceptor(object, current);
670 if (!result.IsEmpty())
671 content = AddKeysFromJSArray(content, v8::Utils::OpenHandle(*result));
672 }
673
674 // If we only want local properties we bail out after the first
675 // iteration.
676 if (type == LOCAL_ONLY)
677 break;
678 }
679 return content;
680}
681
682
683Handle<JSArray> GetKeysFor(Handle<JSObject> object) {
684 Counters::for_in.Increment();
685 Handle<FixedArray> elements = GetKeysInFixedArrayFor(object,
686 INCLUDE_PROTOS);
687 return Factory::NewJSArrayWithElements(elements);
688}
689
690
Steve Blockd0582a62009-12-15 09:54:21 +0000691Handle<FixedArray> GetEnumPropertyKeys(Handle<JSObject> object,
692 bool cache_result) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000693 int index = 0;
694 if (object->HasFastProperties()) {
695 if (object->map()->instance_descriptors()->HasEnumCache()) {
696 Counters::enum_cache_hits.Increment();
697 DescriptorArray* desc = object->map()->instance_descriptors();
698 return Handle<FixedArray>(FixedArray::cast(desc->GetEnumCache()));
699 }
700 Counters::enum_cache_misses.Increment();
701 int num_enum = object->NumberOfEnumProperties();
702 Handle<FixedArray> storage = Factory::NewFixedArray(num_enum);
703 Handle<FixedArray> sort_array = Factory::NewFixedArray(num_enum);
704 Handle<DescriptorArray> descs =
705 Handle<DescriptorArray>(object->map()->instance_descriptors());
706 for (int i = 0; i < descs->number_of_descriptors(); i++) {
707 if (descs->IsProperty(i) && !descs->IsDontEnum(i)) {
708 (*storage)->set(index, descs->GetKey(i));
709 PropertyDetails details(descs->GetDetails(i));
710 (*sort_array)->set(index, Smi::FromInt(details.index()));
711 index++;
712 }
713 }
714 (*storage)->SortPairs(*sort_array, sort_array->length());
Steve Blockd0582a62009-12-15 09:54:21 +0000715 if (cache_result) {
716 Handle<FixedArray> bridge_storage =
717 Factory::NewFixedArray(DescriptorArray::kEnumCacheBridgeLength);
718 DescriptorArray* desc = object->map()->instance_descriptors();
719 desc->SetEnumCache(*bridge_storage, *storage);
720 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000721 ASSERT(storage->length() == index);
722 return storage;
723 } else {
724 int num_enum = object->NumberOfEnumProperties();
725 Handle<FixedArray> storage = Factory::NewFixedArray(num_enum);
726 Handle<FixedArray> sort_array = Factory::NewFixedArray(num_enum);
727 object->property_dictionary()->CopyEnumKeysTo(*storage, *sort_array);
728 return storage;
729 }
730}
731
732
Leon Clarke4515c472010-02-03 11:58:03 +0000733bool EnsureCompiled(Handle<SharedFunctionInfo> shared,
734 ClearExceptionFlag flag) {
735 return shared->is_compiled() || CompileLazyShared(shared, flag);
736}
737
738
739static bool CompileLazyHelper(CompilationInfo* info,
740 ClearExceptionFlag flag) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000741 // Compile the source information to a code object.
Leon Clarke4515c472010-02-03 11:58:03 +0000742 ASSERT(!info->shared_info()->is_compiled());
743 bool result = Compiler::CompileLazy(info);
Steve Blocka7e24c12009-10-30 11:49:00 +0000744 ASSERT(result != Top::has_pending_exception());
745 if (!result && flag == CLEAR_EXCEPTION) Top::clear_pending_exception();
746 return result;
747}
748
749
Leon Clarke4515c472010-02-03 11:58:03 +0000750bool CompileLazyShared(Handle<SharedFunctionInfo> shared,
751 ClearExceptionFlag flag) {
Andrei Popescu31002712010-02-23 13:46:05 +0000752 CompilationInfo info(shared);
Leon Clarke4515c472010-02-03 11:58:03 +0000753 return CompileLazyHelper(&info, flag);
754}
755
756
757bool CompileLazy(Handle<JSFunction> function,
758 Handle<Object> receiver,
759 ClearExceptionFlag flag) {
Andrei Popescu31002712010-02-23 13:46:05 +0000760 CompilationInfo info(function, 0, receiver);
Leon Clarke4515c472010-02-03 11:58:03 +0000761 bool result = CompileLazyHelper(&info, flag);
Steve Block6ded16b2010-05-10 14:33:55 +0100762 PROFILE(FunctionCreateEvent(*function));
Leon Clarked91b9f72010-01-27 17:25:45 +0000763 return result;
Steve Blocka7e24c12009-10-30 11:49:00 +0000764}
765
766
Leon Clarke4515c472010-02-03 11:58:03 +0000767bool CompileLazyInLoop(Handle<JSFunction> function,
768 Handle<Object> receiver,
769 ClearExceptionFlag flag) {
Andrei Popescu31002712010-02-23 13:46:05 +0000770 CompilationInfo info(function, 1, receiver);
Leon Clarke4515c472010-02-03 11:58:03 +0000771 bool result = CompileLazyHelper(&info, flag);
Steve Block6ded16b2010-05-10 14:33:55 +0100772 PROFILE(FunctionCreateEvent(*function));
Leon Clarked91b9f72010-01-27 17:25:45 +0000773 return result;
Steve Blocka7e24c12009-10-30 11:49:00 +0000774}
775
Leon Clarke4515c472010-02-03 11:58:03 +0000776
Steve Blocka7e24c12009-10-30 11:49:00 +0000777OptimizedObjectForAddingMultipleProperties::
778OptimizedObjectForAddingMultipleProperties(Handle<JSObject> object,
779 int expected_additional_properties,
780 bool condition) {
781 object_ = object;
782 if (condition && object_->HasFastProperties()) {
783 // Normalize the properties of object to avoid n^2 behavior
784 // when extending the object multiple properties. Indicate the number of
785 // properties to be added.
786 unused_property_fields_ = object->map()->unused_property_fields();
787 NormalizeProperties(object_,
788 KEEP_INOBJECT_PROPERTIES,
789 expected_additional_properties);
790 has_been_transformed_ = true;
791
792 } else {
793 has_been_transformed_ = false;
794 }
795}
796
797
Steve Blockd0582a62009-12-15 09:54:21 +0000798Handle<Code> ComputeLazyCompile(int argc) {
799 CALL_HEAP_FUNCTION(StubCache::ComputeLazyCompile(argc), Code);
800}
801
802
Steve Blocka7e24c12009-10-30 11:49:00 +0000803OptimizedObjectForAddingMultipleProperties::
804~OptimizedObjectForAddingMultipleProperties() {
805 // Reoptimize the object to allow fast property access.
806 if (has_been_transformed_) {
807 TransformToFastProperties(object_, unused_property_fields_);
808 }
809}
810
Steve Blocka7e24c12009-10-30 11:49:00 +0000811} } // namespace v8::internal