blob: d625d644c776e744251d69bfc7f582b77751c1b2 [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,
245 PropertyAttributes attributes) {
246 CALL_HEAP_FUNCTION(object->SetProperty(*key, *value, attributes), Object);
247}
248
249
250Handle<Object> SetProperty(Handle<Object> object,
251 Handle<Object> key,
252 Handle<Object> value,
253 PropertyAttributes attributes) {
254 CALL_HEAP_FUNCTION(
255 Runtime::SetObjectProperty(object, key, value, attributes), Object);
256}
257
258
259Handle<Object> ForceSetProperty(Handle<JSObject> object,
260 Handle<Object> key,
261 Handle<Object> value,
262 PropertyAttributes attributes) {
263 CALL_HEAP_FUNCTION(
264 Runtime::ForceSetObjectProperty(object, key, value, attributes), Object);
265}
266
267
Andrei Popescu31002712010-02-23 13:46:05 +0000268Handle<Object> SetNormalizedProperty(Handle<JSObject> object,
269 Handle<String> key,
270 Handle<Object> value,
271 PropertyDetails details) {
272 CALL_HEAP_FUNCTION(object->SetNormalizedProperty(*key, *value, details),
273 Object);
274}
275
276
Steve Blocka7e24c12009-10-30 11:49:00 +0000277Handle<Object> ForceDeleteProperty(Handle<JSObject> object,
278 Handle<Object> key) {
279 CALL_HEAP_FUNCTION(Runtime::ForceDeleteObjectProperty(object, key), Object);
280}
281
282
Ben Murdoch086aeea2011-05-13 15:57:08 +0100283Handle<Object> SetLocalPropertyIgnoreAttributes(
Steve Blocka7e24c12009-10-30 11:49:00 +0000284 Handle<JSObject> object,
285 Handle<String> key,
286 Handle<Object> value,
287 PropertyAttributes attributes) {
288 CALL_HEAP_FUNCTION(object->
Ben Murdoch086aeea2011-05-13 15:57:08 +0100289 SetLocalPropertyIgnoreAttributes(*key, *value, attributes), Object);
Steve Blocka7e24c12009-10-30 11:49:00 +0000290}
291
292
Steve Block1e0659c2011-05-24 12:43:12 +0100293void SetLocalPropertyNoThrow(Handle<JSObject> object,
294 Handle<String> key,
295 Handle<Object> value,
296 PropertyAttributes attributes) {
297 ASSERT(!Top::has_pending_exception());
298 CHECK(!SetLocalPropertyIgnoreAttributes(
299 object, key, value, attributes).is_null());
300 CHECK(!Top::has_pending_exception());
301}
302
303
Steve Blocka7e24c12009-10-30 11:49:00 +0000304Handle<Object> SetPropertyWithInterceptor(Handle<JSObject> object,
305 Handle<String> key,
306 Handle<Object> value,
307 PropertyAttributes attributes) {
308 CALL_HEAP_FUNCTION(object->SetPropertyWithInterceptor(*key,
309 *value,
310 attributes),
311 Object);
312}
313
314
315Handle<Object> GetProperty(Handle<JSObject> obj,
316 const char* name) {
317 Handle<String> str = Factory::LookupAsciiSymbol(name);
318 CALL_HEAP_FUNCTION(obj->GetProperty(*str), Object);
319}
320
321
322Handle<Object> GetProperty(Handle<Object> obj,
323 Handle<Object> key) {
324 CALL_HEAP_FUNCTION(Runtime::GetObjectProperty(obj, key), Object);
325}
326
327
Steve Block6ded16b2010-05-10 14:33:55 +0100328Handle<Object> GetElement(Handle<Object> obj,
329 uint32_t index) {
330 CALL_HEAP_FUNCTION(Runtime::GetElement(obj, index), Object);
331}
332
333
Steve Blocka7e24c12009-10-30 11:49:00 +0000334Handle<Object> GetPropertyWithInterceptor(Handle<JSObject> receiver,
335 Handle<JSObject> holder,
336 Handle<String> name,
337 PropertyAttributes* attributes) {
338 CALL_HEAP_FUNCTION(holder->GetPropertyWithInterceptor(*receiver,
339 *name,
340 attributes),
341 Object);
342}
343
344
345Handle<Object> GetPrototype(Handle<Object> obj) {
346 Handle<Object> result(obj->GetPrototype());
347 return result;
348}
349
350
Andrei Popescu402d9372010-02-26 13:31:12 +0000351Handle<Object> SetPrototype(Handle<JSObject> obj, Handle<Object> value) {
352 const bool skip_hidden_prototypes = false;
353 CALL_HEAP_FUNCTION(obj->SetPrototype(*value, skip_hidden_prototypes), Object);
354}
355
356
Steve Blocka7e24c12009-10-30 11:49:00 +0000357Handle<Object> GetHiddenProperties(Handle<JSObject> obj,
358 bool create_if_needed) {
Steve Blockd0582a62009-12-15 09:54:21 +0000359 Object* holder = obj->BypassGlobalProxy();
360 if (holder->IsUndefined()) return Factory::undefined_value();
361 obj = Handle<JSObject>(JSObject::cast(holder));
Steve Blocka7e24c12009-10-30 11:49:00 +0000362
363 if (obj->HasFastProperties()) {
364 // If the object has fast properties, check whether the first slot
365 // in the descriptor array matches the hidden symbol. Since the
366 // hidden symbols hash code is zero (and no other string has hash
367 // code zero) it will always occupy the first entry if present.
368 DescriptorArray* descriptors = obj->map()->instance_descriptors();
369 if ((descriptors->number_of_descriptors() > 0) &&
Steve Blockd0582a62009-12-15 09:54:21 +0000370 (descriptors->GetKey(0) == Heap::hidden_symbol()) &&
Steve Blocka7e24c12009-10-30 11:49:00 +0000371 descriptors->IsProperty(0)) {
372 ASSERT(descriptors->GetType(0) == FIELD);
373 return Handle<Object>(obj->FastPropertyAt(descriptors->GetFieldIndex(0)));
374 }
375 }
376
377 // Only attempt to find the hidden properties in the local object and not
378 // in the prototype chain. Note that HasLocalProperty() can cause a GC in
379 // the general case in the presence of interceptors.
Steve Blockd0582a62009-12-15 09:54:21 +0000380 if (!obj->HasHiddenPropertiesObject()) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000381 // Hidden properties object not found. Allocate a new hidden properties
382 // object if requested. Otherwise return the undefined value.
383 if (create_if_needed) {
384 Handle<Object> hidden_obj = Factory::NewJSObject(Top::object_function());
Steve Blockd0582a62009-12-15 09:54:21 +0000385 CALL_HEAP_FUNCTION(obj->SetHiddenPropertiesObject(*hidden_obj), Object);
Steve Blocka7e24c12009-10-30 11:49:00 +0000386 } else {
387 return Factory::undefined_value();
388 }
389 }
Steve Blockd0582a62009-12-15 09:54:21 +0000390 return Handle<Object>(obj->GetHiddenPropertiesObject());
Steve Blocka7e24c12009-10-30 11:49:00 +0000391}
392
393
394Handle<Object> DeleteElement(Handle<JSObject> obj,
395 uint32_t index) {
396 CALL_HEAP_FUNCTION(obj->DeleteElement(index, JSObject::NORMAL_DELETION),
397 Object);
398}
399
400
401Handle<Object> DeleteProperty(Handle<JSObject> obj,
402 Handle<String> prop) {
403 CALL_HEAP_FUNCTION(obj->DeleteProperty(*prop, JSObject::NORMAL_DELETION),
404 Object);
405}
406
407
408Handle<Object> LookupSingleCharacterStringFromCode(uint32_t index) {
409 CALL_HEAP_FUNCTION(Heap::LookupSingleCharacterStringFromCode(index), Object);
410}
411
412
Steve Block6ded16b2010-05-10 14:33:55 +0100413Handle<String> SubString(Handle<String> str,
414 int start,
415 int end,
416 PretenureFlag pretenure) {
417 CALL_HEAP_FUNCTION(str->SubString(start, end, pretenure), String);
Steve Blocka7e24c12009-10-30 11:49:00 +0000418}
419
420
421Handle<Object> SetElement(Handle<JSObject> object,
422 uint32_t index,
423 Handle<Object> value) {
Steve Block3ce2e202009-11-05 08:53:23 +0000424 if (object->HasPixelElements() || object->HasExternalArrayElements()) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000425 if (!value->IsSmi() && !value->IsHeapNumber() && !value->IsUndefined()) {
426 bool has_exception;
427 Handle<Object> number = Execution::ToNumber(value, &has_exception);
428 if (has_exception) return Handle<Object>();
429 value = number;
430 }
431 }
432 CALL_HEAP_FUNCTION(object->SetElement(index, *value), Object);
433}
434
435
Ben Murdoch086aeea2011-05-13 15:57:08 +0100436Handle<Object> SetOwnElement(Handle<JSObject> object,
437 uint32_t index,
438 Handle<Object> value) {
439 ASSERT(!object->HasPixelElements());
440 ASSERT(!object->HasExternalArrayElements());
441 CALL_HEAP_FUNCTION(object->SetElement(index, *value, false), Object);
442}
443
444
Steve Blocka7e24c12009-10-30 11:49:00 +0000445Handle<JSObject> Copy(Handle<JSObject> obj) {
446 CALL_HEAP_FUNCTION(Heap::CopyJSObject(*obj), JSObject);
447}
448
449
Leon Clarkef7060e22010-06-03 12:02:55 +0100450Handle<Object> SetAccessor(Handle<JSObject> obj, Handle<AccessorInfo> info) {
451 CALL_HEAP_FUNCTION(obj->DefineAccessor(*info), Object);
452}
453
454
Steve Blocka7e24c12009-10-30 11:49:00 +0000455// Wrappers for scripts are kept alive and cached in weak global
456// handles referred from proxy objects held by the scripts as long as
457// they are used. When they are not used anymore, the garbage
458// collector will call the weak callback on the global handle
459// associated with the wrapper and get rid of both the wrapper and the
460// handle.
461static void ClearWrapperCache(Persistent<v8::Value> handle, void*) {
462#ifdef ENABLE_HEAP_PROTECTION
463 // Weak reference callbacks are called as if from outside V8. We
464 // need to reeenter to unprotect the heap.
465 VMState state(OTHER);
466#endif
467 Handle<Object> cache = Utils::OpenHandle(*handle);
468 JSValue* wrapper = JSValue::cast(*cache);
469 Proxy* proxy = Script::cast(wrapper->value())->wrapper();
470 ASSERT(proxy->proxy() == reinterpret_cast<Address>(cache.location()));
471 proxy->set_proxy(0);
472 GlobalHandles::Destroy(cache.location());
473 Counters::script_wrappers.Decrement();
474}
475
476
477Handle<JSValue> GetScriptWrapper(Handle<Script> script) {
478 if (script->wrapper()->proxy() != NULL) {
479 // Return the script wrapper directly from the cache.
480 return Handle<JSValue>(
481 reinterpret_cast<JSValue**>(script->wrapper()->proxy()));
482 }
483
484 // Construct a new script wrapper.
485 Counters::script_wrappers.Increment();
486 Handle<JSFunction> constructor = Top::script_function();
487 Handle<JSValue> result =
488 Handle<JSValue>::cast(Factory::NewJSObject(constructor));
489 result->set_value(*script);
490
491 // Create a new weak global handle and use it to cache the wrapper
492 // for future use. The cache will automatically be cleared by the
493 // garbage collector when it is not used anymore.
494 Handle<Object> handle = GlobalHandles::Create(*result);
495 GlobalHandles::MakeWeak(handle.location(), NULL, &ClearWrapperCache);
496 script->wrapper()->set_proxy(reinterpret_cast<Address>(handle.location()));
497 return result;
498}
499
500
501// Init line_ends array with code positions of line ends inside script
502// source.
503void InitScriptLineEnds(Handle<Script> script) {
504 if (!script->line_ends()->IsUndefined()) return;
505
506 if (!script->source()->IsString()) {
507 ASSERT(script->source()->IsUndefined());
Kristian Monsen0d5e1162010-09-30 15:31:59 +0100508 Handle<FixedArray> empty = Factory::NewFixedArray(0);
509 script->set_line_ends(*empty);
Steve Blockd0582a62009-12-15 09:54:21 +0000510 ASSERT(script->line_ends()->IsFixedArray());
Steve Blocka7e24c12009-10-30 11:49:00 +0000511 return;
512 }
513
514 Handle<String> src(String::cast(script->source()));
Steve Block6ded16b2010-05-10 14:33:55 +0100515
516 Handle<FixedArray> array = CalculateLineEnds(src, true);
517
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -0800518 if (*array != Heap::empty_fixed_array()) {
519 array->set_map(Heap::fixed_cow_array_map());
520 }
521
Steve Block6ded16b2010-05-10 14:33:55 +0100522 script->set_line_ends(*array);
523 ASSERT(script->line_ends()->IsFixedArray());
524}
525
526
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -0800527template <typename SourceChar>
528static void CalculateLineEnds(List<int>* line_ends,
529 Vector<const SourceChar> src,
530 bool with_last_line) {
531 const int src_len = src.length();
532 StringSearch<char, SourceChar> search(CStrVector("\n"));
Steve Blocka7e24c12009-10-30 11:49:00 +0000533
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -0800534 // Find and record line ends.
Steve Blocka7e24c12009-10-30 11:49:00 +0000535 int position = 0;
536 while (position != -1 && position < src_len) {
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -0800537 position = search.Search(src, position);
Steve Blocka7e24c12009-10-30 11:49:00 +0000538 if (position != -1) {
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -0800539 line_ends->Add(position);
Steve Blocka7e24c12009-10-30 11:49:00 +0000540 position++;
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -0800541 } else if (with_last_line) {
Steve Block6ded16b2010-05-10 14:33:55 +0100542 // Even if the last line misses a line end, it is counted.
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -0800543 line_ends->Add(src_len);
544 return;
Steve Block6ded16b2010-05-10 14:33:55 +0100545 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000546 }
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -0800547}
Steve Blocka7e24c12009-10-30 11:49:00 +0000548
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -0800549
550Handle<FixedArray> CalculateLineEnds(Handle<String> src,
551 bool with_last_line) {
552 src = FlattenGetString(src);
553 // Rough estimate of line count based on a roughly estimated average
554 // length of (unpacked) code.
555 int line_count_estimate = src->length() >> 4;
556 List<int> line_ends(line_count_estimate);
557 {
558 AssertNoAllocation no_heap_allocation; // ensure vectors stay valid.
559 // Dispatch on type of strings.
560 if (src->IsAsciiRepresentation()) {
561 CalculateLineEnds(&line_ends, src->ToAsciiVector(), with_last_line);
562 } else {
563 CalculateLineEnds(&line_ends, src->ToUC16Vector(), with_last_line);
564 }
565 }
566 int line_count = line_ends.length();
Steve Blocka7e24c12009-10-30 11:49:00 +0000567 Handle<FixedArray> array = Factory::NewFixedArray(line_count);
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -0800568 for (int i = 0; i < line_count; i++) {
569 array->set(i, Smi::FromInt(line_ends[i]));
Steve Blocka7e24c12009-10-30 11:49:00 +0000570 }
Steve Block6ded16b2010-05-10 14:33:55 +0100571 return array;
Steve Blocka7e24c12009-10-30 11:49:00 +0000572}
573
574
575// Convert code position into line number.
576int GetScriptLineNumber(Handle<Script> script, int code_pos) {
577 InitScriptLineEnds(script);
578 AssertNoAllocation no_allocation;
Andrei Popescu402d9372010-02-26 13:31:12 +0000579 FixedArray* line_ends_array = FixedArray::cast(script->line_ends());
Steve Blockd0582a62009-12-15 09:54:21 +0000580 const int line_ends_len = line_ends_array->length();
Steve Blocka7e24c12009-10-30 11:49:00 +0000581
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -0800582 if (!line_ends_len) return -1;
Andrei Popescu402d9372010-02-26 13:31:12 +0000583
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -0800584 if ((Smi::cast(line_ends_array->get(0)))->value() >= code_pos) {
Andrei Popescu402d9372010-02-26 13:31:12 +0000585 return script->line_offset()->value();
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -0800586 }
Andrei Popescu402d9372010-02-26 13:31:12 +0000587
588 int left = 0;
589 int right = line_ends_len;
590 while (int half = (right - left) / 2) {
591 if ((Smi::cast(line_ends_array->get(left + half)))->value() > code_pos) {
592 right -= half;
593 } else {
594 left += half;
Steve Blocka7e24c12009-10-30 11:49:00 +0000595 }
596 }
Andrei Popescu402d9372010-02-26 13:31:12 +0000597 return right + script->line_offset()->value();
Steve Blocka7e24c12009-10-30 11:49:00 +0000598}
599
600
Steve Block6ded16b2010-05-10 14:33:55 +0100601int GetScriptLineNumberSafe(Handle<Script> script, int code_pos) {
602 AssertNoAllocation no_allocation;
603 if (!script->line_ends()->IsUndefined()) {
604 return GetScriptLineNumber(script, code_pos);
605 }
606 // Slow mode: we do not have line_ends. We have to iterate through source.
607 if (!script->source()->IsString()) {
608 return -1;
609 }
610 String* source = String::cast(script->source());
611 int line = 0;
612 int len = source->length();
613 for (int pos = 0; pos < len; pos++) {
614 if (pos == code_pos) {
615 break;
616 }
617 if (source->Get(pos) == '\n') {
618 line++;
619 }
620 }
621 return line;
622}
623
624
Steve Blocka7e24c12009-10-30 11:49:00 +0000625void CustomArguments::IterateInstance(ObjectVisitor* v) {
Steve Block6ded16b2010-05-10 14:33:55 +0100626 v->VisitPointers(values_, values_ + ARRAY_SIZE(values_));
Steve Blocka7e24c12009-10-30 11:49:00 +0000627}
628
629
630// Compute the property keys from the interceptor.
631v8::Handle<v8::Array> GetKeysForNamedInterceptor(Handle<JSObject> receiver,
632 Handle<JSObject> object) {
633 Handle<InterceptorInfo> interceptor(object->GetNamedInterceptor());
634 CustomArguments args(interceptor->data(), *receiver, *object);
635 v8::AccessorInfo info(args.end());
636 v8::Handle<v8::Array> result;
637 if (!interceptor->enumerator()->IsUndefined()) {
638 v8::NamedPropertyEnumerator enum_fun =
639 v8::ToCData<v8::NamedPropertyEnumerator>(interceptor->enumerator());
640 LOG(ApiObjectAccess("interceptor-named-enum", *object));
641 {
642 // Leaving JavaScript.
643 VMState state(EXTERNAL);
644 result = enum_fun(info);
645 }
646 }
647 return result;
648}
649
650
651// Compute the element keys from the interceptor.
652v8::Handle<v8::Array> GetKeysForIndexedInterceptor(Handle<JSObject> receiver,
653 Handle<JSObject> object) {
654 Handle<InterceptorInfo> interceptor(object->GetIndexedInterceptor());
655 CustomArguments args(interceptor->data(), *receiver, *object);
656 v8::AccessorInfo info(args.end());
657 v8::Handle<v8::Array> result;
658 if (!interceptor->enumerator()->IsUndefined()) {
659 v8::IndexedPropertyEnumerator enum_fun =
660 v8::ToCData<v8::IndexedPropertyEnumerator>(interceptor->enumerator());
661 LOG(ApiObjectAccess("interceptor-indexed-enum", *object));
662 {
663 // Leaving JavaScript.
664 VMState state(EXTERNAL);
665 result = enum_fun(info);
666 }
667 }
668 return result;
669}
670
671
Ben Murdochf87a2032010-10-22 12:50:53 +0100672static bool ContainsOnlyValidKeys(Handle<FixedArray> array) {
673 int len = array->length();
674 for (int i = 0; i < len; i++) {
675 Object* e = array->get(i);
676 if (!(e->IsString() || e->IsNumber())) return false;
677 }
678 return true;
679}
680
681
Steve Blocka7e24c12009-10-30 11:49:00 +0000682Handle<FixedArray> GetKeysInFixedArrayFor(Handle<JSObject> object,
683 KeyCollectionType type) {
Ben Murdochf87a2032010-10-22 12:50:53 +0100684 USE(ContainsOnlyValidKeys);
Steve Blocka7e24c12009-10-30 11:49:00 +0000685 Handle<FixedArray> content = Factory::empty_fixed_array();
Steve Blockd0582a62009-12-15 09:54:21 +0000686 Handle<JSObject> arguments_boilerplate =
687 Handle<JSObject>(
688 Top::context()->global_context()->arguments_boilerplate());
689 Handle<JSFunction> arguments_function =
690 Handle<JSFunction>(
691 JSFunction::cast(arguments_boilerplate->map()->constructor()));
Steve Blocka7e24c12009-10-30 11:49:00 +0000692
693 // Only collect keys if access is permitted.
694 for (Handle<Object> p = object;
695 *p != Heap::null_value();
696 p = Handle<Object>(p->GetPrototype())) {
697 Handle<JSObject> current(JSObject::cast(*p));
698
699 // Check access rights if required.
700 if (current->IsAccessCheckNeeded() &&
Iain Merrick75681382010-08-19 15:07:18 +0100701 !Top::MayNamedAccess(*current, Heap::undefined_value(),
702 v8::ACCESS_KEYS)) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000703 Top::ReportFailedAccessCheck(*current, v8::ACCESS_KEYS);
704 break;
705 }
706
707 // Compute the element keys.
708 Handle<FixedArray> element_keys =
709 Factory::NewFixedArray(current->NumberOfEnumElements());
710 current->GetEnumElementKeys(*element_keys);
711 content = UnionOfKeys(content, element_keys);
Ben Murdochf87a2032010-10-22 12:50:53 +0100712 ASSERT(ContainsOnlyValidKeys(content));
Steve Blocka7e24c12009-10-30 11:49:00 +0000713
714 // Add the element keys from the interceptor.
715 if (current->HasIndexedInterceptor()) {
716 v8::Handle<v8::Array> result =
717 GetKeysForIndexedInterceptor(object, current);
718 if (!result.IsEmpty())
719 content = AddKeysFromJSArray(content, v8::Utils::OpenHandle(*result));
Ben Murdochf87a2032010-10-22 12:50:53 +0100720 ASSERT(ContainsOnlyValidKeys(content));
Steve Blocka7e24c12009-10-30 11:49:00 +0000721 }
722
Steve Blockd0582a62009-12-15 09:54:21 +0000723 // We can cache the computed property keys if access checks are
724 // not needed and no interceptors are involved.
725 //
726 // We do not use the cache if the object has elements and
727 // therefore it does not make sense to cache the property names
728 // for arguments objects. Arguments objects will always have
729 // elements.
Kristian Monsen50ef84f2010-07-29 15:18:00 +0100730 // Wrapped strings have elements, but don't have an elements
731 // array or dictionary. So the fast inline test for whether to
732 // use the cache says yes, so we should not create a cache.
Steve Blockd0582a62009-12-15 09:54:21 +0000733 bool cache_enum_keys =
734 ((current->map()->constructor() != *arguments_function) &&
Kristian Monsen50ef84f2010-07-29 15:18:00 +0100735 !current->IsJSValue() &&
Steve Blockd0582a62009-12-15 09:54:21 +0000736 !current->IsAccessCheckNeeded() &&
737 !current->HasNamedInterceptor() &&
738 !current->HasIndexedInterceptor());
739 // Compute the property keys and cache them if possible.
740 content =
741 UnionOfKeys(content, GetEnumPropertyKeys(current, cache_enum_keys));
Ben Murdochf87a2032010-10-22 12:50:53 +0100742 ASSERT(ContainsOnlyValidKeys(content));
Steve Blocka7e24c12009-10-30 11:49:00 +0000743
744 // Add the property keys from the interceptor.
745 if (current->HasNamedInterceptor()) {
746 v8::Handle<v8::Array> result =
747 GetKeysForNamedInterceptor(object, current);
748 if (!result.IsEmpty())
749 content = AddKeysFromJSArray(content, v8::Utils::OpenHandle(*result));
Ben Murdochf87a2032010-10-22 12:50:53 +0100750 ASSERT(ContainsOnlyValidKeys(content));
Steve Blocka7e24c12009-10-30 11:49:00 +0000751 }
752
753 // If we only want local properties we bail out after the first
754 // iteration.
755 if (type == LOCAL_ONLY)
756 break;
757 }
758 return content;
759}
760
761
762Handle<JSArray> GetKeysFor(Handle<JSObject> object) {
763 Counters::for_in.Increment();
764 Handle<FixedArray> elements = GetKeysInFixedArrayFor(object,
765 INCLUDE_PROTOS);
766 return Factory::NewJSArrayWithElements(elements);
767}
768
769
Steve Blockd0582a62009-12-15 09:54:21 +0000770Handle<FixedArray> GetEnumPropertyKeys(Handle<JSObject> object,
771 bool cache_result) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000772 int index = 0;
773 if (object->HasFastProperties()) {
774 if (object->map()->instance_descriptors()->HasEnumCache()) {
775 Counters::enum_cache_hits.Increment();
776 DescriptorArray* desc = object->map()->instance_descriptors();
777 return Handle<FixedArray>(FixedArray::cast(desc->GetEnumCache()));
778 }
779 Counters::enum_cache_misses.Increment();
780 int num_enum = object->NumberOfEnumProperties();
781 Handle<FixedArray> storage = Factory::NewFixedArray(num_enum);
782 Handle<FixedArray> sort_array = Factory::NewFixedArray(num_enum);
783 Handle<DescriptorArray> descs =
784 Handle<DescriptorArray>(object->map()->instance_descriptors());
785 for (int i = 0; i < descs->number_of_descriptors(); i++) {
786 if (descs->IsProperty(i) && !descs->IsDontEnum(i)) {
787 (*storage)->set(index, descs->GetKey(i));
788 PropertyDetails details(descs->GetDetails(i));
789 (*sort_array)->set(index, Smi::FromInt(details.index()));
790 index++;
791 }
792 }
793 (*storage)->SortPairs(*sort_array, sort_array->length());
Steve Blockd0582a62009-12-15 09:54:21 +0000794 if (cache_result) {
795 Handle<FixedArray> bridge_storage =
796 Factory::NewFixedArray(DescriptorArray::kEnumCacheBridgeLength);
797 DescriptorArray* desc = object->map()->instance_descriptors();
798 desc->SetEnumCache(*bridge_storage, *storage);
799 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000800 ASSERT(storage->length() == index);
801 return storage;
802 } else {
803 int num_enum = object->NumberOfEnumProperties();
804 Handle<FixedArray> storage = Factory::NewFixedArray(num_enum);
805 Handle<FixedArray> sort_array = Factory::NewFixedArray(num_enum);
806 object->property_dictionary()->CopyEnumKeysTo(*storage, *sort_array);
807 return storage;
808 }
809}
810
811
Leon Clarke4515c472010-02-03 11:58:03 +0000812bool EnsureCompiled(Handle<SharedFunctionInfo> shared,
813 ClearExceptionFlag flag) {
814 return shared->is_compiled() || CompileLazyShared(shared, flag);
815}
816
817
818static bool CompileLazyHelper(CompilationInfo* info,
819 ClearExceptionFlag flag) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000820 // Compile the source information to a code object.
Ben Murdochb0fe1622011-05-05 13:52:32 +0100821 ASSERT(info->IsOptimizing() || !info->shared_info()->is_compiled());
Steve Block1e0659c2011-05-24 12:43:12 +0100822 ASSERT(!Top::has_pending_exception());
Leon Clarke4515c472010-02-03 11:58:03 +0000823 bool result = Compiler::CompileLazy(info);
Steve Blocka7e24c12009-10-30 11:49:00 +0000824 ASSERT(result != Top::has_pending_exception());
825 if (!result && flag == CLEAR_EXCEPTION) Top::clear_pending_exception();
826 return result;
827}
828
829
Leon Clarke4515c472010-02-03 11:58:03 +0000830bool CompileLazyShared(Handle<SharedFunctionInfo> shared,
831 ClearExceptionFlag flag) {
Andrei Popescu31002712010-02-23 13:46:05 +0000832 CompilationInfo info(shared);
Leon Clarke4515c472010-02-03 11:58:03 +0000833 return CompileLazyHelper(&info, flag);
834}
835
836
837bool CompileLazy(Handle<JSFunction> function,
Leon Clarke4515c472010-02-03 11:58:03 +0000838 ClearExceptionFlag flag) {
Ben Murdochb0fe1622011-05-05 13:52:32 +0100839 bool result = true;
Iain Merrick75681382010-08-19 15:07:18 +0100840 if (function->shared()->is_compiled()) {
Ben Murdochb0fe1622011-05-05 13:52:32 +0100841 function->ReplaceCode(function->shared()->code());
Iain Merrick75681382010-08-19 15:07:18 +0100842 function->shared()->set_code_age(0);
Iain Merrick75681382010-08-19 15:07:18 +0100843 } else {
Ben Murdochf87a2032010-10-22 12:50:53 +0100844 CompilationInfo info(function);
Ben Murdochb0fe1622011-05-05 13:52:32 +0100845 result = CompileLazyHelper(&info, flag);
Ben Murdochf87a2032010-10-22 12:50:53 +0100846 ASSERT(!result || function->is_compiled());
Iain Merrick75681382010-08-19 15:07:18 +0100847 }
Ben Murdochb0fe1622011-05-05 13:52:32 +0100848 if (result && function->is_compiled()) {
849 PROFILE(FunctionCreateEvent(*function));
850 }
851 return result;
Steve Blocka7e24c12009-10-30 11:49:00 +0000852}
853
854
Leon Clarke4515c472010-02-03 11:58:03 +0000855bool CompileLazyInLoop(Handle<JSFunction> function,
Leon Clarke4515c472010-02-03 11:58:03 +0000856 ClearExceptionFlag flag) {
Ben Murdochb0fe1622011-05-05 13:52:32 +0100857 bool result = true;
Iain Merrick75681382010-08-19 15:07:18 +0100858 if (function->shared()->is_compiled()) {
Ben Murdochb0fe1622011-05-05 13:52:32 +0100859 function->ReplaceCode(function->shared()->code());
Iain Merrick75681382010-08-19 15:07:18 +0100860 function->shared()->set_code_age(0);
Iain Merrick75681382010-08-19 15:07:18 +0100861 } else {
Ben Murdochf87a2032010-10-22 12:50:53 +0100862 CompilationInfo info(function);
863 info.MarkAsInLoop();
Ben Murdochb0fe1622011-05-05 13:52:32 +0100864 result = CompileLazyHelper(&info, flag);
Ben Murdochf87a2032010-10-22 12:50:53 +0100865 ASSERT(!result || function->is_compiled());
Iain Merrick75681382010-08-19 15:07:18 +0100866 }
Ben Murdochb0fe1622011-05-05 13:52:32 +0100867 if (result && function->is_compiled()) {
868 PROFILE(FunctionCreateEvent(*function));
869 }
870 return result;
871}
872
873
874bool CompileOptimized(Handle<JSFunction> function, int osr_ast_id) {
875 CompilationInfo info(function);
876 info.SetOptimizing(osr_ast_id);
877 bool result = CompileLazyHelper(&info, KEEP_EXCEPTION);
878 if (result) PROFILE(FunctionCreateEvent(*function));
879 return result;
Steve Blocka7e24c12009-10-30 11:49:00 +0000880}
881
Leon Clarke4515c472010-02-03 11:58:03 +0000882
Steve Blocka7e24c12009-10-30 11:49:00 +0000883OptimizedObjectForAddingMultipleProperties::
884OptimizedObjectForAddingMultipleProperties(Handle<JSObject> object,
885 int expected_additional_properties,
886 bool condition) {
887 object_ = object;
Steve Block1e0659c2011-05-24 12:43:12 +0100888 if (condition && object_->HasFastProperties() && !object->IsJSGlobalProxy()) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000889 // Normalize the properties of object to avoid n^2 behavior
890 // when extending the object multiple properties. Indicate the number of
891 // properties to be added.
892 unused_property_fields_ = object->map()->unused_property_fields();
893 NormalizeProperties(object_,
894 KEEP_INOBJECT_PROPERTIES,
895 expected_additional_properties);
896 has_been_transformed_ = true;
897
898 } else {
899 has_been_transformed_ = false;
900 }
901}
902
903
Steve Blocka7e24c12009-10-30 11:49:00 +0000904OptimizedObjectForAddingMultipleProperties::
905~OptimizedObjectForAddingMultipleProperties() {
906 // Reoptimize the object to allow fast property access.
907 if (has_been_transformed_) {
908 TransformToFastProperties(object_, unused_property_fields_);
909 }
910}
911
Steve Blocka7e24c12009-10-30 11:49:00 +0000912} } // namespace v8::internal