handles.cc 32.2 KB
Newer Older
1
// Copyright 2011 the V8 project authors. All rights reserved.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
//       copyright notice, this list of conditions and the following
//       disclaimer in the documentation and/or other materials provided
//       with the distribution.
//     * Neither the name of Google Inc. nor the names of its
//       contributors may be used to endorse or promote products derived
//       from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include "v8.h"

#include "accessors.h"
#include "api.h"
32
#include "arguments.h"
33 34 35 36 37 38 39
#include "bootstrapper.h"
#include "compiler.h"
#include "debug.h"
#include "execution.h"
#include "global-handles.h"
#include "natives.h"
#include "runtime.h"
40
#include "string-search.h"
41
#include "stub-cache.h"
42
#include "vm-state-inl.h"
43

44 45
namespace v8 {
namespace internal {
46 47


48
int HandleScope::NumberOfHandles() {
49 50 51
  Isolate* isolate = Isolate::Current();
  HandleScopeImplementer* impl = isolate->handle_scope_implementer();
  int n = impl->blocks()->length();
52
  if (n == 0) return 0;
53
  return ((n - 1) * kHandleBlockSize) + static_cast<int>(
54
      (isolate->handle_scope_data()->next - impl->blocks()->last()));
55 56 57
}


58
Object** HandleScope::Extend() {
59 60 61
  Isolate* isolate = Isolate::Current();
  v8::ImplementationUtilities::HandleScopeData* current =
      isolate->handle_scope_data();
62

63 64 65
  Object** result = current->next;

  ASSERT(result == current->limit);
66 67
  // Make sure there's at least one scope on the stack and that the
  // top of the scope stack isn't a barrier.
68
  if (current->level == 0) {
69 70 71 72
    Utils::ReportApiFailure("v8::HandleScope::CreateHandle()",
                            "Cannot create a handle without a HandleScope");
    return NULL;
  }
73
  HandleScopeImplementer* impl = isolate->handle_scope_implementer();
74 75
  // If there's more room in the last block, we use that. This is used
  // for fast creation of scopes after scope barriers.
76 77
  if (!impl->blocks()->is_empty()) {
    Object** limit = &impl->blocks()->last()[kHandleBlockSize];
78 79 80
    if (current->limit != limit) {
      current->limit = limit;
      ASSERT(limit - current->next < kHandleBlockSize);
81 82
    }
  }
83

84 85
  // If we still haven't found a slot for the handle, we extend the
  // current handle scope by allocating a new handle block.
86
  if (result == current->limit) {
87 88 89 90
    // If there's a spare block, use it for growing the current scope.
    result = impl->GetSpareOrNewBlock();
    // Add the extension to the global list of blocks, but count the
    // extension as part of the current scope.
91
    impl->blocks()->Add(result);
92
    current->limit = &result[kHandleBlockSize];
93
  }
94 95 96 97 98

  return result;
}


99 100 101 102 103
void HandleScope::DeleteExtensions(Isolate* isolate) {
  ASSERT(isolate == Isolate::Current());
  v8::ImplementationUtilities::HandleScopeData* current =
      isolate->handle_scope_data();
  isolate->handle_scope_implementer()->DeleteExtensions(current->limit);
104 105 106
}


107
void HandleScope::ZapRange(Object** start, Object** end) {
108 109
  ASSERT(end - start <= kHandleBlockSize);
  for (Object** p = start; p != end; p++) {
110
    *reinterpret_cast<Address*>(p) = v8::internal::kHandleZapValue;
111 112 113 114
  }
}


115
Address HandleScope::current_level_address() {
116 117
  return reinterpret_cast<Address>(
      &Isolate::Current()->handle_scope_data()->level);
118 119 120 121
}


Address HandleScope::current_next_address() {
122 123
  return reinterpret_cast<Address>(
      &Isolate::Current()->handle_scope_data()->next);
124 125 126 127
}


Address HandleScope::current_limit_address() {
128 129
  return reinterpret_cast<Address>(
      &Isolate::Current()->handle_scope_data()->limit);
130 131 132
}


133 134
Handle<FixedArray> AddKeysFromJSArray(Handle<FixedArray> content,
                                      Handle<JSArray> array) {
135
  CALL_HEAP_FUNCTION(content->GetIsolate(),
136
                     content->AddKeysFromJSArray(*array), FixedArray);
137 138 139 140 141
}


Handle<FixedArray> UnionOfKeys(Handle<FixedArray> first,
                               Handle<FixedArray> second) {
142
  CALL_HEAP_FUNCTION(first->GetIsolate(),
143
                     first->UnionOfKeys(*second), FixedArray);
144 145 146
}


147
Handle<JSGlobalProxy> ReinitializeJSGlobalProxy(
148
    Handle<JSFunction> constructor,
149
    Handle<JSGlobalProxy> global) {
150
  CALL_HEAP_FUNCTION(
151
      constructor->GetIsolate(),
152 153
      constructor->GetHeap()->ReinitializeJSGlobalProxy(*constructor, *global),
      JSGlobalProxy);
154 155 156 157
}


void SetExpectedNofProperties(Handle<JSFunction> func, int nof) {
158
  // If objects constructed from this function exist then changing
159
  // 'estimated_nof_properties' is dangerous since the previous value might
160 161 162 163 164
  // have been compiled into the fast construct stub. More over, the inobject
  // slack tracking logic might have adjusted the previous value, so even
  // passing the same value is risky.
  if (func->shared()->live_objects_may_exist()) return;

165 166 167
  func->shared()->set_expected_nof_properties(nof);
  if (func->has_initial_map()) {
    Handle<Map> new_initial_map =
168 169
        func->GetIsolate()->factory()->CopyMapDropTransitions(
            Handle<Map>(func->initial_map()));
170 171 172 173 174 175 176
    new_initial_map->set_unused_property_fields(nof);
    func->set_initial_map(*new_initial_map);
  }
}


void SetPrototypeProperty(Handle<JSFunction> func, Handle<JSObject> value) {
177
  CALL_HEAP_FUNCTION_VOID(func->GetIsolate(),
178
                          func->SetPrototype(*value));
179 180 181
}


182
static int ExpectedNofPropertiesFromEstimate(int estimate) {
183 184 185 186 187 188 189 190 191 192
  // If no properties are added in the constructor, they are more likely
  // to be added later.
  if (estimate == 0) estimate = 2;

  // We do not shrink objects that go into a snapshot (yet), so we adjust
  // the estimate conservatively.
  if (Serializer::enabled()) return estimate + 2;

  // Inobject slack tracking will reclaim redundant inobject space later,
  // so we can afford to adjust the estimate generously.
193 194 195 196 197
  if (FLAG_clever_optimizations) {
    return estimate + 8;
  } else {
    return estimate + 3;
  }
198 199 200 201 202
}


void SetExpectedNofPropertiesFromEstimate(Handle<SharedFunctionInfo> shared,
                                          int estimate) {
203 204 205
  // See the comment in SetExpectedNofProperties.
  if (shared->live_objects_may_exist()) return;

206 207
  shared->set_expected_nof_properties(
      ExpectedNofPropertiesFromEstimate(estimate));
208 209 210
}


211
void NormalizeProperties(Handle<JSObject> object,
212 213
                         PropertyNormalizationMode mode,
                         int expected_additional_properties) {
214
  CALL_HEAP_FUNCTION_VOID(object->GetIsolate(),
215 216 217
                          object->NormalizeProperties(
                              mode,
                              expected_additional_properties));
218 219 220
}


221 222 223 224
Handle<NumberDictionary> NormalizeElements(Handle<JSObject> object) {
  CALL_HEAP_FUNCTION(object->GetIsolate(),
                     object->NormalizeElements(),
                     NumberDictionary);
225 226 227 228 229 230
}


void TransformToFastProperties(Handle<JSObject> object,
                               int unused_property_fields) {
  CALL_HEAP_FUNCTION_VOID(
231
      object->GetIsolate(),
232 233 234 235
      object->TransformToFastProperties(unused_property_fields));
}


236 237 238 239 240 241 242 243
Handle<NumberDictionary> NumberDictionarySet(
    Handle<NumberDictionary> dictionary,
    uint32_t index,
    Handle<Object> value,
    PropertyDetails details) {
  CALL_HEAP_FUNCTION(dictionary->GetIsolate(),
                     dictionary->Set(index, *value, details),
                     NumberDictionary);
244 245 246
}


247
void FlattenString(Handle<String> string) {
248
  CALL_HEAP_FUNCTION_VOID(string->GetIsolate(), string->TryFlatten());
249 250 251 252
}


Handle<String> FlattenGetString(Handle<String> string) {
253
  CALL_HEAP_FUNCTION(string->GetIsolate(), string->TryFlatten(), String);
254 255 256 257 258
}


Handle<Object> SetPrototype(Handle<JSFunction> function,
                            Handle<Object> prototype) {
259
  ASSERT(function->should_have_prototype());
260
  CALL_HEAP_FUNCTION(function->GetIsolate(),
261
                     Accessors::FunctionSetPrototype(*function,
262 263 264 265 266 267
                                                     *prototype,
                                                     NULL),
                     Object);
}


268
Handle<Object> SetProperty(Handle<JSReceiver> object,
269 270
                           Handle<String> key,
                           Handle<Object> value,
271
                           PropertyAttributes attributes,
272
                           StrictModeFlag strict_mode) {
273
  CALL_HEAP_FUNCTION(object->GetIsolate(),
274
                     object->SetProperty(*key, *value, attributes, strict_mode),
275
                     Object);
276 277 278 279 280 281
}


Handle<Object> SetProperty(Handle<Object> object,
                           Handle<Object> key,
                           Handle<Object> value,
282
                           PropertyAttributes attributes,
283
                           StrictModeFlag strict_mode) {
284
  Isolate* isolate = Isolate::Current();
285
  CALL_HEAP_FUNCTION(
286 287 288
      isolate,
      Runtime::SetObjectProperty(
          isolate, object, key, value, attributes, strict_mode),
289
      Object);
290 291 292
}


293 294 295 296
Handle<Object> ForceSetProperty(Handle<JSObject> object,
                                Handle<Object> key,
                                Handle<Object> value,
                                PropertyAttributes attributes) {
297
  Isolate* isolate = object->GetIsolate();
298
  CALL_HEAP_FUNCTION(
299
      isolate,
300
      Runtime::ForceSetObjectProperty(
301
          isolate, object, key, value, attributes),
302
      Object);
303 304 305
}


306 307 308 309
Handle<Object> SetNormalizedProperty(Handle<JSObject> object,
                                     Handle<String> key,
                                     Handle<Object> value,
                                     PropertyDetails details) {
310 311
  CALL_HEAP_FUNCTION(object->GetIsolate(),
                     object->SetNormalizedProperty(*key, *value, details),
312 313 314 315
                     Object);
}


316 317
Handle<Object> ForceDeleteProperty(Handle<JSObject> object,
                                   Handle<Object> key) {
318 319 320 321
  Isolate* isolate = object->GetIsolate();
  CALL_HEAP_FUNCTION(isolate,
                     Runtime::ForceDeleteObjectProperty(isolate, object, key),
                     Object);
322 323 324
}


325
Handle<Object> SetLocalPropertyIgnoreAttributes(
326 327 328 329
    Handle<JSObject> object,
    Handle<String> key,
    Handle<Object> value,
    PropertyAttributes attributes) {
330 331 332 333
  CALL_HEAP_FUNCTION(
    object->GetIsolate(),
    object->SetLocalPropertyIgnoreAttributes(*key, *value, attributes),
    Object);
334 335
}

336

337 338 339 340
void SetLocalPropertyNoThrow(Handle<JSObject> object,
                             Handle<String> key,
                             Handle<Object> value,
                             PropertyAttributes attributes) {
341 342
  Isolate* isolate = object->GetIsolate();
  ASSERT(!isolate->has_pending_exception());
343 344
  CHECK(!SetLocalPropertyIgnoreAttributes(
        object, key, value, attributes).is_null());
345
  CHECK(!isolate->has_pending_exception());
346 347 348
}


349 350 351
Handle<Object> SetPropertyWithInterceptor(Handle<JSObject> object,
                                          Handle<String> key,
                                          Handle<Object> value,
352
                                          PropertyAttributes attributes,
353
                                          StrictModeFlag strict_mode) {
354 355
  CALL_HEAP_FUNCTION(object->GetIsolate(),
                     object->SetPropertyWithInterceptor(*key,
356
                                                        *value,
357
                                                        attributes,
358
                                                        strict_mode),
359 360 361 362
                     Object);
}


363
Handle<Object> GetProperty(Handle<JSReceiver> obj,
364
                           const char* name) {
365 366 367
  Isolate* isolate = obj->GetIsolate();
  Handle<String> str = isolate->factory()->LookupAsciiSymbol(name);
  CALL_HEAP_FUNCTION(isolate, obj->GetProperty(*str), Object);
368 369 370 371 372
}


Handle<Object> GetProperty(Handle<Object> obj,
                           Handle<Object> key) {
373 374 375
  Isolate* isolate = Isolate::Current();
  CALL_HEAP_FUNCTION(isolate,
                     Runtime::GetObjectProperty(isolate, obj, key), Object);
376 377 378 379 380 381 382
}


Handle<Object> GetPropertyWithInterceptor(Handle<JSObject> receiver,
                                          Handle<JSObject> holder,
                                          Handle<String> name,
                                          PropertyAttributes* attributes) {
383 384 385
  Isolate* isolate = receiver->GetIsolate();
  CALL_HEAP_FUNCTION(isolate,
                     holder->GetPropertyWithInterceptor(*receiver,
386 387 388 389 390 391 392 393 394 395 396 397
                                                        *name,
                                                        attributes),
                     Object);
}


Handle<Object> GetPrototype(Handle<Object> obj) {
  Handle<Object> result(obj->GetPrototype());
  return result;
}


398 399
Handle<Object> SetPrototype(Handle<JSObject> obj, Handle<Object> value) {
  const bool skip_hidden_prototypes = false;
400 401
  CALL_HEAP_FUNCTION(obj->GetIsolate(),
                     obj->SetPrototype(*value, skip_hidden_prototypes), Object);
402 403 404
}


405
Handle<Object> PreventExtensions(Handle<JSObject> object) {
406
  CALL_HEAP_FUNCTION(object->GetIsolate(), object->PreventExtensions(), Object);
407 408 409
}


410 411 412
Handle<Object> SetHiddenProperty(Handle<JSObject> obj,
                                 Handle<String> key,
                                 Handle<Object> value) {
413
  CALL_HEAP_FUNCTION(obj->GetIsolate(),
414
                     obj->SetHiddenProperty(*key, *value),
415 416
                     Object);
}
iposva@chromium.org's avatar
iposva@chromium.org committed
417

418

419
int GetIdentityHash(Handle<JSReceiver> obj) {
420
  CALL_AND_RETRY(obj->GetIsolate(),
421
                 obj->GetIdentityHash(ALLOW_CREATION),
422 423
                 return Smi::cast(__object__)->value(),
                 return 0);
424 425 426
}


427 428
Handle<Object> DeleteElement(Handle<JSObject> obj,
                             uint32_t index) {
429 430
  CALL_HEAP_FUNCTION(obj->GetIsolate(),
                     obj->DeleteElement(index, JSObject::NORMAL_DELETION),
431
                     Object);
432 433 434 435 436
}


Handle<Object> DeleteProperty(Handle<JSObject> obj,
                              Handle<String> prop) {
437 438
  CALL_HEAP_FUNCTION(obj->GetIsolate(),
                     obj->DeleteProperty(*prop, JSObject::NORMAL_DELETION),
439
                     Object);
440 441 442
}


443
Handle<Object> LookupSingleCharacterStringFromCode(uint32_t index) {
444 445 446 447
  Isolate* isolate = Isolate::Current();
  CALL_HEAP_FUNCTION(
      isolate,
      isolate->heap()->LookupSingleCharacterStringFromCode(index), Object);
448 449 450
}


451 452 453 454
Handle<String> SubString(Handle<String> str,
                         int start,
                         int end,
                         PretenureFlag pretenure) {
455 456
  CALL_HEAP_FUNCTION(str->GetIsolate(),
                     str->SubString(start, end, pretenure), String);
457 458 459 460 461
}


Handle<Object> SetElement(Handle<JSObject> object,
                          uint32_t index,
462 463
                          Handle<Object> value,
                          StrictModeFlag strict_mode) {
464
  if (object->HasExternalArrayElements()) {
465 466 467 468 469 470 471
    if (!value->IsSmi() && !value->IsHeapNumber() && !value->IsUndefined()) {
      bool has_exception;
      Handle<Object> number = Execution::ToNumber(value, &has_exception);
      if (has_exception) return Handle<Object>();
      value = number;
    }
  }
472
  CALL_HEAP_FUNCTION(object->GetIsolate(),
473 474
                     object->SetElement(index, *value, strict_mode, true),
                     Object);
475 476 477
}


478 479
Handle<Object> SetOwnElement(Handle<JSObject> object,
                             uint32_t index,
480 481
                             Handle<Object> value,
                             StrictModeFlag strict_mode) {
482
  ASSERT(!object->HasExternalArrayElements());
483 484
  CALL_HEAP_FUNCTION(object->GetIsolate(),
                     object->SetElement(index, *value, strict_mode, false),
485
                     Object);
486 487 488
}


489 490 491 492 493 494 495 496
Handle<Object> TransitionElementsKind(Handle<JSObject> object,
                                      ElementsKind to_kind) {
  CALL_HEAP_FUNCTION(object->GetIsolate(),
                     object->TransitionElementsKind(to_kind),
                     Object);
}


497
Handle<JSObject> Copy(Handle<JSObject> obj) {
498 499 500
  Isolate* isolate = obj->GetIsolate();
  CALL_HEAP_FUNCTION(isolate,
                     isolate->heap()->CopyJSObject(*obj), JSObject);
501 502 503
}


504
Handle<Object> SetAccessor(Handle<JSObject> obj, Handle<AccessorInfo> info) {
505
  CALL_HEAP_FUNCTION(obj->GetIsolate(), obj->DefineAccessor(*info), Object);
506 507 508
}


509
// Wrappers for scripts are kept alive and cached in weak global
510
// handles referred from foreign objects held by the scripts as long as
511 512 513 514
// they are used. When they are not used anymore, the garbage
// collector will call the weak callback on the global handle
// associated with the wrapper and get rid of both the wrapper and the
// handle.
515
static void ClearWrapperCache(Persistent<v8::Value> handle, void*) {
516 517
  Handle<Object> cache = Utils::OpenHandle(*handle);
  JSValue* wrapper = JSValue::cast(*cache);
518
  Foreign* foreign = Script::cast(wrapper->value())->wrapper();
519 520 521
  ASSERT(foreign->foreign_address() ==
         reinterpret_cast<Address>(cache.location()));
  foreign->set_foreign_address(0);
522 523 524
  Isolate* isolate = Isolate::Current();
  isolate->global_handles()->Destroy(cache.location());
  isolate->counters()->script_wrappers()->Decrement();
525 526 527 528
}


Handle<JSValue> GetScriptWrapper(Handle<Script> script) {
529
  if (script->wrapper()->foreign_address() != NULL) {
530
    // Return the script wrapper directly from the cache.
531
    return Handle<JSValue>(
532
        reinterpret_cast<JSValue**>(script->wrapper()->foreign_address()));
533
  }
534
  Isolate* isolate = Isolate::Current();
535
  // Construct a new script wrapper.
536 537
  isolate->counters()->script_wrappers()->Increment();
  Handle<JSFunction> constructor = isolate->script_function();
538
  Handle<JSValue> result =
539
      Handle<JSValue>::cast(isolate->factory()->NewJSObject(constructor));
540 541 542 543 544
  result->set_value(*script);

  // Create a new weak global handle and use it to cache the wrapper
  // for future use. The cache will automatically be cleared by the
  // garbage collector when it is not used anymore.
545 546 547
  Handle<Object> handle = isolate->global_handles()->Create(*result);
  isolate->global_handles()->MakeWeak(handle.location(), NULL,
                                      &ClearWrapperCache);
548 549
  script->wrapper()->set_foreign_address(
      reinterpret_cast<Address>(handle.location()));
550 551 552 553
  return result;
}


554 555 556
// Init line_ends array with code positions of line ends inside script
// source.
void InitScriptLineEnds(Handle<Script> script) {
557
  if (!script->line_ends()->IsUndefined()) return;
558

559 560
  Isolate* isolate = script->GetIsolate();

561 562
  if (!script->source()->IsString()) {
    ASSERT(script->source()->IsUndefined());
563
    Handle<FixedArray> empty = isolate->factory()->NewFixedArray(0);
564
    script->set_line_ends(*empty);
565
    ASSERT(script->line_ends()->IsFixedArray());
566 567 568
    return;
  }

569
  Handle<String> src(String::cast(script->source()), isolate);
570 571 572

  Handle<FixedArray> array = CalculateLineEnds(src, true);

573 574
  if (*array != isolate->heap()->empty_fixed_array()) {
    array->set_map(isolate->heap()->fixed_cow_array_map());
575 576
  }

577 578 579 580 581
  script->set_line_ends(*array);
  ASSERT(script->line_ends()->IsFixedArray());
}


582
template <typename SourceChar>
583 584
static void CalculateLineEnds(Isolate* isolate,
                              List<int>* line_ends,
585 586 587
                              Vector<const SourceChar> src,
                              bool with_last_line) {
  const int src_len = src.length();
588
  StringSearch<char, SourceChar> search(isolate, CStrVector("\n"));
589

590
  // Find and record line ends.
591 592
  int position = 0;
  while (position != -1 && position < src_len) {
593
    position = search.Search(src, position);
594
    if (position != -1) {
595
      line_ends->Add(position);
596
      position++;
597
    } else if (with_last_line) {
598
      // Even if the last line misses a line end, it is counted.
599 600
      line_ends->Add(src_len);
      return;
601
    }
602
  }
603
}
604

605 606 607 608 609 610 611 612

Handle<FixedArray> CalculateLineEnds(Handle<String> src,
                                     bool with_last_line) {
  src = FlattenGetString(src);
  // Rough estimate of line count based on a roughly estimated average
  // length of (unpacked) code.
  int line_count_estimate = src->length() >> 4;
  List<int> line_ends(line_count_estimate);
613
  Isolate* isolate = src->GetIsolate();
614 615 616
  {
    AssertNoAllocation no_heap_allocation;  // ensure vectors stay valid.
    // Dispatch on type of strings.
lrn@chromium.org's avatar
lrn@chromium.org committed
617
    String::FlatContent content = src->GetFlatContent();
618 619
    ASSERT(content.IsFlat());
    if (content.IsAscii()) {
620 621
      CalculateLineEnds(isolate,
                        &line_ends,
622
                        content.ToAsciiVector(),
623
                        with_last_line);
624
    } else {
625 626
      CalculateLineEnds(isolate,
                        &line_ends,
627
                        content.ToUC16Vector(),
628
                        with_last_line);
629
    }
630
  }
631
  int line_count = line_ends.length();
632
  Handle<FixedArray> array = isolate->factory()->NewFixedArray(line_count);
633 634 635
  for (int i = 0; i < line_count; i++) {
    array->set(i, Smi::FromInt(line_ends[i]));
  }
636
  return array;
637 638 639 640 641 642 643
}


// Convert code position into line number.
int GetScriptLineNumber(Handle<Script> script, int code_pos) {
  InitScriptLineEnds(script);
  AssertNoAllocation no_allocation;
644
  FixedArray* line_ends_array = FixedArray::cast(script->line_ends());
645
  const int line_ends_len = line_ends_array->length();
646

647
  if (!line_ends_len) return -1;
648

649
  if ((Smi::cast(line_ends_array->get(0)))->value() >= code_pos) {
650
    return script->line_offset()->value();
651
  }
652 653 654 655 656 657 658 659

  int left = 0;
  int right = line_ends_len;
  while (int half = (right - left) / 2) {
    if ((Smi::cast(line_ends_array->get(left + half)))->value() > code_pos) {
      right -= half;
    } else {
      left += half;
660 661
    }
  }
662
  return right + script->line_offset()->value();
663 664
}

665 666 667 668 669 670 671 672 673 674 675 676 677
// Convert code position into column number.
int GetScriptColumnNumber(Handle<Script> script, int code_pos) {
  int line_number = GetScriptLineNumber(script, code_pos);
  if (line_number == -1) return -1;

  AssertNoAllocation no_allocation;
  FixedArray* line_ends_array = FixedArray::cast(script->line_ends());
  line_number = line_number - script->line_offset()->value();
  if (line_number == 0) return code_pos + script->column_offset()->value();
  int prev_line_end_pos =
      Smi::cast(line_ends_array->get(line_number - 1))->value();
  return code_pos - (prev_line_end_pos + 1);
}
678

679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702
int GetScriptLineNumberSafe(Handle<Script> script, int code_pos) {
  AssertNoAllocation no_allocation;
  if (!script->line_ends()->IsUndefined()) {
    return GetScriptLineNumber(script, code_pos);
  }
  // Slow mode: we do not have line_ends. We have to iterate through source.
  if (!script->source()->IsString()) {
    return -1;
  }
  String* source = String::cast(script->source());
  int line = 0;
  int len = source->length();
  for (int pos = 0; pos < len; pos++) {
    if (pos == code_pos) {
      break;
    }
    if (source->Get(pos) == '\n') {
      line++;
    }
  }
  return line;
}


703
void CustomArguments::IterateInstance(ObjectVisitor* v) {
704
  v->VisitPointers(values_, values_ + ARRAY_SIZE(values_));
705 706 707
}


708
// Compute the property keys from the interceptor.
709
v8::Handle<v8::Array> GetKeysForNamedInterceptor(Handle<JSReceiver> receiver,
710
                                                 Handle<JSObject> object) {
711
  Isolate* isolate = receiver->GetIsolate();
712
  Handle<InterceptorInfo> interceptor(object->GetNamedInterceptor());
713
  CustomArguments args(isolate, interceptor->data(), *receiver, *object);
714
  v8::AccessorInfo info(args.end());
715 716 717 718
  v8::Handle<v8::Array> result;
  if (!interceptor->enumerator()->IsUndefined()) {
    v8::NamedPropertyEnumerator enum_fun =
        v8::ToCData<v8::NamedPropertyEnumerator>(interceptor->enumerator());
719
    LOG(isolate, ApiObjectAccess("interceptor-named-enum", *object));
720 721
    {
      // Leaving JavaScript.
722
      VMState state(isolate, EXTERNAL);
723 724 725 726 727 728 729 730
      result = enum_fun(info);
    }
  }
  return result;
}


// Compute the element keys from the interceptor.
731
v8::Handle<v8::Array> GetKeysForIndexedInterceptor(Handle<JSReceiver> receiver,
732
                                                   Handle<JSObject> object) {
733
  Isolate* isolate = receiver->GetIsolate();
734
  Handle<InterceptorInfo> interceptor(object->GetIndexedInterceptor());
735
  CustomArguments args(isolate, interceptor->data(), *receiver, *object);
736
  v8::AccessorInfo info(args.end());
737 738 739 740
  v8::Handle<v8::Array> result;
  if (!interceptor->enumerator()->IsUndefined()) {
    v8::IndexedPropertyEnumerator enum_fun =
        v8::ToCData<v8::IndexedPropertyEnumerator>(interceptor->enumerator());
741
    LOG(isolate, ApiObjectAccess("interceptor-indexed-enum", *object));
742 743
    {
      // Leaving JavaScript.
744
      VMState state(isolate, EXTERNAL);
745 746 747 748 749 750 751
      result = enum_fun(info);
    }
  }
  return result;
}


752 753 754 755 756 757 758 759 760 761
static bool ContainsOnlyValidKeys(Handle<FixedArray> array) {
  int len = array->length();
  for (int i = 0; i < len; i++) {
    Object* e = array->get(i);
    if (!(e->IsString() || e->IsNumber())) return false;
  }
  return true;
}


762 763 764
Handle<FixedArray> GetKeysInFixedArrayFor(Handle<JSReceiver> object,
                                          KeyCollectionType type,
                                          bool* threw) {
765
  USE(ContainsOnlyValidKeys);
766 767
  Isolate* isolate = object->GetIsolate();
  Handle<FixedArray> content = isolate->factory()->empty_fixed_array();
768 769 770 771 772 773
  Handle<JSObject> arguments_boilerplate = Handle<JSObject>(
      isolate->context()->global_context()->arguments_boilerplate(),
      isolate);
  Handle<JSFunction> arguments_function = Handle<JSFunction>(
      JSFunction::cast(arguments_boilerplate->map()->constructor()),
      isolate);
774 775

  // Only collect keys if access is permitted.
776
  for (Handle<Object> p = object;
777
       *p != isolate->heap()->null_value();
778
       p = Handle<Object>(p->GetPrototype(), isolate)) {
779 780 781 782 783 784 785 786 787 788
    if (p->IsJSProxy()) {
      Handle<JSProxy> proxy(JSProxy::cast(*p), isolate);
      Handle<Object> args[] = { proxy };
      Handle<Object> names = Execution::Call(
          isolate->proxy_enumerate(), object, ARRAY_SIZE(args), args, threw);
      if (*threw) return content;
      content = AddKeysFromJSArray(content, Handle<JSArray>::cast(names));
      break;
    }

789
    Handle<JSObject> current(JSObject::cast(*p), isolate);
790 791 792

    // Check access rights if required.
    if (current->IsAccessCheckNeeded() &&
793 794 795 796
        !isolate->MayNamedAccess(*current,
                                 isolate->heap()->undefined_value(),
                                 v8::ACCESS_KEYS)) {
      isolate->ReportFailedAccessCheck(*current, v8::ACCESS_KEYS);
797 798
      break;
    }
799

800 801
    // Compute the element keys.
    Handle<FixedArray> element_keys =
802
        isolate->factory()->NewFixedArray(current->NumberOfEnumElements());
803 804
    current->GetEnumElementKeys(*element_keys);
    content = UnionOfKeys(content, element_keys);
805
    ASSERT(ContainsOnlyValidKeys(content));
806 807 808 809 810 811 812

    // Add the element keys from the interceptor.
    if (current->HasIndexedInterceptor()) {
      v8::Handle<v8::Array> result =
          GetKeysForIndexedInterceptor(object, current);
      if (!result.IsEmpty())
        content = AddKeysFromJSArray(content, v8::Utils::OpenHandle(*result));
813
      ASSERT(ContainsOnlyValidKeys(content));
814
    }
815

816 817 818 819 820 821 822
    // We can cache the computed property keys if access checks are
    // not needed and no interceptors are involved.
    //
    // We do not use the cache if the object has elements and
    // therefore it does not make sense to cache the property names
    // for arguments objects.  Arguments objects will always have
    // elements.
823 824 825
    // Wrapped strings have elements, but don't have an elements
    // array or dictionary.  So the fast inline test for whether to
    // use the cache says yes, so we should not create a cache.
826 827
    bool cache_enum_keys =
        ((current->map()->constructor() != *arguments_function) &&
828
         !current->IsJSValue() &&
829 830 831 832 833 834
         !current->IsAccessCheckNeeded() &&
         !current->HasNamedInterceptor() &&
         !current->HasIndexedInterceptor());
    // Compute the property keys and cache them if possible.
    content =
        UnionOfKeys(content, GetEnumPropertyKeys(current, cache_enum_keys));
835
    ASSERT(ContainsOnlyValidKeys(content));
836

837 838 839 840 841 842
    // Add the property keys from the interceptor.
    if (current->HasNamedInterceptor()) {
      v8::Handle<v8::Array> result =
          GetKeysForNamedInterceptor(object, current);
      if (!result.IsEmpty())
        content = AddKeysFromJSArray(content, v8::Utils::OpenHandle(*result));
843
      ASSERT(ContainsOnlyValidKeys(content));
844
    }
845 846 847 848 849

    // If we only want local properties we bail out after the first
    // iteration.
    if (type == LOCAL_ONLY)
      break;
850 851 852 853 854
  }
  return content;
}


855
Handle<JSArray> GetKeysFor(Handle<JSReceiver> object, bool* threw) {
856 857
  Isolate* isolate = object->GetIsolate();
  isolate->counters()->for_in()->Increment();
858 859
  Handle<FixedArray> elements =
      GetKeysInFixedArrayFor(object, INCLUDE_PROTOS, threw);
860
  return isolate->factory()->NewJSArrayWithElements(elements);
861 862 863
}


864 865
Handle<FixedArray> GetEnumPropertyKeys(Handle<JSObject> object,
                                       bool cache_result) {
866
  int index = 0;
867
  Isolate* isolate = object->GetIsolate();
868 869
  if (object->HasFastProperties()) {
    if (object->map()->instance_descriptors()->HasEnumCache()) {
870
      isolate->counters()->enum_cache_hits()->Increment();
871
      DescriptorArray* desc = object->map()->instance_descriptors();
872 873
      return Handle<FixedArray>(FixedArray::cast(desc->GetEnumCache()),
                                isolate);
874
    }
875
    isolate->counters()->enum_cache_misses()->Increment();
876
    int num_enum = object->NumberOfEnumProperties();
877 878
    Handle<FixedArray> storage = isolate->factory()->NewFixedArray(num_enum);
    Handle<FixedArray> sort_array = isolate->factory()->NewFixedArray(num_enum);
879
    Handle<DescriptorArray> descs =
880
        Handle<DescriptorArray>(object->map()->instance_descriptors(), isolate);
881 882 883 884 885
    for (int i = 0; i < descs->number_of_descriptors(); i++) {
      if (descs->IsProperty(i) && !descs->IsDontEnum(i)) {
        (*storage)->set(index, descs->GetKey(i));
        PropertyDetails details(descs->GetDetails(i));
        (*sort_array)->set(index, Smi::FromInt(details.index()));
886 887 888
        index++;
      }
    }
889
    (*storage)->SortPairs(*sort_array, sort_array->length());
890 891
    if (cache_result) {
      Handle<FixedArray> bridge_storage =
892 893
          isolate->factory()->NewFixedArray(
              DescriptorArray::kEnumCacheBridgeLength);
894 895 896
      DescriptorArray* desc = object->map()->instance_descriptors();
      desc->SetEnumCache(*bridge_storage, *storage);
    }
897 898 899 900
    ASSERT(storage->length() == index);
    return storage;
  } else {
    int num_enum = object->NumberOfEnumProperties();
901 902
    Handle<FixedArray> storage = isolate->factory()->NewFixedArray(num_enum);
    Handle<FixedArray> sort_array = isolate->factory()->NewFixedArray(num_enum);
903 904 905 906 907 908
    object->property_dictionary()->CopyEnumKeysTo(*storage, *sort_array);
    return storage;
  }
}


909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924
Handle<ObjectHashSet> ObjectHashSetAdd(Handle<ObjectHashSet> table,
                                       Handle<Object> key) {
  CALL_HEAP_FUNCTION(table->GetIsolate(),
                     table->Add(*key),
                     ObjectHashSet);
}


Handle<ObjectHashSet> ObjectHashSetRemove(Handle<ObjectHashSet> table,
                                          Handle<Object> key) {
  CALL_HEAP_FUNCTION(table->GetIsolate(),
                     table->Remove(*key),
                     ObjectHashSet);
}


925
Handle<ObjectHashTable> PutIntoObjectHashTable(Handle<ObjectHashTable> table,
926
                                               Handle<Object> key,
927 928 929 930 931 932 933
                                               Handle<Object> value) {
  CALL_HEAP_FUNCTION(table->GetIsolate(),
                     table->Put(*key, *value),
                     ObjectHashTable);
}


934
} }  // namespace v8::internal