blob: 461c3f5fab9b1280bfad66ceb52c831d8d2ad469 [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
293Handle<Object> SetPropertyWithInterceptor(Handle<JSObject> object,
294 Handle<String> key,
295 Handle<Object> value,
296 PropertyAttributes attributes) {
297 CALL_HEAP_FUNCTION(object->SetPropertyWithInterceptor(*key,
298 *value,
299 attributes),
300 Object);
301}
302
303
304Handle<Object> GetProperty(Handle<JSObject> obj,
305 const char* name) {
306 Handle<String> str = Factory::LookupAsciiSymbol(name);
307 CALL_HEAP_FUNCTION(obj->GetProperty(*str), Object);
308}
309
310
311Handle<Object> GetProperty(Handle<Object> obj,
312 Handle<Object> key) {
313 CALL_HEAP_FUNCTION(Runtime::GetObjectProperty(obj, key), Object);
314}
315
316
Steve Block6ded16b2010-05-10 14:33:55 +0100317Handle<Object> GetElement(Handle<Object> obj,
318 uint32_t index) {
319 CALL_HEAP_FUNCTION(Runtime::GetElement(obj, index), Object);
320}
321
322
Steve Blocka7e24c12009-10-30 11:49:00 +0000323Handle<Object> GetPropertyWithInterceptor(Handle<JSObject> receiver,
324 Handle<JSObject> holder,
325 Handle<String> name,
326 PropertyAttributes* attributes) {
327 CALL_HEAP_FUNCTION(holder->GetPropertyWithInterceptor(*receiver,
328 *name,
329 attributes),
330 Object);
331}
332
333
334Handle<Object> GetPrototype(Handle<Object> obj) {
335 Handle<Object> result(obj->GetPrototype());
336 return result;
337}
338
339
Andrei Popescu402d9372010-02-26 13:31:12 +0000340Handle<Object> SetPrototype(Handle<JSObject> obj, Handle<Object> value) {
341 const bool skip_hidden_prototypes = false;
342 CALL_HEAP_FUNCTION(obj->SetPrototype(*value, skip_hidden_prototypes), Object);
343}
344
345
Steve Blocka7e24c12009-10-30 11:49:00 +0000346Handle<Object> GetHiddenProperties(Handle<JSObject> obj,
347 bool create_if_needed) {
Steve Blockd0582a62009-12-15 09:54:21 +0000348 Object* holder = obj->BypassGlobalProxy();
349 if (holder->IsUndefined()) return Factory::undefined_value();
350 obj = Handle<JSObject>(JSObject::cast(holder));
Steve Blocka7e24c12009-10-30 11:49:00 +0000351
352 if (obj->HasFastProperties()) {
353 // If the object has fast properties, check whether the first slot
354 // in the descriptor array matches the hidden symbol. Since the
355 // hidden symbols hash code is zero (and no other string has hash
356 // code zero) it will always occupy the first entry if present.
357 DescriptorArray* descriptors = obj->map()->instance_descriptors();
358 if ((descriptors->number_of_descriptors() > 0) &&
Steve Blockd0582a62009-12-15 09:54:21 +0000359 (descriptors->GetKey(0) == Heap::hidden_symbol()) &&
Steve Blocka7e24c12009-10-30 11:49:00 +0000360 descriptors->IsProperty(0)) {
361 ASSERT(descriptors->GetType(0) == FIELD);
362 return Handle<Object>(obj->FastPropertyAt(descriptors->GetFieldIndex(0)));
363 }
364 }
365
366 // Only attempt to find the hidden properties in the local object and not
367 // in the prototype chain. Note that HasLocalProperty() can cause a GC in
368 // the general case in the presence of interceptors.
Steve Blockd0582a62009-12-15 09:54:21 +0000369 if (!obj->HasHiddenPropertiesObject()) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000370 // Hidden properties object not found. Allocate a new hidden properties
371 // object if requested. Otherwise return the undefined value.
372 if (create_if_needed) {
373 Handle<Object> hidden_obj = Factory::NewJSObject(Top::object_function());
Steve Blockd0582a62009-12-15 09:54:21 +0000374 CALL_HEAP_FUNCTION(obj->SetHiddenPropertiesObject(*hidden_obj), Object);
Steve Blocka7e24c12009-10-30 11:49:00 +0000375 } else {
376 return Factory::undefined_value();
377 }
378 }
Steve Blockd0582a62009-12-15 09:54:21 +0000379 return Handle<Object>(obj->GetHiddenPropertiesObject());
Steve Blocka7e24c12009-10-30 11:49:00 +0000380}
381
382
383Handle<Object> DeleteElement(Handle<JSObject> obj,
384 uint32_t index) {
385 CALL_HEAP_FUNCTION(obj->DeleteElement(index, JSObject::NORMAL_DELETION),
386 Object);
387}
388
389
390Handle<Object> DeleteProperty(Handle<JSObject> obj,
391 Handle<String> prop) {
392 CALL_HEAP_FUNCTION(obj->DeleteProperty(*prop, JSObject::NORMAL_DELETION),
393 Object);
394}
395
396
397Handle<Object> LookupSingleCharacterStringFromCode(uint32_t index) {
398 CALL_HEAP_FUNCTION(Heap::LookupSingleCharacterStringFromCode(index), Object);
399}
400
401
Steve Block6ded16b2010-05-10 14:33:55 +0100402Handle<String> SubString(Handle<String> str,
403 int start,
404 int end,
405 PretenureFlag pretenure) {
406 CALL_HEAP_FUNCTION(str->SubString(start, end, pretenure), String);
Steve Blocka7e24c12009-10-30 11:49:00 +0000407}
408
409
410Handle<Object> SetElement(Handle<JSObject> object,
411 uint32_t index,
412 Handle<Object> value) {
Steve Block3ce2e202009-11-05 08:53:23 +0000413 if (object->HasPixelElements() || object->HasExternalArrayElements()) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000414 if (!value->IsSmi() && !value->IsHeapNumber() && !value->IsUndefined()) {
415 bool has_exception;
416 Handle<Object> number = Execution::ToNumber(value, &has_exception);
417 if (has_exception) return Handle<Object>();
418 value = number;
419 }
420 }
421 CALL_HEAP_FUNCTION(object->SetElement(index, *value), Object);
422}
423
424
Ben Murdoch086aeea2011-05-13 15:57:08 +0100425Handle<Object> SetOwnElement(Handle<JSObject> object,
426 uint32_t index,
427 Handle<Object> value) {
428 ASSERT(!object->HasPixelElements());
429 ASSERT(!object->HasExternalArrayElements());
430 CALL_HEAP_FUNCTION(object->SetElement(index, *value, false), Object);
431}
432
433
Steve Blocka7e24c12009-10-30 11:49:00 +0000434Handle<JSObject> Copy(Handle<JSObject> obj) {
435 CALL_HEAP_FUNCTION(Heap::CopyJSObject(*obj), JSObject);
436}
437
438
Leon Clarkef7060e22010-06-03 12:02:55 +0100439Handle<Object> SetAccessor(Handle<JSObject> obj, Handle<AccessorInfo> info) {
440 CALL_HEAP_FUNCTION(obj->DefineAccessor(*info), Object);
441}
442
443
Steve Blocka7e24c12009-10-30 11:49:00 +0000444// Wrappers for scripts are kept alive and cached in weak global
445// handles referred from proxy objects held by the scripts as long as
446// they are used. When they are not used anymore, the garbage
447// collector will call the weak callback on the global handle
448// associated with the wrapper and get rid of both the wrapper and the
449// handle.
450static void ClearWrapperCache(Persistent<v8::Value> handle, void*) {
451#ifdef ENABLE_HEAP_PROTECTION
452 // Weak reference callbacks are called as if from outside V8. We
453 // need to reeenter to unprotect the heap.
454 VMState state(OTHER);
455#endif
456 Handle<Object> cache = Utils::OpenHandle(*handle);
457 JSValue* wrapper = JSValue::cast(*cache);
458 Proxy* proxy = Script::cast(wrapper->value())->wrapper();
459 ASSERT(proxy->proxy() == reinterpret_cast<Address>(cache.location()));
460 proxy->set_proxy(0);
461 GlobalHandles::Destroy(cache.location());
462 Counters::script_wrappers.Decrement();
463}
464
465
466Handle<JSValue> GetScriptWrapper(Handle<Script> script) {
467 if (script->wrapper()->proxy() != NULL) {
468 // Return the script wrapper directly from the cache.
469 return Handle<JSValue>(
470 reinterpret_cast<JSValue**>(script->wrapper()->proxy()));
471 }
472
473 // Construct a new script wrapper.
474 Counters::script_wrappers.Increment();
475 Handle<JSFunction> constructor = Top::script_function();
476 Handle<JSValue> result =
477 Handle<JSValue>::cast(Factory::NewJSObject(constructor));
478 result->set_value(*script);
479
480 // Create a new weak global handle and use it to cache the wrapper
481 // for future use. The cache will automatically be cleared by the
482 // garbage collector when it is not used anymore.
483 Handle<Object> handle = GlobalHandles::Create(*result);
484 GlobalHandles::MakeWeak(handle.location(), NULL, &ClearWrapperCache);
485 script->wrapper()->set_proxy(reinterpret_cast<Address>(handle.location()));
486 return result;
487}
488
489
490// Init line_ends array with code positions of line ends inside script
491// source.
492void InitScriptLineEnds(Handle<Script> script) {
493 if (!script->line_ends()->IsUndefined()) return;
494
495 if (!script->source()->IsString()) {
496 ASSERT(script->source()->IsUndefined());
Kristian Monsen0d5e1162010-09-30 15:31:59 +0100497 Handle<FixedArray> empty = Factory::NewFixedArray(0);
498 script->set_line_ends(*empty);
Steve Blockd0582a62009-12-15 09:54:21 +0000499 ASSERT(script->line_ends()->IsFixedArray());
Steve Blocka7e24c12009-10-30 11:49:00 +0000500 return;
501 }
502
503 Handle<String> src(String::cast(script->source()));
Steve Block6ded16b2010-05-10 14:33:55 +0100504
505 Handle<FixedArray> array = CalculateLineEnds(src, true);
506
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -0800507 if (*array != Heap::empty_fixed_array()) {
508 array->set_map(Heap::fixed_cow_array_map());
509 }
510
Steve Block6ded16b2010-05-10 14:33:55 +0100511 script->set_line_ends(*array);
512 ASSERT(script->line_ends()->IsFixedArray());
513}
514
515
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -0800516template <typename SourceChar>
517static void CalculateLineEnds(List<int>* line_ends,
518 Vector<const SourceChar> src,
519 bool with_last_line) {
520 const int src_len = src.length();
521 StringSearch<char, SourceChar> search(CStrVector("\n"));
Steve Blocka7e24c12009-10-30 11:49:00 +0000522
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -0800523 // Find and record line ends.
Steve Blocka7e24c12009-10-30 11:49:00 +0000524 int position = 0;
525 while (position != -1 && position < src_len) {
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -0800526 position = search.Search(src, position);
Steve Blocka7e24c12009-10-30 11:49:00 +0000527 if (position != -1) {
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -0800528 line_ends->Add(position);
Steve Blocka7e24c12009-10-30 11:49:00 +0000529 position++;
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -0800530 } else if (with_last_line) {
Steve Block6ded16b2010-05-10 14:33:55 +0100531 // Even if the last line misses a line end, it is counted.
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -0800532 line_ends->Add(src_len);
533 return;
Steve Block6ded16b2010-05-10 14:33:55 +0100534 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000535 }
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -0800536}
Steve Blocka7e24c12009-10-30 11:49:00 +0000537
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -0800538
539Handle<FixedArray> CalculateLineEnds(Handle<String> src,
540 bool with_last_line) {
541 src = FlattenGetString(src);
542 // Rough estimate of line count based on a roughly estimated average
543 // length of (unpacked) code.
544 int line_count_estimate = src->length() >> 4;
545 List<int> line_ends(line_count_estimate);
546 {
547 AssertNoAllocation no_heap_allocation; // ensure vectors stay valid.
548 // Dispatch on type of strings.
549 if (src->IsAsciiRepresentation()) {
550 CalculateLineEnds(&line_ends, src->ToAsciiVector(), with_last_line);
551 } else {
552 CalculateLineEnds(&line_ends, src->ToUC16Vector(), with_last_line);
553 }
554 }
555 int line_count = line_ends.length();
Steve Blocka7e24c12009-10-30 11:49:00 +0000556 Handle<FixedArray> array = Factory::NewFixedArray(line_count);
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -0800557 for (int i = 0; i < line_count; i++) {
558 array->set(i, Smi::FromInt(line_ends[i]));
Steve Blocka7e24c12009-10-30 11:49:00 +0000559 }
Steve Block6ded16b2010-05-10 14:33:55 +0100560 return array;
Steve Blocka7e24c12009-10-30 11:49:00 +0000561}
562
563
564// Convert code position into line number.
565int GetScriptLineNumber(Handle<Script> script, int code_pos) {
566 InitScriptLineEnds(script);
567 AssertNoAllocation no_allocation;
Andrei Popescu402d9372010-02-26 13:31:12 +0000568 FixedArray* line_ends_array = FixedArray::cast(script->line_ends());
Steve Blockd0582a62009-12-15 09:54:21 +0000569 const int line_ends_len = line_ends_array->length();
Steve Blocka7e24c12009-10-30 11:49:00 +0000570
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -0800571 if (!line_ends_len) return -1;
Andrei Popescu402d9372010-02-26 13:31:12 +0000572
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -0800573 if ((Smi::cast(line_ends_array->get(0)))->value() >= code_pos) {
Andrei Popescu402d9372010-02-26 13:31:12 +0000574 return script->line_offset()->value();
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -0800575 }
Andrei Popescu402d9372010-02-26 13:31:12 +0000576
577 int left = 0;
578 int right = line_ends_len;
579 while (int half = (right - left) / 2) {
580 if ((Smi::cast(line_ends_array->get(left + half)))->value() > code_pos) {
581 right -= half;
582 } else {
583 left += half;
Steve Blocka7e24c12009-10-30 11:49:00 +0000584 }
585 }
Andrei Popescu402d9372010-02-26 13:31:12 +0000586 return right + script->line_offset()->value();
Steve Blocka7e24c12009-10-30 11:49:00 +0000587}
588
589
Steve Block6ded16b2010-05-10 14:33:55 +0100590int GetScriptLineNumberSafe(Handle<Script> script, int code_pos) {
591 AssertNoAllocation no_allocation;
592 if (!script->line_ends()->IsUndefined()) {
593 return GetScriptLineNumber(script, code_pos);
594 }
595 // Slow mode: we do not have line_ends. We have to iterate through source.
596 if (!script->source()->IsString()) {
597 return -1;
598 }
599 String* source = String::cast(script->source());
600 int line = 0;
601 int len = source->length();
602 for (int pos = 0; pos < len; pos++) {
603 if (pos == code_pos) {
604 break;
605 }
606 if (source->Get(pos) == '\n') {
607 line++;
608 }
609 }
610 return line;
611}
612
613
Steve Blocka7e24c12009-10-30 11:49:00 +0000614void CustomArguments::IterateInstance(ObjectVisitor* v) {
Steve Block6ded16b2010-05-10 14:33:55 +0100615 v->VisitPointers(values_, values_ + ARRAY_SIZE(values_));
Steve Blocka7e24c12009-10-30 11:49:00 +0000616}
617
618
619// Compute the property keys from the interceptor.
620v8::Handle<v8::Array> GetKeysForNamedInterceptor(Handle<JSObject> receiver,
621 Handle<JSObject> object) {
622 Handle<InterceptorInfo> interceptor(object->GetNamedInterceptor());
623 CustomArguments args(interceptor->data(), *receiver, *object);
624 v8::AccessorInfo info(args.end());
625 v8::Handle<v8::Array> result;
626 if (!interceptor->enumerator()->IsUndefined()) {
627 v8::NamedPropertyEnumerator enum_fun =
628 v8::ToCData<v8::NamedPropertyEnumerator>(interceptor->enumerator());
629 LOG(ApiObjectAccess("interceptor-named-enum", *object));
630 {
631 // Leaving JavaScript.
632 VMState state(EXTERNAL);
633 result = enum_fun(info);
634 }
635 }
636 return result;
637}
638
639
640// Compute the element keys from the interceptor.
641v8::Handle<v8::Array> GetKeysForIndexedInterceptor(Handle<JSObject> receiver,
642 Handle<JSObject> object) {
643 Handle<InterceptorInfo> interceptor(object->GetIndexedInterceptor());
644 CustomArguments args(interceptor->data(), *receiver, *object);
645 v8::AccessorInfo info(args.end());
646 v8::Handle<v8::Array> result;
647 if (!interceptor->enumerator()->IsUndefined()) {
648 v8::IndexedPropertyEnumerator enum_fun =
649 v8::ToCData<v8::IndexedPropertyEnumerator>(interceptor->enumerator());
650 LOG(ApiObjectAccess("interceptor-indexed-enum", *object));
651 {
652 // Leaving JavaScript.
653 VMState state(EXTERNAL);
654 result = enum_fun(info);
655 }
656 }
657 return result;
658}
659
660
Ben Murdochf87a2032010-10-22 12:50:53 +0100661static bool ContainsOnlyValidKeys(Handle<FixedArray> array) {
662 int len = array->length();
663 for (int i = 0; i < len; i++) {
664 Object* e = array->get(i);
665 if (!(e->IsString() || e->IsNumber())) return false;
666 }
667 return true;
668}
669
670
Steve Blocka7e24c12009-10-30 11:49:00 +0000671Handle<FixedArray> GetKeysInFixedArrayFor(Handle<JSObject> object,
672 KeyCollectionType type) {
Ben Murdochf87a2032010-10-22 12:50:53 +0100673 USE(ContainsOnlyValidKeys);
Steve Blocka7e24c12009-10-30 11:49:00 +0000674 Handle<FixedArray> content = Factory::empty_fixed_array();
Steve Blockd0582a62009-12-15 09:54:21 +0000675 Handle<JSObject> arguments_boilerplate =
676 Handle<JSObject>(
677 Top::context()->global_context()->arguments_boilerplate());
678 Handle<JSFunction> arguments_function =
679 Handle<JSFunction>(
680 JSFunction::cast(arguments_boilerplate->map()->constructor()));
Steve Blocka7e24c12009-10-30 11:49:00 +0000681
682 // Only collect keys if access is permitted.
683 for (Handle<Object> p = object;
684 *p != Heap::null_value();
685 p = Handle<Object>(p->GetPrototype())) {
686 Handle<JSObject> current(JSObject::cast(*p));
687
688 // Check access rights if required.
689 if (current->IsAccessCheckNeeded() &&
Iain Merrick75681382010-08-19 15:07:18 +0100690 !Top::MayNamedAccess(*current, Heap::undefined_value(),
691 v8::ACCESS_KEYS)) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000692 Top::ReportFailedAccessCheck(*current, v8::ACCESS_KEYS);
693 break;
694 }
695
696 // Compute the element keys.
697 Handle<FixedArray> element_keys =
698 Factory::NewFixedArray(current->NumberOfEnumElements());
699 current->GetEnumElementKeys(*element_keys);
700 content = UnionOfKeys(content, element_keys);
Ben Murdochf87a2032010-10-22 12:50:53 +0100701 ASSERT(ContainsOnlyValidKeys(content));
Steve Blocka7e24c12009-10-30 11:49:00 +0000702
703 // Add the element keys from the interceptor.
704 if (current->HasIndexedInterceptor()) {
705 v8::Handle<v8::Array> result =
706 GetKeysForIndexedInterceptor(object, current);
707 if (!result.IsEmpty())
708 content = AddKeysFromJSArray(content, v8::Utils::OpenHandle(*result));
Ben Murdochf87a2032010-10-22 12:50:53 +0100709 ASSERT(ContainsOnlyValidKeys(content));
Steve Blocka7e24c12009-10-30 11:49:00 +0000710 }
711
Steve Blockd0582a62009-12-15 09:54:21 +0000712 // We can cache the computed property keys if access checks are
713 // not needed and no interceptors are involved.
714 //
715 // We do not use the cache if the object has elements and
716 // therefore it does not make sense to cache the property names
717 // for arguments objects. Arguments objects will always have
718 // elements.
Kristian Monsen50ef84f2010-07-29 15:18:00 +0100719 // Wrapped strings have elements, but don't have an elements
720 // array or dictionary. So the fast inline test for whether to
721 // use the cache says yes, so we should not create a cache.
Steve Blockd0582a62009-12-15 09:54:21 +0000722 bool cache_enum_keys =
723 ((current->map()->constructor() != *arguments_function) &&
Kristian Monsen50ef84f2010-07-29 15:18:00 +0100724 !current->IsJSValue() &&
Steve Blockd0582a62009-12-15 09:54:21 +0000725 !current->IsAccessCheckNeeded() &&
726 !current->HasNamedInterceptor() &&
727 !current->HasIndexedInterceptor());
728 // Compute the property keys and cache them if possible.
729 content =
730 UnionOfKeys(content, GetEnumPropertyKeys(current, cache_enum_keys));
Ben Murdochf87a2032010-10-22 12:50:53 +0100731 ASSERT(ContainsOnlyValidKeys(content));
Steve Blocka7e24c12009-10-30 11:49:00 +0000732
733 // Add the property keys from the interceptor.
734 if (current->HasNamedInterceptor()) {
735 v8::Handle<v8::Array> result =
736 GetKeysForNamedInterceptor(object, current);
737 if (!result.IsEmpty())
738 content = AddKeysFromJSArray(content, v8::Utils::OpenHandle(*result));
Ben Murdochf87a2032010-10-22 12:50:53 +0100739 ASSERT(ContainsOnlyValidKeys(content));
Steve Blocka7e24c12009-10-30 11:49:00 +0000740 }
741
742 // If we only want local properties we bail out after the first
743 // iteration.
744 if (type == LOCAL_ONLY)
745 break;
746 }
747 return content;
748}
749
750
751Handle<JSArray> GetKeysFor(Handle<JSObject> object) {
752 Counters::for_in.Increment();
753 Handle<FixedArray> elements = GetKeysInFixedArrayFor(object,
754 INCLUDE_PROTOS);
755 return Factory::NewJSArrayWithElements(elements);
756}
757
758
Steve Blockd0582a62009-12-15 09:54:21 +0000759Handle<FixedArray> GetEnumPropertyKeys(Handle<JSObject> object,
760 bool cache_result) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000761 int index = 0;
762 if (object->HasFastProperties()) {
763 if (object->map()->instance_descriptors()->HasEnumCache()) {
764 Counters::enum_cache_hits.Increment();
765 DescriptorArray* desc = object->map()->instance_descriptors();
766 return Handle<FixedArray>(FixedArray::cast(desc->GetEnumCache()));
767 }
768 Counters::enum_cache_misses.Increment();
769 int num_enum = object->NumberOfEnumProperties();
770 Handle<FixedArray> storage = Factory::NewFixedArray(num_enum);
771 Handle<FixedArray> sort_array = Factory::NewFixedArray(num_enum);
772 Handle<DescriptorArray> descs =
773 Handle<DescriptorArray>(object->map()->instance_descriptors());
774 for (int i = 0; i < descs->number_of_descriptors(); i++) {
775 if (descs->IsProperty(i) && !descs->IsDontEnum(i)) {
776 (*storage)->set(index, descs->GetKey(i));
777 PropertyDetails details(descs->GetDetails(i));
778 (*sort_array)->set(index, Smi::FromInt(details.index()));
779 index++;
780 }
781 }
782 (*storage)->SortPairs(*sort_array, sort_array->length());
Steve Blockd0582a62009-12-15 09:54:21 +0000783 if (cache_result) {
784 Handle<FixedArray> bridge_storage =
785 Factory::NewFixedArray(DescriptorArray::kEnumCacheBridgeLength);
786 DescriptorArray* desc = object->map()->instance_descriptors();
787 desc->SetEnumCache(*bridge_storage, *storage);
788 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000789 ASSERT(storage->length() == index);
790 return storage;
791 } else {
792 int num_enum = object->NumberOfEnumProperties();
793 Handle<FixedArray> storage = Factory::NewFixedArray(num_enum);
794 Handle<FixedArray> sort_array = Factory::NewFixedArray(num_enum);
795 object->property_dictionary()->CopyEnumKeysTo(*storage, *sort_array);
796 return storage;
797 }
798}
799
800
Leon Clarke4515c472010-02-03 11:58:03 +0000801bool EnsureCompiled(Handle<SharedFunctionInfo> shared,
802 ClearExceptionFlag flag) {
803 return shared->is_compiled() || CompileLazyShared(shared, flag);
804}
805
806
807static bool CompileLazyHelper(CompilationInfo* info,
808 ClearExceptionFlag flag) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000809 // Compile the source information to a code object.
Ben Murdochb0fe1622011-05-05 13:52:32 +0100810 ASSERT(info->IsOptimizing() || !info->shared_info()->is_compiled());
Leon Clarke4515c472010-02-03 11:58:03 +0000811 bool result = Compiler::CompileLazy(info);
Steve Blocka7e24c12009-10-30 11:49:00 +0000812 ASSERT(result != Top::has_pending_exception());
813 if (!result && flag == CLEAR_EXCEPTION) Top::clear_pending_exception();
814 return result;
815}
816
817
Leon Clarke4515c472010-02-03 11:58:03 +0000818bool CompileLazyShared(Handle<SharedFunctionInfo> shared,
819 ClearExceptionFlag flag) {
Andrei Popescu31002712010-02-23 13:46:05 +0000820 CompilationInfo info(shared);
Leon Clarke4515c472010-02-03 11:58:03 +0000821 return CompileLazyHelper(&info, flag);
822}
823
824
825bool CompileLazy(Handle<JSFunction> function,
Leon Clarke4515c472010-02-03 11:58:03 +0000826 ClearExceptionFlag flag) {
Ben Murdochb0fe1622011-05-05 13:52:32 +0100827 bool result = true;
Iain Merrick75681382010-08-19 15:07:18 +0100828 if (function->shared()->is_compiled()) {
Ben Murdochb0fe1622011-05-05 13:52:32 +0100829 function->ReplaceCode(function->shared()->code());
Iain Merrick75681382010-08-19 15:07:18 +0100830 function->shared()->set_code_age(0);
Iain Merrick75681382010-08-19 15:07:18 +0100831 } else {
Ben Murdochf87a2032010-10-22 12:50:53 +0100832 CompilationInfo info(function);
Ben Murdochb0fe1622011-05-05 13:52:32 +0100833 result = CompileLazyHelper(&info, flag);
Ben Murdochf87a2032010-10-22 12:50:53 +0100834 ASSERT(!result || function->is_compiled());
Iain Merrick75681382010-08-19 15:07:18 +0100835 }
Ben Murdochb0fe1622011-05-05 13:52:32 +0100836 if (result && function->is_compiled()) {
837 PROFILE(FunctionCreateEvent(*function));
838 }
839 return result;
Steve Blocka7e24c12009-10-30 11:49:00 +0000840}
841
842
Leon Clarke4515c472010-02-03 11:58:03 +0000843bool CompileLazyInLoop(Handle<JSFunction> function,
Leon Clarke4515c472010-02-03 11:58:03 +0000844 ClearExceptionFlag flag) {
Ben Murdochb0fe1622011-05-05 13:52:32 +0100845 bool result = true;
Iain Merrick75681382010-08-19 15:07:18 +0100846 if (function->shared()->is_compiled()) {
Ben Murdochb0fe1622011-05-05 13:52:32 +0100847 function->ReplaceCode(function->shared()->code());
Iain Merrick75681382010-08-19 15:07:18 +0100848 function->shared()->set_code_age(0);
Iain Merrick75681382010-08-19 15:07:18 +0100849 } else {
Ben Murdochf87a2032010-10-22 12:50:53 +0100850 CompilationInfo info(function);
851 info.MarkAsInLoop();
Ben Murdochb0fe1622011-05-05 13:52:32 +0100852 result = CompileLazyHelper(&info, flag);
Ben Murdochf87a2032010-10-22 12:50:53 +0100853 ASSERT(!result || function->is_compiled());
Iain Merrick75681382010-08-19 15:07:18 +0100854 }
Ben Murdochb0fe1622011-05-05 13:52:32 +0100855 if (result && function->is_compiled()) {
856 PROFILE(FunctionCreateEvent(*function));
857 }
858 return result;
859}
860
861
862bool CompileOptimized(Handle<JSFunction> function, int osr_ast_id) {
863 CompilationInfo info(function);
864 info.SetOptimizing(osr_ast_id);
865 bool result = CompileLazyHelper(&info, KEEP_EXCEPTION);
866 if (result) PROFILE(FunctionCreateEvent(*function));
867 return result;
Steve Blocka7e24c12009-10-30 11:49:00 +0000868}
869
Leon Clarke4515c472010-02-03 11:58:03 +0000870
Steve Blocka7e24c12009-10-30 11:49:00 +0000871OptimizedObjectForAddingMultipleProperties::
872OptimizedObjectForAddingMultipleProperties(Handle<JSObject> object,
873 int expected_additional_properties,
874 bool condition) {
875 object_ = object;
876 if (condition && object_->HasFastProperties()) {
877 // Normalize the properties of object to avoid n^2 behavior
878 // when extending the object multiple properties. Indicate the number of
879 // properties to be added.
880 unused_property_fields_ = object->map()->unused_property_fields();
881 NormalizeProperties(object_,
882 KEEP_INOBJECT_PROPERTIES,
883 expected_additional_properties);
884 has_been_transformed_ = true;
885
886 } else {
887 has_been_transformed_ = false;
888 }
889}
890
891
Steve Blocka7e24c12009-10-30 11:49:00 +0000892OptimizedObjectForAddingMultipleProperties::
893~OptimizedObjectForAddingMultipleProperties() {
894 // Reoptimize the object to allow fast property access.
895 if (has_been_transformed_) {
896 TransformToFastProperties(object_, unused_property_fields_);
897 }
898}
899
Steve Blocka7e24c12009-10-30 11:49:00 +0000900} } // namespace v8::internal