blob: efef095a2d4d04d1044f90003b7259bf9bc1161b [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"
34#include "compiler.h"
35#include "debug.h"
36#include "execution.h"
37#include "global-handles.h"
38#include "natives.h"
39#include "runtime.h"
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -080040#include "string-search.h"
Steve Blockd0582a62009-12-15 09:54:21 +000041#include "stub-cache.h"
Ben Murdochb0fe1622011-05-05 13:52:32 +010042#include "vm-state-inl.h"
Steve Blocka7e24c12009-10-30 11:49:00 +000043
44namespace v8 {
45namespace internal {
46
47
48v8::ImplementationUtilities::HandleScopeData HandleScope::current_ =
John Reck59135872010-11-02 12:39:01 -070049 { NULL, NULL, 0 };
Steve Blocka7e24c12009-10-30 11:49:00 +000050
51
52int HandleScope::NumberOfHandles() {
53 int n = HandleScopeImplementer::instance()->blocks()->length();
54 if (n == 0) return 0;
Steve Blockd0582a62009-12-15 09:54:21 +000055 return ((n - 1) * kHandleBlockSize) + static_cast<int>(
56 (current_.next - HandleScopeImplementer::instance()->blocks()->last()));
Steve Blocka7e24c12009-10-30 11:49:00 +000057}
58
59
60Object** HandleScope::Extend() {
61 Object** result = current_.next;
62
63 ASSERT(result == current_.limit);
64 // Make sure there's at least one scope on the stack and that the
65 // top of the scope stack isn't a barrier.
John Reck59135872010-11-02 12:39:01 -070066 if (current_.level == 0) {
Steve Blocka7e24c12009-10-30 11:49:00 +000067 Utils::ReportApiFailure("v8::HandleScope::CreateHandle()",
68 "Cannot create a handle without a HandleScope");
69 return NULL;
70 }
71 HandleScopeImplementer* impl = HandleScopeImplementer::instance();
72 // If there's more room in the last block, we use that. This is used
73 // for fast creation of scopes after scope barriers.
74 if (!impl->blocks()->is_empty()) {
75 Object** limit = &impl->blocks()->last()[kHandleBlockSize];
76 if (current_.limit != limit) {
77 current_.limit = limit;
John Reck59135872010-11-02 12:39:01 -070078 ASSERT(limit - current_.next < kHandleBlockSize);
Steve Blocka7e24c12009-10-30 11:49:00 +000079 }
80 }
81
82 // If we still haven't found a slot for the handle, we extend the
83 // current handle scope by allocating a new handle block.
84 if (result == current_.limit) {
85 // If there's a spare block, use it for growing the current scope.
86 result = impl->GetSpareOrNewBlock();
87 // Add the extension to the global list of blocks, but count the
88 // extension as part of the current scope.
89 impl->blocks()->Add(result);
Steve Blocka7e24c12009-10-30 11:49:00 +000090 current_.limit = &result[kHandleBlockSize];
91 }
92
93 return result;
94}
95
96
97void HandleScope::DeleteExtensions() {
John Reck59135872010-11-02 12:39:01 -070098 HandleScopeImplementer::instance()->DeleteExtensions(current_.limit);
Steve Blocka7e24c12009-10-30 11:49:00 +000099}
100
101
102void HandleScope::ZapRange(Object** start, Object** end) {
John Reck59135872010-11-02 12:39:01 -0700103 ASSERT(end - start <= kHandleBlockSize);
104 for (Object** p = start; p != end; p++) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000105 *reinterpret_cast<Address*>(p) = v8::internal::kHandleZapValue;
106 }
107}
108
109
John Reck59135872010-11-02 12:39:01 -0700110Address HandleScope::current_level_address() {
111 return reinterpret_cast<Address>(&current_.level);
Steve Blockd0582a62009-12-15 09:54:21 +0000112}
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) {
Kristian Monsen0d5e1162010-09-30 15:31:59 +0100146 // If objects constructed from this function exist then changing
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -0800147 // 'estimated_nof_properties' is dangerous since the previous value might
Kristian Monsen0d5e1162010-09-30 15:31:59 +0100148 // have been compiled into the fast construct stub. More over, the inobject
149 // slack tracking logic might have adjusted the previous value, so even
150 // passing the same value is risky.
151 if (func->shared()->live_objects_may_exist()) return;
152
Steve Blocka7e24c12009-10-30 11:49:00 +0000153 func->shared()->set_expected_nof_properties(nof);
154 if (func->has_initial_map()) {
155 Handle<Map> new_initial_map =
156 Factory::CopyMapDropTransitions(Handle<Map>(func->initial_map()));
157 new_initial_map->set_unused_property_fields(nof);
158 func->set_initial_map(*new_initial_map);
159 }
160}
161
162
163void SetPrototypeProperty(Handle<JSFunction> func, Handle<JSObject> value) {
164 CALL_HEAP_FUNCTION_VOID(func->SetPrototype(*value));
165}
166
167
168static int ExpectedNofPropertiesFromEstimate(int estimate) {
Kristian Monsen0d5e1162010-09-30 15:31:59 +0100169 // If no properties are added in the constructor, they are more likely
170 // to be added later.
171 if (estimate == 0) estimate = 2;
172
173 // We do not shrink objects that go into a snapshot (yet), so we adjust
174 // the estimate conservatively.
175 if (Serializer::enabled()) return estimate + 2;
176
177 // Inobject slack tracking will reclaim redundant inobject space later,
178 // so we can afford to adjust the estimate generously.
Ben Murdochf87a2032010-10-22 12:50:53 +0100179 return estimate + 8;
Steve Blocka7e24c12009-10-30 11:49:00 +0000180}
181
182
183void SetExpectedNofPropertiesFromEstimate(Handle<SharedFunctionInfo> shared,
184 int estimate) {
Kristian Monsen0d5e1162010-09-30 15:31:59 +0100185 // See the comment in SetExpectedNofProperties.
186 if (shared->live_objects_may_exist()) return;
187
Steve Blocka7e24c12009-10-30 11:49:00 +0000188 shared->set_expected_nof_properties(
189 ExpectedNofPropertiesFromEstimate(estimate));
190}
191
192
Steve Blocka7e24c12009-10-30 11:49:00 +0000193void NormalizeProperties(Handle<JSObject> object,
194 PropertyNormalizationMode mode,
195 int expected_additional_properties) {
196 CALL_HEAP_FUNCTION_VOID(object->NormalizeProperties(
197 mode,
198 expected_additional_properties));
199}
200
201
202void NormalizeElements(Handle<JSObject> object) {
203 CALL_HEAP_FUNCTION_VOID(object->NormalizeElements());
204}
205
206
207void TransformToFastProperties(Handle<JSObject> object,
208 int unused_property_fields) {
209 CALL_HEAP_FUNCTION_VOID(
210 object->TransformToFastProperties(unused_property_fields));
211}
212
213
John Reck59135872010-11-02 12:39:01 -0700214void NumberDictionarySet(Handle<NumberDictionary> dictionary,
215 uint32_t index,
216 Handle<Object> value,
217 PropertyDetails details) {
218 CALL_HEAP_FUNCTION_VOID(dictionary->Set(index, *value, details));
219}
220
221
Steve Blocka7e24c12009-10-30 11:49:00 +0000222void FlattenString(Handle<String> string) {
Steve Block6ded16b2010-05-10 14:33:55 +0100223 CALL_HEAP_FUNCTION_VOID(string->TryFlatten());
Steve Block8defd9f2010-07-08 12:39:36 +0100224}
225
226
227Handle<String> FlattenGetString(Handle<String> string) {
Ben Murdochb0fe1622011-05-05 13:52:32 +0100228 CALL_HEAP_FUNCTION(string->TryFlatten(), String);
Steve Blocka7e24c12009-10-30 11:49:00 +0000229}
230
231
232Handle<Object> SetPrototype(Handle<JSFunction> function,
233 Handle<Object> prototype) {
Steve Block6ded16b2010-05-10 14:33:55 +0100234 ASSERT(function->should_have_prototype());
Steve Blocka7e24c12009-10-30 11:49:00 +0000235 CALL_HEAP_FUNCTION(Accessors::FunctionSetPrototype(*function,
236 *prototype,
237 NULL),
238 Object);
239}
240
241
242Handle<Object> SetProperty(Handle<JSObject> object,
243 Handle<String> key,
244 Handle<Object> value,
Ben Murdoche0cee9b2011-05-25 10:26:03 +0100245 PropertyAttributes attributes,
246 StrictModeFlag strict_mode) {
247 CALL_HEAP_FUNCTION(object->SetProperty(*key, *value, attributes, strict_mode),
248 Object);
Steve Blocka7e24c12009-10-30 11:49:00 +0000249}
250
251
252Handle<Object> SetProperty(Handle<Object> object,
253 Handle<Object> key,
254 Handle<Object> value,
Ben Murdoche0cee9b2011-05-25 10:26:03 +0100255 PropertyAttributes attributes,
256 StrictModeFlag strict_mode) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000257 CALL_HEAP_FUNCTION(
Ben Murdoche0cee9b2011-05-25 10:26:03 +0100258 Runtime::SetObjectProperty(object, key, value, attributes, strict_mode),
259 Object);
Steve Blocka7e24c12009-10-30 11:49:00 +0000260}
261
262
263Handle<Object> ForceSetProperty(Handle<JSObject> object,
264 Handle<Object> key,
265 Handle<Object> value,
266 PropertyAttributes attributes) {
267 CALL_HEAP_FUNCTION(
Ben Murdoche0cee9b2011-05-25 10:26:03 +0100268 Runtime::ForceSetObjectProperty(
269 object, key, value, attributes),
270 Object);
Steve Blocka7e24c12009-10-30 11:49:00 +0000271}
272
273
Andrei Popescu31002712010-02-23 13:46:05 +0000274Handle<Object> SetNormalizedProperty(Handle<JSObject> object,
275 Handle<String> key,
276 Handle<Object> value,
277 PropertyDetails details) {
278 CALL_HEAP_FUNCTION(object->SetNormalizedProperty(*key, *value, details),
279 Object);
280}
281
282
Steve Blocka7e24c12009-10-30 11:49:00 +0000283Handle<Object> ForceDeleteProperty(Handle<JSObject> object,
284 Handle<Object> key) {
285 CALL_HEAP_FUNCTION(Runtime::ForceDeleteObjectProperty(object, key), Object);
286}
287
288
Ben Murdoch086aeea2011-05-13 15:57:08 +0100289Handle<Object> SetLocalPropertyIgnoreAttributes(
Steve Blocka7e24c12009-10-30 11:49:00 +0000290 Handle<JSObject> object,
291 Handle<String> key,
292 Handle<Object> value,
293 PropertyAttributes attributes) {
294 CALL_HEAP_FUNCTION(object->
Ben Murdoch086aeea2011-05-13 15:57:08 +0100295 SetLocalPropertyIgnoreAttributes(*key, *value, attributes), Object);
Steve Blocka7e24c12009-10-30 11:49:00 +0000296}
297
298
Steve Block1e0659c2011-05-24 12:43:12 +0100299void SetLocalPropertyNoThrow(Handle<JSObject> object,
300 Handle<String> key,
301 Handle<Object> value,
302 PropertyAttributes attributes) {
303 ASSERT(!Top::has_pending_exception());
304 CHECK(!SetLocalPropertyIgnoreAttributes(
305 object, key, value, attributes).is_null());
306 CHECK(!Top::has_pending_exception());
307}
308
309
Steve Blocka7e24c12009-10-30 11:49:00 +0000310Handle<Object> SetPropertyWithInterceptor(Handle<JSObject> object,
311 Handle<String> key,
312 Handle<Object> value,
Ben Murdoche0cee9b2011-05-25 10:26:03 +0100313 PropertyAttributes attributes,
314 StrictModeFlag strict_mode) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000315 CALL_HEAP_FUNCTION(object->SetPropertyWithInterceptor(*key,
316 *value,
Ben Murdoche0cee9b2011-05-25 10:26:03 +0100317 attributes,
318 strict_mode),
Steve Blocka7e24c12009-10-30 11:49:00 +0000319 Object);
320}
321
322
323Handle<Object> GetProperty(Handle<JSObject> obj,
324 const char* name) {
325 Handle<String> str = Factory::LookupAsciiSymbol(name);
326 CALL_HEAP_FUNCTION(obj->GetProperty(*str), Object);
327}
328
329
330Handle<Object> GetProperty(Handle<Object> obj,
331 Handle<Object> key) {
332 CALL_HEAP_FUNCTION(Runtime::GetObjectProperty(obj, key), Object);
333}
334
335
Steve Block6ded16b2010-05-10 14:33:55 +0100336Handle<Object> GetElement(Handle<Object> obj,
337 uint32_t index) {
338 CALL_HEAP_FUNCTION(Runtime::GetElement(obj, index), Object);
339}
340
341
Steve Blocka7e24c12009-10-30 11:49:00 +0000342Handle<Object> GetPropertyWithInterceptor(Handle<JSObject> receiver,
343 Handle<JSObject> holder,
344 Handle<String> name,
345 PropertyAttributes* attributes) {
346 CALL_HEAP_FUNCTION(holder->GetPropertyWithInterceptor(*receiver,
347 *name,
348 attributes),
349 Object);
350}
351
352
353Handle<Object> GetPrototype(Handle<Object> obj) {
354 Handle<Object> result(obj->GetPrototype());
355 return result;
356}
357
358
Andrei Popescu402d9372010-02-26 13:31:12 +0000359Handle<Object> SetPrototype(Handle<JSObject> obj, Handle<Object> value) {
360 const bool skip_hidden_prototypes = false;
361 CALL_HEAP_FUNCTION(obj->SetPrototype(*value, skip_hidden_prototypes), Object);
362}
363
364
Steve Blocka7e24c12009-10-30 11:49:00 +0000365Handle<Object> GetHiddenProperties(Handle<JSObject> obj,
366 bool create_if_needed) {
Steve Blockd0582a62009-12-15 09:54:21 +0000367 Object* holder = obj->BypassGlobalProxy();
368 if (holder->IsUndefined()) return Factory::undefined_value();
369 obj = Handle<JSObject>(JSObject::cast(holder));
Steve Blocka7e24c12009-10-30 11:49:00 +0000370
371 if (obj->HasFastProperties()) {
372 // If the object has fast properties, check whether the first slot
373 // in the descriptor array matches the hidden symbol. Since the
374 // hidden symbols hash code is zero (and no other string has hash
375 // code zero) it will always occupy the first entry if present.
376 DescriptorArray* descriptors = obj->map()->instance_descriptors();
377 if ((descriptors->number_of_descriptors() > 0) &&
Steve Blockd0582a62009-12-15 09:54:21 +0000378 (descriptors->GetKey(0) == Heap::hidden_symbol()) &&
Steve Blocka7e24c12009-10-30 11:49:00 +0000379 descriptors->IsProperty(0)) {
380 ASSERT(descriptors->GetType(0) == FIELD);
381 return Handle<Object>(obj->FastPropertyAt(descriptors->GetFieldIndex(0)));
382 }
383 }
384
385 // Only attempt to find the hidden properties in the local object and not
386 // in the prototype chain. Note that HasLocalProperty() can cause a GC in
387 // the general case in the presence of interceptors.
Steve Blockd0582a62009-12-15 09:54:21 +0000388 if (!obj->HasHiddenPropertiesObject()) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000389 // Hidden properties object not found. Allocate a new hidden properties
390 // object if requested. Otherwise return the undefined value.
391 if (create_if_needed) {
392 Handle<Object> hidden_obj = Factory::NewJSObject(Top::object_function());
Steve Blockd0582a62009-12-15 09:54:21 +0000393 CALL_HEAP_FUNCTION(obj->SetHiddenPropertiesObject(*hidden_obj), Object);
Steve Blocka7e24c12009-10-30 11:49:00 +0000394 } else {
395 return Factory::undefined_value();
396 }
397 }
Steve Blockd0582a62009-12-15 09:54:21 +0000398 return Handle<Object>(obj->GetHiddenPropertiesObject());
Steve Blocka7e24c12009-10-30 11:49:00 +0000399}
400
401
402Handle<Object> DeleteElement(Handle<JSObject> obj,
403 uint32_t index) {
404 CALL_HEAP_FUNCTION(obj->DeleteElement(index, JSObject::NORMAL_DELETION),
405 Object);
406}
407
408
409Handle<Object> DeleteProperty(Handle<JSObject> obj,
410 Handle<String> prop) {
411 CALL_HEAP_FUNCTION(obj->DeleteProperty(*prop, JSObject::NORMAL_DELETION),
412 Object);
413}
414
415
416Handle<Object> LookupSingleCharacterStringFromCode(uint32_t index) {
417 CALL_HEAP_FUNCTION(Heap::LookupSingleCharacterStringFromCode(index), Object);
418}
419
420
Steve Block6ded16b2010-05-10 14:33:55 +0100421Handle<String> SubString(Handle<String> str,
422 int start,
423 int end,
424 PretenureFlag pretenure) {
425 CALL_HEAP_FUNCTION(str->SubString(start, end, pretenure), String);
Steve Blocka7e24c12009-10-30 11:49:00 +0000426}
427
428
429Handle<Object> SetElement(Handle<JSObject> object,
430 uint32_t index,
Ben Murdoche0cee9b2011-05-25 10:26:03 +0100431 Handle<Object> value,
432 StrictModeFlag strict_mode) {
Steve Block3ce2e202009-11-05 08:53:23 +0000433 if (object->HasPixelElements() || object->HasExternalArrayElements()) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000434 if (!value->IsSmi() && !value->IsHeapNumber() && !value->IsUndefined()) {
435 bool has_exception;
436 Handle<Object> number = Execution::ToNumber(value, &has_exception);
437 if (has_exception) return Handle<Object>();
438 value = number;
439 }
440 }
Ben Murdoche0cee9b2011-05-25 10:26:03 +0100441 CALL_HEAP_FUNCTION(object->SetElement(index, *value, strict_mode), Object);
Steve Blocka7e24c12009-10-30 11:49:00 +0000442}
443
444
Ben Murdoch086aeea2011-05-13 15:57:08 +0100445Handle<Object> SetOwnElement(Handle<JSObject> object,
446 uint32_t index,
Ben Murdoche0cee9b2011-05-25 10:26:03 +0100447 Handle<Object> value,
448 StrictModeFlag strict_mode) {
Ben Murdoch086aeea2011-05-13 15:57:08 +0100449 ASSERT(!object->HasPixelElements());
450 ASSERT(!object->HasExternalArrayElements());
Ben Murdoche0cee9b2011-05-25 10:26:03 +0100451 CALL_HEAP_FUNCTION(object->SetElement(index, *value, strict_mode, false),
452 Object);
Ben Murdoch086aeea2011-05-13 15:57:08 +0100453}
454
455
Steve Blocka7e24c12009-10-30 11:49:00 +0000456Handle<JSObject> Copy(Handle<JSObject> obj) {
457 CALL_HEAP_FUNCTION(Heap::CopyJSObject(*obj), JSObject);
458}
459
460
Leon Clarkef7060e22010-06-03 12:02:55 +0100461Handle<Object> SetAccessor(Handle<JSObject> obj, Handle<AccessorInfo> info) {
462 CALL_HEAP_FUNCTION(obj->DefineAccessor(*info), Object);
463}
464
465
Steve Blocka7e24c12009-10-30 11:49:00 +0000466// Wrappers for scripts are kept alive and cached in weak global
467// handles referred from proxy objects held by the scripts as long as
468// they are used. When they are not used anymore, the garbage
469// collector will call the weak callback on the global handle
470// associated with the wrapper and get rid of both the wrapper and the
471// handle.
472static void ClearWrapperCache(Persistent<v8::Value> handle, void*) {
473#ifdef ENABLE_HEAP_PROTECTION
474 // Weak reference callbacks are called as if from outside V8. We
475 // need to reeenter to unprotect the heap.
476 VMState state(OTHER);
477#endif
478 Handle<Object> cache = Utils::OpenHandle(*handle);
479 JSValue* wrapper = JSValue::cast(*cache);
480 Proxy* proxy = Script::cast(wrapper->value())->wrapper();
481 ASSERT(proxy->proxy() == reinterpret_cast<Address>(cache.location()));
482 proxy->set_proxy(0);
483 GlobalHandles::Destroy(cache.location());
484 Counters::script_wrappers.Decrement();
485}
486
487
488Handle<JSValue> GetScriptWrapper(Handle<Script> script) {
489 if (script->wrapper()->proxy() != NULL) {
490 // Return the script wrapper directly from the cache.
491 return Handle<JSValue>(
492 reinterpret_cast<JSValue**>(script->wrapper()->proxy()));
493 }
494
495 // Construct a new script wrapper.
496 Counters::script_wrappers.Increment();
497 Handle<JSFunction> constructor = Top::script_function();
498 Handle<JSValue> result =
499 Handle<JSValue>::cast(Factory::NewJSObject(constructor));
500 result->set_value(*script);
501
502 // Create a new weak global handle and use it to cache the wrapper
503 // for future use. The cache will automatically be cleared by the
504 // garbage collector when it is not used anymore.
505 Handle<Object> handle = GlobalHandles::Create(*result);
506 GlobalHandles::MakeWeak(handle.location(), NULL, &ClearWrapperCache);
507 script->wrapper()->set_proxy(reinterpret_cast<Address>(handle.location()));
508 return result;
509}
510
511
512// Init line_ends array with code positions of line ends inside script
513// source.
514void InitScriptLineEnds(Handle<Script> script) {
515 if (!script->line_ends()->IsUndefined()) return;
516
517 if (!script->source()->IsString()) {
518 ASSERT(script->source()->IsUndefined());
Kristian Monsen0d5e1162010-09-30 15:31:59 +0100519 Handle<FixedArray> empty = Factory::NewFixedArray(0);
520 script->set_line_ends(*empty);
Steve Blockd0582a62009-12-15 09:54:21 +0000521 ASSERT(script->line_ends()->IsFixedArray());
Steve Blocka7e24c12009-10-30 11:49:00 +0000522 return;
523 }
524
525 Handle<String> src(String::cast(script->source()));
Steve Block6ded16b2010-05-10 14:33:55 +0100526
527 Handle<FixedArray> array = CalculateLineEnds(src, true);
528
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -0800529 if (*array != Heap::empty_fixed_array()) {
530 array->set_map(Heap::fixed_cow_array_map());
531 }
532
Steve Block6ded16b2010-05-10 14:33:55 +0100533 script->set_line_ends(*array);
534 ASSERT(script->line_ends()->IsFixedArray());
535}
536
537
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -0800538template <typename SourceChar>
539static void CalculateLineEnds(List<int>* line_ends,
540 Vector<const SourceChar> src,
541 bool with_last_line) {
542 const int src_len = src.length();
543 StringSearch<char, SourceChar> search(CStrVector("\n"));
Steve Blocka7e24c12009-10-30 11:49:00 +0000544
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -0800545 // Find and record line ends.
Steve Blocka7e24c12009-10-30 11:49:00 +0000546 int position = 0;
547 while (position != -1 && position < src_len) {
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -0800548 position = search.Search(src, position);
Steve Blocka7e24c12009-10-30 11:49:00 +0000549 if (position != -1) {
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -0800550 line_ends->Add(position);
Steve Blocka7e24c12009-10-30 11:49:00 +0000551 position++;
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -0800552 } else if (with_last_line) {
Steve Block6ded16b2010-05-10 14:33:55 +0100553 // Even if the last line misses a line end, it is counted.
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -0800554 line_ends->Add(src_len);
555 return;
Steve Block6ded16b2010-05-10 14:33:55 +0100556 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000557 }
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -0800558}
Steve Blocka7e24c12009-10-30 11:49:00 +0000559
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -0800560
561Handle<FixedArray> CalculateLineEnds(Handle<String> src,
562 bool with_last_line) {
563 src = FlattenGetString(src);
564 // Rough estimate of line count based on a roughly estimated average
565 // length of (unpacked) code.
566 int line_count_estimate = src->length() >> 4;
567 List<int> line_ends(line_count_estimate);
568 {
569 AssertNoAllocation no_heap_allocation; // ensure vectors stay valid.
570 // Dispatch on type of strings.
571 if (src->IsAsciiRepresentation()) {
572 CalculateLineEnds(&line_ends, src->ToAsciiVector(), with_last_line);
573 } else {
574 CalculateLineEnds(&line_ends, src->ToUC16Vector(), with_last_line);
575 }
576 }
577 int line_count = line_ends.length();
Steve Blocka7e24c12009-10-30 11:49:00 +0000578 Handle<FixedArray> array = Factory::NewFixedArray(line_count);
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -0800579 for (int i = 0; i < line_count; i++) {
580 array->set(i, Smi::FromInt(line_ends[i]));
Steve Blocka7e24c12009-10-30 11:49:00 +0000581 }
Steve Block6ded16b2010-05-10 14:33:55 +0100582 return array;
Steve Blocka7e24c12009-10-30 11:49:00 +0000583}
584
585
586// Convert code position into line number.
587int GetScriptLineNumber(Handle<Script> script, int code_pos) {
588 InitScriptLineEnds(script);
589 AssertNoAllocation no_allocation;
Andrei Popescu402d9372010-02-26 13:31:12 +0000590 FixedArray* line_ends_array = FixedArray::cast(script->line_ends());
Steve Blockd0582a62009-12-15 09:54:21 +0000591 const int line_ends_len = line_ends_array->length();
Steve Blocka7e24c12009-10-30 11:49:00 +0000592
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -0800593 if (!line_ends_len) return -1;
Andrei Popescu402d9372010-02-26 13:31:12 +0000594
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -0800595 if ((Smi::cast(line_ends_array->get(0)))->value() >= code_pos) {
Andrei Popescu402d9372010-02-26 13:31:12 +0000596 return script->line_offset()->value();
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -0800597 }
Andrei Popescu402d9372010-02-26 13:31:12 +0000598
599 int left = 0;
600 int right = line_ends_len;
601 while (int half = (right - left) / 2) {
602 if ((Smi::cast(line_ends_array->get(left + half)))->value() > code_pos) {
603 right -= half;
604 } else {
605 left += half;
Steve Blocka7e24c12009-10-30 11:49:00 +0000606 }
607 }
Andrei Popescu402d9372010-02-26 13:31:12 +0000608 return right + script->line_offset()->value();
Steve Blocka7e24c12009-10-30 11:49:00 +0000609}
610
611
Steve Block6ded16b2010-05-10 14:33:55 +0100612int GetScriptLineNumberSafe(Handle<Script> script, int code_pos) {
613 AssertNoAllocation no_allocation;
614 if (!script->line_ends()->IsUndefined()) {
615 return GetScriptLineNumber(script, code_pos);
616 }
617 // Slow mode: we do not have line_ends. We have to iterate through source.
618 if (!script->source()->IsString()) {
619 return -1;
620 }
621 String* source = String::cast(script->source());
622 int line = 0;
623 int len = source->length();
624 for (int pos = 0; pos < len; pos++) {
625 if (pos == code_pos) {
626 break;
627 }
628 if (source->Get(pos) == '\n') {
629 line++;
630 }
631 }
632 return line;
633}
634
635
Steve Blocka7e24c12009-10-30 11:49:00 +0000636void CustomArguments::IterateInstance(ObjectVisitor* v) {
Steve Block6ded16b2010-05-10 14:33:55 +0100637 v->VisitPointers(values_, values_ + ARRAY_SIZE(values_));
Steve Blocka7e24c12009-10-30 11:49:00 +0000638}
639
640
641// Compute the property keys from the interceptor.
642v8::Handle<v8::Array> GetKeysForNamedInterceptor(Handle<JSObject> receiver,
643 Handle<JSObject> object) {
644 Handle<InterceptorInfo> interceptor(object->GetNamedInterceptor());
645 CustomArguments args(interceptor->data(), *receiver, *object);
646 v8::AccessorInfo info(args.end());
647 v8::Handle<v8::Array> result;
648 if (!interceptor->enumerator()->IsUndefined()) {
649 v8::NamedPropertyEnumerator enum_fun =
650 v8::ToCData<v8::NamedPropertyEnumerator>(interceptor->enumerator());
651 LOG(ApiObjectAccess("interceptor-named-enum", *object));
652 {
653 // Leaving JavaScript.
654 VMState state(EXTERNAL);
655 result = enum_fun(info);
656 }
657 }
658 return result;
659}
660
661
662// Compute the element keys from the interceptor.
663v8::Handle<v8::Array> GetKeysForIndexedInterceptor(Handle<JSObject> receiver,
664 Handle<JSObject> object) {
665 Handle<InterceptorInfo> interceptor(object->GetIndexedInterceptor());
666 CustomArguments args(interceptor->data(), *receiver, *object);
667 v8::AccessorInfo info(args.end());
668 v8::Handle<v8::Array> result;
669 if (!interceptor->enumerator()->IsUndefined()) {
670 v8::IndexedPropertyEnumerator enum_fun =
671 v8::ToCData<v8::IndexedPropertyEnumerator>(interceptor->enumerator());
672 LOG(ApiObjectAccess("interceptor-indexed-enum", *object));
673 {
674 // Leaving JavaScript.
675 VMState state(EXTERNAL);
676 result = enum_fun(info);
677 }
678 }
679 return result;
680}
681
682
Ben Murdochf87a2032010-10-22 12:50:53 +0100683static bool ContainsOnlyValidKeys(Handle<FixedArray> array) {
684 int len = array->length();
685 for (int i = 0; i < len; i++) {
686 Object* e = array->get(i);
687 if (!(e->IsString() || e->IsNumber())) return false;
688 }
689 return true;
690}
691
692
Steve Blocka7e24c12009-10-30 11:49:00 +0000693Handle<FixedArray> GetKeysInFixedArrayFor(Handle<JSObject> object,
694 KeyCollectionType type) {
Ben Murdochf87a2032010-10-22 12:50:53 +0100695 USE(ContainsOnlyValidKeys);
Steve Blocka7e24c12009-10-30 11:49:00 +0000696 Handle<FixedArray> content = Factory::empty_fixed_array();
Steve Blockd0582a62009-12-15 09:54:21 +0000697 Handle<JSObject> arguments_boilerplate =
698 Handle<JSObject>(
699 Top::context()->global_context()->arguments_boilerplate());
700 Handle<JSFunction> arguments_function =
701 Handle<JSFunction>(
702 JSFunction::cast(arguments_boilerplate->map()->constructor()));
Steve Blocka7e24c12009-10-30 11:49:00 +0000703
704 // Only collect keys if access is permitted.
705 for (Handle<Object> p = object;
706 *p != Heap::null_value();
707 p = Handle<Object>(p->GetPrototype())) {
708 Handle<JSObject> current(JSObject::cast(*p));
709
710 // Check access rights if required.
711 if (current->IsAccessCheckNeeded() &&
Iain Merrick75681382010-08-19 15:07:18 +0100712 !Top::MayNamedAccess(*current, Heap::undefined_value(),
713 v8::ACCESS_KEYS)) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000714 Top::ReportFailedAccessCheck(*current, v8::ACCESS_KEYS);
715 break;
716 }
717
718 // Compute the element keys.
719 Handle<FixedArray> element_keys =
720 Factory::NewFixedArray(current->NumberOfEnumElements());
721 current->GetEnumElementKeys(*element_keys);
722 content = UnionOfKeys(content, element_keys);
Ben Murdochf87a2032010-10-22 12:50:53 +0100723 ASSERT(ContainsOnlyValidKeys(content));
Steve Blocka7e24c12009-10-30 11:49:00 +0000724
725 // Add the element keys from the interceptor.
726 if (current->HasIndexedInterceptor()) {
727 v8::Handle<v8::Array> result =
728 GetKeysForIndexedInterceptor(object, current);
729 if (!result.IsEmpty())
730 content = AddKeysFromJSArray(content, v8::Utils::OpenHandle(*result));
Ben Murdochf87a2032010-10-22 12:50:53 +0100731 ASSERT(ContainsOnlyValidKeys(content));
Steve Blocka7e24c12009-10-30 11:49:00 +0000732 }
733
Steve Blockd0582a62009-12-15 09:54:21 +0000734 // We can cache the computed property keys if access checks are
735 // not needed and no interceptors are involved.
736 //
737 // We do not use the cache if the object has elements and
738 // therefore it does not make sense to cache the property names
739 // for arguments objects. Arguments objects will always have
740 // elements.
Kristian Monsen50ef84f2010-07-29 15:18:00 +0100741 // Wrapped strings have elements, but don't have an elements
742 // array or dictionary. So the fast inline test for whether to
743 // use the cache says yes, so we should not create a cache.
Steve Blockd0582a62009-12-15 09:54:21 +0000744 bool cache_enum_keys =
745 ((current->map()->constructor() != *arguments_function) &&
Kristian Monsen50ef84f2010-07-29 15:18:00 +0100746 !current->IsJSValue() &&
Steve Blockd0582a62009-12-15 09:54:21 +0000747 !current->IsAccessCheckNeeded() &&
748 !current->HasNamedInterceptor() &&
749 !current->HasIndexedInterceptor());
750 // Compute the property keys and cache them if possible.
751 content =
752 UnionOfKeys(content, GetEnumPropertyKeys(current, cache_enum_keys));
Ben Murdochf87a2032010-10-22 12:50:53 +0100753 ASSERT(ContainsOnlyValidKeys(content));
Steve Blocka7e24c12009-10-30 11:49:00 +0000754
755 // Add the property keys from the interceptor.
756 if (current->HasNamedInterceptor()) {
757 v8::Handle<v8::Array> result =
758 GetKeysForNamedInterceptor(object, current);
759 if (!result.IsEmpty())
760 content = AddKeysFromJSArray(content, v8::Utils::OpenHandle(*result));
Ben Murdochf87a2032010-10-22 12:50:53 +0100761 ASSERT(ContainsOnlyValidKeys(content));
Steve Blocka7e24c12009-10-30 11:49:00 +0000762 }
763
764 // If we only want local properties we bail out after the first
765 // iteration.
766 if (type == LOCAL_ONLY)
767 break;
768 }
769 return content;
770}
771
772
773Handle<JSArray> GetKeysFor(Handle<JSObject> object) {
774 Counters::for_in.Increment();
775 Handle<FixedArray> elements = GetKeysInFixedArrayFor(object,
776 INCLUDE_PROTOS);
777 return Factory::NewJSArrayWithElements(elements);
778}
779
780
Steve Blockd0582a62009-12-15 09:54:21 +0000781Handle<FixedArray> GetEnumPropertyKeys(Handle<JSObject> object,
782 bool cache_result) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000783 int index = 0;
784 if (object->HasFastProperties()) {
785 if (object->map()->instance_descriptors()->HasEnumCache()) {
786 Counters::enum_cache_hits.Increment();
787 DescriptorArray* desc = object->map()->instance_descriptors();
788 return Handle<FixedArray>(FixedArray::cast(desc->GetEnumCache()));
789 }
790 Counters::enum_cache_misses.Increment();
791 int num_enum = object->NumberOfEnumProperties();
792 Handle<FixedArray> storage = Factory::NewFixedArray(num_enum);
793 Handle<FixedArray> sort_array = Factory::NewFixedArray(num_enum);
794 Handle<DescriptorArray> descs =
795 Handle<DescriptorArray>(object->map()->instance_descriptors());
796 for (int i = 0; i < descs->number_of_descriptors(); i++) {
797 if (descs->IsProperty(i) && !descs->IsDontEnum(i)) {
798 (*storage)->set(index, descs->GetKey(i));
799 PropertyDetails details(descs->GetDetails(i));
800 (*sort_array)->set(index, Smi::FromInt(details.index()));
801 index++;
802 }
803 }
804 (*storage)->SortPairs(*sort_array, sort_array->length());
Steve Blockd0582a62009-12-15 09:54:21 +0000805 if (cache_result) {
806 Handle<FixedArray> bridge_storage =
807 Factory::NewFixedArray(DescriptorArray::kEnumCacheBridgeLength);
808 DescriptorArray* desc = object->map()->instance_descriptors();
809 desc->SetEnumCache(*bridge_storage, *storage);
810 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000811 ASSERT(storage->length() == index);
812 return storage;
813 } else {
814 int num_enum = object->NumberOfEnumProperties();
815 Handle<FixedArray> storage = Factory::NewFixedArray(num_enum);
816 Handle<FixedArray> sort_array = Factory::NewFixedArray(num_enum);
817 object->property_dictionary()->CopyEnumKeysTo(*storage, *sort_array);
818 return storage;
819 }
820}
821
822
Leon Clarke4515c472010-02-03 11:58:03 +0000823bool EnsureCompiled(Handle<SharedFunctionInfo> shared,
824 ClearExceptionFlag flag) {
825 return shared->is_compiled() || CompileLazyShared(shared, flag);
826}
827
828
829static bool CompileLazyHelper(CompilationInfo* info,
830 ClearExceptionFlag flag) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000831 // Compile the source information to a code object.
Ben Murdochb0fe1622011-05-05 13:52:32 +0100832 ASSERT(info->IsOptimizing() || !info->shared_info()->is_compiled());
Steve Block1e0659c2011-05-24 12:43:12 +0100833 ASSERT(!Top::has_pending_exception());
Leon Clarke4515c472010-02-03 11:58:03 +0000834 bool result = Compiler::CompileLazy(info);
Steve Blocka7e24c12009-10-30 11:49:00 +0000835 ASSERT(result != Top::has_pending_exception());
836 if (!result && flag == CLEAR_EXCEPTION) Top::clear_pending_exception();
837 return result;
838}
839
840
Leon Clarke4515c472010-02-03 11:58:03 +0000841bool CompileLazyShared(Handle<SharedFunctionInfo> shared,
842 ClearExceptionFlag flag) {
Andrei Popescu31002712010-02-23 13:46:05 +0000843 CompilationInfo info(shared);
Leon Clarke4515c472010-02-03 11:58:03 +0000844 return CompileLazyHelper(&info, flag);
845}
846
847
Ben Murdoche0cee9b2011-05-25 10:26:03 +0100848static bool CompileLazyFunction(Handle<JSFunction> function,
849 ClearExceptionFlag flag,
850 InLoopFlag in_loop_flag) {
Ben Murdochb0fe1622011-05-05 13:52:32 +0100851 bool result = true;
Iain Merrick75681382010-08-19 15:07:18 +0100852 if (function->shared()->is_compiled()) {
Ben Murdochb0fe1622011-05-05 13:52:32 +0100853 function->ReplaceCode(function->shared()->code());
Iain Merrick75681382010-08-19 15:07:18 +0100854 function->shared()->set_code_age(0);
Iain Merrick75681382010-08-19 15:07:18 +0100855 } else {
Ben Murdochf87a2032010-10-22 12:50:53 +0100856 CompilationInfo info(function);
Ben Murdoche0cee9b2011-05-25 10:26:03 +0100857 if (in_loop_flag == IN_LOOP) info.MarkAsInLoop();
Ben Murdochb0fe1622011-05-05 13:52:32 +0100858 result = CompileLazyHelper(&info, flag);
Ben Murdochf87a2032010-10-22 12:50:53 +0100859 ASSERT(!result || function->is_compiled());
Iain Merrick75681382010-08-19 15:07:18 +0100860 }
Ben Murdochb0fe1622011-05-05 13:52:32 +0100861 return result;
Steve Blocka7e24c12009-10-30 11:49:00 +0000862}
863
864
Ben Murdoche0cee9b2011-05-25 10:26:03 +0100865bool CompileLazy(Handle<JSFunction> function,
866 ClearExceptionFlag flag) {
867 return CompileLazyFunction(function, flag, NOT_IN_LOOP);
868}
869
870
Leon Clarke4515c472010-02-03 11:58:03 +0000871bool CompileLazyInLoop(Handle<JSFunction> function,
Leon Clarke4515c472010-02-03 11:58:03 +0000872 ClearExceptionFlag flag) {
Ben Murdoche0cee9b2011-05-25 10:26:03 +0100873 return CompileLazyFunction(function, flag, IN_LOOP);
Ben Murdochb0fe1622011-05-05 13:52:32 +0100874}
875
876
Ben Murdoche0cee9b2011-05-25 10:26:03 +0100877bool CompileOptimized(Handle<JSFunction> function,
878 int osr_ast_id,
879 ClearExceptionFlag flag) {
Ben Murdochb0fe1622011-05-05 13:52:32 +0100880 CompilationInfo info(function);
881 info.SetOptimizing(osr_ast_id);
Ben Murdoche0cee9b2011-05-25 10:26:03 +0100882 return CompileLazyHelper(&info, flag);
Steve Blocka7e24c12009-10-30 11:49:00 +0000883}
884
Leon Clarke4515c472010-02-03 11:58:03 +0000885
Steve Blocka7e24c12009-10-30 11:49:00 +0000886OptimizedObjectForAddingMultipleProperties::
887OptimizedObjectForAddingMultipleProperties(Handle<JSObject> object,
888 int expected_additional_properties,
889 bool condition) {
890 object_ = object;
Steve Block1e0659c2011-05-24 12:43:12 +0100891 if (condition && object_->HasFastProperties() && !object->IsJSGlobalProxy()) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000892 // Normalize the properties of object to avoid n^2 behavior
893 // when extending the object multiple properties. Indicate the number of
894 // properties to be added.
895 unused_property_fields_ = object->map()->unused_property_fields();
896 NormalizeProperties(object_,
897 KEEP_INOBJECT_PROPERTIES,
898 expected_additional_properties);
899 has_been_transformed_ = true;
900
901 } else {
902 has_been_transformed_ = false;
903 }
904}
905
906
Steve Blocka7e24c12009-10-30 11:49:00 +0000907OptimizedObjectForAddingMultipleProperties::
908~OptimizedObjectForAddingMultipleProperties() {
909 // Reoptimize the object to allow fast property access.
910 if (has_been_transformed_) {
911 TransformToFastProperties(object_, unused_property_fields_);
912 }
913}
914
Steve Blocka7e24c12009-10-30 11:49:00 +0000915} } // namespace v8::internal