blob: 1d4465f3bf296b0ab188729046229a502210c0de [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
402// Wrappers for scripts are kept alive and cached in weak global
403// handles referred from proxy objects held by the scripts as long as
404// they are used. When they are not used anymore, the garbage
405// collector will call the weak callback on the global handle
406// associated with the wrapper and get rid of both the wrapper and the
407// handle.
408static void ClearWrapperCache(Persistent<v8::Value> handle, void*) {
409#ifdef ENABLE_HEAP_PROTECTION
410 // Weak reference callbacks are called as if from outside V8. We
411 // need to reeenter to unprotect the heap.
412 VMState state(OTHER);
413#endif
414 Handle<Object> cache = Utils::OpenHandle(*handle);
415 JSValue* wrapper = JSValue::cast(*cache);
416 Proxy* proxy = Script::cast(wrapper->value())->wrapper();
417 ASSERT(proxy->proxy() == reinterpret_cast<Address>(cache.location()));
418 proxy->set_proxy(0);
419 GlobalHandles::Destroy(cache.location());
420 Counters::script_wrappers.Decrement();
421}
422
423
424Handle<JSValue> GetScriptWrapper(Handle<Script> script) {
425 if (script->wrapper()->proxy() != NULL) {
426 // Return the script wrapper directly from the cache.
427 return Handle<JSValue>(
428 reinterpret_cast<JSValue**>(script->wrapper()->proxy()));
429 }
430
431 // Construct a new script wrapper.
432 Counters::script_wrappers.Increment();
433 Handle<JSFunction> constructor = Top::script_function();
434 Handle<JSValue> result =
435 Handle<JSValue>::cast(Factory::NewJSObject(constructor));
436 result->set_value(*script);
437
438 // Create a new weak global handle and use it to cache the wrapper
439 // for future use. The cache will automatically be cleared by the
440 // garbage collector when it is not used anymore.
441 Handle<Object> handle = GlobalHandles::Create(*result);
442 GlobalHandles::MakeWeak(handle.location(), NULL, &ClearWrapperCache);
443 script->wrapper()->set_proxy(reinterpret_cast<Address>(handle.location()));
444 return result;
445}
446
447
448// Init line_ends array with code positions of line ends inside script
449// source.
450void InitScriptLineEnds(Handle<Script> script) {
451 if (!script->line_ends()->IsUndefined()) return;
452
453 if (!script->source()->IsString()) {
454 ASSERT(script->source()->IsUndefined());
Steve Blockd0582a62009-12-15 09:54:21 +0000455 script->set_line_ends(*(Factory::NewFixedArray(0)));
456 ASSERT(script->line_ends()->IsFixedArray());
Steve Blocka7e24c12009-10-30 11:49:00 +0000457 return;
458 }
459
460 Handle<String> src(String::cast(script->source()));
Steve Block6ded16b2010-05-10 14:33:55 +0100461
462 Handle<FixedArray> array = CalculateLineEnds(src, true);
463
464 script->set_line_ends(*array);
465 ASSERT(script->line_ends()->IsFixedArray());
466}
467
468
469Handle<FixedArray> CalculateLineEnds(Handle<String> src,
470 bool with_imaginary_last_new_line) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000471 const int src_len = src->length();
472 Handle<String> new_line = Factory::NewStringFromAscii(CStrVector("\n"));
473
474 // Pass 1: Identify line count.
475 int line_count = 0;
476 int position = 0;
477 while (position != -1 && position < src_len) {
478 position = Runtime::StringMatch(src, new_line, position);
479 if (position != -1) {
480 position++;
481 }
Steve Block6ded16b2010-05-10 14:33:55 +0100482 if (position != -1) {
483 line_count++;
484 } else if (with_imaginary_last_new_line) {
485 // Even if the last line misses a line end, it is counted.
486 line_count++;
487 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000488 }
489
490 // Pass 2: Fill in line ends positions
491 Handle<FixedArray> array = Factory::NewFixedArray(line_count);
492 int array_index = 0;
493 position = 0;
494 while (position != -1 && position < src_len) {
495 position = Runtime::StringMatch(src, new_line, position);
Steve Block6ded16b2010-05-10 14:33:55 +0100496 if (position != -1) {
497 array->set(array_index++, Smi::FromInt(position++));
498 } else if (with_imaginary_last_new_line) {
499 // If the script does not end with a line ending add the final end
500 // position as just past the last line ending.
501 array->set(array_index++, Smi::FromInt(src_len));
502 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000503 }
504 ASSERT(array_index == line_count);
505
Steve Block6ded16b2010-05-10 14:33:55 +0100506 return array;
Steve Blocka7e24c12009-10-30 11:49:00 +0000507}
508
509
510// Convert code position into line number.
511int GetScriptLineNumber(Handle<Script> script, int code_pos) {
512 InitScriptLineEnds(script);
513 AssertNoAllocation no_allocation;
Andrei Popescu402d9372010-02-26 13:31:12 +0000514 FixedArray* line_ends_array = FixedArray::cast(script->line_ends());
Steve Blockd0582a62009-12-15 09:54:21 +0000515 const int line_ends_len = line_ends_array->length();
Steve Blocka7e24c12009-10-30 11:49:00 +0000516
Andrei Popescu402d9372010-02-26 13:31:12 +0000517 if (!line_ends_len)
518 return -1;
519
520 if ((Smi::cast(line_ends_array->get(0)))->value() >= code_pos)
521 return script->line_offset()->value();
522
523 int left = 0;
524 int right = line_ends_len;
525 while (int half = (right - left) / 2) {
526 if ((Smi::cast(line_ends_array->get(left + half)))->value() > code_pos) {
527 right -= half;
528 } else {
529 left += half;
Steve Blocka7e24c12009-10-30 11:49:00 +0000530 }
531 }
Andrei Popescu402d9372010-02-26 13:31:12 +0000532 return right + script->line_offset()->value();
Steve Blocka7e24c12009-10-30 11:49:00 +0000533}
534
535
Steve Block6ded16b2010-05-10 14:33:55 +0100536int GetScriptLineNumberSafe(Handle<Script> script, int code_pos) {
537 AssertNoAllocation no_allocation;
538 if (!script->line_ends()->IsUndefined()) {
539 return GetScriptLineNumber(script, code_pos);
540 }
541 // Slow mode: we do not have line_ends. We have to iterate through source.
542 if (!script->source()->IsString()) {
543 return -1;
544 }
545 String* source = String::cast(script->source());
546 int line = 0;
547 int len = source->length();
548 for (int pos = 0; pos < len; pos++) {
549 if (pos == code_pos) {
550 break;
551 }
552 if (source->Get(pos) == '\n') {
553 line++;
554 }
555 }
556 return line;
557}
558
559
Steve Blocka7e24c12009-10-30 11:49:00 +0000560void CustomArguments::IterateInstance(ObjectVisitor* v) {
Steve Block6ded16b2010-05-10 14:33:55 +0100561 v->VisitPointers(values_, values_ + ARRAY_SIZE(values_));
Steve Blocka7e24c12009-10-30 11:49:00 +0000562}
563
564
565// Compute the property keys from the interceptor.
566v8::Handle<v8::Array> GetKeysForNamedInterceptor(Handle<JSObject> receiver,
567 Handle<JSObject> object) {
568 Handle<InterceptorInfo> interceptor(object->GetNamedInterceptor());
569 CustomArguments args(interceptor->data(), *receiver, *object);
570 v8::AccessorInfo info(args.end());
571 v8::Handle<v8::Array> result;
572 if (!interceptor->enumerator()->IsUndefined()) {
573 v8::NamedPropertyEnumerator enum_fun =
574 v8::ToCData<v8::NamedPropertyEnumerator>(interceptor->enumerator());
575 LOG(ApiObjectAccess("interceptor-named-enum", *object));
576 {
577 // Leaving JavaScript.
578 VMState state(EXTERNAL);
579 result = enum_fun(info);
580 }
581 }
582 return result;
583}
584
585
586// Compute the element keys from the interceptor.
587v8::Handle<v8::Array> GetKeysForIndexedInterceptor(Handle<JSObject> receiver,
588 Handle<JSObject> object) {
589 Handle<InterceptorInfo> interceptor(object->GetIndexedInterceptor());
590 CustomArguments args(interceptor->data(), *receiver, *object);
591 v8::AccessorInfo info(args.end());
592 v8::Handle<v8::Array> result;
593 if (!interceptor->enumerator()->IsUndefined()) {
594 v8::IndexedPropertyEnumerator enum_fun =
595 v8::ToCData<v8::IndexedPropertyEnumerator>(interceptor->enumerator());
596 LOG(ApiObjectAccess("interceptor-indexed-enum", *object));
597 {
598 // Leaving JavaScript.
599 VMState state(EXTERNAL);
600 result = enum_fun(info);
601 }
602 }
603 return result;
604}
605
606
607Handle<FixedArray> GetKeysInFixedArrayFor(Handle<JSObject> object,
608 KeyCollectionType type) {
609 Handle<FixedArray> content = Factory::empty_fixed_array();
Steve Blockd0582a62009-12-15 09:54:21 +0000610 Handle<JSObject> arguments_boilerplate =
611 Handle<JSObject>(
612 Top::context()->global_context()->arguments_boilerplate());
613 Handle<JSFunction> arguments_function =
614 Handle<JSFunction>(
615 JSFunction::cast(arguments_boilerplate->map()->constructor()));
Steve Blocka7e24c12009-10-30 11:49:00 +0000616
617 // Only collect keys if access is permitted.
618 for (Handle<Object> p = object;
619 *p != Heap::null_value();
620 p = Handle<Object>(p->GetPrototype())) {
621 Handle<JSObject> current(JSObject::cast(*p));
622
623 // Check access rights if required.
624 if (current->IsAccessCheckNeeded() &&
625 !Top::MayNamedAccess(*current, Heap::undefined_value(),
626 v8::ACCESS_KEYS)) {
627 Top::ReportFailedAccessCheck(*current, v8::ACCESS_KEYS);
628 break;
629 }
630
631 // Compute the element keys.
632 Handle<FixedArray> element_keys =
633 Factory::NewFixedArray(current->NumberOfEnumElements());
634 current->GetEnumElementKeys(*element_keys);
635 content = UnionOfKeys(content, element_keys);
636
637 // Add the element keys from the interceptor.
638 if (current->HasIndexedInterceptor()) {
639 v8::Handle<v8::Array> result =
640 GetKeysForIndexedInterceptor(object, current);
641 if (!result.IsEmpty())
642 content = AddKeysFromJSArray(content, v8::Utils::OpenHandle(*result));
643 }
644
Steve Blockd0582a62009-12-15 09:54:21 +0000645 // We can cache the computed property keys if access checks are
646 // not needed and no interceptors are involved.
647 //
648 // We do not use the cache if the object has elements and
649 // therefore it does not make sense to cache the property names
650 // for arguments objects. Arguments objects will always have
651 // elements.
652 bool cache_enum_keys =
653 ((current->map()->constructor() != *arguments_function) &&
654 !current->IsAccessCheckNeeded() &&
655 !current->HasNamedInterceptor() &&
656 !current->HasIndexedInterceptor());
657 // Compute the property keys and cache them if possible.
658 content =
659 UnionOfKeys(content, GetEnumPropertyKeys(current, cache_enum_keys));
Steve Blocka7e24c12009-10-30 11:49:00 +0000660
661 // Add the property keys from the interceptor.
662 if (current->HasNamedInterceptor()) {
663 v8::Handle<v8::Array> result =
664 GetKeysForNamedInterceptor(object, current);
665 if (!result.IsEmpty())
666 content = AddKeysFromJSArray(content, v8::Utils::OpenHandle(*result));
667 }
668
669 // If we only want local properties we bail out after the first
670 // iteration.
671 if (type == LOCAL_ONLY)
672 break;
673 }
674 return content;
675}
676
677
678Handle<JSArray> GetKeysFor(Handle<JSObject> object) {
679 Counters::for_in.Increment();
680 Handle<FixedArray> elements = GetKeysInFixedArrayFor(object,
681 INCLUDE_PROTOS);
682 return Factory::NewJSArrayWithElements(elements);
683}
684
685
Steve Blockd0582a62009-12-15 09:54:21 +0000686Handle<FixedArray> GetEnumPropertyKeys(Handle<JSObject> object,
687 bool cache_result) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000688 int index = 0;
689 if (object->HasFastProperties()) {
690 if (object->map()->instance_descriptors()->HasEnumCache()) {
691 Counters::enum_cache_hits.Increment();
692 DescriptorArray* desc = object->map()->instance_descriptors();
693 return Handle<FixedArray>(FixedArray::cast(desc->GetEnumCache()));
694 }
695 Counters::enum_cache_misses.Increment();
696 int num_enum = object->NumberOfEnumProperties();
697 Handle<FixedArray> storage = Factory::NewFixedArray(num_enum);
698 Handle<FixedArray> sort_array = Factory::NewFixedArray(num_enum);
699 Handle<DescriptorArray> descs =
700 Handle<DescriptorArray>(object->map()->instance_descriptors());
701 for (int i = 0; i < descs->number_of_descriptors(); i++) {
702 if (descs->IsProperty(i) && !descs->IsDontEnum(i)) {
703 (*storage)->set(index, descs->GetKey(i));
704 PropertyDetails details(descs->GetDetails(i));
705 (*sort_array)->set(index, Smi::FromInt(details.index()));
706 index++;
707 }
708 }
709 (*storage)->SortPairs(*sort_array, sort_array->length());
Steve Blockd0582a62009-12-15 09:54:21 +0000710 if (cache_result) {
711 Handle<FixedArray> bridge_storage =
712 Factory::NewFixedArray(DescriptorArray::kEnumCacheBridgeLength);
713 DescriptorArray* desc = object->map()->instance_descriptors();
714 desc->SetEnumCache(*bridge_storage, *storage);
715 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000716 ASSERT(storage->length() == index);
717 return storage;
718 } else {
719 int num_enum = object->NumberOfEnumProperties();
720 Handle<FixedArray> storage = Factory::NewFixedArray(num_enum);
721 Handle<FixedArray> sort_array = Factory::NewFixedArray(num_enum);
722 object->property_dictionary()->CopyEnumKeysTo(*storage, *sort_array);
723 return storage;
724 }
725}
726
727
Leon Clarke4515c472010-02-03 11:58:03 +0000728bool EnsureCompiled(Handle<SharedFunctionInfo> shared,
729 ClearExceptionFlag flag) {
730 return shared->is_compiled() || CompileLazyShared(shared, flag);
731}
732
733
734static bool CompileLazyHelper(CompilationInfo* info,
735 ClearExceptionFlag flag) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000736 // Compile the source information to a code object.
Leon Clarke4515c472010-02-03 11:58:03 +0000737 ASSERT(!info->shared_info()->is_compiled());
738 bool result = Compiler::CompileLazy(info);
Steve Blocka7e24c12009-10-30 11:49:00 +0000739 ASSERT(result != Top::has_pending_exception());
740 if (!result && flag == CLEAR_EXCEPTION) Top::clear_pending_exception();
741 return result;
742}
743
744
Leon Clarke4515c472010-02-03 11:58:03 +0000745bool CompileLazyShared(Handle<SharedFunctionInfo> shared,
746 ClearExceptionFlag flag) {
Andrei Popescu31002712010-02-23 13:46:05 +0000747 CompilationInfo info(shared);
Leon Clarke4515c472010-02-03 11:58:03 +0000748 return CompileLazyHelper(&info, flag);
749}
750
751
752bool CompileLazy(Handle<JSFunction> function,
753 Handle<Object> receiver,
754 ClearExceptionFlag flag) {
Andrei Popescu31002712010-02-23 13:46:05 +0000755 CompilationInfo info(function, 0, receiver);
Leon Clarke4515c472010-02-03 11:58:03 +0000756 bool result = CompileLazyHelper(&info, flag);
Steve Block6ded16b2010-05-10 14:33:55 +0100757 PROFILE(FunctionCreateEvent(*function));
Leon Clarked91b9f72010-01-27 17:25:45 +0000758 return result;
Steve Blocka7e24c12009-10-30 11:49:00 +0000759}
760
761
Leon Clarke4515c472010-02-03 11:58:03 +0000762bool CompileLazyInLoop(Handle<JSFunction> function,
763 Handle<Object> receiver,
764 ClearExceptionFlag flag) {
Andrei Popescu31002712010-02-23 13:46:05 +0000765 CompilationInfo info(function, 1, receiver);
Leon Clarke4515c472010-02-03 11:58:03 +0000766 bool result = CompileLazyHelper(&info, flag);
Steve Block6ded16b2010-05-10 14:33:55 +0100767 PROFILE(FunctionCreateEvent(*function));
Leon Clarked91b9f72010-01-27 17:25:45 +0000768 return result;
Steve Blocka7e24c12009-10-30 11:49:00 +0000769}
770
Leon Clarke4515c472010-02-03 11:58:03 +0000771
Steve Blocka7e24c12009-10-30 11:49:00 +0000772OptimizedObjectForAddingMultipleProperties::
773OptimizedObjectForAddingMultipleProperties(Handle<JSObject> object,
774 int expected_additional_properties,
775 bool condition) {
776 object_ = object;
777 if (condition && object_->HasFastProperties()) {
778 // Normalize the properties of object to avoid n^2 behavior
779 // when extending the object multiple properties. Indicate the number of
780 // properties to be added.
781 unused_property_fields_ = object->map()->unused_property_fields();
782 NormalizeProperties(object_,
783 KEEP_INOBJECT_PROPERTIES,
784 expected_additional_properties);
785 has_been_transformed_ = true;
786
787 } else {
788 has_been_transformed_ = false;
789 }
790}
791
792
Steve Blockd0582a62009-12-15 09:54:21 +0000793Handle<Code> ComputeLazyCompile(int argc) {
794 CALL_HEAP_FUNCTION(StubCache::ComputeLazyCompile(argc), Code);
795}
796
797
Steve Blocka7e24c12009-10-30 11:49:00 +0000798OptimizedObjectForAddingMultipleProperties::
799~OptimizedObjectForAddingMultipleProperties() {
800 // Reoptimize the object to allow fast property access.
801 if (has_been_transformed_) {
802 TransformToFastProperties(object_, unused_property_fields_);
803 }
804}
805
Steve Blocka7e24c12009-10-30 11:49:00 +0000806} } // namespace v8::internal