runtime.cc 370 KB
Newer Older
1
// Copyright 2010 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 32 33 34
// 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 <stdlib.h>

#include "v8.h"

#include "accessors.h"
#include "api.h"
#include "arguments.h"
35
#include "codegen.h"
36
#include "compilation-cache.h"
37 38
#include "compiler.h"
#include "cpu.h"
39
#include "dateparser-inl.h"
40
#include "debug.h"
41
#include "deoptimizer.h"
42 43
#include "execution.h"
#include "jsregexp.h"
44
#include "liveedit.h"
45
#include "parser.h"
46 47
#include "platform.h"
#include "runtime.h"
48
#include "runtime-profiler.h"
49
#include "scopeinfo.h"
50
#include "smart-pointer.h"
51
#include "stub-cache.h"
52
#include "v8threads.h"
53
#include "string-search.h"
54

55 56
namespace v8 {
namespace internal {
57 58


59 60
#define RUNTIME_ASSERT(value) \
  if (!(value)) return Top::ThrowIllegalOperation();
61 62 63 64 65 66 67 68 69 70 71 72

// Cast the given object to a value of the specified type and store
// it in a variable with the given name.  If the object is not of the
// expected type call IllegalOperation and return.
#define CONVERT_CHECKED(Type, name, obj)                             \
  RUNTIME_ASSERT(obj->Is##Type());                                   \
  Type* name = Type::cast(obj);

#define CONVERT_ARG_CHECKED(Type, name, index)                       \
  RUNTIME_ASSERT(args[index]->Is##Type());                           \
  Handle<Type> name = args.at<Type>(index);

73 74 75 76 77 78 79
// Cast the given object to a boolean and store it in a variable with
// the given name.  If the object is not a boolean call IllegalOperation
// and return.
#define CONVERT_BOOLEAN_CHECKED(name, obj)                            \
  RUNTIME_ASSERT(obj->IsBoolean());                                   \
  bool name = (obj)->IsTrue();

80 81 82 83 84 85 86
// Cast the given object to a Smi and store its value in an int variable
// with the given name.  If the object is not a Smi call IllegalOperation
// and return.
#define CONVERT_SMI_CHECKED(name, obj)                            \
  RUNTIME_ASSERT(obj->IsSmi());                                   \
  int name = Smi::cast(obj)->value();

87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
// Cast the given object to a double and store it in a variable with
// the given name.  If the object is not a number (as opposed to
// the number not-a-number) call IllegalOperation and return.
#define CONVERT_DOUBLE_CHECKED(name, obj)                            \
  RUNTIME_ASSERT(obj->IsNumber());                                   \
  double name = (obj)->Number();

// Call the specified converter on the object *comand store the result in
// a variable of the specified type with the given name.  If the
// object is not a Number call IllegalOperation and return.
#define CONVERT_NUMBER_CHECKED(type, name, Type, obj)                \
  RUNTIME_ASSERT(obj->IsNumber());                                   \
  type name = NumberTo##Type(obj);

// Non-reentrant string buffer for efficient general use in this file.
102
static StaticResource<StringInputBuffer> runtime_string_input_buffer;
103 104


105
MUST_USE_RESULT static MaybeObject* DeepCopyBoilerplate(JSObject* boilerplate) {
106 107 108
  StackLimitCheck check;
  if (check.HasOverflowed()) return Top::StackOverflow();

109 110 111 112
  Object* result;
  { MaybeObject* maybe_result = Heap::CopyJSObject(boilerplate);
    if (!maybe_result->ToObject(&result)) return maybe_result;
  }
113 114 115 116 117 118 119 120
  JSObject* copy = JSObject::cast(result);

  // Deep copy local properties.
  if (copy->HasFastProperties()) {
    FixedArray* properties = copy->properties();
    for (int i = 0; i < properties->length(); i++) {
      Object* value = properties->get(i);
      if (value->IsJSObject()) {
121
        JSObject* js_object = JSObject::cast(value);
122 123 124
        { MaybeObject* maybe_result = DeepCopyBoilerplate(js_object);
          if (!maybe_result->ToObject(&result)) return maybe_result;
        }
125
        properties->set(i, result);
126 127
      }
    }
128 129
    int nof = copy->map()->inobject_properties();
    for (int i = 0; i < nof; i++) {
130 131
      Object* value = copy->InObjectPropertyAt(i);
      if (value->IsJSObject()) {
132
        JSObject* js_object = JSObject::cast(value);
133 134 135
        { MaybeObject* maybe_result = DeepCopyBoilerplate(js_object);
          if (!maybe_result->ToObject(&result)) return maybe_result;
        }
136
        copy->InObjectPropertyAtPut(i, result);
137 138 139
      }
    }
  } else {
140 141 142 143
    { MaybeObject* maybe_result =
          Heap::AllocateFixedArray(copy->NumberOfLocalProperties(NONE));
      if (!maybe_result->ToObject(&result)) return maybe_result;
    }
144 145 146 147
    FixedArray* names = FixedArray::cast(result);
    copy->GetLocalPropertyNames(names, 0);
    for (int i = 0; i < names->length(); i++) {
      ASSERT(names->get(i)->IsString());
148
      String* key_string = String::cast(names->get(i));
149
      PropertyAttributes attributes =
150
          copy->GetLocalPropertyAttribute(key_string);
151 152 153 154
      // Only deep copy fields from the object literal expression.
      // In particular, don't try to copy the length attribute of
      // an array.
      if (attributes != NONE) continue;
155 156
      Object* value =
          copy->GetProperty(key_string, &attributes)->ToObjectUnchecked();
157
      if (value->IsJSObject()) {
158
        JSObject* js_object = JSObject::cast(value);
159 160 161 162 163 164 165
        { MaybeObject* maybe_result = DeepCopyBoilerplate(js_object);
          if (!maybe_result->ToObject(&result)) return maybe_result;
        }
        { MaybeObject* maybe_result =
              copy->SetProperty(key_string, result, NONE);
          if (!maybe_result->ToObject(&result)) return maybe_result;
        }
166 167 168 169 170
      }
    }
  }

  // Deep copy local elements.
171
  // Pixel elements cannot be created using an object literal.
172
  ASSERT(!copy->HasPixelElements() && !copy->HasExternalArrayElements());
173 174 175
  switch (copy->GetElementsKind()) {
    case JSObject::FAST_ELEMENTS: {
      FixedArray* elements = FixedArray::cast(copy->elements());
176 177 178 179 180 181 182 183 184 185 186 187
      if (elements->map() == Heap::fixed_cow_array_map()) {
        Counters::cow_arrays_created_runtime.Increment();
#ifdef DEBUG
        for (int i = 0; i < elements->length(); i++) {
          ASSERT(!elements->get(i)->IsJSObject());
        }
#endif
      } else {
        for (int i = 0; i < elements->length(); i++) {
          Object* value = elements->get(i);
          if (value->IsJSObject()) {
            JSObject* js_object = JSObject::cast(value);
188 189 190
            { MaybeObject* maybe_result = DeepCopyBoilerplate(js_object);
              if (!maybe_result->ToObject(&result)) return maybe_result;
            }
191 192
            elements->set(i, result);
          }
193 194 195 196 197 198 199 200 201 202 203 204
        }
      }
      break;
    }
    case JSObject::DICTIONARY_ELEMENTS: {
      NumberDictionary* element_dictionary = copy->element_dictionary();
      int capacity = element_dictionary->Capacity();
      for (int i = 0; i < capacity; i++) {
        Object* k = element_dictionary->KeyAt(i);
        if (element_dictionary->IsKey(k)) {
          Object* value = element_dictionary->ValueAt(i);
          if (value->IsJSObject()) {
205
            JSObject* js_object = JSObject::cast(value);
206 207 208
            { MaybeObject* maybe_result = DeepCopyBoilerplate(js_object);
              if (!maybe_result->ToObject(&result)) return maybe_result;
            }
209 210
            element_dictionary->ValueAtPut(i, result);
          }
211 212
        }
      }
213
      break;
214
    }
215 216 217
    default:
      UNREACHABLE();
      break;
218 219 220 221 222
  }
  return copy;
}


223
static MaybeObject* Runtime_CloneLiteralBoilerplate(Arguments args) {
224 225 226 227 228
  CONVERT_CHECKED(JSObject, boilerplate, args[0]);
  return DeepCopyBoilerplate(boilerplate);
}


229
static MaybeObject* Runtime_CloneShallowLiteralBoilerplate(Arguments args) {
230
  CONVERT_CHECKED(JSObject, boilerplate, args[0]);
231
  return Heap::CopyJSObject(boilerplate);
232 233 234
}


235 236 237
static Handle<Map> ComputeObjectLiteralMap(
    Handle<Context> context,
    Handle<FixedArray> constant_properties,
238
    bool* is_result_from_cache) {
239 240
  int properties_length = constant_properties->length();
  int number_of_properties = properties_length / 2;
241
  if (FLAG_canonicalize_object_literal_maps) {
242
    // Check that there are only symbols and array indices among keys.
243
    int number_of_symbol_keys = 0;
244 245 246 247 248 249 250 251 252 253 254 255 256 257
    for (int p = 0; p != properties_length; p += 2) {
      Object* key = constant_properties->get(p);
      uint32_t element_index = 0;
      if (key->IsSymbol()) {
        number_of_symbol_keys++;
      } else if (key->ToArrayIndex(&element_index)) {
        // An index key does not require space in the property backing store.
        number_of_properties--;
      } else {
        // Bail out as a non-symbol non-index key makes caching impossible.
        // ASSERT to make sure that the if condition after the loop is false.
        ASSERT(number_of_symbol_keys != number_of_properties);
        break;
      }
258
    }
259 260
    // If we only have symbols and array indices among keys then we can
    // use the map cache in the global context.
261
    const int kMaxKeys = 10;
262 263
    if ((number_of_symbol_keys == number_of_properties) &&
        (number_of_symbol_keys < kMaxKeys)) {
264 265
      // Create the fixed array with the key.
      Handle<FixedArray> keys = Factory::NewFixedArray(number_of_symbol_keys);
266 267 268 269 270 271 272 273 274
      if (number_of_symbol_keys > 0) {
        int index = 0;
        for (int p = 0; p < properties_length; p += 2) {
          Object* key = constant_properties->get(p);
          if (key->IsSymbol()) {
            keys->set(index++, key);
          }
        }
        ASSERT(index == number_of_symbol_keys);
275
      }
276
      *is_result_from_cache = true;
277 278 279
      return Factory::ObjectLiteralMapFromCache(context, keys);
    }
  }
280
  *is_result_from_cache = false;
281 282 283
  return Factory::CopyMap(
      Handle<Map>(context->object_function()->initial_map()),
      number_of_properties);
284 285 286
}


287 288 289
static Handle<Object> CreateLiteralBoilerplate(
    Handle<FixedArray> literals,
    Handle<FixedArray> constant_properties);
290

291 292 293

static Handle<Object> CreateObjectLiteralBoilerplate(
    Handle<FixedArray> literals,
294 295
    Handle<FixedArray> constant_properties,
    bool should_have_fast_elements) {
296 297 298 299 300 301
  // Get the global context from the literals array.  This is the
  // context in which the function was created and we use the object
  // function from this context to create the object literal.  We do
  // not use the object function from the current global context
  // because this might be the object function from another context
  // which we should not have access to.
302 303 304 305 306 307
  Handle<Context> context =
      Handle<Context>(JSFunction::GlobalContextFromLiterals(*literals));

  bool is_result_from_cache;
  Handle<Map> map = ComputeObjectLiteralMap(context,
                                            constant_properties,
308
                                            &is_result_from_cache);
309

310
  Handle<JSObject> boilerplate = Factory::NewJSObjectFromMap(map);
311 312 313 314

  // Normalize the elements of the boilerplate to save space if needed.
  if (!should_have_fast_elements) NormalizeElements(boilerplate);

315
  {  // Add the constant properties to the boilerplate.
316
    int length = constant_properties->length();
317
    OptimizedObjectForAddingMultipleProperties opt(boilerplate,
318
                                                   length / 2,
319
                                                   !is_result_from_cache);
320 321 322
    for (int index = 0; index < length; index +=2) {
      Handle<Object> key(constant_properties->get(index+0));
      Handle<Object> value(constant_properties->get(index+1));
323 324 325 326 327 328 329
      if (value->IsFixedArray()) {
        // The value contains the constant_properties of a
        // simple object literal.
        Handle<FixedArray> array = Handle<FixedArray>::cast(value);
        value = CreateLiteralBoilerplate(literals, array);
        if (value.is_null()) return value;
      }
330
      Handle<Object> result;
331
      uint32_t element_index = 0;
332
      if (key->IsSymbol()) {
333 334 335 336 337 338 339 340 341
        if (Handle<String>::cast(key)->AsArrayIndex(&element_index)) {
          // Array index as string (uint32).
          result = SetOwnElement(boilerplate, element_index, value);
        } else {
          Handle<String> name(String::cast(*key));
          ASSERT(!name->AsArrayIndex(&element_index));
          result = SetLocalPropertyIgnoreAttributes(boilerplate, name,
                                                    value, NONE);
        }
342 343
      } else if (key->ToArrayIndex(&element_index)) {
        // Array index (uint32).
344
        result = SetOwnElement(boilerplate, element_index, value);
345 346 347 348 349 350 351 352
      } else {
        // Non-uint32 number.
        ASSERT(key->IsNumber());
        double num = key->Number();
        char arr[100];
        Vector<char> buffer(arr, ARRAY_SIZE(arr));
        const char* str = DoubleToCString(num, buffer);
        Handle<String> name = Factory::NewStringFromAscii(CStrVector(str));
353 354
        result = SetLocalPropertyIgnoreAttributes(boilerplate, name,
                                                  value, NONE);
355
      }
356 357 358 359
      // If setting the property on the boilerplate throws an
      // exception, the exception is converted to an empty handle in
      // the handle based operations.  In that case, we need to
      // convert back to an exception.
360
      if (result.is_null()) return result;
361 362 363
    }
  }

364 365 366 367 368 369 370 371 372 373 374 375
  return boilerplate;
}


static Handle<Object> CreateArrayLiteralBoilerplate(
    Handle<FixedArray> literals,
    Handle<FixedArray> elements) {
  // Create the JSArray.
  Handle<JSFunction> constructor(
      JSFunction::GlobalContextFromLiterals(*literals)->array_function());
  Handle<Object> object = Factory::NewJSObject(constructor);

376 377 378
  const bool is_cow = (elements->map() == Heap::fixed_cow_array_map());
  Handle<FixedArray> copied_elements =
      is_cow ? elements : Factory::CopyFixedArray(elements);
379 380

  Handle<FixedArray> content = Handle<FixedArray>::cast(copied_elements);
381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398
  if (is_cow) {
#ifdef DEBUG
    // Copy-on-write arrays must be shallow (and simple).
    for (int i = 0; i < content->length(); i++) {
      ASSERT(!content->get(i)->IsFixedArray());
    }
#endif
  } else {
    for (int i = 0; i < content->length(); i++) {
      if (content->get(i)->IsFixedArray()) {
        // The value contains the constant_properties of a
        // simple object literal.
        Handle<FixedArray> fa(FixedArray::cast(content->get(i)));
        Handle<Object> result =
            CreateLiteralBoilerplate(literals, fa);
        if (result.is_null()) return result;
        content->set(i, *result);
      }
399 400 401 402 403 404 405 406 407 408 409 410 411 412
    }
  }

  // Set the elements.
  Handle<JSArray>::cast(object)->SetContent(*content);
  return object;
}


static Handle<Object> CreateLiteralBoilerplate(
    Handle<FixedArray> literals,
    Handle<FixedArray> array) {
  Handle<FixedArray> elements = CompileTimeValue::GetElements(array);
  switch (CompileTimeValue::GetType(array)) {
413 414 415 416
    case CompileTimeValue::OBJECT_LITERAL_FAST_ELEMENTS:
      return CreateObjectLiteralBoilerplate(literals, elements, true);
    case CompileTimeValue::OBJECT_LITERAL_SLOW_ELEMENTS:
      return CreateObjectLiteralBoilerplate(literals, elements, false);
417 418 419 420 421 422 423 424 425
    case CompileTimeValue::ARRAY_LITERAL:
      return CreateArrayLiteralBoilerplate(literals, elements);
    default:
      UNREACHABLE();
      return Handle<Object>::null();
  }
}


426
static MaybeObject* Runtime_CreateArrayLiteralBoilerplate(Arguments args) {
427 428 429
  // Takes a FixedArray of elements containing the literal elements of
  // the array literal and produces JSArray with those elements.
  // Additionally takes the literals array of the surrounding function
430 431
  // which contains the context from which to get the Array function
  // to use for creating the array literal.
432 433 434 435 436
  HandleScope scope;
  ASSERT(args.length() == 3);
  CONVERT_ARG_CHECKED(FixedArray, literals, 0);
  CONVERT_SMI_CHECKED(literals_index, args[1]);
  CONVERT_ARG_CHECKED(FixedArray, elements, 2);
437

438 439
  Handle<Object> object = CreateArrayLiteralBoilerplate(literals, elements);
  if (object.is_null()) return Failure::Exception();
440

441 442 443
  // Update the functions literal and return the boilerplate.
  literals->set(literals_index, *object);
  return *object;
444 445 446
}


447
static MaybeObject* Runtime_CreateObjectLiteral(Arguments args) {
448
  HandleScope scope;
449
  ASSERT(args.length() == 4);
450 451 452
  CONVERT_ARG_CHECKED(FixedArray, literals, 0);
  CONVERT_SMI_CHECKED(literals_index, args[1]);
  CONVERT_ARG_CHECKED(FixedArray, constant_properties, 2);
453 454
  CONVERT_SMI_CHECKED(fast_elements, args[3]);
  bool should_have_fast_elements = fast_elements == 1;
455 456 457 458

  // Check if boilerplate exists. If not, create it first.
  Handle<Object> boilerplate(literals->get(literals_index));
  if (*boilerplate == Heap::undefined_value()) {
459 460 461
    boilerplate = CreateObjectLiteralBoilerplate(literals,
                                                 constant_properties,
                                                 should_have_fast_elements);
462 463 464 465 466 467 468 469
    if (boilerplate.is_null()) return Failure::Exception();
    // Update the functions literal and return the boilerplate.
    literals->set(literals_index, *boilerplate);
  }
  return DeepCopyBoilerplate(JSObject::cast(*boilerplate));
}


470
static MaybeObject* Runtime_CreateObjectLiteralShallow(Arguments args) {
471
  HandleScope scope;
472
  ASSERT(args.length() == 4);
473 474 475
  CONVERT_ARG_CHECKED(FixedArray, literals, 0);
  CONVERT_SMI_CHECKED(literals_index, args[1]);
  CONVERT_ARG_CHECKED(FixedArray, constant_properties, 2);
476 477
  CONVERT_SMI_CHECKED(fast_elements, args[3]);
  bool should_have_fast_elements = fast_elements == 1;
478 479 480 481

  // Check if boilerplate exists. If not, create it first.
  Handle<Object> boilerplate(literals->get(literals_index));
  if (*boilerplate == Heap::undefined_value()) {
482 483 484
    boilerplate = CreateObjectLiteralBoilerplate(literals,
                                                 constant_properties,
                                                 should_have_fast_elements);
485 486 487 488 489 490 491 492
    if (boilerplate.is_null()) return Failure::Exception();
    // Update the functions literal and return the boilerplate.
    literals->set(literals_index, *boilerplate);
  }
  return Heap::CopyJSObject(JSObject::cast(*boilerplate));
}


493
static MaybeObject* Runtime_CreateArrayLiteral(Arguments args) {
494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511
  HandleScope scope;
  ASSERT(args.length() == 3);
  CONVERT_ARG_CHECKED(FixedArray, literals, 0);
  CONVERT_SMI_CHECKED(literals_index, args[1]);
  CONVERT_ARG_CHECKED(FixedArray, elements, 2);

  // Check if boilerplate exists. If not, create it first.
  Handle<Object> boilerplate(literals->get(literals_index));
  if (*boilerplate == Heap::undefined_value()) {
    boilerplate = CreateArrayLiteralBoilerplate(literals, elements);
    if (boilerplate.is_null()) return Failure::Exception();
    // Update the functions literal and return the boilerplate.
    literals->set(literals_index, *boilerplate);
  }
  return DeepCopyBoilerplate(JSObject::cast(*boilerplate));
}


512
static MaybeObject* Runtime_CreateArrayLiteralShallow(Arguments args) {
513 514 515 516 517 518 519 520 521 522 523 524 525 526
  HandleScope scope;
  ASSERT(args.length() == 3);
  CONVERT_ARG_CHECKED(FixedArray, literals, 0);
  CONVERT_SMI_CHECKED(literals_index, args[1]);
  CONVERT_ARG_CHECKED(FixedArray, elements, 2);

  // Check if boilerplate exists. If not, create it first.
  Handle<Object> boilerplate(literals->get(literals_index));
  if (*boilerplate == Heap::undefined_value()) {
    boilerplate = CreateArrayLiteralBoilerplate(literals, elements);
    if (boilerplate.is_null()) return Failure::Exception();
    // Update the functions literal and return the boilerplate.
    literals->set(literals_index, *boilerplate);
  }
527 528 529 530
  if (JSObject::cast(*boilerplate)->elements()->map() ==
      Heap::fixed_cow_array_map()) {
    Counters::cow_arrays_created_runtime.Increment();
  }
531 532 533 534
  return Heap::CopyJSObject(JSObject::cast(*boilerplate));
}


535
static MaybeObject* Runtime_CreateCatchExtensionObject(Arguments args) {
536 537 538 539 540 541
  ASSERT(args.length() == 2);
  CONVERT_CHECKED(String, key, args[0]);
  Object* value = args[1];
  // Create a catch context extension object.
  JSFunction* constructor =
      Top::context()->global_context()->context_extension_function();
542 543 544 545
  Object* object;
  { MaybeObject* maybe_object = Heap::AllocateJSObject(constructor);
    if (!maybe_object->ToObject(&object)) return maybe_object;
  }
546 547
  // Assign the exception value to the catch variable and make sure
  // that the catch variable is DontDelete.
548 549 550 551
  { MaybeObject* maybe_value =
        JSObject::cast(object)->SetProperty(key, value, DONT_DELETE);
    if (!maybe_value->ToObject(&value)) return maybe_value;
  }
552 553 554 555
  return object;
}


556
static MaybeObject* Runtime_ClassOf(Arguments args) {
557 558 559 560 561 562 563
  NoHandleAllocation ha;
  ASSERT(args.length() == 1);
  Object* obj = args[0];
  if (!obj->IsJSObject()) return Heap::null_value();
  return JSObject::cast(obj)->class_name();
}

564

565
static MaybeObject* Runtime_IsInPrototypeChain(Arguments args) {
566 567 568 569 570 571 572 573 574 575 576 577 578 579
  NoHandleAllocation ha;
  ASSERT(args.length() == 2);
  // See ECMA-262, section 15.3.5.3, page 88 (steps 5 - 8).
  Object* O = args[0];
  Object* V = args[1];
  while (true) {
    Object* prototype = V->GetPrototype();
    if (prototype->IsNull()) return Heap::false_value();
    if (O == prototype) return Heap::true_value();
    V = prototype;
  }
}


580
// Inserts an object as the hidden prototype of another object.
581
static MaybeObject* Runtime_SetHiddenPrototype(Arguments args) {
582 583 584 585 586 587 588 589 590 591 592 593 594
  NoHandleAllocation ha;
  ASSERT(args.length() == 2);
  CONVERT_CHECKED(JSObject, jsobject, args[0]);
  CONVERT_CHECKED(JSObject, proto, args[1]);

  // Sanity checks.  The old prototype (that we are replacing) could
  // theoretically be null, but if it is not null then check that we
  // didn't already install a hidden prototype here.
  RUNTIME_ASSERT(!jsobject->GetPrototype()->IsHeapObject() ||
    !HeapObject::cast(jsobject->GetPrototype())->map()->is_hidden_prototype());
  RUNTIME_ASSERT(!proto->map()->is_hidden_prototype());

  // Allocate up front before we start altering state in case we get a GC.
595 596 597 598 599 600
  Object* map_or_failure;
  { MaybeObject* maybe_map_or_failure = proto->map()->CopyDropTransitions();
    if (!maybe_map_or_failure->ToObject(&map_or_failure)) {
      return maybe_map_or_failure;
    }
  }
601 602
  Map* new_proto_map = Map::cast(map_or_failure);

603 604 605 606 607
  { MaybeObject* maybe_map_or_failure = jsobject->map()->CopyDropTransitions();
    if (!maybe_map_or_failure->ToObject(&map_or_failure)) {
      return maybe_map_or_failure;
    }
  }
608 609 610 611 612 613 614 615 616 617 618 619 620 621 622
  Map* new_map = Map::cast(map_or_failure);

  // Set proto's prototype to be the old prototype of the object.
  new_proto_map->set_prototype(jsobject->GetPrototype());
  proto->set_map(new_proto_map);
  new_proto_map->set_is_hidden_prototype();

  // Set the object's prototype to proto.
  new_map->set_prototype(proto);
  jsobject->set_map(new_map);

  return Heap::undefined_value();
}


623
static MaybeObject* Runtime_IsConstructCall(Arguments args) {
624
  NoHandleAllocation ha;
625
  ASSERT(args.length() == 0);
626 627 628 629 630
  JavaScriptFrameIterator it;
  return Heap::ToBoolean(it.frame()->IsConstructor());
}


631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646
// Recursively traverses hidden prototypes if property is not found
static void GetOwnPropertyImplementation(JSObject* obj,
                                         String* name,
                                         LookupResult* result) {
  obj->LocalLookupRealNamedProperty(name, result);

  if (!result->IsProperty()) {
    Object* proto = obj->GetPrototype();
    if (proto->IsJSObject() &&
      JSObject::cast(proto)->map()->is_hidden_prototype())
      GetOwnPropertyImplementation(JSObject::cast(proto),
                                   name, result);
  }
}


647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 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 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717
static bool CheckAccessException(LookupResult* result,
                                 v8::AccessType access_type) {
  if (result->type() == CALLBACKS) {
    Object* callback = result->GetCallbackObject();
    if (callback->IsAccessorInfo()) {
      AccessorInfo* info = AccessorInfo::cast(callback);
      bool can_access =
          (access_type == v8::ACCESS_HAS &&
              (info->all_can_read() || info->all_can_write())) ||
          (access_type == v8::ACCESS_GET && info->all_can_read()) ||
          (access_type == v8::ACCESS_SET && info->all_can_write());
      return can_access;
    }
  }

  return false;
}


static bool CheckAccess(JSObject* obj,
                        String* name,
                        LookupResult* result,
                        v8::AccessType access_type) {
  ASSERT(result->IsProperty());

  JSObject* holder = result->holder();
  JSObject* current = obj;
  while (true) {
    if (current->IsAccessCheckNeeded() &&
        !Top::MayNamedAccess(current, name, access_type)) {
      // Access check callback denied the access, but some properties
      // can have a special permissions which override callbacks descision
      // (currently see v8::AccessControl).
      break;
    }

    if (current == holder) {
      return true;
    }

    current = JSObject::cast(current->GetPrototype());
  }

  // API callbacks can have per callback access exceptions.
  switch (result->type()) {
    case CALLBACKS: {
      if (CheckAccessException(result, access_type)) {
        return true;
      }
      break;
    }
    case INTERCEPTOR: {
      // If the object has an interceptor, try real named properties.
      // Overwrite the result to fetch the correct property later.
      holder->LookupRealNamedProperty(name, result);
      if (result->IsProperty()) {
        if (CheckAccessException(result, access_type)) {
          return true;
        }
      }
      break;
    }
    default:
      break;
  }

  Top::ReportFailedAccessCheck(current, access_type);
  return false;
}


718 719 720 721 722 723 724 725 726 727 728 729 730
// TODO(1095): we should traverse hidden prototype hierachy as well.
static bool CheckElementAccess(JSObject* obj,
                               uint32_t index,
                               v8::AccessType access_type) {
  if (obj->IsAccessCheckNeeded() &&
      !Top::MayIndexedAccess(obj, index, access_type)) {
    return false;
  }

  return true;
}


731 732 733 734 735 736 737 738 739 740 741 742
// Enumerator used as indices into the array returned from GetOwnProperty
enum PropertyDescriptorIndices {
  IS_ACCESSOR_INDEX,
  VALUE_INDEX,
  GETTER_INDEX,
  SETTER_INDEX,
  WRITABLE_INDEX,
  ENUMERABLE_INDEX,
  CONFIGURABLE_INDEX,
  DESCRIPTOR_SIZE
};

743 744 745 746 747 748 749
// Returns an array with the property description:
//  if args[1] is not a property on args[0]
//          returns undefined
//  if args[1] is a data property on args[0]
//         [false, value, Writeable, Enumerable, Configurable]
//  if args[1] is an accessor on args[0]
//         [true, GetFunction, SetFunction, Enumerable, Configurable]
750
static MaybeObject* Runtime_GetOwnProperty(Arguments args) {
antonm@chromium.org's avatar
antonm@chromium.org committed
751
  ASSERT(args.length() == 2);
752
  HandleScope scope;
753
  Handle<FixedArray> elms = Factory::NewFixedArray(DESCRIPTOR_SIZE);
754 755
  Handle<JSArray> desc = Factory::NewJSArrayWithElements(elms);
  LookupResult result;
756 757
  CONVERT_ARG_CHECKED(JSObject, obj, 0);
  CONVERT_ARG_CHECKED(String, name, 1);
758

759 760 761
  // This could be an element.
  uint32_t index;
  if (name->AsArrayIndex(&index)) {
762 763 764 765 766 767 768 769 770
    switch (obj->HasLocalElement(index)) {
      case JSObject::UNDEFINED_ELEMENT:
        return Heap::undefined_value();

      case JSObject::STRING_CHARACTER_ELEMENT: {
        // Special handling of string objects according to ECMAScript 5
        // 15.5.5.2. Note that this might be a string object with elements
        // other than the actual string value. This is covered by the
        // subsequent cases.
771 772
        Handle<JSValue> js_value = Handle<JSValue>::cast(obj);
        Handle<String> str(String::cast(js_value->value()));
773
        Handle<String> substr = SubString(str, index, index + 1, NOT_TENURED);
774

775
        elms->set(IS_ACCESSOR_INDEX, Heap::false_value());
776
        elms->set(VALUE_INDEX, *substr);
777 778 779 780 781
        elms->set(WRITABLE_INDEX, Heap::false_value());
        elms->set(ENUMERABLE_INDEX,  Heap::false_value());
        elms->set(CONFIGURABLE_INDEX, Heap::false_value());
        return *desc;
      }
782

783
      case JSObject::INTERCEPTED_ELEMENT:
784
      case JSObject::FAST_ELEMENT: {
785
        elms->set(IS_ACCESSOR_INDEX, Heap::false_value());
786
        elms->set(VALUE_INDEX, *GetElement(obj, index));
787 788 789 790
        elms->set(WRITABLE_INDEX, Heap::true_value());
        elms->set(ENUMERABLE_INDEX,  Heap::true_value());
        elms->set(CONFIGURABLE_INDEX, Heap::true_value());
        return *desc;
791
      }
792 793

      case JSObject::DICTIONARY_ELEMENT: {
794
        Handle<JSObject> holder = obj;
795 796 797 798
        if (obj->IsJSGlobalProxy()) {
          Object* proto = obj->GetPrototype();
          if (proto->IsNull()) return Heap::undefined_value();
          ASSERT(proto->IsJSGlobalObject());
799
          holder = Handle<JSObject>(JSObject::cast(proto));
800
        }
801
        NumberDictionary* dictionary = holder->element_dictionary();
802 803 804 805 806 807 808 809 810
        int entry = dictionary->FindEntry(index);
        ASSERT(entry != NumberDictionary::kNotFound);
        PropertyDetails details = dictionary->DetailsAt(entry);
        switch (details.type()) {
          case CALLBACKS: {
            // This is an accessor property with getter and/or setter.
            FixedArray* callbacks =
                FixedArray::cast(dictionary->ValueAt(entry));
            elms->set(IS_ACCESSOR_INDEX, Heap::true_value());
811 812 813 814 815 816
            if (CheckElementAccess(*obj, index, v8::ACCESS_GET)) {
              elms->set(GETTER_INDEX, callbacks->get(0));
            }
            if (CheckElementAccess(*obj, index, v8::ACCESS_SET)) {
              elms->set(SETTER_INDEX, callbacks->get(1));
            }
817 818 819 820 821
            break;
          }
          case NORMAL:
            // This is a data property.
            elms->set(IS_ACCESSOR_INDEX, Heap::false_value());
822
            elms->set(VALUE_INDEX, *GetElement(obj, index));
823 824 825 826 827 828 829 830 831 832
            elms->set(WRITABLE_INDEX, Heap::ToBoolean(!details.IsReadOnly()));
            break;
          default:
            UNREACHABLE();
            break;
        }
        elms->set(ENUMERABLE_INDEX, Heap::ToBoolean(!details.IsDontEnum()));
        elms->set(CONFIGURABLE_INDEX, Heap::ToBoolean(!details.IsDontDelete()));
        return *desc;
      }
833 834 835
    }
  }

836
  // Use recursive implementation to also traverse hidden prototypes
837
  GetOwnPropertyImplementation(*obj, *name, &result);
838

839
  if (!result.IsProperty()) {
840
    return Heap::undefined_value();
841
  }
842

843 844 845 846
  if (!CheckAccess(*obj, *name, &result, v8::ACCESS_HAS)) {
    return Heap::undefined_value();
  }

847 848 849 850 851 852 853 854 855
  elms->set(ENUMERABLE_INDEX, Heap::ToBoolean(!result.IsDontEnum()));
  elms->set(CONFIGURABLE_INDEX, Heap::ToBoolean(!result.IsDontDelete()));

  bool is_js_accessor = (result.type() == CALLBACKS) &&
                        (result.GetCallbackObject()->IsFixedArray());

  if (is_js_accessor) {
    // __defineGetter__/__defineSetter__ callback.
    elms->set(IS_ACCESSOR_INDEX, Heap::true_value());
856 857 858 859 860 861 862 863

    FixedArray* structure = FixedArray::cast(result.GetCallbackObject());
    if (CheckAccess(*obj, *name, &result, v8::ACCESS_GET)) {
      elms->set(GETTER_INDEX, structure->get(0));
    }
    if (CheckAccess(*obj, *name, &result, v8::ACCESS_SET)) {
      elms->set(SETTER_INDEX, structure->get(1));
    }
864
  } else {
865 866
    elms->set(IS_ACCESSOR_INDEX, Heap::false_value());
    elms->set(WRITABLE_INDEX, Heap::ToBoolean(!result.IsReadOnly()));
867 868 869

    PropertyAttributes attrs;
    Object* value;
870
    // GetProperty will check access and report any violations.
871 872 873 874
    { MaybeObject* maybe_value = obj->GetProperty(*obj, &result, *name, &attrs);
      if (!maybe_value->ToObject(&value)) return maybe_value;
    }
    elms->set(VALUE_INDEX, value);
875 876 877 878 879 880
  }

  return *desc;
}


881
static MaybeObject* Runtime_PreventExtensions(Arguments args) {
882 883 884 885 886
  ASSERT(args.length() == 1);
  CONVERT_CHECKED(JSObject, obj, args[0]);
  return obj->PreventExtensions();
}

887
static MaybeObject* Runtime_IsExtensible(Arguments args) {
888 889 890 891 892 893 894
  ASSERT(args.length() == 1);
  CONVERT_CHECKED(JSObject, obj, args[0]);
  return obj->map()->is_extensible() ?  Heap::true_value()
                                     : Heap::false_value();
}


895
static MaybeObject* Runtime_RegExpCompile(Arguments args) {
896
  HandleScope scope;
897
  ASSERT(args.length() == 3);
898 899 900
  CONVERT_ARG_CHECKED(JSRegExp, re, 0);
  CONVERT_ARG_CHECKED(String, pattern, 1);
  CONVERT_ARG_CHECKED(String, flags, 2);
901 902 903
  Handle<Object> result = RegExpImpl::Compile(re, pattern, flags);
  if (result.is_null()) return Failure::Exception();
  return *result;
904 905 906
}


907
static MaybeObject* Runtime_CreateApiFunction(Arguments args) {
908 909
  HandleScope scope;
  ASSERT(args.length() == 1);
910
  CONVERT_ARG_CHECKED(FunctionTemplateInfo, data, 0);
911 912 913 914
  return *Factory::CreateApiFunction(data);
}


915
static MaybeObject* Runtime_IsTemplate(Arguments args) {
916 917
  ASSERT(args.length() == 1);
  Object* arg = args[0];
918
  bool result = arg->IsObjectTemplateInfo() || arg->IsFunctionTemplateInfo();
919 920 921 922
  return Heap::ToBoolean(result);
}


923
static MaybeObject* Runtime_GetTemplateField(Arguments args) {
924 925 926
  ASSERT(args.length() == 2);
  CONVERT_CHECKED(HeapObject, templ, args[0]);
  CONVERT_CHECKED(Smi, field, args[1]);
927 928 929 930 931 932
  int index = field->value();
  int offset = index * kPointerSize + HeapObject::kHeaderSize;
  InstanceType type = templ->map()->instance_type();
  RUNTIME_ASSERT(type ==  FUNCTION_TEMPLATE_INFO_TYPE ||
                 type ==  OBJECT_TEMPLATE_INFO_TYPE);
  RUNTIME_ASSERT(offset > 0);
933
  if (type == FUNCTION_TEMPLATE_INFO_TYPE) {
934 935 936 937 938
    RUNTIME_ASSERT(offset < FunctionTemplateInfo::kSize);
  } else {
    RUNTIME_ASSERT(offset < ObjectTemplateInfo::kSize);
  }
  return *HeapObject::RawField(templ, offset);
939 940 941
}


942
static MaybeObject* Runtime_DisableAccessChecks(Arguments args) {
943 944
  ASSERT(args.length() == 1);
  CONVERT_CHECKED(HeapObject, object, args[0]);
945 946 947 948
  Map* old_map = object->map();
  bool needs_access_checks = old_map->is_access_check_needed();
  if (needs_access_checks) {
    // Copy map so it won't interfere constructor's initial map.
949 950 951 952
    Object* new_map;
    { MaybeObject* maybe_new_map = old_map->CopyDropTransitions();
      if (!maybe_new_map->ToObject(&new_map)) return maybe_new_map;
    }
953 954 955 956

    Map::cast(new_map)->set_is_access_check_needed(false);
    object->set_map(Map::cast(new_map));
  }
957 958 959 960
  return needs_access_checks ? Heap::true_value() : Heap::false_value();
}


961
static MaybeObject* Runtime_EnableAccessChecks(Arguments args) {
962 963
  ASSERT(args.length() == 1);
  CONVERT_CHECKED(HeapObject, object, args[0]);
964 965 966
  Map* old_map = object->map();
  if (!old_map->is_access_check_needed()) {
    // Copy map so it won't interfere constructor's initial map.
967 968 969 970
    Object* new_map;
    { MaybeObject* maybe_new_map = old_map->CopyDropTransitions();
      if (!maybe_new_map->ToObject(&new_map)) return maybe_new_map;
    }
971 972 973 974

    Map::cast(new_map)->set_is_access_check_needed(true);
    object->set_map(Map::cast(new_map));
  }
975 976 977 978
  return Heap::undefined_value();
}


979
static Failure* ThrowRedeclarationError(const char* type, Handle<String> name) {
980 981 982 983 984 985 986 987 988
  HandleScope scope;
  Handle<Object> type_handle = Factory::NewStringFromAscii(CStrVector(type));
  Handle<Object> args[2] = { type_handle, name };
  Handle<Object> error =
      Factory::NewTypeError("redeclaration", HandleVector(args, 2));
  return Top::Throw(*error);
}


989
static MaybeObject* Runtime_DeclareGlobals(Arguments args) {
990 991 992
  HandleScope scope;
  Handle<GlobalObject> global = Handle<GlobalObject>(Top::context()->global());

993 994
  Handle<Context> context = args.at<Context>(0);
  CONVERT_ARG_CHECKED(FixedArray, pairs, 1);
995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057
  bool is_eval = Smi::cast(args[2])->value() == 1;

  // Compute the property attributes. According to ECMA-262, section
  // 13, page 71, the property must be read-only and
  // non-deletable. However, neither SpiderMonkey nor KJS creates the
  // property as read-only, so we don't either.
  PropertyAttributes base = is_eval ? NONE : DONT_DELETE;

  // Traverse the name/value pairs and set the properties.
  int length = pairs->length();
  for (int i = 0; i < length; i += 2) {
    HandleScope scope;
    Handle<String> name(String::cast(pairs->get(i)));
    Handle<Object> value(pairs->get(i + 1));

    // We have to declare a global const property. To capture we only
    // assign to it when evaluating the assignment for "const x =
    // <expr>" the initial value is the hole.
    bool is_const_property = value->IsTheHole();

    if (value->IsUndefined() || is_const_property) {
      // Lookup the property in the global object, and don't set the
      // value of the variable if the property is already there.
      LookupResult lookup;
      global->Lookup(*name, &lookup);
      if (lookup.IsProperty()) {
        // Determine if the property is local by comparing the holder
        // against the global object. The information will be used to
        // avoid throwing re-declaration errors when declaring
        // variables or constants that exist in the prototype chain.
        bool is_local = (*global == lookup.holder());
        // Get the property attributes and determine if the property is
        // read-only.
        PropertyAttributes attributes = global->GetPropertyAttribute(*name);
        bool is_read_only = (attributes & READ_ONLY) != 0;
        if (lookup.type() == INTERCEPTOR) {
          // If the interceptor says the property is there, we
          // just return undefined without overwriting the property.
          // Otherwise, we continue to setting the property.
          if (attributes != ABSENT) {
            // Check if the existing property conflicts with regards to const.
            if (is_local && (is_read_only || is_const_property)) {
              const char* type = (is_read_only) ? "const" : "var";
              return ThrowRedeclarationError(type, name);
            };
            // The property already exists without conflicting: Go to
            // the next declaration.
            continue;
          }
          // Fall-through and introduce the absent property by using
          // SetProperty.
        } else {
          if (is_local && (is_read_only || is_const_property)) {
            const char* type = (is_read_only) ? "const" : "var";
            return ThrowRedeclarationError(type, name);
          }
          // The property already exists without conflicting: Go to
          // the next declaration.
          continue;
        }
      }
    } else {
      // Copy the function and update its context. Use it as value.
1058 1059
      Handle<SharedFunctionInfo> shared =
          Handle<SharedFunctionInfo>::cast(value);
1060
      Handle<JSFunction> function =
1061
          Factory::NewFunctionFromSharedFunctionInfo(shared, context, TENURED);
1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092
      value = function;
    }

    LookupResult lookup;
    global->LocalLookup(*name, &lookup);

    PropertyAttributes attributes = is_const_property
        ? static_cast<PropertyAttributes>(base | READ_ONLY)
        : base;

    if (lookup.IsProperty()) {
      // There's a local property that we need to overwrite because
      // we're either declaring a function or there's an interceptor
      // that claims the property is absent.

      // Check for conflicting re-declarations. We cannot have
      // conflicting types in case of intercepted properties because
      // they are absent.
      if (lookup.type() != INTERCEPTOR &&
          (lookup.IsReadOnly() || is_const_property)) {
        const char* type = (lookup.IsReadOnly()) ? "const" : "var";
        return ThrowRedeclarationError(type, name);
      }
      SetProperty(global, name, value, attributes);
    } else {
      // If a property with this name does not already exist on the
      // global object add the property locally.  We take special
      // precautions to always add it as a local property even in case
      // of callbacks in the prototype chain (this rules out using
      // SetProperty).  Also, we must use the handle-based version to
      // avoid GC issues.
1093
      SetLocalPropertyIgnoreAttributes(global, name, value, attributes);
1094 1095
    }
  }
1096

1097 1098 1099 1100
  return Heap::undefined_value();
}


1101
static MaybeObject* Runtime_DeclareContextSlot(Arguments args) {
1102
  HandleScope scope;
1103
  ASSERT(args.length() == 4);
1104

1105 1106
  CONVERT_ARG_CHECKED(Context, context, 0);
  Handle<String> name(String::cast(args[1]));
1107
  PropertyAttributes mode =
1108
      static_cast<PropertyAttributes>(Smi::cast(args[2])->value());
1109
  RUNTIME_ASSERT(mode == READ_ONLY || mode == NONE);
1110
  Handle<Object> initial_value(args[3]);
1111 1112 1113 1114 1115 1116 1117

  // Declarations are always done in the function context.
  context = Handle<Context>(context->fcontext());

  int index;
  PropertyAttributes attributes;
  ContextLookupFlags flags = DONT_FOLLOW_CHAINS;
1118
  Handle<Object> holder =
1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135
      context->Lookup(name, flags, &index, &attributes);

  if (attributes != ABSENT) {
    // The name was declared before; check for conflicting
    // re-declarations: This is similar to the code in parser.cc in
    // the AstBuildingParser::Declare function.
    if (((attributes & READ_ONLY) != 0) || (mode == READ_ONLY)) {
      // Functions are not read-only.
      ASSERT(mode != READ_ONLY || initial_value->IsTheHole());
      const char* type = ((attributes & READ_ONLY) != 0) ? "const" : "var";
      return ThrowRedeclarationError(type, name);
    }

    // Initialize it if necessary.
    if (*initial_value != NULL) {
      if (index >= 0) {
        // The variable or constant context slot should always be in
1136 1137 1138 1139 1140 1141 1142 1143
        // the function context or the arguments object.
        if (holder->IsContext()) {
          ASSERT(holder.is_identical_to(context));
          if (((attributes & READ_ONLY) == 0) ||
              context->get(index)->IsTheHole()) {
            context->set(index, *initial_value);
          }
        } else {
1144 1145 1146
          // The holder is an arguments object.
          Handle<JSObject> arguments(Handle<JSObject>::cast(holder));
          SetElement(arguments, index, initial_value);
1147 1148 1149
        }
      } else {
        // Slow case: The property is not in the FixedArray part of the context.
1150
        Handle<JSObject> context_ext = Handle<JSObject>::cast(holder);
1151 1152 1153 1154 1155
        SetProperty(context_ext, name, initial_value, mode);
      }
    }

  } else {
1156 1157 1158 1159
    // The property is not in the function context. It needs to be
    // "declared" in the function context's extension context, or in the
    // global context.
    Handle<JSObject> context_ext;
1160
    if (context->has_extension()) {
1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179
      // The function context's extension context exists - use it.
      context_ext = Handle<JSObject>(context->extension());
    } else {
      // The function context's extension context does not exists - allocate
      // it.
      context_ext = Factory::NewJSObject(Top::context_extension_function());
      // And store it in the extension slot.
      context->set_extension(*context_ext);
    }
    ASSERT(*context_ext != NULL);

    // Declare the property by setting it to the initial value if provided,
    // or undefined, and use the correct mode (e.g. READ_ONLY attribute for
    // constant declarations).
    ASSERT(!context_ext->HasLocalProperty(*name));
    Handle<Object> value(Heap::undefined_value());
    if (*initial_value != NULL) value = initial_value;
    SetProperty(context_ext, name, value, mode);
    ASSERT(context_ext->GetLocalPropertyAttribute(*name) == mode);
1180
  }
1181 1182

  return Heap::undefined_value();
1183 1184 1185
}


1186
static MaybeObject* Runtime_InitializeVarGlobal(Arguments args) {
1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201
  NoHandleAllocation nha;

  // Determine if we need to assign to the variable if it already
  // exists (based on the number of arguments).
  RUNTIME_ASSERT(args.length() == 1 || args.length() == 2);
  bool assign = args.length() == 2;

  CONVERT_ARG_CHECKED(String, name, 0);
  GlobalObject* global = Top::context()->global();

  // According to ECMA-262, section 12.2, page 62, the property must
  // not be deletable.
  PropertyAttributes attributes = DONT_DELETE;

  // Lookup the property locally in the global object. If it isn't
1202 1203 1204 1205 1206 1207
  // there, there is a property with this name in the prototype chain.
  // We follow Safari and Firefox behavior and only set the property
  // locally if there is an explicit initialization value that we have
  // to assign to the property. When adding the property we take
  // special precautions to always add it as a local property even in
  // case of callbacks in the prototype chain (this rules out using
1208
  // SetProperty).  We have SetLocalPropertyIgnoreAttributes for
1209
  // this.
1210 1211 1212
  // Note that objects can have hidden prototypes, so we need to traverse
  // the whole chain of hidden prototypes to do a 'local' lookup.
  JSObject* real_holder = global;
1213
  LookupResult lookup;
1214 1215 1216 1217 1218 1219 1220 1221 1222 1223
  while (true) {
    real_holder->LocalLookup(*name, &lookup);
    if (lookup.IsProperty()) {
      // Determine if this is a redeclaration of something read-only.
      if (lookup.IsReadOnly()) {
        // If we found readonly property on one of hidden prototypes,
        // just shadow it.
        if (real_holder != Top::context()->global()) break;
        return ThrowRedeclarationError("const", name);
      }
1224

1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246
      // Determine if this is a redeclaration of an intercepted read-only
      // property and figure out if the property exists at all.
      bool found = true;
      PropertyType type = lookup.type();
      if (type == INTERCEPTOR) {
        HandleScope handle_scope;
        Handle<JSObject> holder(real_holder);
        PropertyAttributes intercepted = holder->GetPropertyAttribute(*name);
        real_holder = *holder;
        if (intercepted == ABSENT) {
          // The interceptor claims the property isn't there. We need to
          // make sure to introduce it.
          found = false;
        } else if ((intercepted & READ_ONLY) != 0) {
          // The property is present, but read-only. Since we're trying to
          // overwrite it with a variable declaration we must throw a
          // re-declaration error.  However if we found readonly property
          // on one of hidden prototypes, just shadow it.
          if (real_holder != Top::context()->global()) break;
          return ThrowRedeclarationError("const", name);
        }
      }
1247

1248 1249 1250 1251 1252 1253 1254 1255 1256
      if (found && !assign) {
        // The global property is there and we're not assigning any value
        // to it. Just return.
        return Heap::undefined_value();
      }

      // Assign the value (or undefined) to the property.
      Object* value = (assign) ? args[1] : Heap::undefined_value();
      return real_holder->SetProperty(&lookup, *name, value, attributes);
1257 1258
    }

1259 1260 1261 1262 1263 1264 1265 1266
    Object* proto = real_holder->GetPrototype();
    if (!proto->IsJSObject())
      break;

    if (!JSObject::cast(proto)->map()->is_hidden_prototype())
      break;

    real_holder = JSObject::cast(proto);
1267 1268
  }

1269 1270
  global = Top::context()->global();
  if (assign) {
1271 1272 1273
    return global->SetLocalPropertyIgnoreAttributes(*name,
                                                    args[1],
                                                    attributes);
1274 1275
  }
  return Heap::undefined_value();
1276 1277 1278
}


1279
static MaybeObject* Runtime_InitializeConstGlobal(Arguments args) {
1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298
  // All constants are declared with an initial value. The name
  // of the constant is the first argument and the initial value
  // is the second.
  RUNTIME_ASSERT(args.length() == 2);
  CONVERT_ARG_CHECKED(String, name, 0);
  Handle<Object> value = args.at<Object>(1);

  // Get the current global object from top.
  GlobalObject* global = Top::context()->global();

  // According to ECMA-262, section 12.2, page 62, the property must
  // not be deletable. Since it's a const, it must be READ_ONLY too.
  PropertyAttributes attributes =
      static_cast<PropertyAttributes>(DONT_DELETE | READ_ONLY);

  // Lookup the property locally in the global object. If it isn't
  // there, we add the property and take special precautions to always
  // add it as a local property even in case of callbacks in the
  // prototype chain (this rules out using SetProperty).
1299
  // We use SetLocalPropertyIgnoreAttributes instead
1300 1301 1302
  LookupResult lookup;
  global->LocalLookup(*name, &lookup);
  if (!lookup.IsProperty()) {
1303 1304 1305
    return global->SetLocalPropertyIgnoreAttributes(*name,
                                                    *value,
                                                    attributes);
1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326
  }

  // Determine if this is a redeclaration of something not
  // read-only. In case the result is hidden behind an interceptor we
  // need to ask it for the property attributes.
  if (!lookup.IsReadOnly()) {
    if (lookup.type() != INTERCEPTOR) {
      return ThrowRedeclarationError("var", name);
    }

    PropertyAttributes intercepted = global->GetPropertyAttribute(*name);

    // Throw re-declaration error if the intercepted property is present
    // but not read-only.
    if (intercepted != ABSENT && (intercepted & READ_ONLY) == 0) {
      return ThrowRedeclarationError("var", name);
    }

    // Restore global object from context (in case of GC) and continue
    // with setting the value because the property is either absent or
    // read-only. We also have to do redo the lookup.
1327 1328
    HandleScope handle_scope;
    Handle<GlobalObject>global(Top::context()->global());
1329 1330 1331 1332

    // BUG 1213579: Handle the case where we have to set a read-only
    // property through an interceptor and only do it if it's
    // uninitialized, e.g. the hole. Nirk...
1333
    SetProperty(global, name, value, attributes);
1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347
    return *value;
  }

  // Set the value, but only we're assigning the initial value to a
  // constant. For now, we determine this by checking if the
  // current value is the hole.
  PropertyType type = lookup.type();
  if (type == FIELD) {
    FixedArray* properties = global->properties();
    int index = lookup.GetFieldIndex();
    if (properties->get(index)->IsTheHole()) {
      properties->set(index, *value);
    }
  } else if (type == NORMAL) {
1348 1349
    if (global->GetNormalizedProperty(&lookup)->IsTheHole()) {
      global->SetNormalizedProperty(&lookup, *value);
1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361
    }
  } else {
    // Ignore re-initialization of constants that have already been
    // assigned a function value.
    ASSERT(lookup.IsReadOnly() && type == CONSTANT_FUNCTION);
  }

  // Use the set value as the result of the operation.
  return *value;
}


1362
static MaybeObject* Runtime_InitializeConstContextSlot(Arguments args) {
1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375
  HandleScope scope;
  ASSERT(args.length() == 3);

  Handle<Object> value(args[0]);
  ASSERT(!value->IsTheHole());
  CONVERT_ARG_CHECKED(Context, context, 1);
  Handle<String> name(String::cast(args[2]));

  // Initializations are always done in the function context.
  context = Handle<Context>(context->fcontext());

  int index;
  PropertyAttributes attributes;
1376
  ContextLookupFlags flags = FOLLOW_CHAINS;
1377
  Handle<Object> holder =
1378 1379
      context->Lookup(name, flags, &index, &attributes);

1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391
  // In most situations, the property introduced by the const
  // declaration should be present in the context extension object.
  // However, because declaration and initialization are separate, the
  // property might have been deleted (if it was introduced by eval)
  // before we reach the initialization point.
  //
  // Example:
  //
  //    function f() { eval("delete x; const x;"); }
  //
  // In that case, the initialization behaves like a normal assignment
  // to property 'x'.
1392
  if (index >= 0) {
1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404
    // Property was found in a context.
    if (holder->IsContext()) {
      // The holder cannot be the function context.  If it is, there
      // should have been a const redeclaration error when declaring
      // the const property.
      ASSERT(!holder.is_identical_to(context));
      if ((attributes & READ_ONLY) == 0) {
        Handle<Context>::cast(holder)->set(index, *value);
      }
    } else {
      // The holder is an arguments object.
      ASSERT((attributes & READ_ONLY) == 0);
1405 1406
      Handle<JSObject> arguments(Handle<JSObject>::cast(holder));
      SetElement(arguments, index, value);
1407 1408 1409 1410
    }
    return *value;
  }

1411 1412 1413 1414 1415 1416 1417
  // The property could not be found, we introduce it in the global
  // context.
  if (attributes == ABSENT) {
    Handle<JSObject> global = Handle<JSObject>(Top::context()->global());
    SetProperty(global, name, value, NONE);
    return *value;
  }
1418

1419 1420
  // The property was present in a context extension object.
  Handle<JSObject> context_ext = Handle<JSObject>::cast(holder);
1421

1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439
  if (*context_ext == context->extension()) {
    // This is the property that was introduced by the const
    // declaration.  Set it if it hasn't been set before.  NOTE: We
    // cannot use GetProperty() to get the current value as it
    // 'unholes' the value.
    LookupResult lookup;
    context_ext->LocalLookupRealNamedProperty(*name, &lookup);
    ASSERT(lookup.IsProperty());  // the property was declared
    ASSERT(lookup.IsReadOnly());  // and it was declared as read-only

    PropertyType type = lookup.type();
    if (type == FIELD) {
      FixedArray* properties = context_ext->properties();
      int index = lookup.GetFieldIndex();
      if (properties->get(index)->IsTheHole()) {
        properties->set(index, *value);
      }
    } else if (type == NORMAL) {
1440 1441
      if (context_ext->GetNormalizedProperty(&lookup)->IsTheHole()) {
        context_ext->SetNormalizedProperty(&lookup, *value);
1442 1443 1444 1445 1446
      }
    } else {
      // We should not reach here. Any real, named property should be
      // either a field or a dictionary slot.
      UNREACHABLE();
1447 1448
    }
  } else {
1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460
    // The property was found in a different context extension object.
    // Set it if it is not a read-only property.
    if ((attributes & READ_ONLY) == 0) {
      Handle<Object> set = SetProperty(context_ext, name, value, attributes);
      // Setting a property might throw an exception.  Exceptions
      // are converted to empty handles in handle operations.  We
      // need to convert back to exceptions here.
      if (set.is_null()) {
        ASSERT(Top::has_pending_exception());
        return Failure::Exception();
      }
    }
1461
  }
1462

1463 1464 1465 1466
  return *value;
}


1467
static MaybeObject* Runtime_OptimizeObjectForAddingMultipleProperties(
1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479
    Arguments args) {
  HandleScope scope;
  ASSERT(args.length() == 2);
  CONVERT_ARG_CHECKED(JSObject, object, 0);
  CONVERT_SMI_CHECKED(properties, args[1]);
  if (object->HasFastProperties()) {
    NormalizeProperties(object, KEEP_INOBJECT_PROPERTIES, properties);
  }
  return *object;
}


1480
static MaybeObject* Runtime_RegExpExec(Arguments args) {
1481
  HandleScope scope;
1482
  ASSERT(args.length() == 4);
1483 1484
  CONVERT_ARG_CHECKED(JSRegExp, regexp, 0);
  CONVERT_ARG_CHECKED(String, subject, 1);
1485
  // Due to the way the JS calls are constructed this must be less than the
1486
  // length of a string, i.e. it is always a Smi.  We check anyway for security.
1487
  CONVERT_SMI_CHECKED(index, args[2]);
1488
  CONVERT_ARG_CHECKED(JSArray, last_match_info, 3);
1489
  RUNTIME_ASSERT(last_match_info->HasFastElements());
1490 1491
  RUNTIME_ASSERT(index >= 0);
  RUNTIME_ASSERT(index <= subject->length());
1492
  Counters::regexp_entry_runtime.Increment();
1493 1494
  Handle<Object> result = RegExpImpl::Exec(regexp,
                                           subject,
1495
                                           index,
1496
                                           last_match_info);
1497 1498
  if (result.is_null()) return Failure::Exception();
  return *result;
1499 1500 1501
}


1502
static MaybeObject* Runtime_RegExpConstructResult(Arguments args) {
1503 1504 1505 1506 1507
  ASSERT(args.length() == 3);
  CONVERT_SMI_CHECKED(elements_count, args[0]);
  if (elements_count > JSArray::kMaxFastElementsLength) {
    return Top::ThrowIllegalOperation();
  }
1508 1509 1510 1511 1512
  Object* new_object;
  { MaybeObject* maybe_new_object =
        Heap::AllocateFixedArrayWithHoles(elements_count);
    if (!maybe_new_object->ToObject(&new_object)) return maybe_new_object;
  }
1513
  FixedArray* elements = FixedArray::cast(new_object);
1514 1515 1516 1517 1518
  { MaybeObject* maybe_new_object = Heap::AllocateRaw(JSRegExpResult::kSize,
                                                      NEW_SPACE,
                                                      OLD_POINTER_SPACE);
    if (!maybe_new_object->ToObject(&new_object)) return maybe_new_object;
  }
1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535
  {
    AssertNoAllocation no_gc;
    HandleScope scope;
    reinterpret_cast<HeapObject*>(new_object)->
        set_map(Top::global_context()->regexp_result_map());
  }
  JSArray* array = JSArray::cast(new_object);
  array->set_properties(Heap::empty_fixed_array());
  array->set_elements(elements);
  array->set_length(Smi::FromInt(elements_count));
  // Write in-object properties after the length of the array.
  array->InObjectPropertyAtPut(JSRegExpResult::kIndexIndex, args[1]);
  array->InObjectPropertyAtPut(JSRegExpResult::kInputIndex, args[2]);
  return array;
}


1536
static MaybeObject* Runtime_RegExpInitializeObject(Arguments args) {
1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567
  AssertNoAllocation no_alloc;
  ASSERT(args.length() == 5);
  CONVERT_CHECKED(JSRegExp, regexp, args[0]);
  CONVERT_CHECKED(String, source, args[1]);

  Object* global = args[2];
  if (!global->IsTrue()) global = Heap::false_value();

  Object* ignoreCase = args[3];
  if (!ignoreCase->IsTrue()) ignoreCase = Heap::false_value();

  Object* multiline = args[4];
  if (!multiline->IsTrue()) multiline = Heap::false_value();

  Map* map = regexp->map();
  Object* constructor = map->constructor();
  if (constructor->IsJSFunction() &&
      JSFunction::cast(constructor)->initial_map() == map) {
    // If we still have the original map, set in-object properties directly.
    regexp->InObjectPropertyAtPut(JSRegExp::kSourceFieldIndex, source);
    // TODO(lrn): Consider skipping write barrier on booleans as well.
    // Both true and false should be in oldspace at all times.
    regexp->InObjectPropertyAtPut(JSRegExp::kGlobalFieldIndex, global);
    regexp->InObjectPropertyAtPut(JSRegExp::kIgnoreCaseFieldIndex, ignoreCase);
    regexp->InObjectPropertyAtPut(JSRegExp::kMultilineFieldIndex, multiline);
    regexp->InObjectPropertyAtPut(JSRegExp::kLastIndexFieldIndex,
                                  Smi::FromInt(0),
                                  SKIP_WRITE_BARRIER);
    return regexp;
  }

1568 1569 1570
  // Map has changed, so use generic, but slower, method.  Since these
  // properties were all added as DONT_DELETE they must be present and
  // normal so no failures can be expected.
1571 1572 1573 1574
  PropertyAttributes final =
      static_cast<PropertyAttributes>(READ_ONLY | DONT_ENUM | DONT_DELETE);
  PropertyAttributes writable =
      static_cast<PropertyAttributes>(DONT_ENUM | DONT_DELETE);
1575
  MaybeObject* result;
1576 1577 1578
  result = regexp->SetLocalPropertyIgnoreAttributes(Heap::source_symbol(),
                                                    source,
                                                    final);
1579
  ASSERT(!result->IsFailure());
1580 1581 1582
  result = regexp->SetLocalPropertyIgnoreAttributes(Heap::global_symbol(),
                                                    global,
                                                    final);
1583 1584
  ASSERT(!result->IsFailure());
  result =
1585 1586 1587
      regexp->SetLocalPropertyIgnoreAttributes(Heap::ignore_case_symbol(),
                                               ignoreCase,
                                               final);
1588
  ASSERT(!result->IsFailure());
1589 1590 1591
  result = regexp->SetLocalPropertyIgnoreAttributes(Heap::multiline_symbol(),
                                                    multiline,
                                                    final);
1592 1593
  ASSERT(!result->IsFailure());
  result =
1594 1595 1596
      regexp->SetLocalPropertyIgnoreAttributes(Heap::last_index_symbol(),
                                               Smi::FromInt(0),
                                               writable);
1597 1598
  ASSERT(!result->IsFailure());
  USE(result);
1599 1600 1601 1602
  return regexp;
}


1603
static MaybeObject* Runtime_FinishArrayPrototypeSetup(Arguments args) {
1604 1605 1606 1607 1608 1609 1610 1611 1612 1613
  HandleScope scope;
  ASSERT(args.length() == 1);
  CONVERT_ARG_CHECKED(JSArray, prototype, 0);
  // This is necessary to enable fast checks for absence of elements
  // on Array.prototype and below.
  prototype->set_elements(Heap::empty_fixed_array());
  return Smi::FromInt(0);
}


1614 1615
static Handle<JSFunction> InstallBuiltin(Handle<JSObject> holder,
                                         const char* name,
1616
                                         Builtins::Name builtin_name) {
1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629
  Handle<String> key = Factory::LookupAsciiSymbol(name);
  Handle<Code> code(Builtins::builtin(builtin_name));
  Handle<JSFunction> optimized = Factory::NewFunction(key,
                                                      JS_OBJECT_TYPE,
                                                      JSObject::kHeaderSize,
                                                      code,
                                                      false);
  optimized->shared()->DontAdaptArguments();
  SetProperty(holder, key, optimized, NONE);
  return optimized;
}


1630
static MaybeObject* Runtime_SpecialArrayFunctions(Arguments args) {
1631 1632 1633 1634
  HandleScope scope;
  ASSERT(args.length() == 1);
  CONVERT_ARG_CHECKED(JSObject, holder, 0);

1635 1636
  InstallBuiltin(holder, "pop", Builtins::ArrayPop);
  InstallBuiltin(holder, "push", Builtins::ArrayPush);
1637 1638 1639 1640
  InstallBuiltin(holder, "shift", Builtins::ArrayShift);
  InstallBuiltin(holder, "unshift", Builtins::ArrayUnshift);
  InstallBuiltin(holder, "slice", Builtins::ArraySlice);
  InstallBuiltin(holder, "splice", Builtins::ArraySplice);
1641
  InstallBuiltin(holder, "concat", Builtins::ArrayConcat);
1642 1643 1644 1645 1646

  return *holder;
}


1647
static MaybeObject* Runtime_GetGlobalReceiver(Arguments args) {
1648 1649 1650 1651 1652 1653
  // Returns a real global receiver, not one of builtins object.
  Context* global_context = Top::context()->global()->global_context();
  return global_context->global()->global_receiver();
}


1654
static MaybeObject* Runtime_MaterializeRegExpLiteral(Arguments args) {
1655 1656 1657 1658 1659 1660 1661
  HandleScope scope;
  ASSERT(args.length() == 4);
  CONVERT_ARG_CHECKED(FixedArray, literals, 0);
  int index = Smi::cast(args[1])->value();
  Handle<String> pattern = args.at<String>(2);
  Handle<String> flags = args.at<String>(3);

1662 1663 1664 1665 1666
  // Get the RegExp function from the context in the literals array.
  // This is the RegExp function from the context in which the
  // function was created.  We do not use the RegExp function from the
  // current global context because this might be the RegExp function
  // from another context which we should not have access to.
1667
  Handle<JSFunction> constructor =
1668 1669
      Handle<JSFunction>(
          JSFunction::GlobalContextFromLiterals(*literals)->regexp_function());
1670 1671 1672
  // Compute the regular expression literal.
  bool has_pending_exception;
  Handle<Object> regexp =
1673 1674
      RegExpImpl::CreateRegExpLiteral(constructor, pattern, flags,
                                      &has_pending_exception);
1675 1676 1677 1678 1679 1680 1681 1682 1683
  if (has_pending_exception) {
    ASSERT(Top::has_pending_exception());
    return Failure::Exception();
  }
  literals->set(index, *regexp);
  return *regexp;
}


1684
static MaybeObject* Runtime_FunctionGetName(Arguments args) {
1685 1686 1687 1688 1689 1690 1691 1692
  NoHandleAllocation ha;
  ASSERT(args.length() == 1);

  CONVERT_CHECKED(JSFunction, f, args[0]);
  return f->shared()->name();
}


1693
static MaybeObject* Runtime_FunctionSetName(Arguments args) {
1694 1695 1696 1697 1698 1699 1700 1701 1702 1703
  NoHandleAllocation ha;
  ASSERT(args.length() == 2);

  CONVERT_CHECKED(JSFunction, f, args[0]);
  CONVERT_CHECKED(String, name, args[1]);
  f->shared()->set_name(name);
  return Heap::undefined_value();
}


1704
static MaybeObject* Runtime_FunctionRemovePrototype(Arguments args) {
1705 1706 1707 1708
  NoHandleAllocation ha;
  ASSERT(args.length() == 1);

  CONVERT_CHECKED(JSFunction, f, args[0]);
1709 1710 1711 1712
  Object* obj;
  { MaybeObject* maybe_obj = f->RemovePrototype();
    if (!maybe_obj->ToObject(&obj)) return maybe_obj;
  }
1713 1714 1715 1716 1717

  return Heap::undefined_value();
}


1718
static MaybeObject* Runtime_FunctionGetScript(Arguments args) {
1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729
  HandleScope scope;
  ASSERT(args.length() == 1);

  CONVERT_CHECKED(JSFunction, fun, args[0]);
  Handle<Object> script = Handle<Object>(fun->shared()->script());
  if (!script->IsScript()) return Heap::undefined_value();

  return *GetScriptWrapper(Handle<Script>::cast(script));
}


1730
static MaybeObject* Runtime_FunctionGetSourceCode(Arguments args) {
1731 1732 1733 1734 1735 1736 1737 1738
  NoHandleAllocation ha;
  ASSERT(args.length() == 1);

  CONVERT_CHECKED(JSFunction, f, args[0]);
  return f->shared()->GetSourceCode();
}


1739
static MaybeObject* Runtime_FunctionGetScriptSourcePosition(Arguments args) {
1740 1741 1742 1743 1744 1745 1746 1747 1748
  NoHandleAllocation ha;
  ASSERT(args.length() == 1);

  CONVERT_CHECKED(JSFunction, fun, args[0]);
  int pos = fun->shared()->start_position();
  return Smi::FromInt(pos);
}


1749
static MaybeObject* Runtime_FunctionGetPositionForOffset(Arguments args) {
1750 1751
  ASSERT(args.length() == 2);

1752
  CONVERT_CHECKED(Code, code, args[0]);
1753 1754 1755 1756 1757
  CONVERT_NUMBER_CHECKED(int, offset, Int32, args[1]);

  RUNTIME_ASSERT(0 <= offset && offset < code->Size());

  Address pc = code->address() + offset;
1758
  return Smi::FromInt(code->SourcePosition(pc));
1759 1760 1761 1762
}



1763
static MaybeObject* Runtime_FunctionSetInstanceClassName(Arguments args) {
1764 1765 1766 1767 1768 1769 1770 1771 1772 1773
  NoHandleAllocation ha;
  ASSERT(args.length() == 2);

  CONVERT_CHECKED(JSFunction, fun, args[0]);
  CONVERT_CHECKED(String, name, args[1]);
  fun->SetInstanceClassName(name);
  return Heap::undefined_value();
}


1774
static MaybeObject* Runtime_FunctionSetLength(Arguments args) {
1775 1776 1777 1778 1779 1780 1781 1782 1783 1784
  NoHandleAllocation ha;
  ASSERT(args.length() == 2);

  CONVERT_CHECKED(JSFunction, fun, args[0]);
  CONVERT_CHECKED(Smi, length, args[1]);
  fun->shared()->set_length(length->value());
  return length;
}


1785
static MaybeObject* Runtime_FunctionSetPrototype(Arguments args) {
1786
  NoHandleAllocation ha;
1787 1788 1789
  ASSERT(args.length() == 2);

  CONVERT_CHECKED(JSFunction, fun, args[0]);
1790
  ASSERT(fun->should_have_prototype());
1791 1792 1793 1794 1795
  Object* obj;
  { MaybeObject* maybe_obj =
        Accessors::FunctionSetPrototype(fun, args[1], NULL);
    if (!maybe_obj->ToObject(&obj)) return maybe_obj;
  }
1796 1797 1798 1799
  return args[0];  // return TOS
}


1800
static MaybeObject* Runtime_FunctionIsAPIFunction(Arguments args) {
1801 1802 1803 1804
  NoHandleAllocation ha;
  ASSERT(args.length() == 1);

  CONVERT_CHECKED(JSFunction, f, args[0]);
1805 1806
  return f->shared()->IsApiFunction() ? Heap::true_value()
                                      : Heap::false_value();
1807 1808
}

1809
static MaybeObject* Runtime_FunctionIsBuiltin(Arguments args) {
1810 1811 1812 1813 1814 1815 1816
  NoHandleAllocation ha;
  ASSERT(args.length() == 1);

  CONVERT_CHECKED(JSFunction, f, args[0]);
  return f->IsBuiltin() ? Heap::true_value() : Heap::false_value();
}

1817

1818
static MaybeObject* Runtime_SetCode(Arguments args) {
1819 1820 1821
  HandleScope scope;
  ASSERT(args.length() == 2);

1822
  CONVERT_ARG_CHECKED(JSFunction, target, 0);
1823 1824 1825 1826 1827 1828 1829
  Handle<Object> code = args.at<Object>(1);

  Handle<Context> context(target->context());

  if (!code->IsNull()) {
    RUNTIME_ASSERT(code->IsJSFunction());
    Handle<JSFunction> fun = Handle<JSFunction>::cast(code);
1830 1831 1832
    Handle<SharedFunctionInfo> shared(fun->shared());

    if (!EnsureCompiled(shared, KEEP_EXCEPTION)) {
1833 1834
      return Failure::Exception();
    }
1835 1836 1837 1838
    // Since we don't store the source for this we should never
    // optimize this.
    shared->code()->set_optimizable(false);

1839 1840
    // Set the code, scope info, formal parameter count,
    // and the length of the target function.
1841
    target->shared()->set_code(shared->code());
1842
    target->ReplaceCode(shared->code());
1843
    target->shared()->set_scope_info(shared->scope_info());
1844
    target->shared()->set_length(shared->length());
1845
    target->shared()->set_formal_parameter_count(
1846
        shared->formal_parameter_count());
whesse@chromium.org's avatar
whesse@chromium.org committed
1847 1848 1849 1850 1851
    // Set the source code of the target function to undefined.
    // SetCode is only used for built-in constructors like String,
    // Array, and Object, and some web code
    // doesn't like seeing source code for constructors.
    target->shared()->set_script(Heap::undefined_value());
1852
    target->shared()->code()->set_optimizable(false);
1853 1854 1855
    // Clear the optimization hints related to the compiled code as these are no
    // longer valid when the code is overwritten.
    target->shared()->ClearThisPropertyAssignmentsInfo();
1856 1857 1858 1859
    context = Handle<Context>(fun->context());

    // Make sure we get a fresh copy of the literal vector to avoid
    // cross context contamination.
1860 1861 1862
    int number_of_literals = fun->NumberOfLiterals();
    Handle<FixedArray> literals =
        Factory::NewFixedArray(number_of_literals, TENURED);
1863
    if (number_of_literals > 0) {
1864 1865 1866
      // Insert the object, regexp and array functions in the literals
      // array prefix.  These are the functions that will be used when
      // creating object, regexp and array literals.
1867 1868
      literals->set(JSFunction::kLiteralGlobalContextIndex,
                    context->global_context());
1869
    }
1870 1871
    // It's okay to skip the write barrier here because the literals
    // are guaranteed to be in old space.
1872
    target->set_literals(*literals, SKIP_WRITE_BARRIER);
1873
    target->set_next_function_link(Heap::undefined_value());
1874 1875 1876 1877 1878 1879 1880
  }

  target->set_context(*context);
  return *target;
}


1881
static MaybeObject* Runtime_SetExpectedNumberOfProperties(Arguments args) {
1882 1883 1884 1885 1886 1887 1888 1889 1890 1891
  HandleScope scope;
  ASSERT(args.length() == 2);
  CONVERT_ARG_CHECKED(JSFunction, function, 0);
  CONVERT_SMI_CHECKED(num, args[1]);
  RUNTIME_ASSERT(num >= 0);
  SetExpectedNofProperties(function, num);
  return Heap::undefined_value();
}


1892
MUST_USE_RESULT static MaybeObject* CharFromCode(Object* char_code) {
1893
  uint32_t code;
1894
  if (char_code->ToArrayIndex(&code)) {
1895 1896 1897 1898 1899 1900 1901 1902
    if (code <= 0xffff) {
      return Heap::LookupSingleCharacterStringFromCode(code);
    }
  }
  return Heap::empty_string();
}


1903
static MaybeObject* Runtime_StringCharCodeAt(Arguments args) {
1904 1905 1906 1907 1908
  NoHandleAllocation ha;
  ASSERT(args.length() == 2);

  CONVERT_CHECKED(String, subject, args[0]);
  Object* index = args[1];
1909
  RUNTIME_ASSERT(index->IsNumber());
1910

1911 1912 1913 1914 1915 1916 1917 1918
  uint32_t i = 0;
  if (index->IsSmi()) {
    int value = Smi::cast(index)->value();
    if (value < 0) return Heap::nan_value();
    i = value;
  } else {
    ASSERT(index->IsHeapNumber());
    double value = HeapNumber::cast(index)->value();
1919
    i = static_cast<uint32_t>(DoubleToInteger(value));
1920
  }
1921

1922 1923 1924
  // Flatten the string.  If someone wants to get a char at an index
  // in a cons string, it is likely that more indices will be
  // accessed.
1925 1926 1927 1928
  Object* flat;
  { MaybeObject* maybe_flat = subject->TryFlatten();
    if (!maybe_flat->ToObject(&flat)) return maybe_flat;
  }
1929
  subject = String::cast(flat);
1930

1931 1932
  if (i >= static_cast<uint32_t>(subject->length())) {
    return Heap::nan_value();
1933
  }
1934 1935

  return Smi::FromInt(subject->Get(i));
1936 1937 1938
}


1939
static MaybeObject* Runtime_CharFromCode(Arguments args) {
1940 1941
  NoHandleAllocation ha;
  ASSERT(args.length() == 1);
1942
  return CharFromCode(args[0]);
1943 1944
}

1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026

class FixedArrayBuilder {
 public:
  explicit FixedArrayBuilder(int initial_capacity)
      : array_(Factory::NewFixedArrayWithHoles(initial_capacity)),
        length_(0) {
    // Require a non-zero initial size. Ensures that doubling the size to
    // extend the array will work.
    ASSERT(initial_capacity > 0);
  }

  explicit FixedArrayBuilder(Handle<FixedArray> backing_store)
      : array_(backing_store),
        length_(0) {
    // Require a non-zero initial size. Ensures that doubling the size to
    // extend the array will work.
    ASSERT(backing_store->length() > 0);
  }

  bool HasCapacity(int elements) {
    int length = array_->length();
    int required_length = length_ + elements;
    return (length >= required_length);
  }

  void EnsureCapacity(int elements) {
    int length = array_->length();
    int required_length = length_ + elements;
    if (length < required_length) {
      int new_length = length;
      do {
        new_length *= 2;
      } while (new_length < required_length);
      Handle<FixedArray> extended_array =
          Factory::NewFixedArrayWithHoles(new_length);
      array_->CopyTo(0, *extended_array, 0, length_);
      array_ = extended_array;
    }
  }

  void Add(Object* value) {
    ASSERT(length_ < capacity());
    array_->set(length_, value);
    length_++;
  }

  void Add(Smi* value) {
    ASSERT(length_ < capacity());
    array_->set(length_, value);
    length_++;
  }

  Handle<FixedArray> array() {
    return array_;
  }

  int length() {
    return length_;
  }

  int capacity() {
    return array_->length();
  }

  Handle<JSArray> ToJSArray() {
    Handle<JSArray> result_array = Factory::NewJSArrayWithElements(array_);
    result_array->set_length(Smi::FromInt(length_));
    return result_array;
  }

  Handle<JSArray> ToJSArray(Handle<JSArray> target_array) {
    target_array->set_elements(*array_);
    target_array->set_length(Smi::FromInt(length_));
    return target_array;
  }

 private:
  Handle<FixedArray> array_;
  int length_;
};


2027
// Forward declarations.
2028 2029
const int kStringBuilderConcatHelperLengthBits = 11;
const int kStringBuilderConcatHelperPositionBits = 19;
2030 2031 2032 2033 2034 2035 2036

template <typename schar>
static inline void StringBuilderConcatHelper(String*,
                                             schar*,
                                             FixedArray*,
                                             int);

2037 2038 2039 2040 2041 2042 2043
typedef BitField<int, 0, kStringBuilderConcatHelperLengthBits>
    StringBuilderSubstringLength;
typedef BitField<int,
                 kStringBuilderConcatHelperLengthBits,
                 kStringBuilderConcatHelperPositionBits>
    StringBuilderSubstringPosition;

2044 2045 2046 2047

class ReplacementStringBuilder {
 public:
  ReplacementStringBuilder(Handle<String> subject, int estimated_part_count)
2048 2049
      : array_builder_(estimated_part_count),
        subject_(subject),
2050
        character_count_(0),
2051
        is_ascii_(subject->IsAsciiRepresentation()) {
2052 2053 2054 2055 2056
    // Require a non-zero initial size. Ensures that doubling the size to
    // extend the array will work.
    ASSERT(estimated_part_count > 0);
  }

2057 2058 2059
  static inline void AddSubjectSlice(FixedArrayBuilder* builder,
                                     int from,
                                     int to) {
2060 2061
    ASSERT(from >= 0);
    int length = to - from;
2062 2063 2064 2065 2066
    ASSERT(length > 0);
    if (StringBuilderSubstringLength::is_valid(length) &&
        StringBuilderSubstringPosition::is_valid(from)) {
      int encoded_slice = StringBuilderSubstringLength::encode(length) |
          StringBuilderSubstringPosition::encode(from);
2067
      builder->Add(Smi::FromInt(encoded_slice));
2068
    } else {
2069
      // Otherwise encode as two smis.
2070 2071
      builder->Add(Smi::FromInt(-length));
      builder->Add(Smi::FromInt(from));
2072
    }
2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083
  }


  void EnsureCapacity(int elements) {
    array_builder_.EnsureCapacity(elements);
  }


  void AddSubjectSlice(int from, int to) {
    AddSubjectSlice(&array_builder_, from, to);
    IncrementCharacterCount(to - from);
2084 2085 2086 2087
  }


  void AddString(Handle<String> string) {
2088
    int length = string->length();
2089 2090
    ASSERT(length > 0);
    AddElement(*string);
2091
    if (!string->IsAsciiRepresentation()) {
2092
      is_ascii_ = false;
2093
    }
2094
    IncrementCharacterCount(length);
2095 2096 2097 2098
  }


  Handle<String> ToString() {
2099
    if (array_builder_.length() == 0) {
2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110
      return Factory::empty_string();
    }

    Handle<String> joined_string;
    if (is_ascii_) {
      joined_string = NewRawAsciiString(character_count_);
      AssertNoAllocation no_alloc;
      SeqAsciiString* seq = SeqAsciiString::cast(*joined_string);
      char* char_buffer = seq->GetChars();
      StringBuilderConcatHelper(*subject_,
                                char_buffer,
2111 2112
                                *array_builder_.array(),
                                array_builder_.length());
2113 2114 2115 2116 2117 2118 2119 2120
    } else {
      // Non-ASCII.
      joined_string = NewRawTwoByteString(character_count_);
      AssertNoAllocation no_alloc;
      SeqTwoByteString* seq = SeqTwoByteString::cast(*joined_string);
      uc16* char_buffer = seq->GetChars();
      StringBuilderConcatHelper(*subject_,
                                char_buffer,
2121 2122
                                *array_builder_.array(),
                                array_builder_.length());
2123 2124 2125 2126 2127 2128
    }
    return joined_string;
  }


  void IncrementCharacterCount(int by) {
2129
    if (character_count_ > String::kMaxLength - by) {
2130 2131 2132 2133 2134
      V8::FatalProcessOutOfMemory("String.replace result too large.");
    }
    character_count_ += by;
  }

2135
  Handle<JSArray> GetParts() {
2136
    return array_builder_.ToJSArray();
2137
  }
2138

2139
 private:
2140 2141 2142 2143 2144 2145 2146 2147 2148 2149
  Handle<String> NewRawAsciiString(int size) {
    CALL_HEAP_FUNCTION(Heap::AllocateRawAsciiString(size), String);
  }


  Handle<String> NewRawTwoByteString(int size) {
    CALL_HEAP_FUNCTION(Heap::AllocateRawTwoByteString(size), String);
  }


2150
  void AddElement(Object* element) {
2151
    ASSERT(element->IsSmi() || element->IsString());
2152 2153
    ASSERT(array_builder_.capacity() > array_builder_.length());
    array_builder_.Add(element);
2154 2155
  }

2156
  FixedArrayBuilder array_builder_;
2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319
  Handle<String> subject_;
  int character_count_;
  bool is_ascii_;
};


class CompiledReplacement {
 public:
  CompiledReplacement()
      : parts_(1), replacement_substrings_(0) {}

  void Compile(Handle<String> replacement,
               int capture_count,
               int subject_length);

  void Apply(ReplacementStringBuilder* builder,
             int match_from,
             int match_to,
             Handle<JSArray> last_match_info);

  // Number of distinct parts of the replacement pattern.
  int parts() {
    return parts_.length();
  }
 private:
  enum PartType {
    SUBJECT_PREFIX = 1,
    SUBJECT_SUFFIX,
    SUBJECT_CAPTURE,
    REPLACEMENT_SUBSTRING,
    REPLACEMENT_STRING,

    NUMBER_OF_PART_TYPES
  };

  struct ReplacementPart {
    static inline ReplacementPart SubjectMatch() {
      return ReplacementPart(SUBJECT_CAPTURE, 0);
    }
    static inline ReplacementPart SubjectCapture(int capture_index) {
      return ReplacementPart(SUBJECT_CAPTURE, capture_index);
    }
    static inline ReplacementPart SubjectPrefix() {
      return ReplacementPart(SUBJECT_PREFIX, 0);
    }
    static inline ReplacementPart SubjectSuffix(int subject_length) {
      return ReplacementPart(SUBJECT_SUFFIX, subject_length);
    }
    static inline ReplacementPart ReplacementString() {
      return ReplacementPart(REPLACEMENT_STRING, 0);
    }
    static inline ReplacementPart ReplacementSubString(int from, int to) {
      ASSERT(from >= 0);
      ASSERT(to > from);
      return ReplacementPart(-from, to);
    }

    // If tag <= 0 then it is the negation of a start index of a substring of
    // the replacement pattern, otherwise it's a value from PartType.
    ReplacementPart(int tag, int data)
        : tag(tag), data(data) {
      // Must be non-positive or a PartType value.
      ASSERT(tag < NUMBER_OF_PART_TYPES);
    }
    // Either a value of PartType or a non-positive number that is
    // the negation of an index into the replacement string.
    int tag;
    // The data value's interpretation depends on the value of tag:
    // tag == SUBJECT_PREFIX ||
    // tag == SUBJECT_SUFFIX:  data is unused.
    // tag == SUBJECT_CAPTURE: data is the number of the capture.
    // tag == REPLACEMENT_SUBSTRING ||
    // tag == REPLACEMENT_STRING:    data is index into array of substrings
    //                               of the replacement string.
    // tag <= 0: Temporary representation of the substring of the replacement
    //           string ranging over -tag .. data.
    //           Is replaced by REPLACEMENT_{SUB,}STRING when we create the
    //           substring objects.
    int data;
  };

  template<typename Char>
  static void ParseReplacementPattern(ZoneList<ReplacementPart>* parts,
                                      Vector<Char> characters,
                                      int capture_count,
                                      int subject_length) {
    int length = characters.length();
    int last = 0;
    for (int i = 0; i < length; i++) {
      Char c = characters[i];
      if (c == '$') {
        int next_index = i + 1;
        if (next_index == length) {  // No next character!
          break;
        }
        Char c2 = characters[next_index];
        switch (c2) {
        case '$':
          if (i > last) {
            // There is a substring before. Include the first "$".
            parts->Add(ReplacementPart::ReplacementSubString(last, next_index));
            last = next_index + 1;  // Continue after the second "$".
          } else {
            // Let the next substring start with the second "$".
            last = next_index;
          }
          i = next_index;
          break;
        case '`':
          if (i > last) {
            parts->Add(ReplacementPart::ReplacementSubString(last, i));
          }
          parts->Add(ReplacementPart::SubjectPrefix());
          i = next_index;
          last = i + 1;
          break;
        case '\'':
          if (i > last) {
            parts->Add(ReplacementPart::ReplacementSubString(last, i));
          }
          parts->Add(ReplacementPart::SubjectSuffix(subject_length));
          i = next_index;
          last = i + 1;
          break;
        case '&':
          if (i > last) {
            parts->Add(ReplacementPart::ReplacementSubString(last, i));
          }
          parts->Add(ReplacementPart::SubjectMatch());
          i = next_index;
          last = i + 1;
          break;
        case '0':
        case '1':
        case '2':
        case '3':
        case '4':
        case '5':
        case '6':
        case '7':
        case '8':
        case '9': {
          int capture_ref = c2 - '0';
          if (capture_ref > capture_count) {
            i = next_index;
            continue;
          }
          int second_digit_index = next_index + 1;
          if (second_digit_index < length) {
            // Peek ahead to see if we have two digits.
            Char c3 = characters[second_digit_index];
            if ('0' <= c3 && c3 <= '9') {  // Double digits.
              int double_digit_ref = capture_ref * 10 + c3 - '0';
              if (double_digit_ref <= capture_count) {
                next_index = second_digit_index;
                capture_ref = double_digit_ref;
              }
            }
          }
          if (capture_ref > 0) {
            if (i > last) {
              parts->Add(ReplacementPart::ReplacementSubString(last, i));
            }
2320
            ASSERT(capture_ref <= capture_count);
2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349
            parts->Add(ReplacementPart::SubjectCapture(capture_ref));
            last = next_index + 1;
          }
          i = next_index;
          break;
        }
        default:
          i = next_index;
          break;
        }
      }
    }
    if (length > last) {
      if (last == 0) {
        parts->Add(ReplacementPart::ReplacementString());
      } else {
        parts->Add(ReplacementPart::ReplacementSubString(last, length));
      }
    }
  }

  ZoneList<ReplacementPart> parts_;
  ZoneList<Handle<String> > replacement_substrings_;
};


void CompiledReplacement::Compile(Handle<String> replacement,
                                  int capture_count,
                                  int subject_length) {
2350
  ASSERT(replacement->IsFlat());
2351
  if (replacement->IsAsciiRepresentation()) {
2352 2353 2354 2355 2356 2357
    AssertNoAllocation no_alloc;
    ParseReplacementPattern(&parts_,
                            replacement->ToAsciiVector(),
                            capture_count,
                            subject_length);
  } else {
2358
    ASSERT(replacement->IsTwoByteRepresentation());
2359 2360 2361 2362 2363 2364 2365
    AssertNoAllocation no_alloc;

    ParseReplacementPattern(&parts_,
                            replacement->ToUC16Vector(),
                            capture_count,
                            subject_length);
  }
2366
  // Find substrings of replacement string and create them as String objects.
2367 2368 2369 2370 2371 2372
  int substring_index = 0;
  for (int i = 0, n = parts_.length(); i < n; i++) {
    int tag = parts_[i].tag;
    if (tag <= 0) {  // A replacement string slice.
      int from = -tag;
      int to = parts_[i].data;
2373
      replacement_substrings_.Add(Factory::NewSubString(replacement, from, to));
2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393
      parts_[i].tag = REPLACEMENT_SUBSTRING;
      parts_[i].data = substring_index;
      substring_index++;
    } else if (tag == REPLACEMENT_STRING) {
      replacement_substrings_.Add(replacement);
      parts_[i].data = substring_index;
      substring_index++;
    }
  }
}


void CompiledReplacement::Apply(ReplacementStringBuilder* builder,
                                int match_from,
                                int match_to,
                                Handle<JSArray> last_match_info) {
  for (int i = 0, n = parts_.length(); i < n; i++) {
    ReplacementPart part = parts_[i];
    switch (part.tag) {
      case SUBJECT_PREFIX:
2394
        if (match_from > 0) builder->AddSubjectSlice(0, match_from);
2395 2396 2397
        break;
      case SUBJECT_SUFFIX: {
        int subject_length = part.data;
2398 2399 2400
        if (match_to < subject_length) {
          builder->AddSubjectSlice(match_to, subject_length);
        }
2401 2402 2403 2404
        break;
      }
      case SUBJECT_CAPTURE: {
        int capture = part.data;
2405
        FixedArray* match_info = FixedArray::cast(last_match_info->elements());
2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424
        int from = RegExpImpl::GetCapture(match_info, capture * 2);
        int to = RegExpImpl::GetCapture(match_info, capture * 2 + 1);
        if (from >= 0 && to > from) {
          builder->AddSubjectSlice(from, to);
        }
        break;
      }
      case REPLACEMENT_SUBSTRING:
      case REPLACEMENT_STRING:
        builder->AddString(replacement_substrings_[part.data]);
        break;
      default:
        UNREACHABLE();
    }
  }
}



2425 2426 2427 2428 2429
MUST_USE_RESULT static MaybeObject* StringReplaceRegExpWithString(
    String* subject,
    JSRegExp* regexp,
    String* replacement,
    JSArray* last_match_info) {
2430 2431
  ASSERT(subject->IsFlat());
  ASSERT(replacement->IsFlat());
2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453

  HandleScope handles;

  int length = subject->length();
  Handle<String> subject_handle(subject);
  Handle<JSRegExp> regexp_handle(regexp);
  Handle<String> replacement_handle(replacement);
  Handle<JSArray> last_match_info_handle(last_match_info);
  Handle<Object> match = RegExpImpl::Exec(regexp_handle,
                                          subject_handle,
                                          0,
                                          last_match_info_handle);
  if (match.is_null()) {
    return Failure::Exception();
  }
  if (match->IsNull()) {
    return *subject_handle;
  }

  int capture_count = regexp_handle->CaptureCount();

  // CompiledReplacement uses zone allocation.
2454
  CompilationZoneScope zone(DELETE_ON_EXIT);
2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471
  CompiledReplacement compiled_replacement;
  compiled_replacement.Compile(replacement_handle,
                               capture_count,
                               length);

  bool is_global = regexp_handle->GetFlags().is_global();

  // Guessing the number of parts that the final result string is built
  // from. Global regexps can match any number of times, so we guess
  // conservatively.
  int expected_parts =
      (compiled_replacement.parts() + 1) * (is_global ? 4 : 1) + 1;
  ReplacementStringBuilder builder(subject_handle, expected_parts);

  // Index of end of last match.
  int prev = 0;

2472 2473 2474 2475
  // Number of parts added by compiled replacement plus preceeding
  // string and possibly suffix after last match.  It is possible for
  // all components to use two elements when encoded as two smis.
  const int parts_added_per_loop = 2 * (compiled_replacement.parts() + 2);
2476
  bool matched = true;
2477 2478
  do {
    ASSERT(last_match_info_handle->HasFastElements());
2479 2480 2481 2482 2483
    // Increase the capacity of the builder before entering local handle-scope,
    // so its internal buffer can safely allocate a new handle if it grows.
    builder.EnsureCapacity(parts_added_per_loop);

    HandleScope loop_scope;
2484 2485 2486
    int start, end;
    {
      AssertNoAllocation match_info_array_is_not_in_a_handle;
2487 2488
      FixedArray* match_info_array =
          FixedArray::cast(last_match_info_handle->elements());
2489 2490 2491 2492 2493 2494

      ASSERT_EQ(capture_count * 2 + 2,
                RegExpImpl::GetLastCaptureCount(match_info_array));
      start = RegExpImpl::GetCapture(match_info_array, 0);
      end = RegExpImpl::GetCapture(match_info_array, 1);
    }
2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521

    if (prev < start) {
      builder.AddSubjectSlice(prev, start);
    }
    compiled_replacement.Apply(&builder,
                               start,
                               end,
                               last_match_info_handle);
    prev = end;

    // Only continue checking for global regexps.
    if (!is_global) break;

    // Continue from where the match ended, unless it was an empty match.
    int next = end;
    if (start == end) {
      next = end + 1;
      if (next > length) break;
    }

    match = RegExpImpl::Exec(regexp_handle,
                             subject_handle,
                             next,
                             last_match_info_handle);
    if (match.is_null()) {
      return Failure::Exception();
    }
2522 2523
    matched = !match->IsNull();
  } while (matched);
2524 2525 2526 2527 2528 2529 2530 2531

  if (prev < length) {
    builder.AddSubjectSlice(prev, length);
  }

  return *(builder.ToString());
}

2532

2533
template <typename ResultSeqString>
2534 2535 2536 2537
MUST_USE_RESULT static MaybeObject* StringReplaceRegExpWithEmptyString(
    String* subject,
    JSRegExp* regexp,
    JSArray* last_match_info) {
2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570
  ASSERT(subject->IsFlat());

  HandleScope handles;

  Handle<String> subject_handle(subject);
  Handle<JSRegExp> regexp_handle(regexp);
  Handle<JSArray> last_match_info_handle(last_match_info);
  Handle<Object> match = RegExpImpl::Exec(regexp_handle,
                                          subject_handle,
                                          0,
                                          last_match_info_handle);
  if (match.is_null()) return Failure::Exception();
  if (match->IsNull()) return *subject_handle;

  ASSERT(last_match_info_handle->HasFastElements());

  HandleScope loop_scope;
  int start, end;
  {
    AssertNoAllocation match_info_array_is_not_in_a_handle;
    FixedArray* match_info_array =
        FixedArray::cast(last_match_info_handle->elements());

    start = RegExpImpl::GetCapture(match_info_array, 0);
    end = RegExpImpl::GetCapture(match_info_array, 1);
  }

  int length = subject->length();
  int new_length = length - (end - start);
  if (new_length == 0) {
    return Heap::empty_string();
  }
  Handle<ResultSeqString> answer;
2571
  if (ResultSeqString::kHasAsciiEncoding) {
2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660
    answer =
        Handle<ResultSeqString>::cast(Factory::NewRawAsciiString(new_length));
  } else {
    answer =
        Handle<ResultSeqString>::cast(Factory::NewRawTwoByteString(new_length));
  }

  // If the regexp isn't global, only match once.
  if (!regexp_handle->GetFlags().is_global()) {
    if (start > 0) {
      String::WriteToFlat(*subject_handle,
                          answer->GetChars(),
                          0,
                          start);
    }
    if (end < length) {
      String::WriteToFlat(*subject_handle,
                          answer->GetChars() + start,
                          end,
                          length);
    }
    return *answer;
  }

  int prev = 0;  // Index of end of last match.
  int next = 0;  // Start of next search (prev unless last match was empty).
  int position = 0;

  do {
    if (prev < start) {
      // Add substring subject[prev;start] to answer string.
      String::WriteToFlat(*subject_handle,
                          answer->GetChars() + position,
                          prev,
                          start);
      position += start - prev;
    }
    prev = end;
    next = end;
    // Continue from where the match ended, unless it was an empty match.
    if (start == end) {
      next++;
      if (next > length) break;
    }
    match = RegExpImpl::Exec(regexp_handle,
                             subject_handle,
                             next,
                             last_match_info_handle);
    if (match.is_null()) return Failure::Exception();
    if (match->IsNull()) break;

    ASSERT(last_match_info_handle->HasFastElements());
    HandleScope loop_scope;
    {
      AssertNoAllocation match_info_array_is_not_in_a_handle;
      FixedArray* match_info_array =
          FixedArray::cast(last_match_info_handle->elements());
      start = RegExpImpl::GetCapture(match_info_array, 0);
      end = RegExpImpl::GetCapture(match_info_array, 1);
    }
  } while (true);

  if (prev < length) {
    // Add substring subject[prev;length] to answer string.
    String::WriteToFlat(*subject_handle,
                        answer->GetChars() + position,
                        prev,
                        length);
    position += length - prev;
  }

  if (position == 0) {
    return Heap::empty_string();
  }

  // Shorten string and fill
  int string_size = ResultSeqString::SizeFor(position);
  int allocated_string_size = ResultSeqString::SizeFor(new_length);
  int delta = allocated_string_size - string_size;

  answer->set_length(position);
  if (delta == 0) return *answer;

  Address end_of_string = answer->address() + string_size;
  Heap::CreateFillerObjectAt(end_of_string, delta);

  return *answer;
}

2661

2662
static MaybeObject* Runtime_StringReplaceRegExpWithString(Arguments args) {
2663 2664 2665
  ASSERT(args.length() == 4);

  CONVERT_CHECKED(String, subject, args[0]);
2666
  if (!subject->IsFlat()) {
2667 2668 2669 2670 2671
    Object* flat_subject;
    { MaybeObject* maybe_flat_subject = subject->TryFlatten();
      if (!maybe_flat_subject->ToObject(&flat_subject)) {
        return maybe_flat_subject;
      }
2672 2673 2674 2675 2676
    }
    subject = String::cast(flat_subject);
  }

  CONVERT_CHECKED(String, replacement, args[2]);
2677
  if (!replacement->IsFlat()) {
2678 2679 2680 2681 2682
    Object* flat_replacement;
    { MaybeObject* maybe_flat_replacement = replacement->TryFlatten();
      if (!maybe_flat_replacement->ToObject(&flat_replacement)) {
        return maybe_flat_replacement;
      }
2683 2684 2685 2686 2687 2688 2689 2690 2691
    }
    replacement = String::cast(flat_replacement);
  }

  CONVERT_CHECKED(JSRegExp, regexp, args[1]);
  CONVERT_CHECKED(JSArray, last_match_info, args[3]);

  ASSERT(last_match_info->HasFastElements());

2692
  if (replacement->length() == 0) {
2693 2694 2695
    if (subject->HasOnlyAsciiChars()) {
      return StringReplaceRegExpWithEmptyString<SeqAsciiString>(
          subject, regexp, last_match_info);
2696
    } else {
2697 2698
      return StringReplaceRegExpWithEmptyString<SeqTwoByteString>(
          subject, regexp, last_match_info);
2699 2700 2701
    }
  }

2702 2703 2704 2705 2706 2707 2708
  return StringReplaceRegExpWithString(subject,
                                       regexp,
                                       replacement,
                                       last_match_info);
}


2709 2710
// Perform string match of pattern on subject, starting at start index.
// Caller must ensure that 0 <= start_index <= sub->length(),
2711
// and should check that pat->length() + start_index <= sub->length().
2712 2713 2714
int Runtime::StringMatch(Handle<String> sub,
                         Handle<String> pat,
                         int start_index) {
2715
  ASSERT(0 <= start_index);
2716
  ASSERT(start_index <= sub->length());
2717

2718
  int pattern_length = pat->length();
2719 2720
  if (pattern_length == 0) return start_index;

2721
  int subject_length = sub->length();
2722 2723
  if (start_index + pattern_length > subject_length) return -1;

2724 2725
  if (!sub->IsFlat()) FlattenString(sub);
  if (!pat->IsFlat()) FlattenString(pat);
2726 2727

  AssertNoAllocation no_heap_allocation;  // ensure vectors stay valid
2728 2729
  // Extract flattened substrings of cons strings before determining asciiness.
  String* seq_sub = *sub;
2730
  if (seq_sub->IsConsString()) seq_sub = ConsString::cast(seq_sub)->first();
2731
  String* seq_pat = *pat;
2732
  if (seq_pat->IsConsString()) seq_pat = ConsString::cast(seq_pat)->first();
2733

2734
  // dispatch on type of strings
2735 2736 2737
  if (seq_pat->IsAsciiRepresentation()) {
    Vector<const char> pat_vector = seq_pat->ToAsciiVector();
    if (seq_sub->IsAsciiRepresentation()) {
2738
      return SearchString(seq_sub->ToAsciiVector(), pat_vector, start_index);
2739
    }
2740
    return SearchString(seq_sub->ToUC16Vector(), pat_vector, start_index);
2741
  }
2742 2743
  Vector<const uc16> pat_vector = seq_pat->ToUC16Vector();
  if (seq_sub->IsAsciiRepresentation()) {
2744
    return SearchString(seq_sub->ToAsciiVector(), pat_vector, start_index);
2745
  }
2746
  return SearchString(seq_sub->ToUC16Vector(), pat_vector, start_index);
2747 2748
}

2749

2750
static MaybeObject* Runtime_StringIndexOf(Arguments args) {
2751
  HandleScope scope;  // create a new handle scope
2752 2753
  ASSERT(args.length() == 3);

2754 2755 2756
  CONVERT_ARG_CHECKED(String, sub, 0);
  CONVERT_ARG_CHECKED(String, pat, 1);

2757 2758
  Object* index = args[2];
  uint32_t start_index;
2759
  if (!index->ToArrayIndex(&start_index)) return Smi::FromInt(-1);
2760

2761
  RUNTIME_ASSERT(start_index <= static_cast<uint32_t>(sub->length()));
2762
  int position = Runtime::StringMatch(sub, pat, start_index);
2763
  return Smi::FromInt(position);
2764 2765 2766
}


2767
template <typename schar, typename pchar>
2768 2769
static int StringMatchBackwards(Vector<const schar> subject,
                                Vector<const pchar> pattern,
2770
                                int idx) {
2771 2772 2773
  int pattern_length = pattern.length();
  ASSERT(pattern_length >= 1);
  ASSERT(idx + pattern_length <= subject.length());
2774 2775

  if (sizeof(schar) == 1 && sizeof(pchar) > 1) {
2776 2777
    for (int i = 0; i < pattern_length; i++) {
      uc16 c = pattern[i];
2778 2779 2780 2781 2782 2783
      if (c > String::kMaxAsciiCharCode) {
        return -1;
      }
    }
  }

2784
  pchar pattern_first_char = pattern[0];
2785
  for (int i = idx; i >= 0; i--) {
2786
    if (subject[i] != pattern_first_char) continue;
2787
    int j = 1;
2788 2789
    while (j < pattern_length) {
      if (pattern[j] != subject[i+j]) {
2790 2791 2792 2793
        break;
      }
      j++;
    }
2794
    if (j == pattern_length) {
2795 2796 2797 2798 2799 2800
      return i;
    }
  }
  return -1;
}

2801
static MaybeObject* Runtime_StringLastIndexOf(Arguments args) {
2802
  HandleScope scope;  // create a new handle scope
2803 2804
  ASSERT(args.length() == 3);

2805 2806
  CONVERT_ARG_CHECKED(String, sub, 0);
  CONVERT_ARG_CHECKED(String, pat, 1);
2807

2808
  Object* index = args[2];
2809
  uint32_t start_index;
2810
  if (!index->ToArrayIndex(&start_index)) return Smi::FromInt(-1);
2811

2812 2813 2814 2815 2816
  uint32_t pat_length = pat->length();
  uint32_t sub_length = sub->length();

  if (start_index + pat_length > sub_length) {
    start_index = sub_length - pat_length;
2817 2818
  }

2819 2820 2821
  if (pat_length == 0) {
    return Smi::FromInt(start_index);
  }
2822

2823 2824
  if (!sub->IsFlat()) FlattenString(sub);
  if (!pat->IsFlat()) FlattenString(pat);
2825

2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850
  AssertNoAllocation no_heap_allocation;  // ensure vectors stay valid

  int position = -1;

  if (pat->IsAsciiRepresentation()) {
    Vector<const char> pat_vector = pat->ToAsciiVector();
    if (sub->IsAsciiRepresentation()) {
      position = StringMatchBackwards(sub->ToAsciiVector(),
                                      pat_vector,
                                      start_index);
    } else {
      position = StringMatchBackwards(sub->ToUC16Vector(),
                                      pat_vector,
                                      start_index);
    }
  } else {
    Vector<const uc16> pat_vector = pat->ToUC16Vector();
    if (sub->IsAsciiRepresentation()) {
      position = StringMatchBackwards(sub->ToAsciiVector(),
                                      pat_vector,
                                      start_index);
    } else {
      position = StringMatchBackwards(sub->ToUC16Vector(),
                                      pat_vector,
                                      start_index);
2851 2852 2853
    }
  }

2854
  return Smi::FromInt(position);
2855 2856 2857
}


2858
static MaybeObject* Runtime_StringLocaleCompare(Arguments args) {
2859 2860 2861 2862 2863 2864 2865
  NoHandleAllocation ha;
  ASSERT(args.length() == 2);

  CONVERT_CHECKED(String, str1, args[0]);
  CONVERT_CHECKED(String, str2, args[1]);

  if (str1 == str2) return Smi::FromInt(0);  // Equal.
2866 2867
  int str1_length = str1->length();
  int str2_length = str2->length();
2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881

  // Decide trivial cases without flattening.
  if (str1_length == 0) {
    if (str2_length == 0) return Smi::FromInt(0);  // Equal.
    return Smi::FromInt(-str2_length);
  } else {
    if (str2_length == 0) return Smi::FromInt(str1_length);
  }

  int end = str1_length < str2_length ? str1_length : str2_length;

  // No need to flatten if we are going to find the answer on the first
  // character.  At this point we know there is at least one character
  // in each string, due to the trivial case handling above.
2882
  int d = str1->Get(0) - str2->Get(0);
2883 2884
  if (d != 0) return Smi::FromInt(d);

2885 2886
  str1->TryFlatten();
  str2->TryFlatten();
2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903

  static StringInputBuffer buf1;
  static StringInputBuffer buf2;

  buf1.Reset(str1);
  buf2.Reset(str2);

  for (int i = 0; i < end; i++) {
    uint16_t char1 = buf1.GetNext();
    uint16_t char2 = buf2.GetNext();
    if (char1 != char2) return Smi::FromInt(char1 - char2);
  }

  return Smi::FromInt(str1_length - str2_length);
}


2904
static MaybeObject* Runtime_SubString(Arguments args) {
2905 2906 2907 2908
  NoHandleAllocation ha;
  ASSERT(args.length() == 3);

  CONVERT_CHECKED(String, value, args[0]);
2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922
  Object* from = args[1];
  Object* to = args[2];
  int start, end;
  // We have a fast integer-only case here to avoid a conversion to double in
  // the common case where from and to are Smis.
  if (from->IsSmi() && to->IsSmi()) {
    start = Smi::cast(from)->value();
    end = Smi::cast(to)->value();
  } else {
    CONVERT_DOUBLE_CHECKED(from_number, from);
    CONVERT_DOUBLE_CHECKED(to_number, to);
    start = FastD2I(from_number);
    end = FastD2I(to_number);
  }
2923 2924
  RUNTIME_ASSERT(end >= start);
  RUNTIME_ASSERT(start >= 0);
2925
  RUNTIME_ASSERT(end <= value->length());
2926
  Counters::sub_string_runtime.Increment();
2927
  return value->SubString(start, end);
2928 2929 2930
}


2931
static MaybeObject* Runtime_StringMatch(Arguments args) {
2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948
  ASSERT_EQ(3, args.length());

  CONVERT_ARG_CHECKED(String, subject, 0);
  CONVERT_ARG_CHECKED(JSRegExp, regexp, 1);
  CONVERT_ARG_CHECKED(JSArray, regexp_info, 2);
  HandleScope handles;

  Handle<Object> match = RegExpImpl::Exec(regexp, subject, 0, regexp_info);

  if (match.is_null()) {
    return Failure::Exception();
  }
  if (match->IsNull()) {
    return Heap::null_value();
  }
  int length = subject->length();

2949
  CompilationZoneScope zone_space(DELETE_ON_EXIT);
2950 2951 2952 2953 2954 2955
  ZoneList<int> offsets(8);
  do {
    int start;
    int end;
    {
      AssertNoAllocation no_alloc;
2956
      FixedArray* elements = FixedArray::cast(regexp_info->elements());
2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973
      start = Smi::cast(elements->get(RegExpImpl::kFirstCapture))->value();
      end = Smi::cast(elements->get(RegExpImpl::kFirstCapture + 1))->value();
    }
    offsets.Add(start);
    offsets.Add(end);
    int index = start < end ? end : end + 1;
    if (index > length) break;
    match = RegExpImpl::Exec(regexp, subject, index, regexp_info);
    if (match.is_null()) {
      return Failure::Exception();
    }
  } while (!match->IsNull());
  int matches = offsets.length() / 2;
  Handle<FixedArray> elements = Factory::NewFixedArray(matches);
  for (int i = 0; i < matches ; i++) {
    int from = offsets.at(i * 2);
    int to = offsets.at(i * 2 + 1);
2974 2975
    Handle<String> match = Factory::NewSubString(subject, from, to);
    elements->set(i, *match);
2976 2977 2978 2979 2980 2981 2982
  }
  Handle<JSArray> result = Factory::NewJSArrayWithElements(elements);
  result->set_length(Smi::FromInt(matches));
  return *result;
}


2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002
// Two smis before and after the match, for very long strings.
const int kMaxBuilderEntriesPerRegExpMatch = 5;


static void SetLastMatchInfoNoCaptures(Handle<String> subject,
                                       Handle<JSArray> last_match_info,
                                       int match_start,
                                       int match_end) {
  // Fill last_match_info with a single capture.
  last_match_info->EnsureSize(2 + RegExpImpl::kLastMatchOverhead);
  AssertNoAllocation no_gc;
  FixedArray* elements = FixedArray::cast(last_match_info->elements());
  RegExpImpl::SetLastCaptureCount(elements, 2);
  RegExpImpl::SetLastInput(elements, *subject);
  RegExpImpl::SetLastSubject(elements, *subject);
  RegExpImpl::SetCapture(elements, 0, match_start);
  RegExpImpl::SetCapture(elements, 1, match_end);
}


3003 3004 3005 3006
template <typename SubjectChar, typename PatternChar>
static bool SearchStringMultiple(Vector<const SubjectChar> subject,
                                 Vector<const PatternChar> pattern,
                                 String* pattern_string,
3007 3008 3009 3010
                                 FixedArrayBuilder* builder,
                                 int* match_pos) {
  int pos = *match_pos;
  int subject_length = subject.length();
3011
  int pattern_length = pattern.length();
3012
  int max_search_start = subject_length - pattern_length;
3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027
  StringSearch<PatternChar, SubjectChar> search(pattern);
  while (pos <= max_search_start) {
    if (!builder->HasCapacity(kMaxBuilderEntriesPerRegExpMatch)) {
      *match_pos = pos;
      return false;
    }
    // Position of end of previous match.
    int match_end = pos + pattern_length;
    int new_pos = search.Search(subject, match_end);
    if (new_pos >= 0) {
      // A match.
      if (new_pos > match_end) {
        ReplacementStringBuilder::AddSubjectSlice(builder,
            match_end,
            new_pos);
3028
      }
3029 3030 3031
      pos = new_pos;
      builder->Add(pattern_string);
    } else {
3032
      break;
3033
    }
3034
  }
3035

3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063
  if (pos < max_search_start) {
    ReplacementStringBuilder::AddSubjectSlice(builder,
                                              pos + pattern_length,
                                              subject_length);
  }
  *match_pos = pos;
  return true;
}


static bool SearchStringMultiple(Handle<String> subject,
                                 Handle<String> pattern,
                                 Handle<JSArray> last_match_info,
                                 FixedArrayBuilder* builder) {
  ASSERT(subject->IsFlat());
  ASSERT(pattern->IsFlat());

  // Treating as if a previous match was before first character.
  int match_pos = -pattern->length();

  for (;;) {  // Break when search complete.
    builder->EnsureCapacity(kMaxBuilderEntriesPerRegExpMatch);
    AssertNoAllocation no_gc;
    if (subject->IsAsciiRepresentation()) {
      Vector<const char> subject_vector = subject->ToAsciiVector();
      if (pattern->IsAsciiRepresentation()) {
        if (SearchStringMultiple(subject_vector,
                                 pattern->ToAsciiVector(),
3064
                                 *pattern,
3065 3066 3067 3068 3069
                                 builder,
                                 &match_pos)) break;
      } else {
        if (SearchStringMultiple(subject_vector,
                                 pattern->ToUC16Vector(),
3070
                                 *pattern,
3071 3072 3073 3074 3075 3076 3077 3078
                                 builder,
                                 &match_pos)) break;
      }
    } else {
      Vector<const uc16> subject_vector = subject->ToUC16Vector();
      if (pattern->IsAsciiRepresentation()) {
        if (SearchStringMultiple(subject_vector,
                                 pattern->ToAsciiVector(),
3079
                                 *pattern,
3080 3081 3082 3083 3084
                                 builder,
                                 &match_pos)) break;
      } else {
        if (SearchStringMultiple(subject_vector,
                                 pattern->ToUC16Vector(),
3085
                                 *pattern,
3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115
                                 builder,
                                 &match_pos)) break;
      }
    }
  }

  if (match_pos >= 0) {
    SetLastMatchInfoNoCaptures(subject,
                               last_match_info,
                               match_pos,
                               match_pos + pattern->length());
    return true;
  }
  return false;  // No matches at all.
}


static RegExpImpl::IrregexpResult SearchRegExpNoCaptureMultiple(
    Handle<String> subject,
    Handle<JSRegExp> regexp,
    Handle<JSArray> last_match_array,
    FixedArrayBuilder* builder) {
  ASSERT(subject->IsFlat());
  int match_start = -1;
  int match_end = 0;
  int pos = 0;
  int required_registers = RegExpImpl::IrregexpPrepare(regexp, subject);
  if (required_registers < 0) return RegExpImpl::RE_EXCEPTION;

  OffsetsVector registers(required_registers);
3116
  Vector<int32_t> register_vector(registers.vector(), registers.length());
3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177
  int subject_length = subject->length();

  for (;;) {  // Break on failure, return on exception.
    RegExpImpl::IrregexpResult result =
        RegExpImpl::IrregexpExecOnce(regexp,
                                     subject,
                                     pos,
                                     register_vector);
    if (result == RegExpImpl::RE_SUCCESS) {
      match_start = register_vector[0];
      builder->EnsureCapacity(kMaxBuilderEntriesPerRegExpMatch);
      if (match_end < match_start) {
        ReplacementStringBuilder::AddSubjectSlice(builder,
                                                  match_end,
                                                  match_start);
      }
      match_end = register_vector[1];
      HandleScope loop_scope;
      builder->Add(*Factory::NewSubString(subject, match_start, match_end));
      if (match_start != match_end) {
        pos = match_end;
      } else {
        pos = match_end + 1;
        if (pos > subject_length) break;
      }
    } else if (result == RegExpImpl::RE_FAILURE) {
      break;
    } else {
      ASSERT_EQ(result, RegExpImpl::RE_EXCEPTION);
      return result;
    }
  }

  if (match_start >= 0) {
    if (match_end < subject_length) {
      ReplacementStringBuilder::AddSubjectSlice(builder,
                                                match_end,
                                                subject_length);
    }
    SetLastMatchInfoNoCaptures(subject,
                               last_match_array,
                               match_start,
                               match_end);
    return RegExpImpl::RE_SUCCESS;
  } else {
    return RegExpImpl::RE_FAILURE;  // No matches at all.
  }
}


static RegExpImpl::IrregexpResult SearchRegExpMultiple(
    Handle<String> subject,
    Handle<JSRegExp> regexp,
    Handle<JSArray> last_match_array,
    FixedArrayBuilder* builder) {

  ASSERT(subject->IsFlat());
  int required_registers = RegExpImpl::IrregexpPrepare(regexp, subject);
  if (required_registers < 0) return RegExpImpl::RE_EXCEPTION;

  OffsetsVector registers(required_registers);
3178
  Vector<int32_t> register_vector(registers.vector(), registers.length());
3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214

  RegExpImpl::IrregexpResult result =
      RegExpImpl::IrregexpExecOnce(regexp,
                                   subject,
                                   0,
                                   register_vector);

  int capture_count = regexp->CaptureCount();
  int subject_length = subject->length();

  // Position to search from.
  int pos = 0;
  // End of previous match. Differs from pos if match was empty.
  int match_end = 0;
  if (result == RegExpImpl::RE_SUCCESS) {
    // Need to keep a copy of the previous match for creating last_match_info
    // at the end, so we have two vectors that we swap between.
    OffsetsVector registers2(required_registers);
    Vector<int> prev_register_vector(registers2.vector(), registers2.length());

    do {
      int match_start = register_vector[0];
      builder->EnsureCapacity(kMaxBuilderEntriesPerRegExpMatch);
      if (match_end < match_start) {
        ReplacementStringBuilder::AddSubjectSlice(builder,
                                                  match_end,
                                                  match_start);
      }
      match_end = register_vector[1];

      {
        // Avoid accumulating new handles inside loop.
        HandleScope temp_scope;
        // Arguments array to replace function is match, captures, index and
        // subject, i.e., 3 + capture count in total.
        Handle<FixedArray> elements = Factory::NewFixedArray(3 + capture_count);
3215 3216 3217 3218
        Handle<String> match = Factory::NewSubString(subject,
                                                     match_start,
                                                     match_end);
        elements->set(0, *match);
3219
        for (int i = 1; i <= capture_count; i++) {
3220 3221 3222 3223
          int start = register_vector[i * 2];
          if (start >= 0) {
            int end = register_vector[i * 2 + 1];
            ASSERT(start <= end);
vitalyr@chromium.org's avatar
vitalyr@chromium.org committed
3224 3225 3226
            Handle<String> substring = Factory::NewSubString(subject,
                                                             start,
                                                             end);
3227 3228 3229 3230 3231
            elements->set(i, *substring);
          } else {
            ASSERT(register_vector[i * 2 + 1] < 0);
            elements->set(i, Heap::undefined_value());
          }
3232 3233 3234 3235 3236 3237 3238
        }
        elements->set(capture_count + 1, Smi::FromInt(match_start));
        elements->set(capture_count + 2, *subject);
        builder->Add(*Factory::NewJSArrayWithElements(elements));
      }
      // Swap register vectors, so the last successful match is in
      // prev_register_vector.
3239
      Vector<int32_t> tmp = prev_register_vector;
3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285
      prev_register_vector = register_vector;
      register_vector = tmp;

      if (match_end > match_start) {
        pos = match_end;
      } else {
        pos = match_end + 1;
        if (pos > subject_length) {
          break;
        }
      }

      result = RegExpImpl::IrregexpExecOnce(regexp,
                                            subject,
                                            pos,
                                            register_vector);
    } while (result == RegExpImpl::RE_SUCCESS);

    if (result != RegExpImpl::RE_EXCEPTION) {
      // Finished matching, with at least one match.
      if (match_end < subject_length) {
        ReplacementStringBuilder::AddSubjectSlice(builder,
                                                  match_end,
                                                  subject_length);
      }

      int last_match_capture_count = (capture_count + 1) * 2;
      int last_match_array_size =
          last_match_capture_count + RegExpImpl::kLastMatchOverhead;
      last_match_array->EnsureSize(last_match_array_size);
      AssertNoAllocation no_gc;
      FixedArray* elements = FixedArray::cast(last_match_array->elements());
      RegExpImpl::SetLastCaptureCount(elements, last_match_capture_count);
      RegExpImpl::SetLastSubject(elements, *subject);
      RegExpImpl::SetLastInput(elements, *subject);
      for (int i = 0; i < last_match_capture_count; i++) {
        RegExpImpl::SetCapture(elements, i, prev_register_vector[i]);
      }
      return RegExpImpl::RE_SUCCESS;
    }
  }
  // No matches at all, return failure or exception result directly.
  return result;
}


3286
static MaybeObject* Runtime_RegExpExecMultiple(Arguments args) {
3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309
  ASSERT(args.length() == 4);
  HandleScope handles;

  CONVERT_ARG_CHECKED(String, subject, 1);
  if (!subject->IsFlat()) { FlattenString(subject); }
  CONVERT_ARG_CHECKED(JSRegExp, regexp, 0);
  CONVERT_ARG_CHECKED(JSArray, last_match_info, 2);
  CONVERT_ARG_CHECKED(JSArray, result_array, 3);

  ASSERT(last_match_info->HasFastElements());
  ASSERT(regexp->GetFlags().is_global());
  Handle<FixedArray> result_elements;
  if (result_array->HasFastElements()) {
    result_elements =
        Handle<FixedArray>(FixedArray::cast(result_array->elements()));
  } else {
    result_elements = Factory::NewFixedArrayWithHoles(16);
  }
  FixedArrayBuilder builder(result_elements);

  if (regexp->TypeTag() == JSRegExp::ATOM) {
    Handle<String> pattern(
        String::cast(regexp->DataAt(JSRegExp::kAtomPatternIndex)));
3310
    ASSERT(pattern->IsFlat());
3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334
    if (SearchStringMultiple(subject, pattern, last_match_info, &builder)) {
      return *builder.ToJSArray(result_array);
    }
    return Heap::null_value();
  }

  ASSERT_EQ(regexp->TypeTag(), JSRegExp::IRREGEXP);

  RegExpImpl::IrregexpResult result;
  if (regexp->CaptureCount() == 0) {
    result = SearchRegExpNoCaptureMultiple(subject,
                                           regexp,
                                           last_match_info,
                                           &builder);
  } else {
    result = SearchRegExpMultiple(subject, regexp, last_match_info, &builder);
  }
  if (result == RegExpImpl::RE_SUCCESS) return *builder.ToJSArray(result_array);
  if (result == RegExpImpl::RE_FAILURE) return Heap::null_value();
  ASSERT_EQ(result, RegExpImpl::RE_EXCEPTION);
  return Failure::Exception();
}


3335
static MaybeObject* Runtime_NumberToRadixString(Arguments args) {
3336 3337 3338
  NoHandleAllocation ha;
  ASSERT(args.length() == 2);

3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351
  // Fast case where the result is a one character string.
  if (args[0]->IsSmi() && args[1]->IsSmi()) {
    int value = Smi::cast(args[0])->value();
    int radix = Smi::cast(args[1])->value();
    if (value >= 0 && value < radix) {
      RUNTIME_ASSERT(radix <= 36);
      // Character array used for conversion.
      static const char kCharTable[] = "0123456789abcdefghijklmnopqrstuvwxyz";
      return Heap::LookupSingleCharacterStringFromCode(kCharTable[value]);
    }
  }

  // Slow case.
3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365
  CONVERT_DOUBLE_CHECKED(value, args[0]);
  if (isnan(value)) {
    return Heap::AllocateStringFromAscii(CStrVector("NaN"));
  }
  if (isinf(value)) {
    if (value < 0) {
      return Heap::AllocateStringFromAscii(CStrVector("-Infinity"));
    }
    return Heap::AllocateStringFromAscii(CStrVector("Infinity"));
  }
  CONVERT_DOUBLE_CHECKED(radix_number, args[1]);
  int radix = FastD2I(radix_number);
  RUNTIME_ASSERT(2 <= radix && radix <= 36);
  char* str = DoubleToRadixCString(value, radix);
3366
  MaybeObject* result = Heap::AllocateStringFromAscii(CStrVector(str));
3367 3368 3369 3370 3371
  DeleteArray(str);
  return result;
}


3372
static MaybeObject* Runtime_NumberToFixed(Arguments args) {
3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389
  NoHandleAllocation ha;
  ASSERT(args.length() == 2);

  CONVERT_DOUBLE_CHECKED(value, args[0]);
  if (isnan(value)) {
    return Heap::AllocateStringFromAscii(CStrVector("NaN"));
  }
  if (isinf(value)) {
    if (value < 0) {
      return Heap::AllocateStringFromAscii(CStrVector("-Infinity"));
    }
    return Heap::AllocateStringFromAscii(CStrVector("Infinity"));
  }
  CONVERT_DOUBLE_CHECKED(f_number, args[1]);
  int f = FastD2I(f_number);
  RUNTIME_ASSERT(f >= 0);
  char* str = DoubleToFixedCString(value, f);
3390
  MaybeObject* result = Heap::AllocateStringFromAscii(CStrVector(str));
3391
  DeleteArray(str);
3392
  return result;
3393 3394 3395
}


3396
static MaybeObject* Runtime_NumberToExponential(Arguments args) {
3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413
  NoHandleAllocation ha;
  ASSERT(args.length() == 2);

  CONVERT_DOUBLE_CHECKED(value, args[0]);
  if (isnan(value)) {
    return Heap::AllocateStringFromAscii(CStrVector("NaN"));
  }
  if (isinf(value)) {
    if (value < 0) {
      return Heap::AllocateStringFromAscii(CStrVector("-Infinity"));
    }
    return Heap::AllocateStringFromAscii(CStrVector("Infinity"));
  }
  CONVERT_DOUBLE_CHECKED(f_number, args[1]);
  int f = FastD2I(f_number);
  RUNTIME_ASSERT(f >= -1 && f <= 20);
  char* str = DoubleToExponentialCString(value, f);
3414
  MaybeObject* result = Heap::AllocateStringFromAscii(CStrVector(str));
3415
  DeleteArray(str);
3416
  return result;
3417 3418 3419
}


3420
static MaybeObject* Runtime_NumberToPrecision(Arguments args) {
3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437
  NoHandleAllocation ha;
  ASSERT(args.length() == 2);

  CONVERT_DOUBLE_CHECKED(value, args[0]);
  if (isnan(value)) {
    return Heap::AllocateStringFromAscii(CStrVector("NaN"));
  }
  if (isinf(value)) {
    if (value < 0) {
      return Heap::AllocateStringFromAscii(CStrVector("-Infinity"));
    }
    return Heap::AllocateStringFromAscii(CStrVector("Infinity"));
  }
  CONVERT_DOUBLE_CHECKED(f_number, args[1]);
  int f = FastD2I(f_number);
  RUNTIME_ASSERT(f >= 1 && f <= 21);
  char* str = DoubleToPrecisionCString(value, f);
3438
  MaybeObject* result = Heap::AllocateStringFromAscii(CStrVector(str));
3439
  DeleteArray(str);
3440
  return result;
3441 3442 3443 3444 3445
}


// Returns a single character string where first character equals
// string->Get(index).
3446
static Handle<Object> GetCharAt(Handle<String> string, uint32_t index) {
3447
  if (index < static_cast<uint32_t>(string->length())) {
3448
    string->TryFlatten();
3449
    return LookupSingleCharacterStringFromCode(
3450
        string->Get(index));
3451
  }
3452
  return Execution::CharAt(string, index);
3453 3454 3455
}


3456 3457
MaybeObject* Runtime::GetElementOrCharAt(Handle<Object> object,
                                         uint32_t index) {
3458 3459
  // Handle [] indexing on Strings
  if (object->IsString()) {
3460 3461
    Handle<Object> result = GetCharAt(Handle<String>::cast(object), index);
    if (!result->IsUndefined()) return *result;
3462 3463 3464 3465
  }

  // Handle [] indexing on String objects
  if (object->IsStringObjectWithCharacterAt(index)) {
3466 3467 3468 3469
    Handle<JSValue> js_value = Handle<JSValue>::cast(object);
    Handle<Object> result =
        GetCharAt(Handle<String>(String::cast(js_value->value())), index);
    if (!result->IsUndefined()) return *result;
3470 3471 3472
  }

  if (object->IsString() || object->IsNumber() || object->IsBoolean()) {
3473
    Handle<Object> prototype = GetPrototype(object);
3474 3475 3476
    return prototype->GetElement(index);
  }

3477 3478 3479 3480
  return GetElement(object, index);
}


3481
MaybeObject* Runtime::GetElement(Handle<Object> object, uint32_t index) {
3482 3483 3484 3485
  return object->GetElement(index);
}


3486 3487
MaybeObject* Runtime::GetObjectProperty(Handle<Object> object,
                                        Handle<Object> key) {
3488 3489
  HandleScope scope;

3490
  if (object->IsUndefined() || object->IsNull()) {
3491
    Handle<Object> args[2] = { key, object };
3492 3493 3494 3495 3496 3497 3498 3499
    Handle<Object> error =
        Factory::NewTypeError("non_object_property_load",
                              HandleVector(args, 2));
    return Top::Throw(*error);
  }

  // Check if the given key is an array index.
  uint32_t index;
3500
  if (key->ToArrayIndex(&index)) {
3501 3502 3503 3504
    return GetElementOrCharAt(object, index);
  }

  // Convert the key to a string - possibly by calling back into JavaScript.
3505
  Handle<String> name;
3506
  if (key->IsString()) {
3507
    name = Handle<String>::cast(key);
3508 3509 3510
  } else {
    bool has_pending_exception = false;
    Handle<Object> converted =
3511
        Execution::ToString(key, &has_pending_exception);
3512
    if (has_pending_exception) return Failure::Exception();
3513
    name = Handle<String>::cast(converted);
3514 3515
  }

3516
  // Check if the name is trivially convertible to an index and get
3517 3518 3519 3520 3521
  // the element if so.
  if (name->AsArrayIndex(&index)) {
    return GetElementOrCharAt(object, index);
  } else {
    PropertyAttributes attr;
3522
    return object->GetProperty(*name, &attr);
3523 3524 3525 3526
  }
}


3527
static MaybeObject* Runtime_GetProperty(Arguments args) {
3528 3529 3530 3531
  NoHandleAllocation ha;
  ASSERT(args.length() == 2);

  Handle<Object> object = args.at<Object>(0);
3532
  Handle<Object> key = args.at<Object>(1);
3533 3534 3535 3536 3537

  return Runtime::GetObjectProperty(object, key);
}


3538
// KeyedStringGetProperty is called from KeyedLoadIC::GenerateGeneric.
3539
static MaybeObject* Runtime_KeyedGetProperty(Arguments args) {
3540 3541 3542
  NoHandleAllocation ha;
  ASSERT(args.length() == 2);

3543
  // Fast cases for getting named properties of the receiver JSObject
3544 3545 3546
  // itself.
  //
  // The global proxy objects has to be excluded since LocalLookup on
3547
  // the global proxy object can return a valid result even though the
3548 3549 3550 3551 3552 3553
  // global proxy object never has properties.  This is the case
  // because the global proxy object forwards everything to its hidden
  // prototype including local lookups.
  //
  // Additionally, we need to make sure that we do not cache results
  // for objects that require access checks.
3554 3555
  if (args[0]->IsJSObject() &&
      !args[0]->IsJSGlobalProxy() &&
3556
      !args[0]->IsAccessCheckNeeded() &&
3557 3558 3559 3560 3561 3562
      args[1]->IsString()) {
    JSObject* receiver = JSObject::cast(args[0]);
    String* key = String::cast(args[1]);
    if (receiver->HasFastProperties()) {
      // Attempt to use lookup cache.
      Map* receiver_map = receiver->map();
3563 3564
      int offset = KeyedLookupCache::Lookup(receiver_map, key);
      if (offset != -1) {
3565 3566 3567
        Object* value = receiver->FastPropertyAt(offset);
        return value->IsTheHole() ? Heap::undefined_value() : value;
      }
3568
      // Lookup cache miss.  Perform lookup and update the cache if appropriate.
3569 3570
      LookupResult result;
      receiver->LocalLookup(key, &result);
3571
      if (result.IsProperty() && result.type() == FIELD) {
3572
        int offset = result.GetFieldIndex();
3573
        KeyedLookupCache::Update(receiver_map, key, offset);
3574
        return receiver->FastPropertyAt(offset);
3575 3576 3577
      }
    } else {
      // Attempt dictionary lookup.
3578 3579 3580
      StringDictionary* dictionary = receiver->property_dictionary();
      int entry = dictionary->FindEntry(key);
      if ((entry != StringDictionary::kNotFound) &&
3581
          (dictionary->DetailsAt(entry).type() == NORMAL)) {
3582
        Object* value = dictionary->ValueAt(entry);
3583 3584 3585 3586
        if (!receiver->IsGlobalObject()) return value;
        value = JSGlobalPropertyCell::cast(value)->value();
        if (!value->IsTheHole()) return value;
        // If value is the hole do the general lookup.
3587
      }
3588
    }
3589 3590 3591 3592 3593
  } else if (args[0]->IsString() && args[1]->IsSmi()) {
    // Fast case for string indexing using [] with a smi index.
    HandleScope scope;
    Handle<String> str = args.at<String>(0);
    int index = Smi::cast(args[1])->value();
3594 3595 3596 3597
    if (index >= 0 && index < str->length()) {
      Handle<Object> result = GetCharAt(str, index);
      return *result;
    }
3598
  }
3599 3600

  // Fall back to GetObjectProperty.
3601 3602 3603 3604
  return Runtime::GetObjectProperty(args.at<Object>(0),
                                    args.at<Object>(1));
}

3605 3606 3607 3608 3609 3610
// Implements part of 8.12.9 DefineOwnProperty.
// There are 3 cases that lead here:
// Step 4b - define a new accessor property.
// Steps 9c & 12 - replace an existing data property with an accessor property.
// Step 12 - update an existing accessor property with an accessor or generic
//           descriptor.
3611
static MaybeObject* Runtime_DefineOrRedefineAccessorProperty(Arguments args) {
3612 3613
  ASSERT(args.length() == 5);
  HandleScope scope;
3614
  CONVERT_ARG_CHECKED(JSObject, obj, 0);
3615 3616
  CONVERT_CHECKED(String, name, args[1]);
  CONVERT_CHECKED(Smi, flag_setter, args[2]);
3617 3618
  Object* fun = args[3];
  RUNTIME_ASSERT(fun->IsJSFunction() || fun->IsUndefined());
3619 3620 3621
  CONVERT_CHECKED(Smi, flag_attr, args[4]);
  int unchecked = flag_attr->value();
  RUNTIME_ASSERT((unchecked & ~(READ_ONLY | DONT_ENUM | DONT_DELETE)) == 0);
3622
  RUNTIME_ASSERT(!obj->IsNull());
3623 3624 3625 3626 3627 3628 3629
  LookupResult result;
  obj->LocalLookupRealNamedProperty(name, &result);

  PropertyAttributes attr = static_cast<PropertyAttributes>(unchecked);
  // If an existing property is either FIELD, NORMAL or CONSTANT_FUNCTION
  // delete it to avoid running into trouble in DefineAccessor, which
  // handles this incorrectly if the property is readonly (does nothing)
3630
  if (result.IsProperty() &&
3631 3632
      (result.type() == FIELD || result.type() == NORMAL
       || result.type() == CONSTANT_FUNCTION)) {
3633 3634 3635 3636 3637
    Object* ok;
    { MaybeObject* maybe_ok =
          obj->DeleteProperty(name, JSObject::NORMAL_DELETION);
      if (!maybe_ok->ToObject(&ok)) return maybe_ok;
    }
3638
  }
3639 3640 3641
  return obj->DefineAccessor(name, flag_setter->value() == 0, fun, attr);
}

3642 3643 3644 3645 3646 3647
// Implements part of 8.12.9 DefineOwnProperty.
// There are 3 cases that lead here:
// Step 4a - define a new data property.
// Steps 9b & 12 - replace an existing accessor property with a data property.
// Step 12 - update an existing data property with a data or generic
//           descriptor.
3648
static MaybeObject* Runtime_DefineOrRedefineDataProperty(Arguments args) {
3649 3650
  ASSERT(args.length() == 4);
  HandleScope scope;
3651 3652
  CONVERT_ARG_CHECKED(JSObject, js_object, 0);
  CONVERT_ARG_CHECKED(String, name, 1);
3653
  Handle<Object> obj_value = args.at<Object>(2);
3654

3655 3656 3657 3658
  CONVERT_CHECKED(Smi, flag, args[3]);
  int unchecked = flag->value();
  RUNTIME_ASSERT((unchecked & ~(READ_ONLY | DONT_ENUM | DONT_DELETE)) == 0);

3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670
  PropertyAttributes attr = static_cast<PropertyAttributes>(unchecked);

  // Check if this is an element.
  uint32_t index;
  bool is_element = name->AsArrayIndex(&index);

  // Special case for elements if any of the flags are true.
  // If elements are in fast case we always implicitly assume that:
  // DONT_DELETE: false, DONT_ENUM: false, READ_ONLY: false.
  if (((unchecked & (DONT_DELETE | DONT_ENUM | READ_ONLY)) != 0) &&
      is_element) {
    // Normalize the elements to enable attributes on the property.
3671 3672 3673
    if (!js_object->IsJSGlobalProxy()) {
      NormalizeElements(js_object);
    }
3674
    Handle<NumberDictionary> dictionary(js_object->element_dictionary());
3675 3676 3677
    // Make sure that we never go back to fast case.
    dictionary->set_requires_slow_elements();
    PropertyDetails details = PropertyDetails(attr, NORMAL);
3678
    NumberDictionarySet(dictionary, index, obj_value, details);
3679 3680
  }

3681
  LookupResult result;
3682
  js_object->LookupRealNamedProperty(*name, &result);
3683 3684 3685 3686 3687 3688 3689

  // Take special care when attributes are different and there is already
  // a property. For simplicity we normalize the property which enables us
  // to not worry about changing the instance_descriptor and creating a new
  // map. The current version of SetObjectProperty does not handle attributes
  // correctly in the case where a property is a field and is reset with
  // new attributes.
3690 3691
  if (result.IsProperty() &&
      (attr != result.GetAttributes() || result.type() == CALLBACKS)) {
3692
    // New attributes - normalize to avoid writing to instance descriptor
3693 3694 3695
    if (!js_object->IsJSGlobalProxy()) {
      NormalizeProperties(js_object, CLEAR_INOBJECT_PROPERTIES, 0);
    }
3696 3697
    // Use IgnoreAttributes version since a readonly property may be
    // overridden and SetProperty does not allow this.
3698 3699 3700
    return js_object->SetLocalPropertyIgnoreAttributes(*name,
                                                       *obj_value,
                                                       attr);
3701
  }
3702

3703 3704 3705 3706
  return Runtime::SetObjectProperty(js_object, name, obj_value, attr);
}


3707 3708 3709 3710
MaybeObject* Runtime::SetObjectProperty(Handle<Object> object,
                                        Handle<Object> key,
                                        Handle<Object> value,
                                        PropertyAttributes attr) {
3711 3712
  HandleScope scope;

3713
  if (object->IsUndefined() || object->IsNull()) {
3714
    Handle<Object> args[2] = { key, object };
3715 3716 3717 3718 3719 3720 3721 3722 3723
    Handle<Object> error =
        Factory::NewTypeError("non_object_property_store",
                              HandleVector(args, 2));
    return Top::Throw(*error);
  }

  // If the object isn't a JavaScript object, we ignore the store.
  if (!object->IsJSObject()) return *value;

3724 3725
  Handle<JSObject> js_object = Handle<JSObject>::cast(object);

3726 3727
  // Check if the given key is an array index.
  uint32_t index;
3728
  if (key->ToArrayIndex(&index)) {
3729 3730 3731 3732 3733 3734 3735
    // In Firefox/SpiderMonkey, Safari and Opera you can access the characters
    // of a string using [] notation.  We need to support this too in
    // JavaScript.
    // In the case of a String object we just need to redirect the assignment to
    // the underlying string if the index is in range.  Since the underlying
    // string does nothing with the assignment then we can ignore such
    // assignments.
3736
    if (js_object->IsStringObjectWithCharacterAt(index)) {
3737
      return *value;
3738
    }
3739

3740 3741
    Handle<Object> result = SetElement(js_object, index, value);
    if (result.is_null()) return Failure::Exception();
3742 3743 3744 3745
    return *value;
  }

  if (key->IsString()) {
3746 3747 3748
    Handle<Object> result;
    if (Handle<String>::cast(key)->AsArrayIndex(&index)) {
      result = SetElement(js_object, index, value);
3749
    } else {
3750
      Handle<String> key_string = Handle<String>::cast(key);
3751
      key_string->TryFlatten();
3752
      result = SetProperty(js_object, key_string, value, attr);
3753
    }
3754
    if (result.is_null()) return Failure::Exception();
3755 3756 3757 3758 3759 3760 3761 3762 3763 3764
    return *value;
  }

  // Call-back into JavaScript to convert the key to a string.
  bool has_pending_exception = false;
  Handle<Object> converted = Execution::ToString(key, &has_pending_exception);
  if (has_pending_exception) return Failure::Exception();
  Handle<String> name = Handle<String>::cast(converted);

  if (name->AsArrayIndex(&index)) {
3765
    return js_object->SetElement(index, *value);
3766
  } else {
3767
    return js_object->SetProperty(*name, *value, attr);
3768 3769 3770 3771
  }
}


3772 3773 3774 3775
MaybeObject* Runtime::ForceSetObjectProperty(Handle<JSObject> js_object,
                                             Handle<Object> key,
                                             Handle<Object> value,
                                             PropertyAttributes attr) {
3776 3777 3778 3779
  HandleScope scope;

  // Check if the given key is an array index.
  uint32_t index;
3780
  if (key->ToArrayIndex(&index)) {
3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799
    // In Firefox/SpiderMonkey, Safari and Opera you can access the characters
    // of a string using [] notation.  We need to support this too in
    // JavaScript.
    // In the case of a String object we just need to redirect the assignment to
    // the underlying string if the index is in range.  Since the underlying
    // string does nothing with the assignment then we can ignore such
    // assignments.
    if (js_object->IsStringObjectWithCharacterAt(index)) {
      return *value;
    }

    return js_object->SetElement(index, *value);
  }

  if (key->IsString()) {
    if (Handle<String>::cast(key)->AsArrayIndex(&index)) {
      return js_object->SetElement(index, *value);
    } else {
      Handle<String> key_string = Handle<String>::cast(key);
3800
      key_string->TryFlatten();
3801 3802 3803
      return js_object->SetLocalPropertyIgnoreAttributes(*key_string,
                                                         *value,
                                                         attr);
3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815
    }
  }

  // Call-back into JavaScript to convert the key to a string.
  bool has_pending_exception = false;
  Handle<Object> converted = Execution::ToString(key, &has_pending_exception);
  if (has_pending_exception) return Failure::Exception();
  Handle<String> name = Handle<String>::cast(converted);

  if (name->AsArrayIndex(&index)) {
    return js_object->SetElement(index, *value);
  } else {
3816
    return js_object->SetLocalPropertyIgnoreAttributes(*name, *value, attr);
3817 3818 3819 3820
  }
}


3821 3822
MaybeObject* Runtime::ForceDeleteObjectProperty(Handle<JSObject> js_object,
                                                Handle<Object> key) {
3823 3824 3825 3826
  HandleScope scope;

  // Check if the given key is an array index.
  uint32_t index;
3827
  if (key->ToArrayIndex(&index)) {
3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851
    // In Firefox/SpiderMonkey, Safari and Opera you can access the
    // characters of a string using [] notation.  In the case of a
    // String object we just need to redirect the deletion to the
    // underlying string if the index is in range.  Since the
    // underlying string does nothing with the deletion, we can ignore
    // such deletions.
    if (js_object->IsStringObjectWithCharacterAt(index)) {
      return Heap::true_value();
    }

    return js_object->DeleteElement(index, JSObject::FORCE_DELETION);
  }

  Handle<String> key_string;
  if (key->IsString()) {
    key_string = Handle<String>::cast(key);
  } else {
    // Call-back into JavaScript to convert the key to a string.
    bool has_pending_exception = false;
    Handle<Object> converted = Execution::ToString(key, &has_pending_exception);
    if (has_pending_exception) return Failure::Exception();
    key_string = Handle<String>::cast(converted);
  }

3852
  key_string->TryFlatten();
3853 3854 3855 3856
  return js_object->DeleteProperty(*key_string, JSObject::FORCE_DELETION);
}


3857
static MaybeObject* Runtime_SetProperty(Arguments args) {
3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868
  NoHandleAllocation ha;
  RUNTIME_ASSERT(args.length() == 3 || args.length() == 4);

  Handle<Object> object = args.at<Object>(0);
  Handle<Object> key = args.at<Object>(1);
  Handle<Object> value = args.at<Object>(2);

  // Compute attributes.
  PropertyAttributes attributes = NONE;
  if (args.length() == 4) {
    CONVERT_CHECKED(Smi, value_obj, args[3]);
3869
    int unchecked_value = value_obj->value();
3870
    // Only attribute bits should be set.
3871 3872 3873
    RUNTIME_ASSERT(
        (unchecked_value & ~(READ_ONLY | DONT_ENUM | DONT_DELETE)) == 0);
    attributes = static_cast<PropertyAttributes>(unchecked_value);
3874 3875 3876 3877 3878 3879 3880
  }
  return Runtime::SetObjectProperty(object, key, value, attributes);
}


// Set a local property, even if it is READ_ONLY.  If the property does not
// exist, it will be added with attributes NONE.
3881
static MaybeObject* Runtime_IgnoreAttributesAndSetProperty(Arguments args) {
3882
  NoHandleAllocation ha;
3883
  RUNTIME_ASSERT(args.length() == 3 || args.length() == 4);
3884 3885
  CONVERT_CHECKED(JSObject, object, args[0]);
  CONVERT_CHECKED(String, name, args[1]);
3886 3887 3888 3889 3890 3891 3892 3893 3894 3895
  // Compute attributes.
  PropertyAttributes attributes = NONE;
  if (args.length() == 4) {
    CONVERT_CHECKED(Smi, value_obj, args[3]);
    int unchecked_value = value_obj->value();
    // Only attribute bits should be set.
    RUNTIME_ASSERT(
        (unchecked_value & ~(READ_ONLY | DONT_ENUM | DONT_DELETE)) == 0);
    attributes = static_cast<PropertyAttributes>(unchecked_value);
  }
3896

3897
  return object->
3898
      SetLocalPropertyIgnoreAttributes(name, args[2], attributes);
3899 3900 3901
}


3902
static MaybeObject* Runtime_DeleteProperty(Arguments args) {
3903 3904 3905 3906 3907
  NoHandleAllocation ha;
  ASSERT(args.length() == 2);

  CONVERT_CHECKED(JSObject, object, args[0]);
  CONVERT_CHECKED(String, key, args[1]);
3908
  return object->DeleteProperty(key, JSObject::NORMAL_DELETION);
3909 3910 3911
}


3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926
static Object* HasLocalPropertyImplementation(Handle<JSObject> object,
                                              Handle<String> key) {
  if (object->HasLocalProperty(*key)) return Heap::true_value();
  // Handle hidden prototypes.  If there's a hidden prototype above this thing
  // then we have to check it for properties, because they are supposed to
  // look like they are on this object.
  Handle<Object> proto(object->GetPrototype());
  if (proto->IsJSObject() &&
      Handle<JSObject>::cast(proto)->map()->is_hidden_prototype()) {
    return HasLocalPropertyImplementation(Handle<JSObject>::cast(proto), key);
  }
  return Heap::false_value();
}


3927
static MaybeObject* Runtime_HasLocalProperty(Arguments args) {
3928 3929 3930 3931 3932
  NoHandleAllocation ha;
  ASSERT(args.length() == 2);
  CONVERT_CHECKED(String, key, args[1]);

  Object* obj = args[0];
3933
  // Only JS objects can have properties.
3934 3935
  if (obj->IsJSObject()) {
    JSObject* object = JSObject::cast(obj);
3936 3937 3938 3939 3940 3941 3942
    // Fast case - no interceptors.
    if (object->HasRealNamedProperty(key)) return Heap::true_value();
    // Slow case.  Either it's not there or we have an interceptor.  We should
    // have handles for this kind of deal.
    HandleScope scope;
    return HasLocalPropertyImplementation(Handle<JSObject>(object),
                                          Handle<String>(key));
3943
  } else if (obj->IsString()) {
3944 3945 3946
    // Well, there is one exception:  Handle [] on strings.
    uint32_t index;
    if (key->AsArrayIndex(&index)) {
3947
      String* string = String::cast(obj);
3948
      if (index < static_cast<uint32_t>(string->length()))
3949 3950 3951 3952 3953 3954 3955
        return Heap::true_value();
    }
  }
  return Heap::false_value();
}


3956
static MaybeObject* Runtime_HasProperty(Arguments args) {
3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969
  NoHandleAllocation na;
  ASSERT(args.length() == 2);

  // Only JS objects can have properties.
  if (args[0]->IsJSObject()) {
    JSObject* object = JSObject::cast(args[0]);
    CONVERT_CHECKED(String, key, args[1]);
    if (object->HasProperty(key)) return Heap::true_value();
  }
  return Heap::false_value();
}


3970
static MaybeObject* Runtime_HasElement(Arguments args) {
3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984
  NoHandleAllocation na;
  ASSERT(args.length() == 2);

  // Only JS objects can have elements.
  if (args[0]->IsJSObject()) {
    JSObject* object = JSObject::cast(args[0]);
    CONVERT_CHECKED(Smi, index_obj, args[1]);
    uint32_t index = index_obj->value();
    if (object->HasElement(index)) return Heap::true_value();
  }
  return Heap::false_value();
}


3985
static MaybeObject* Runtime_IsPropertyEnumerable(Arguments args) {
3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996
  NoHandleAllocation ha;
  ASSERT(args.length() == 2);

  CONVERT_CHECKED(JSObject, object, args[0]);
  CONVERT_CHECKED(String, key, args[1]);

  uint32_t index;
  if (key->AsArrayIndex(&index)) {
    return Heap::ToBoolean(object->HasElement(index));
  }

3997
  PropertyAttributes att = object->GetLocalPropertyAttribute(key);
3998
  return Heap::ToBoolean(att != ABSENT && (att & DONT_ENUM) == 0);
3999 4000 4001
}


4002
static MaybeObject* Runtime_GetPropertyNames(Arguments args) {
4003 4004
  HandleScope scope;
  ASSERT(args.length() == 1);
4005
  CONVERT_ARG_CHECKED(JSObject, object, 0);
4006 4007 4008 4009 4010 4011 4012 4013 4014
  return *GetKeysFor(object);
}


// Returns either a FixedArray as Runtime_GetPropertyNames,
// or, if the given object has an enum cache that contains
// all enumerable properties of the object and its prototypes
// have none, the map of the object. This is used to speed up
// the check for deletions during a for-in.
4015
static MaybeObject* Runtime_GetPropertyNamesFast(Arguments args) {
4016 4017 4018 4019 4020 4021 4022 4023
  ASSERT(args.length() == 1);

  CONVERT_CHECKED(JSObject, raw_object, args[0]);

  if (raw_object->IsSimpleEnum()) return raw_object->map();

  HandleScope scope;
  Handle<JSObject> object(raw_object);
4024 4025
  Handle<FixedArray> content = GetKeysInFixedArrayFor(object,
                                                      INCLUDE_PROTOS);
4026 4027 4028 4029 4030 4031 4032 4033

  // Test again, since cache may have been built by preceding call.
  if (object->IsSimpleEnum()) return object->map();

  return *content;
}


4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050
// Find the length of the prototype chain that is to to handled as one. If a
// prototype object is hidden it is to be viewed as part of the the object it
// is prototype for.
static int LocalPrototypeChainLength(JSObject* obj) {
  int count = 1;
  Object* proto = obj->GetPrototype();
  while (proto->IsJSObject() &&
         JSObject::cast(proto)->map()->is_hidden_prototype()) {
    count++;
    proto = JSObject::cast(proto)->GetPrototype();
  }
  return count;
}


// Return the names of the local named properties.
// args[0]: object
4051
static MaybeObject* Runtime_GetLocalPropertyNames(Arguments args) {
4052 4053 4054 4055 4056 4057 4058 4059 4060 4061
  HandleScope scope;
  ASSERT(args.length() == 1);
  if (!args[0]->IsJSObject()) {
    return Heap::undefined_value();
  }
  CONVERT_ARG_CHECKED(JSObject, obj, 0);

  // Skip the global proxy as it has no properties and always delegates to the
  // real global object.
  if (obj->IsJSGlobalProxy()) {
4062 4063 4064 4065 4066 4067
    // Only collect names if access is permitted.
    if (obj->IsAccessCheckNeeded() &&
        !Top::MayNamedAccess(*obj, Heap::undefined_value(), v8::ACCESS_KEYS)) {
      Top::ReportFailedAccessCheck(*obj, v8::ACCESS_KEYS);
      return *Factory::NewJSArray(0);
    }
4068 4069 4070 4071 4072 4073 4074
    obj = Handle<JSObject>(JSObject::cast(obj->GetPrototype()));
  }

  // Find the number of objects making up this.
  int length = LocalPrototypeChainLength(*obj);

  // Find the number of local properties for each of the objects.
4075
  ScopedVector<int> local_property_count(length);
4076 4077 4078
  int total_property_count = 0;
  Handle<JSObject> jsproto = obj;
  for (int i = 0; i < length; i++) {
4079 4080 4081 4082 4083 4084 4085 4086
    // Only collect names if access is permitted.
    if (jsproto->IsAccessCheckNeeded() &&
        !Top::MayNamedAccess(*jsproto,
                             Heap::undefined_value(),
                             v8::ACCESS_KEYS)) {
      Top::ReportFailedAccessCheck(*jsproto, v8::ACCESS_KEYS);
      return *Factory::NewJSArray(0);
    }
4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133
    int n;
    n = jsproto->NumberOfLocalProperties(static_cast<PropertyAttributes>(NONE));
    local_property_count[i] = n;
    total_property_count += n;
    if (i < length - 1) {
      jsproto = Handle<JSObject>(JSObject::cast(jsproto->GetPrototype()));
    }
  }

  // Allocate an array with storage for all the property names.
  Handle<FixedArray> names = Factory::NewFixedArray(total_property_count);

  // Get the property names.
  jsproto = obj;
  int proto_with_hidden_properties = 0;
  for (int i = 0; i < length; i++) {
    jsproto->GetLocalPropertyNames(*names,
                                   i == 0 ? 0 : local_property_count[i - 1]);
    if (!GetHiddenProperties(jsproto, false)->IsUndefined()) {
      proto_with_hidden_properties++;
    }
    if (i < length - 1) {
      jsproto = Handle<JSObject>(JSObject::cast(jsproto->GetPrototype()));
    }
  }

  // Filter out name of hidden propeties object.
  if (proto_with_hidden_properties > 0) {
    Handle<FixedArray> old_names = names;
    names = Factory::NewFixedArray(
        names->length() - proto_with_hidden_properties);
    int dest_pos = 0;
    for (int i = 0; i < total_property_count; i++) {
      Object* name = old_names->get(i);
      if (name == Heap::hidden_symbol()) {
        continue;
      }
      names->set(dest_pos++, name);
    }
  }

  return *Factory::NewJSArrayWithElements(names);
}


// Return the names of the local indexed properties.
// args[0]: object
4134
static MaybeObject* Runtime_GetLocalElementNames(Arguments args) {
4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150
  HandleScope scope;
  ASSERT(args.length() == 1);
  if (!args[0]->IsJSObject()) {
    return Heap::undefined_value();
  }
  CONVERT_ARG_CHECKED(JSObject, obj, 0);

  int n = obj->NumberOfLocalElements(static_cast<PropertyAttributes>(NONE));
  Handle<FixedArray> names = Factory::NewFixedArray(n);
  obj->GetLocalElementKeys(*names, static_cast<PropertyAttributes>(NONE));
  return *Factory::NewJSArrayWithElements(names);
}


// Return information on whether an object has a named or indexed interceptor.
// args[0]: object
4151
static MaybeObject* Runtime_GetInterceptorInfo(Arguments args) {
4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168
  HandleScope scope;
  ASSERT(args.length() == 1);
  if (!args[0]->IsJSObject()) {
    return Smi::FromInt(0);
  }
  CONVERT_ARG_CHECKED(JSObject, obj, 0);

  int result = 0;
  if (obj->HasNamedInterceptor()) result |= 2;
  if (obj->HasIndexedInterceptor()) result |= 1;

  return Smi::FromInt(result);
}


// Return property names from named interceptor.
// args[0]: object
4169
static MaybeObject* Runtime_GetNamedInterceptorPropertyNames(Arguments args) {
4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183
  HandleScope scope;
  ASSERT(args.length() == 1);
  CONVERT_ARG_CHECKED(JSObject, obj, 0);

  if (obj->HasNamedInterceptor()) {
    v8::Handle<v8::Array> result = GetKeysForNamedInterceptor(obj, obj);
    if (!result.IsEmpty()) return *v8::Utils::OpenHandle(*result);
  }
  return Heap::undefined_value();
}


// Return element names from indexed interceptor.
// args[0]: object
4184
static MaybeObject* Runtime_GetIndexedInterceptorElementNames(Arguments args) {
4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196
  HandleScope scope;
  ASSERT(args.length() == 1);
  CONVERT_ARG_CHECKED(JSObject, obj, 0);

  if (obj->HasIndexedInterceptor()) {
    v8::Handle<v8::Array> result = GetKeysForIndexedInterceptor(obj, obj);
    if (!result.IsEmpty()) return *v8::Utils::OpenHandle(*result);
  }
  return Heap::undefined_value();
}


4197
static MaybeObject* Runtime_LocalKeys(Arguments args) {
4198 4199 4200 4201 4202 4203 4204 4205 4206
  ASSERT_EQ(args.length(), 1);
  CONVERT_CHECKED(JSObject, raw_object, args[0]);
  HandleScope scope;
  Handle<JSObject> object(raw_object);
  Handle<FixedArray> contents = GetKeysInFixedArrayFor(object,
                                                       LOCAL_ONLY);
  // Some fast paths through GetKeysInFixedArrayFor reuse a cached
  // property array and since the result is mutable we have to create
  // a fresh clone on each invocation.
4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220
  int length = contents->length();
  Handle<FixedArray> copy = Factory::NewFixedArray(length);
  for (int i = 0; i < length; i++) {
    Object* entry = contents->get(i);
    if (entry->IsString()) {
      copy->set(i, entry);
    } else {
      ASSERT(entry->IsNumber());
      HandleScope scope;
      Handle<Object> entry_handle(entry);
      Handle<Object> entry_str = Factory::NumberToString(entry_handle);
      copy->set(i, *entry_str);
    }
  }
4221 4222 4223 4224
  return *Factory::NewJSArrayWithElements(copy);
}


4225
static MaybeObject* Runtime_GetArgumentsProperty(Arguments args) {
4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239
  NoHandleAllocation ha;
  ASSERT(args.length() == 1);

  // Compute the frame holding the arguments.
  JavaScriptFrameIterator it;
  it.AdvanceToArgumentsFrame();
  JavaScriptFrame* frame = it.frame();

  // Get the actual number of provided arguments.
  const uint32_t n = frame->GetProvidedParametersCount();

  // Try to convert the key to an index. If successful and within
  // index return the the argument from the frame.
  uint32_t index;
4240
  if (args[0]->ToArrayIndex(&index) && index < n) {
4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269
    return frame->GetParameter(index);
  }

  // Convert the key to a string.
  HandleScope scope;
  bool exception = false;
  Handle<Object> converted =
      Execution::ToString(args.at<Object>(0), &exception);
  if (exception) return Failure::Exception();
  Handle<String> key = Handle<String>::cast(converted);

  // Try to convert the string key into an array index.
  if (key->AsArrayIndex(&index)) {
    if (index < n) {
      return frame->GetParameter(index);
    } else {
      return Top::initial_object_prototype()->GetElement(index);
    }
  }

  // Handle special arguments properties.
  if (key->Equals(Heap::length_symbol())) return Smi::FromInt(n);
  if (key->Equals(Heap::callee_symbol())) return frame->function();

  // Lookup in the initial Object.prototype object.
  return Top::initial_object_prototype()->GetProperty(*key);
}


4270
static MaybeObject* Runtime_ToFastProperties(Arguments args) {
4271 4272
  HandleScope scope;

4273
  ASSERT(args.length() == 1);
4274 4275 4276
  Handle<Object> object = args.at<Object>(0);
  if (object->IsJSObject()) {
    Handle<JSObject> js_object = Handle<JSObject>::cast(object);
4277
    if (!js_object->HasFastProperties() && !js_object->IsGlobalObject()) {
4278 4279
      MaybeObject* ok = js_object->TransformToFastProperties(0);
      if (ok->IsRetryAfterGC()) return ok;
4280
    }
4281
  }
4282 4283 4284 4285
  return *object;
}


4286
static MaybeObject* Runtime_ToSlowProperties(Arguments args) {
4287 4288
  HandleScope scope;

4289
  ASSERT(args.length() == 1);
4290
  Handle<Object> object = args.at<Object>(0);
4291
  if (object->IsJSObject() && !object->IsJSGlobalProxy()) {
4292
    Handle<JSObject> js_object = Handle<JSObject>::cast(object);
4293
    NormalizeProperties(js_object, CLEAR_INOBJECT_PROPERTIES, 0);
4294
  }
4295 4296 4297 4298
  return *object;
}


4299
static MaybeObject* Runtime_ToBool(Arguments args) {
4300 4301 4302 4303 4304 4305 4306 4307 4308
  NoHandleAllocation ha;
  ASSERT(args.length() == 1);

  return args[0]->ToBoolean();
}


// Returns the type string of a value; see ECMA-262, 11.4.3 (p 47).
// Possible optimizations: put the type string into the oddballs.
4309
static MaybeObject* Runtime_Typeof(Arguments args) {
4310 4311 4312 4313 4314 4315 4316
  NoHandleAllocation ha;

  Object* obj = args[0];
  if (obj->IsNumber()) return Heap::number_symbol();
  HeapObject* heap_obj = HeapObject::cast(obj);

  // typeof an undetectable object is 'undefined'
4317
  if (heap_obj->map()->is_undetectable()) return Heap::undefined_symbol();
4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333

  InstanceType instance_type = heap_obj->map()->instance_type();
  if (instance_type < FIRST_NONSTRING_TYPE) {
    return Heap::string_symbol();
  }

  switch (instance_type) {
    case ODDBALL_TYPE:
      if (heap_obj->IsTrue() || heap_obj->IsFalse()) {
        return Heap::boolean_symbol();
      }
      if (heap_obj->IsNull()) {
        return Heap::object_symbol();
      }
      ASSERT(heap_obj->IsUndefined());
      return Heap::undefined_symbol();
4334
    case JS_FUNCTION_TYPE: case JS_REGEXP_TYPE:
4335 4336 4337 4338 4339 4340 4341 4342 4343
      return Heap::function_symbol();
    default:
      // For any kind of object not handled above, the spec rule for
      // host objects gives that it is okay to return "object"
      return Heap::object_symbol();
  }
}


4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365
static bool AreDigits(const char*s, int from, int to) {
  for (int i = from; i < to; i++) {
    if (s[i] < '0' || s[i] > '9') return false;
  }

  return true;
}


static int ParseDecimalInteger(const char*s, int from, int to) {
  ASSERT(to - from < 10);  // Overflow is not possible.
  ASSERT(from < to);
  int d = s[from] - '0';

  for (int i = from + 1; i < to; i++) {
    d = 10 * d + (s[i] - '0');
  }

  return d;
}


4366
static MaybeObject* Runtime_StringToNumber(Arguments args) {
4367 4368 4369
  NoHandleAllocation ha;
  ASSERT(args.length() == 1);
  CONVERT_CHECKED(String, subject, args[0]);
4370
  subject->TryFlatten();
4371 4372 4373 4374 4375 4376 4377 4378 4379 4380

  // Fast case: short integer or some sorts of junk values.
  int len = subject->length();
  if (subject->IsSeqAsciiString()) {
    if (len == 0) return Smi::FromInt(0);

    char const* data = SeqAsciiString::cast(subject)->GetChars();
    bool minus = (data[0] == '-');
    int start_pos = (minus ? 1 : 0);

4381 4382 4383
    if (start_pos == len) {
      return Heap::nan_value();
    } else if (data[start_pos] > '9') {
4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397
      // Fast check for a junk value. A valid string may start from a
      // whitespace, a sign ('+' or '-'), the decimal point, a decimal digit or
      // the 'I' character ('Infinity'). All of that have codes not greater than
      // '9' except 'I'.
      if (data[start_pos] != 'I') {
        return Heap::nan_value();
      }
    } else if (len - start_pos < 10 && AreDigits(data, start_pos, len)) {
      // The maximal/minimal smi has 10 digits. If the string has less digits we
      // know it will fit into the smi-data type.
      int d = ParseDecimalInteger(data, start_pos, len);
      if (minus) {
        if (d == 0) return Heap::minus_zero_value();
        d = -d;
4398 4399 4400 4401 4402
      } else if (!subject->HasHashCode() &&
                 len <= String::kMaxArrayIndexSize &&
                 (len == 1 || data[0] != '0')) {
        // String hash is not calculated yet but all the data are present.
        // Update the hash field to speed up sequential convertions.
4403
        uint32_t hash = StringHasher::MakeArrayIndexHash(d, len);
4404 4405 4406 4407 4408 4409
#ifdef DEBUG
        subject->Hash();  // Force hash calculation.
        ASSERT_EQ(static_cast<int>(subject->hash_field()),
                  static_cast<int>(hash));
#endif
        subject->set_hash_field(hash);
4410 4411 4412 4413 4414 4415
      }
      return Smi::FromInt(d);
    }
  }

  // Slower case.
4416 4417 4418 4419
  return Heap::NumberFromDouble(StringToDouble(subject, ALLOW_HEX));
}


4420
static MaybeObject* Runtime_StringFromCharCodeArray(Arguments args) {
4421 4422 4423 4424 4425 4426 4427 4428 4429
  NoHandleAllocation ha;
  ASSERT(args.length() == 1);

  CONVERT_CHECKED(JSArray, codes, args[0]);
  int length = Smi::cast(codes->length())->value();

  // Check if the string can be ASCII.
  int i;
  for (i = 0; i < length; i++) {
4430 4431 4432 4433 4434 4435
    Object* element;
    { MaybeObject* maybe_element = codes->GetElement(i);
      // We probably can't get an exception here, but just in order to enforce
      // the checking of inputs in the runtime calls we check here.
      if (!maybe_element->ToObject(&element)) return maybe_element;
    }
4436 4437 4438 4439 4440
    CONVERT_NUMBER_CHECKED(int, chr, Int32, element);
    if ((chr & 0xffff) > String::kMaxAsciiCharCode)
      break;
  }

4441
  MaybeObject* maybe_object = NULL;
4442
  if (i == length) {  // The string is ASCII.
4443
    maybe_object = Heap::AllocateRawAsciiString(length);
4444
  } else {  // The string is not ASCII.
4445
    maybe_object = Heap::AllocateRawTwoByteString(length);
4446 4447
  }

4448 4449
  Object* object = NULL;
  if (!maybe_object->ToObject(&object)) return maybe_object;
4450 4451
  String* result = String::cast(object);
  for (int i = 0; i < length; i++) {
4452 4453 4454 4455
    Object* element;
    { MaybeObject* maybe_element = codes->GetElement(i);
      if (!maybe_element->ToObject(&element)) return maybe_element;
    }
4456
    CONVERT_NUMBER_CHECKED(int, chr, Int32, element);
4457
    result->Set(i, chr & 0xffff);
4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499
  }
  return result;
}


// kNotEscaped is generated by the following:
//
// #!/bin/perl
// for (my $i = 0; $i < 256; $i++) {
//   print "\n" if $i % 16 == 0;
//   my $c = chr($i);
//   my $escaped = 1;
//   $escaped = 0 if $c =~ m#[A-Za-z0-9@*_+./-]#;
//   print $escaped ? "0, " : "1, ";
// }


static bool IsNotEscaped(uint16_t character) {
  // Only for 8 bit characters, the rest are always escaped (in a different way)
  ASSERT(character < 256);
  static const char kNotEscaped[256] = {
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1,
    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,
    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,
    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  };
  return kNotEscaped[character] != 0;
}


4500
static MaybeObject* Runtime_URIEscape(Arguments args) {
4501 4502 4503 4504 4505
  const char hex_chars[] = "0123456789ABCDEF";
  NoHandleAllocation ha;
  ASSERT(args.length() == 1);
  CONVERT_CHECKED(String, source, args[0]);

4506
  source->TryFlatten();
4507 4508 4509 4510

  int escaped_length = 0;
  int length = source->length();
  {
4511
    Access<StringInputBuffer> buffer(&runtime_string_input_buffer);
4512 4513 4514 4515 4516 4517 4518 4519 4520 4521
    buffer->Reset(source);
    while (buffer->has_more()) {
      uint16_t character = buffer->GetNext();
      if (character >= 256) {
        escaped_length += 6;
      } else if (IsNotEscaped(character)) {
        escaped_length++;
      } else {
        escaped_length += 3;
      }
4522
      // We don't allow strings that are longer than a maximal length.
4523
      ASSERT(String::kMaxLength < 0x7fffffff - 6);  // Cannot overflow.
4524
      if (escaped_length > String::kMaxLength) {
4525 4526 4527 4528 4529 4530 4531 4532 4533
        Top::context()->mark_out_of_memory();
        return Failure::OutOfMemoryException();
      }
    }
  }
  // No length change implies no change.  Return original string if no change.
  if (escaped_length == length) {
    return source;
  }
4534 4535 4536 4537
  Object* o;
  { MaybeObject* maybe_o = Heap::AllocateRawAsciiString(escaped_length);
    if (!maybe_o->ToObject(&o)) return maybe_o;
  }
4538 4539 4540
  String* destination = String::cast(o);
  int dest_position = 0;

4541
  Access<StringInputBuffer> buffer(&runtime_string_input_buffer);
4542 4543
  buffer->Rewind();
  while (buffer->has_more()) {
4544 4545
    uint16_t chr = buffer->GetNext();
    if (chr >= 256) {
4546 4547 4548 4549 4550 4551
      destination->Set(dest_position, '%');
      destination->Set(dest_position+1, 'u');
      destination->Set(dest_position+2, hex_chars[chr >> 12]);
      destination->Set(dest_position+3, hex_chars[(chr >> 8) & 0xf]);
      destination->Set(dest_position+4, hex_chars[(chr >> 4) & 0xf]);
      destination->Set(dest_position+5, hex_chars[chr & 0xf]);
4552
      dest_position += 6;
4553
    } else if (IsNotEscaped(chr)) {
4554
      destination->Set(dest_position, chr);
4555 4556
      dest_position++;
    } else {
4557 4558 4559
      destination->Set(dest_position, '%');
      destination->Set(dest_position+1, hex_chars[chr >> 4]);
      destination->Set(dest_position+2, hex_chars[chr & 0xf]);
4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586
      dest_position += 3;
    }
  }
  return destination;
}


static inline int TwoDigitHex(uint16_t character1, uint16_t character2) {
  static const signed char kHexValue['g'] = {
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
    0,  1,  2,   3,  4,  5,  6,  7,  8,  9, -1, -1, -1, -1, -1, -1,
    -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
    -1, 10, 11, 12, 13, 14, 15 };

  if (character1 > 'f') return -1;
  int hi = kHexValue[character1];
  if (hi == -1) return -1;
  if (character2 > 'f') return -1;
  int lo = kHexValue[character2];
  if (lo == -1) return -1;
  return (hi << 4) + lo;
}


4587 4588 4589 4590
static inline int Unescape(String* source,
                           int i,
                           int length,
                           int* step) {
4591
  uint16_t character = source->Get(i);
4592 4593
  int32_t hi = 0;
  int32_t lo = 0;
4594 4595
  if (character == '%' &&
      i <= length - 6 &&
4596 4597 4598 4599 4600
      source->Get(i + 1) == 'u' &&
      (hi = TwoDigitHex(source->Get(i + 2),
                        source->Get(i + 3))) != -1 &&
      (lo = TwoDigitHex(source->Get(i + 4),
                        source->Get(i + 5))) != -1) {
4601 4602 4603 4604
    *step = 6;
    return (hi << 8) + lo;
  } else if (character == '%' &&
      i <= length - 3 &&
4605 4606
      (lo = TwoDigitHex(source->Get(i + 1),
                        source->Get(i + 2))) != -1) {
4607 4608 4609 4610 4611 4612 4613 4614 4615
    *step = 3;
    return lo;
  } else {
    *step = 1;
    return character;
  }
}


4616
static MaybeObject* Runtime_URIUnescape(Arguments args) {
4617 4618 4619 4620
  NoHandleAllocation ha;
  ASSERT(args.length() == 1);
  CONVERT_CHECKED(String, source, args[0]);

4621
  source->TryFlatten();
4622 4623

  bool ascii = true;
4624
  int length = source->length();
4625 4626 4627 4628

  int unescaped_length = 0;
  for (int i = 0; i < length; unescaped_length++) {
    int step;
4629
    if (Unescape(source, i, length, &step) > String::kMaxAsciiCharCode) {
4630
      ascii = false;
4631
    }
4632 4633 4634 4635 4636 4637 4638
    i += step;
  }

  // No length change implies no change.  Return original string if no change.
  if (unescaped_length == length)
    return source;

4639 4640 4641 4642 4643 4644
  Object* o;
  { MaybeObject* maybe_o = ascii ?
                           Heap::AllocateRawAsciiString(unescaped_length) :
                           Heap::AllocateRawTwoByteString(unescaped_length);
    if (!maybe_o->ToObject(&o)) return maybe_o;
  }
4645 4646 4647 4648 4649
  String* destination = String::cast(o);

  int dest_position = 0;
  for (int i = 0; i < length; dest_position++) {
    int step;
4650
    destination->Set(dest_position, Unescape(source, i, length, &step));
4651 4652 4653 4654 4655 4656
    i += step;
  }
  return destination;
}


4657 4658
static const unsigned int kQuoteTableLength = 128u;

4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705
static const int kJsonQuotesCharactersPerEntry = 8;
static const char* const JsonQuotes =
    "\\u0000  \\u0001  \\u0002  \\u0003  "
    "\\u0004  \\u0005  \\u0006  \\u0007  "
    "\\b      \\t      \\n      \\u000b  "
    "\\f      \\r      \\u000e  \\u000f  "
    "\\u0010  \\u0011  \\u0012  \\u0013  "
    "\\u0014  \\u0015  \\u0016  \\u0017  "
    "\\u0018  \\u0019  \\u001a  \\u001b  "
    "\\u001c  \\u001d  \\u001e  \\u001f  "
    "        !       \\\"      #       "
    "$       %       &       '       "
    "(       )       *       +       "
    ",       -       .       /       "
    "0       1       2       3       "
    "4       5       6       7       "
    "8       9       :       ;       "
    "<       =       >       ?       "
    "@       A       B       C       "
    "D       E       F       G       "
    "H       I       J       K       "
    "L       M       N       O       "
    "P       Q       R       S       "
    "T       U       V       W       "
    "X       Y       Z       [       "
    "\\\\      ]       ^       _       "
    "`       a       b       c       "
    "d       e       f       g       "
    "h       i       j       k       "
    "l       m       n       o       "
    "p       q       r       s       "
    "t       u       v       w       "
    "x       y       z       {       "
    "|       }       ~       \177       ";


// For a string that is less than 32k characters it should always be
// possible to allocate it in new space.
static const int kMaxGuaranteedNewSpaceString = 32 * 1024;


// Doing JSON quoting cannot make the string more than this many times larger.
static const int kJsonQuoteWorstCaseBlowup = 6;


// Covers the entire ASCII range (all other characters are unchanged by JSON
// quoting).
4706
static const byte JsonQuoteLengths[kQuoteTableLength] = {
4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741
    6, 6, 6, 6, 6, 6, 6, 6,
    2, 2, 2, 6, 2, 2, 6, 6,
    6, 6, 6, 6, 6, 6, 6, 6,
    6, 6, 6, 6, 6, 6, 6, 6,
    1, 1, 2, 1, 1, 1, 1, 1,
    1, 1, 1, 1, 1, 1, 1, 1,
    1, 1, 1, 1, 1, 1, 1, 1,
    1, 1, 1, 1, 1, 1, 1, 1,
    1, 1, 1, 1, 1, 1, 1, 1,
    1, 1, 1, 1, 1, 1, 1, 1,
    1, 1, 1, 1, 1, 1, 1, 1,
    1, 1, 1, 1, 2, 1, 1, 1,
    1, 1, 1, 1, 1, 1, 1, 1,
    1, 1, 1, 1, 1, 1, 1, 1,
    1, 1, 1, 1, 1, 1, 1, 1,
    1, 1, 1, 1, 1, 1, 1, 1,
};


template <typename StringType>
MaybeObject* AllocateRawString(int length);


template <>
MaybeObject* AllocateRawString<SeqTwoByteString>(int length) {
  return Heap::AllocateRawTwoByteString(length);
}


template <>
MaybeObject* AllocateRawString<SeqAsciiString>(int length) {
  return Heap::AllocateRawAsciiString(length);
}


4742
template <typename Char, typename StringType, bool comma>
4743
static MaybeObject* SlowQuoteJsonString(Vector<const Char> characters) {
4744
  int length = characters.length();
4745 4746
  const Char* read_cursor = characters.start();
  const Char* end = read_cursor + length;
4747
  const int kSpaceForQuotes = 2 + (comma ? 1 :0);
4748 4749 4750 4751 4752
  int quoted_length = kSpaceForQuotes;
  while (read_cursor < end) {
    Char c = *(read_cursor++);
    if (sizeof(Char) > 1u && static_cast<unsigned>(c) >= kQuoteTableLength) {
      quoted_length++;
4753
    } else {
4754
      quoted_length += JsonQuoteLengths[static_cast<unsigned>(c)];
4755 4756 4757 4758 4759 4760 4761 4762 4763
    }
  }
  MaybeObject* new_alloc = AllocateRawString<StringType>(quoted_length);
  Object* new_object;
  if (!new_alloc->ToObject(&new_object)) {
    return new_alloc;
  }
  StringType* new_string = StringType::cast(new_object);

4764 4765
  Char* write_cursor = reinterpret_cast<Char*>(
      new_string->address() + SeqAsciiString::kHeaderSize);
4766
  if (comma) *(write_cursor++) = ',';
4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787
  *(write_cursor++) = '"';

  read_cursor = characters.start();
  while (read_cursor < end) {
    Char c = *(read_cursor++);
    if (sizeof(Char) > 1u && static_cast<unsigned>(c) >= kQuoteTableLength) {
      *(write_cursor++) = c;
    } else {
      int len = JsonQuoteLengths[static_cast<unsigned>(c)];
      const char* replacement = JsonQuotes +
          static_cast<unsigned>(c) * kJsonQuotesCharactersPerEntry;
      for (int i = 0; i < len; i++) {
        *write_cursor++ = *replacement++;
      }
    }
  }
  *(write_cursor++) = '"';
  return new_string;
}


4788
template <typename Char, typename StringType, bool comma>
4789 4790 4791
static MaybeObject* QuoteJsonString(Vector<const Char> characters) {
  int length = characters.length();
  Counters::quote_json_char_count.Increment(length);
4792
  const int kSpaceForQuotes = 2 + (comma ? 1 :0);
4793 4794
  int worst_case_length = length * kJsonQuoteWorstCaseBlowup + kSpaceForQuotes;
  if (worst_case_length > kMaxGuaranteedNewSpaceString) {
4795
    return SlowQuoteJsonString<Char, StringType, comma>(characters);
4796 4797 4798 4799 4800 4801 4802
  }

  MaybeObject* new_alloc = AllocateRawString<StringType>(worst_case_length);
  Object* new_object;
  if (!new_alloc->ToObject(&new_object)) {
    return new_alloc;
  }
4803 4804 4805 4806
  if (!Heap::new_space()->Contains(new_object)) {
    // Even if our string is small enough to fit in new space we still have to
    // handle it being allocated in old space as may happen in the third
    // attempt.  See CALL_AND_RETRY in heap-inl.h and similar code in
4807
    // CEntryStub::GenerateCore.
4808
    return SlowQuoteJsonString<Char, StringType, comma>(characters);
4809
  }
4810 4811
  StringType* new_string = StringType::cast(new_object);
  ASSERT(Heap::new_space()->Contains(new_string));
4812 4813 4814 4815

  STATIC_ASSERT(SeqTwoByteString::kHeaderSize == SeqAsciiString::kHeaderSize);
  Char* write_cursor = reinterpret_cast<Char*>(
      new_string->address() + SeqAsciiString::kHeaderSize);
4816
  if (comma) *(write_cursor++) = ',';
4817
  *(write_cursor++) = '"';
4818

4819
  const Char* read_cursor = characters.start();
4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837
  const Char* end = read_cursor + length;
  while (read_cursor < end) {
    Char c = *(read_cursor++);
    if (sizeof(Char) > 1u && static_cast<unsigned>(c) >= kQuoteTableLength) {
      *(write_cursor++) = c;
    } else {
      int len = JsonQuoteLengths[static_cast<unsigned>(c)];
      const char* replacement = JsonQuotes +
          static_cast<unsigned>(c) * kJsonQuotesCharactersPerEntry;
      write_cursor[0] = replacement[0];
      if (len > 1) {
        write_cursor[1] = replacement[1];
        if (len > 2) {
          ASSERT(len == 6);
          write_cursor[2] = replacement[2];
          write_cursor[3] = replacement[3];
          write_cursor[4] = replacement[4];
          write_cursor[5] = replacement[5];
4838
        }
4839
      }
4840
      write_cursor += len;
4841 4842 4843
    }
  }
  *(write_cursor++) = '"';
4844

4845
  int final_length = static_cast<int>(
4846
      write_cursor - reinterpret_cast<Char*>(
4847
          new_string->address() + SeqAsciiString::kHeaderSize));
4848 4849
  Heap::new_space()->ShrinkStringAtAllocationBoundary<StringType>(new_string,
                                                                  final_length);
4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866
  return new_string;
}


static MaybeObject* Runtime_QuoteJSONString(Arguments args) {
  NoHandleAllocation ha;
  CONVERT_CHECKED(String, str, args[0]);
  if (!str->IsFlat()) {
    MaybeObject* try_flatten = str->TryFlatten();
    Object* flat;
    if (!try_flatten->ToObject(&flat)) {
      return try_flatten;
    }
    str = String::cast(flat);
    ASSERT(str->IsFlat());
  }
  if (str->IsTwoByteRepresentation()) {
4867
    return QuoteJsonString<uc16, SeqTwoByteString, false>(str->ToUC16Vector());
4868
  } else {
4869
    return QuoteJsonString<char, SeqAsciiString, false>(str->ToAsciiVector());
4870 4871 4872 4873
  }
}


4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892
static MaybeObject* Runtime_QuoteJSONStringComma(Arguments args) {
  NoHandleAllocation ha;
  CONVERT_CHECKED(String, str, args[0]);
  if (!str->IsFlat()) {
    MaybeObject* try_flatten = str->TryFlatten();
    Object* flat;
    if (!try_flatten->ToObject(&flat)) {
      return try_flatten;
    }
    str = String::cast(flat);
    ASSERT(str->IsFlat());
  }
  if (str->IsTwoByteRepresentation()) {
    return QuoteJsonString<uc16, SeqTwoByteString, true>(str->ToUC16Vector());
  } else {
    return QuoteJsonString<char, SeqAsciiString, true>(str->ToAsciiVector());
  }
}

4893

4894
static MaybeObject* Runtime_StringParseInt(Arguments args) {
4895 4896 4897
  NoHandleAllocation ha;

  CONVERT_CHECKED(String, s, args[0]);
4898
  CONVERT_SMI_CHECKED(radix, args[1]);
4899

4900
  s->TryFlatten();
4901

4902 4903 4904
  RUNTIME_ASSERT(radix == 0 || (2 <= radix && radix <= 36));
  double value = StringToInt(s, radix);
  return Heap::NumberFromDouble(value);
4905 4906 4907
}


4908
static MaybeObject* Runtime_StringParseFloat(Arguments args) {
4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924
  NoHandleAllocation ha;
  CONVERT_CHECKED(String, str, args[0]);

  // ECMA-262 section 15.1.2.3, empty string is NaN
  double value = StringToDouble(str, ALLOW_TRAILING_JUNK, OS::nan_value());

  // Create a number object from the value.
  return Heap::NumberFromDouble(value);
}


static unibrow::Mapping<unibrow::ToUppercase, 128> to_upper_mapping;
static unibrow::Mapping<unibrow::ToLowercase, 128> to_lower_mapping;


template <class Converter>
4925 4926 4927 4928 4929
MUST_USE_RESULT static MaybeObject* ConvertCaseHelper(
    String* s,
    int length,
    int input_string_length,
    unibrow::Mapping<Converter, 128>* mapping) {
4930 4931 4932 4933 4934
  // We try this twice, once with the assumption that the result is no longer
  // than the input and, if that assumption breaks, again with the exact
  // length.  This may not be pretty, but it is nicer than what was here before
  // and I hereby claim my vaffel-is.
  //
4935 4936 4937 4938 4939 4940
  // Allocate the resulting string.
  //
  // NOTE: This assumes that the upper/lower case of an ascii
  // character is also ascii.  This is currently the case, but it
  // might break in the future if we implement more context and locale
  // dependent upper/lower conversions.
4941 4942 4943 4944 4945 4946
  Object* o;
  { MaybeObject* maybe_o = s->IsAsciiRepresentation()
                   ? Heap::AllocateRawAsciiString(length)
                   : Heap::AllocateRawTwoByteString(length);
    if (!maybe_o->ToObject(&o)) return maybe_o;
  }
4947 4948 4949 4950 4951
  String* result = String::cast(o);
  bool has_changed_character = false;

  // Convert all characters to upper case, assuming that they will fit
  // in the buffer
4952
  Access<StringInputBuffer> buffer(&runtime_string_input_buffer);
4953
  buffer->Reset(s);
4954
  unibrow::uchar chars[Converter::kMaxWidth];
4955 4956
  // We can assume that the string is not empty
  uc32 current = buffer->GetNext();
erik.corry@gmail.com's avatar
erik.corry@gmail.com committed
4957
  for (int i = 0; i < length;) {
4958 4959
    bool has_next = buffer->has_more();
    uc32 next = has_next ? buffer->GetNext() : 0;
4960 4961 4962
    int char_length = mapping->get(current, next, chars);
    if (char_length == 0) {
      // The case conversion of this character is the character itself.
4963
      result->Set(i, current);
4964 4965 4966 4967
      i++;
    } else if (char_length == 1) {
      // Common case: converting the letter resulted in one character.
      ASSERT(static_cast<uc32>(chars[0]) != current);
4968
      result->Set(i, chars[0]);
4969 4970
      has_changed_character = true;
      i++;
4971
    } else if (length == input_string_length) {
4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982
      // We've assumed that the result would be as long as the
      // input but here is a character that converts to several
      // characters.  No matter, we calculate the exact length
      // of the result and try the whole thing again.
      //
      // Note that this leaves room for optimization.  We could just
      // memcpy what we already have to the result string.  Also,
      // the result string is the last object allocated we could
      // "realloc" it and probably, in the vast majority of cases,
      // extend the existing string to be able to hold the full
      // result.
4983 4984 4985 4986 4987 4988
      int next_length = 0;
      if (has_next) {
        next_length = mapping->get(next, 0, chars);
        if (next_length == 0) next_length = 1;
      }
      int current_length = i + char_length + next_length;
4989 4990
      while (buffer->has_more()) {
        current = buffer->GetNext();
4991 4992 4993 4994
        // NOTE: we use 0 as the next character here because, while
        // the next character may affect what a character converts to,
        // it does not in any case affect the length of what it convert
        // to.
4995 4996
        int char_length = mapping->get(current, 0, chars);
        if (char_length == 0) char_length = 1;
4997
        current_length += char_length;
4998 4999 5000 5001
        if (current_length > Smi::kMaxValue) {
          Top::context()->mark_out_of_memory();
          return Failure::OutOfMemoryException();
        }
5002
      }
5003 5004
      // Try again with the real length.
      return Smi::FromInt(current_length);
5005 5006
    } else {
      for (int j = 0; j < char_length; j++) {
5007
        result->Set(i, chars[j]);
5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025
        i++;
      }
      has_changed_character = true;
    }
    current = next;
  }
  if (has_changed_character) {
    return result;
  } else {
    // If we didn't actually change anything in doing the conversion
    // we simple return the result and let the converted string
    // become garbage; there is no reason to keep two identical strings
    // alive.
    return s;
  }
}


5026 5027
namespace {

5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056
static const uintptr_t kOneInEveryByte = kUintptrAllBitsSet / 0xFF;


// Given a word and two range boundaries returns a word with high bit
// set in every byte iff the corresponding input byte was strictly in
// the range (m, n). All the other bits in the result are cleared.
// This function is only useful when it can be inlined and the
// boundaries are statically known.
// Requires: all bytes in the input word and the boundaries must be
// ascii (less than 0x7F).
static inline uintptr_t AsciiRangeMask(uintptr_t w, char m, char n) {
  // Every byte in an ascii string is less than or equal to 0x7F.
  ASSERT((w & (kOneInEveryByte * 0x7F)) == w);
  // Use strict inequalities since in edge cases the function could be
  // further simplified.
  ASSERT(0 < m && m < n && n < 0x7F);
  // Has high bit set in every w byte less than n.
  uintptr_t tmp1 = kOneInEveryByte * (0x7F + n) - w;
  // Has high bit set in every w byte greater than m.
  uintptr_t tmp2 = w + kOneInEveryByte * (0x7F - m);
  return (tmp1 & tmp2 & (kOneInEveryByte * 0x80));
}


enum AsciiCaseConversion {
  ASCII_TO_LOWER,
  ASCII_TO_UPPER
};

5057

5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070
template <AsciiCaseConversion dir>
struct FastAsciiConverter {
  static bool Convert(char* dst, char* src, int length) {
#ifdef DEBUG
    char* saved_dst = dst;
    char* saved_src = src;
#endif
    // We rely on the distance between upper and lower case letters
    // being a known power of 2.
    ASSERT('a' - 'A' == (1 << 5));
    // Boundaries for the range of input characters than require conversion.
    const char lo = (dir == ASCII_TO_LOWER) ? 'A' - 1 : 'a' - 1;
    const char hi = (dir == ASCII_TO_LOWER) ? 'Z' + 1 : 'z' + 1;
5071
    bool changed = false;
5072 5073 5074 5075 5076 5077 5078
    char* const limit = src + length;
#ifdef V8_HOST_CAN_READ_UNALIGNED
    // Process the prefix of the input that requires no conversion one
    // (machine) word at a time.
    while (src <= limit - sizeof(uintptr_t)) {
      uintptr_t w = *reinterpret_cast<uintptr_t*>(src);
      if (AsciiRangeMask(w, lo, hi) != 0) {
5079
        changed = true;
5080
        break;
5081
      }
5082 5083 5084
      *reinterpret_cast<uintptr_t*>(dst) = w;
      src += sizeof(uintptr_t);
      dst += sizeof(uintptr_t);
5085
    }
5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113
    // Process the remainder of the input performing conversion when
    // required one word at a time.
    while (src <= limit - sizeof(uintptr_t)) {
      uintptr_t w = *reinterpret_cast<uintptr_t*>(src);
      uintptr_t m = AsciiRangeMask(w, lo, hi);
      // The mask has high (7th) bit set in every byte that needs
      // conversion and we know that the distance between cases is
      // 1 << 5.
      *reinterpret_cast<uintptr_t*>(dst) = w ^ (m >> 2);
      src += sizeof(uintptr_t);
      dst += sizeof(uintptr_t);
    }
#endif
    // Process the last few bytes of the input (or the whole input if
    // unaligned access is not supported).
    while (src < limit) {
      char c = *src;
      if (lo < c && c < hi) {
        c ^= (1 << 5);
        changed = true;
      }
      *dst = c;
      ++src;
      ++dst;
    }
#ifdef DEBUG
    CheckConvert(saved_dst, saved_src, length, changed);
#endif
5114 5115
    return changed;
  }
5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141

#ifdef DEBUG
  static void CheckConvert(char* dst, char* src, int length, bool changed) {
    bool expected_changed = false;
    for (int i = 0; i < length; i++) {
      if (dst[i] == src[i]) continue;
      expected_changed = true;
      if (dir == ASCII_TO_LOWER) {
        ASSERT('A' <= src[i] && src[i] <= 'Z');
        ASSERT(dst[i] == src[i] + ('a' - 'A'));
      } else {
        ASSERT(dir == ASCII_TO_UPPER);
        ASSERT('a' <= src[i] && src[i] <= 'z');
        ASSERT(dst[i] == src[i] - ('a' - 'A'));
      }
    }
    ASSERT(expected_changed == changed);
  }
#endif
};


struct ToLowerTraits {
  typedef unibrow::ToLowercase UnibrowConverter;

  typedef FastAsciiConverter<ASCII_TO_LOWER> AsciiConverter;
5142
};
5143

5144 5145 5146 5147

struct ToUpperTraits {
  typedef unibrow::ToUppercase UnibrowConverter;

5148
  typedef FastAsciiConverter<ASCII_TO_UPPER> AsciiConverter;
5149 5150 5151 5152 5153 5154
};

}  // namespace


template <typename ConvertTraits>
5155
MUST_USE_RESULT static MaybeObject* ConvertCase(
5156 5157 5158
    Arguments args,
    unibrow::Mapping<typename ConvertTraits::UnibrowConverter, 128>* mapping) {
  NoHandleAllocation ha;
5159
  CONVERT_CHECKED(String, s, args[0]);
5160
  s = s->TryFlattenGetString();
5161

5162
  const int length = s->length();
5163
  // Assume that the string is not empty; we need this assumption later
5164 5165 5166 5167 5168 5169 5170 5171
  if (length == 0) return s;

  // Simpler handling of ascii strings.
  //
  // NOTE: This assumes that the upper/lower case of an ascii
  // character is also ascii.  This is currently the case, but it
  // might break in the future if we implement more context and locale
  // dependent upper/lower conversions.
5172
  if (s->IsSeqAsciiString()) {
5173 5174 5175 5176
    Object* o;
    { MaybeObject* maybe_o = Heap::AllocateRawAsciiString(length);
      if (!maybe_o->ToObject(&o)) return maybe_o;
    }
5177
    SeqAsciiString* result = SeqAsciiString::cast(o);
5178
    bool has_changed_character = ConvertTraits::AsciiConverter::Convert(
5179
        result->GetChars(), SeqAsciiString::cast(s)->GetChars(), length);
5180 5181
    return has_changed_character ? result : s;
  }
5182

5183 5184 5185 5186
  Object* answer;
  { MaybeObject* maybe_answer = ConvertCaseHelper(s, length, length, mapping);
    if (!maybe_answer->ToObject(&answer)) return maybe_answer;
  }
5187 5188
  if (answer->IsSmi()) {
    // Retry with correct length.
5189 5190 5191 5192
    { MaybeObject* maybe_answer =
          ConvertCaseHelper(s, Smi::cast(answer)->value(), length, mapping);
      if (!maybe_answer->ToObject(&answer)) return maybe_answer;
    }
5193
  }
5194
  return answer;
5195 5196 5197
}


5198
static MaybeObject* Runtime_StringToLowerCase(Arguments args) {
5199
  return ConvertCase<ToLowerTraits>(args, &to_lower_mapping);
5200 5201 5202
}


5203
static MaybeObject* Runtime_StringToUpperCase(Arguments args) {
5204
  return ConvertCase<ToUpperTraits>(args, &to_upper_mapping);
5205 5206
}

5207

5208 5209 5210 5211
static inline bool IsTrimWhiteSpace(unibrow::uchar c) {
  return unibrow::WhiteSpace::Is(c) || c == 0x200b;
}

5212

5213
static MaybeObject* Runtime_StringTrim(Arguments args) {
5214 5215 5216 5217 5218 5219 5220
  NoHandleAllocation ha;
  ASSERT(args.length() == 3);

  CONVERT_CHECKED(String, s, args[0]);
  CONVERT_BOOLEAN_CHECKED(trimLeft, args[1]);
  CONVERT_BOOLEAN_CHECKED(trimRight, args[2]);

5221
  s->TryFlatten();
5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236
  int length = s->length();

  int left = 0;
  if (trimLeft) {
    while (left < length && IsTrimWhiteSpace(s->Get(left))) {
      left++;
    }
  }

  int right = length;
  if (trimRight) {
    while (right > left && IsTrimWhiteSpace(s->Get(right - 1))) {
      right--;
    }
  }
5237
  return s->SubString(left, right);
5238
}
5239

5240

5241 5242 5243
template <typename SubjectChar, typename PatternChar>
void FindStringIndices(Vector<const SubjectChar> subject,
                       Vector<const PatternChar> pattern,
5244 5245 5246 5247 5248
                       ZoneList<int>* indices,
                       unsigned int limit) {
  ASSERT(limit > 0);
  // Collect indices of pattern in subject, and the end-of-string index.
  // Stop after finding at most limit values.
5249 5250 5251 5252 5253 5254 5255 5256 5257
  StringSearch<PatternChar, SubjectChar> search(pattern);
  int pattern_length = pattern.length();
  int index = 0;
  while (limit > 0) {
    index = search.Search(subject, index);
    if (index < 0) return;
    indices->Add(index);
    index += pattern_length;
    limit--;
5258 5259 5260 5261
  }
}


5262
static MaybeObject* Runtime_StringSplit(Arguments args) {
5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285
  ASSERT(args.length() == 3);
  HandleScope handle_scope;
  CONVERT_ARG_CHECKED(String, subject, 0);
  CONVERT_ARG_CHECKED(String, pattern, 1);
  CONVERT_NUMBER_CHECKED(uint32_t, limit, Uint32, args[2]);

  int subject_length = subject->length();
  int pattern_length = pattern->length();
  RUNTIME_ASSERT(pattern_length > 0);

  // The limit can be very large (0xffffffffu), but since the pattern
  // isn't empty, we can never create more parts than ~half the length
  // of the subject.

  if (!subject->IsFlat()) FlattenString(subject);

  static const int kMaxInitialListCapacity = 16;

  ZoneScope scope(DELETE_ON_EXIT);

  // Find (up to limit) indices of separator and end-of-string in subject
  int initial_capacity = Min<uint32_t>(kMaxInitialListCapacity, limit);
  ZoneList<int> indices(initial_capacity);
5286
  if (!pattern->IsFlat()) FlattenString(pattern);
5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303

  // No allocation block.
  {
    AssertNoAllocation nogc;
    if (subject->IsAsciiRepresentation()) {
      Vector<const char> subject_vector = subject->ToAsciiVector();
      if (pattern->IsAsciiRepresentation()) {
        FindStringIndices(subject_vector,
                          pattern->ToAsciiVector(),
                          &indices,
                          limit);
      } else {
        FindStringIndices(subject_vector,
                          pattern->ToUC16Vector(),
                          &indices,
                          limit);
      }
5304
    } else {
5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316
      Vector<const uc16> subject_vector = subject->ToUC16Vector();
      if (pattern->IsAsciiRepresentation()) {
        FindStringIndices(subject_vector,
                          pattern->ToAsciiVector(),
                          &indices,
                          limit);
      } else {
        FindStringIndices(subject_vector,
                          pattern->ToUC16Vector(),
                          &indices,
                          limit);
      }
5317 5318
    }
  }
5319

5320 5321 5322 5323
  if (static_cast<uint32_t>(indices.length()) < limit) {
    indices.Add(subject_length);
  }

5324
  // The list indices now contains the end of each part to create.
5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353

  // Create JSArray of substrings separated by separator.
  int part_count = indices.length();

  Handle<JSArray> result = Factory::NewJSArray(part_count);
  result->set_length(Smi::FromInt(part_count));

  ASSERT(result->HasFastElements());

  if (part_count == 1 && indices.at(0) == subject_length) {
    FixedArray::cast(result->elements())->set(0, *subject);
    return *result;
  }

  Handle<FixedArray> elements(FixedArray::cast(result->elements()));
  int part_start = 0;
  for (int i = 0; i < part_count; i++) {
    HandleScope local_loop_handle;
    int part_end = indices.at(i);
    Handle<String> substring =
        Factory::NewSubString(subject, part_start, part_end);
    elements->set(i, *substring);
    part_start = part_end + pattern_length;
  }

  return *result;
}


5354 5355
// Copies ascii characters to the given fixed array looking up
// one-char strings in the cache. Gives up on the first char that is
5356 5357
// not in the cache and fills the remainder with smi zeros. Returns
// the length of the successfully copied prefix.
5358 5359 5360 5361 5362 5363
static int CopyCachedAsciiCharsToArray(const char* chars,
                                       FixedArray* elements,
                                       int length) {
  AssertNoAllocation nogc;
  FixedArray* ascii_cache = Heap::single_character_string_cache();
  Object* undefined = Heap::undefined_value();
5364 5365
  int i;
  for (i = 0; i < length; ++i) {
5366
    Object* value = ascii_cache->get(chars[i]);
5367
    if (value == undefined) break;
5368 5369 5370
    ASSERT(!Heap::InNewSpace(value));
    elements->set(i, value, SKIP_WRITE_BARRIER);
  }
5371 5372
  if (i < length) {
    ASSERT(Smi::FromInt(0) == 0);
5373
    memset(elements->data_start() + i, 0, kPointerSize * (length - i));
5374 5375 5376 5377 5378 5379 5380 5381 5382
  }
#ifdef DEBUG
  for (int j = 0; j < length; ++j) {
    Object* element = elements->get(j);
    ASSERT(element == Smi::FromInt(0) ||
           (element->IsString() && String::cast(element)->LooksValid()));
  }
#endif
  return i;
5383 5384 5385 5386 5387
}


// Converts a String to JSArray.
// For example, "foo" => ["f", "o", "o"].
5388
static MaybeObject* Runtime_StringToArray(Arguments args) {
5389
  HandleScope scope;
5390
  ASSERT(args.length() == 2);
5391
  CONVERT_ARG_CHECKED(String, s, 0);
5392
  CONVERT_NUMBER_CHECKED(uint32_t, limit, Uint32, args[1]);
5393 5394

  s->TryFlatten();
5395
  const int length = static_cast<int>(Min<uint32_t>(s->length(), limit));
5396

5397 5398
  Handle<FixedArray> elements;
  if (s->IsFlat() && s->IsAsciiRepresentation()) {
5399 5400 5401 5402
    Object* obj;
    { MaybeObject* maybe_obj = Heap::AllocateUninitializedFixedArray(length);
      if (!maybe_obj->ToObject(&obj)) return maybe_obj;
    }
5403 5404 5405 5406 5407 5408 5409 5410 5411 5412
    elements = Handle<FixedArray>(FixedArray::cast(obj));

    Vector<const char> chars = s->ToAsciiVector();
    // Note, this will initialize all elements (not only the prefix)
    // to prevent GC from seeing partially initialized array.
    int num_copied_from_cache = CopyCachedAsciiCharsToArray(chars.start(),
                                                            *elements,
                                                            length);

    for (int i = num_copied_from_cache; i < length; ++i) {
5413 5414
      Handle<Object> str = LookupSingleCharacterStringFromCode(chars[i]);
      elements->set(i, *str);
5415 5416
    }
  } else {
5417
    elements = Factory::NewFixedArray(length);
5418
    for (int i = 0; i < length; ++i) {
5419 5420
      Handle<Object> str = LookupSingleCharacterStringFromCode(s->Get(i));
      elements->set(i, *str);
5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433
    }
  }

#ifdef DEBUG
  for (int i = 0; i < length; ++i) {
    ASSERT(String::cast(elements->get(i))->length() == 1);
  }
#endif

  return *Factory::NewJSArrayWithElements(elements);
}


5434
static MaybeObject* Runtime_NewStringWrapper(Arguments args) {
5435 5436 5437 5438 5439 5440 5441
  NoHandleAllocation ha;
  ASSERT(args.length() == 1);
  CONVERT_CHECKED(String, value, args[0]);
  return value->ToObject();
}


5442 5443 5444 5445 5446 5447 5448
bool Runtime::IsUpperCaseChar(uint16_t ch) {
  unibrow::uchar chars[unibrow::ToUppercase::kMaxWidth];
  int char_length = to_upper_mapping.get(ch, 0, chars);
  return char_length == 0;
}


5449
static MaybeObject* Runtime_NumberToString(Arguments args) {
5450 5451 5452 5453 5454 5455
  NoHandleAllocation ha;
  ASSERT(args.length() == 1);

  Object* number = args[0];
  RUNTIME_ASSERT(number->IsNumber());

5456
  return Heap::NumberToString(number);
5457 5458 5459
}


5460
static MaybeObject* Runtime_NumberToStringSkipCache(Arguments args) {
5461 5462 5463 5464 5465 5466 5467 5468 5469 5470
  NoHandleAllocation ha;
  ASSERT(args.length() == 1);

  Object* number = args[0];
  RUNTIME_ASSERT(number->IsNumber());

  return Heap::NumberToString(number, false);
}


5471
static MaybeObject* Runtime_NumberToInteger(Arguments args) {
5472 5473 5474
  NoHandleAllocation ha;
  ASSERT(args.length() == 1);

5475 5476 5477 5478 5479 5480
  CONVERT_DOUBLE_CHECKED(number, args[0]);

  // We do not include 0 so that we don't have to treat +0 / -0 cases.
  if (number > 0 && number <= Smi::kMaxValue) {
    return Smi::FromInt(static_cast<int>(number));
  }
5481
  return Heap::NumberFromDouble(DoubleToInteger(number));
5482 5483 5484
}


5485
static MaybeObject* Runtime_NumberToIntegerMapMinusZero(Arguments args) {
5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503
  NoHandleAllocation ha;
  ASSERT(args.length() == 1);

  CONVERT_DOUBLE_CHECKED(number, args[0]);

  // We do not include 0 so that we don't have to treat +0 / -0 cases.
  if (number > 0 && number <= Smi::kMaxValue) {
    return Smi::FromInt(static_cast<int>(number));
  }

  double double_value = DoubleToInteger(number);
  // Map both -0 and +0 to +0.
  if (double_value == 0) double_value = 0;

  return Heap::NumberFromDouble(double_value);
}


5504
static MaybeObject* Runtime_NumberToJSUint32(Arguments args) {
5505 5506 5507
  NoHandleAllocation ha;
  ASSERT(args.length() == 1);

5508
  CONVERT_NUMBER_CHECKED(int32_t, number, Uint32, args[0]);
5509 5510 5511 5512
  return Heap::NumberFromUint32(number);
}


5513
static MaybeObject* Runtime_NumberToJSInt32(Arguments args) {
5514 5515 5516
  NoHandleAllocation ha;
  ASSERT(args.length() == 1);

5517 5518 5519 5520 5521
  CONVERT_DOUBLE_CHECKED(number, args[0]);

  // We do not include 0 so that we don't have to treat +0 / -0 cases.
  if (number > 0 && number <= Smi::kMaxValue) {
    return Smi::FromInt(static_cast<int>(number));
ager@chromium.org's avatar
ager@chromium.org committed
5522
  }
5523
  return Heap::NumberFromInt32(DoubleToInt32(number));
5524 5525 5526
}


5527 5528
// Converts a Number to a Smi, if possible. Returns NaN if the number is not
// a small integer.
5529
static MaybeObject* Runtime_NumberToSmi(Arguments args) {
5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546
  NoHandleAllocation ha;
  ASSERT(args.length() == 1);

  Object* obj = args[0];
  if (obj->IsSmi()) {
    return obj;
  }
  if (obj->IsHeapNumber()) {
    double value = HeapNumber::cast(obj)->value();
    int int_value = FastD2I(value);
    if (value == FastI2D(int_value) && Smi::IsValid(int_value)) {
      return Smi::FromInt(int_value);
    }
  }
  return Heap::nan_value();
}

5547

5548 5549 5550 5551 5552 5553 5554
static MaybeObject* Runtime_AllocateHeapNumber(Arguments args) {
  NoHandleAllocation ha;
  ASSERT(args.length() == 0);
  return Heap::AllocateHeapNumber(0);
}


5555
static MaybeObject* Runtime_NumberAdd(Arguments args) {
5556 5557 5558 5559 5560
  NoHandleAllocation ha;
  ASSERT(args.length() == 2);

  CONVERT_DOUBLE_CHECKED(x, args[0]);
  CONVERT_DOUBLE_CHECKED(y, args[1]);
5561
  return Heap::NumberFromDouble(x + y);
5562 5563 5564
}


5565
static MaybeObject* Runtime_NumberSub(Arguments args) {
5566 5567 5568 5569 5570
  NoHandleAllocation ha;
  ASSERT(args.length() == 2);

  CONVERT_DOUBLE_CHECKED(x, args[0]);
  CONVERT_DOUBLE_CHECKED(y, args[1]);
5571
  return Heap::NumberFromDouble(x - y);
5572 5573 5574
}


5575
static MaybeObject* Runtime_NumberMul(Arguments args) {
5576 5577 5578 5579 5580
  NoHandleAllocation ha;
  ASSERT(args.length() == 2);

  CONVERT_DOUBLE_CHECKED(x, args[0]);
  CONVERT_DOUBLE_CHECKED(y, args[1]);
5581
  return Heap::NumberFromDouble(x * y);
5582 5583 5584
}


5585
static MaybeObject* Runtime_NumberUnaryMinus(Arguments args) {
5586 5587 5588 5589
  NoHandleAllocation ha;
  ASSERT(args.length() == 1);

  CONVERT_DOUBLE_CHECKED(x, args[0]);
5590
  return Heap::NumberFromDouble(-x);
5591 5592 5593
}


5594
static MaybeObject* Runtime_NumberAlloc(Arguments args) {
5595 5596 5597 5598 5599 5600 5601
  NoHandleAllocation ha;
  ASSERT(args.length() == 0);

  return Heap::NumberFromDouble(9876543210.0);
}


5602
static MaybeObject* Runtime_NumberDiv(Arguments args) {
5603 5604 5605 5606 5607
  NoHandleAllocation ha;
  ASSERT(args.length() == 2);

  CONVERT_DOUBLE_CHECKED(x, args[0]);
  CONVERT_DOUBLE_CHECKED(y, args[1]);
5608
  return Heap::NumberFromDouble(x / y);
5609 5610 5611
}


5612
static MaybeObject* Runtime_NumberMod(Arguments args) {
5613 5614 5615 5616 5617 5618
  NoHandleAllocation ha;
  ASSERT(args.length() == 2);

  CONVERT_DOUBLE_CHECKED(x, args[0]);
  CONVERT_DOUBLE_CHECKED(y, args[1]);

5619
  x = modulo(x, y);
5620 5621
  // NumberFromDouble may return a Smi instead of a Number object
  return Heap::NumberFromDouble(x);
5622 5623 5624
}


5625
static MaybeObject* Runtime_StringAdd(Arguments args) {
5626 5627 5628 5629
  NoHandleAllocation ha;
  ASSERT(args.length() == 2);
  CONVERT_CHECKED(String, str1, args[0]);
  CONVERT_CHECKED(String, str2, args[1]);
5630
  Counters::string_add_runtime.Increment();
5631
  return Heap::AllocateConsString(str1, str2);
5632 5633 5634
}


5635
template <typename sinkchar>
5636 5637 5638 5639 5640 5641 5642 5643
static inline void StringBuilderConcatHelper(String* special,
                                             sinkchar* sink,
                                             FixedArray* fixed_array,
                                             int array_length) {
  int position = 0;
  for (int i = 0; i < array_length; i++) {
    Object* element = fixed_array->get(i);
    if (element->IsSmi()) {
5644
      // Smi encoding of position and length.
5645
      int encoded_slice = Smi::cast(element)->value();
5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658
      int pos;
      int len;
      if (encoded_slice > 0) {
        // Position and length encoded in one smi.
        pos = StringBuilderSubstringPosition::decode(encoded_slice);
        len = StringBuilderSubstringLength::decode(encoded_slice);
      } else {
        // Position and length encoded in two smis.
        Object* obj = fixed_array->get(++i);
        ASSERT(obj->IsSmi());
        pos = Smi::cast(obj)->value();
        len = -encoded_slice;
      }
5659 5660 5661 5662
      String::WriteToFlat(special,
                          sink + position,
                          pos,
                          pos + len);
5663 5664 5665
      position += len;
    } else {
      String* string = String::cast(element);
5666 5667
      int element_length = string->length();
      String::WriteToFlat(string, sink + position, 0, element_length);
5668 5669 5670 5671 5672 5673
      position += element_length;
    }
  }
}


5674
static MaybeObject* Runtime_StringBuilderConcat(Arguments args) {
5675
  NoHandleAllocation ha;
5676
  ASSERT(args.length() == 3);
5677
  CONVERT_CHECKED(JSArray, array, args[0]);
5678 5679 5680 5681 5682 5683
  if (!args[1]->IsSmi()) {
    Top::context()->mark_out_of_memory();
    return Failure::OutOfMemoryException();
  }
  int array_length = Smi::cast(args[1])->value();
  CONVERT_CHECKED(String, special, args[2]);
5684 5685 5686 5687

  // This assumption is used by the slice encoding in one or two smis.
  ASSERT(Smi::kMaxValue >= String::kMaxLength);

5688
  int special_length = special->length();
5689 5690 5691 5692
  if (!array->HasFastElements()) {
    return Top::Throw(Heap::illegal_argument_symbol());
  }
  FixedArray* fixed_array = FixedArray::cast(array->elements());
5693
  if (fixed_array->length() < array_length) {
5694
    array_length = fixed_array->length();
5695
  }
5696 5697 5698 5699 5700 5701 5702 5703

  if (array_length == 0) {
    return Heap::empty_string();
  } else if (array_length == 1) {
    Object* first = fixed_array->get(0);
    if (first->IsString()) return first;
  }

5704
  bool ascii = special->HasOnlyAsciiChars();
5705 5706
  int position = 0;
  for (int i = 0; i < array_length; i++) {
5707
    int increment = 0;
5708 5709
    Object* elt = fixed_array->get(i);
    if (elt->IsSmi()) {
5710
      // Smi encoding of position and length.
5711 5712 5713 5714
      int smi_value = Smi::cast(elt)->value();
      int pos;
      int len;
      if (smi_value > 0) {
5715
        // Position and length encoded in one smi.
5716 5717
        pos = StringBuilderSubstringPosition::decode(smi_value);
        len = StringBuilderSubstringLength::decode(smi_value);
5718 5719
      } else {
        // Position and length encoded in two smis.
5720 5721
        len = -smi_value;
        // Get the position and check that it is a positive smi.
5722 5723 5724 5725
        i++;
        if (i >= array_length) {
          return Top::Throw(Heap::illegal_argument_symbol());
        }
5726 5727
        Object* next_smi = fixed_array->get(i);
        if (!next_smi->IsSmi()) {
5728 5729
          return Top::Throw(Heap::illegal_argument_symbol());
        }
5730 5731 5732 5733 5734 5735 5736 5737 5738
        pos = Smi::cast(next_smi)->value();
        if (pos < 0) {
          return Top::Throw(Heap::illegal_argument_symbol());
        }
      }
      ASSERT(pos >= 0);
      ASSERT(len >= 0);
      if (pos > special_length || len > special_length - pos) {
        return Top::Throw(Heap::illegal_argument_symbol());
5739
      }
5740
      increment = len;
5741 5742
    } else if (elt->IsString()) {
      String* element = String::cast(elt);
5743
      int element_length = element->length();
5744
      increment = element_length;
5745
      if (ascii && !element->HasOnlyAsciiChars()) {
5746
        ascii = false;
5747
      }
5748 5749 5750
    } else {
      return Top::Throw(Heap::illegal_argument_symbol());
    }
5751
    if (increment > String::kMaxLength - position) {
5752 5753 5754
      Top::context()->mark_out_of_memory();
      return Failure::OutOfMemoryException();
    }
5755
    position += increment;
5756 5757 5758 5759
  }

  int length = position;
  Object* object;
5760

5761
  if (ascii) {
5762 5763 5764
    { MaybeObject* maybe_object = Heap::AllocateRawAsciiString(length);
      if (!maybe_object->ToObject(&object)) return maybe_object;
    }
5765 5766 5767 5768 5769 5770
    SeqAsciiString* answer = SeqAsciiString::cast(object);
    StringBuilderConcatHelper(special,
                              answer->GetChars(),
                              fixed_array,
                              array_length);
    return answer;
5771
  } else {
5772 5773 5774
    { MaybeObject* maybe_object = Heap::AllocateRawTwoByteString(length);
      if (!maybe_object->ToObject(&object)) return maybe_object;
    }
5775 5776 5777 5778 5779 5780
    SeqTwoByteString* answer = SeqTwoByteString::cast(object);
    StringBuilderConcatHelper(special,
                              answer->GetChars(),
                              fixed_array,
                              array_length);
    return answer;
5781 5782 5783 5784
  }
}


5785
static MaybeObject* Runtime_NumberOr(Arguments args) {
5786 5787 5788 5789 5790 5791 5792 5793 5794
  NoHandleAllocation ha;
  ASSERT(args.length() == 2);

  CONVERT_NUMBER_CHECKED(int32_t, x, Int32, args[0]);
  CONVERT_NUMBER_CHECKED(int32_t, y, Int32, args[1]);
  return Heap::NumberFromInt32(x | y);
}


5795
static MaybeObject* Runtime_NumberAnd(Arguments args) {
5796 5797 5798 5799 5800 5801 5802 5803 5804
  NoHandleAllocation ha;
  ASSERT(args.length() == 2);

  CONVERT_NUMBER_CHECKED(int32_t, x, Int32, args[0]);
  CONVERT_NUMBER_CHECKED(int32_t, y, Int32, args[1]);
  return Heap::NumberFromInt32(x & y);
}


5805
static MaybeObject* Runtime_NumberXor(Arguments args) {
5806 5807 5808 5809 5810 5811 5812 5813 5814
  NoHandleAllocation ha;
  ASSERT(args.length() == 2);

  CONVERT_NUMBER_CHECKED(int32_t, x, Int32, args[0]);
  CONVERT_NUMBER_CHECKED(int32_t, y, Int32, args[1]);
  return Heap::NumberFromInt32(x ^ y);
}


5815
static MaybeObject* Runtime_NumberNot(Arguments args) {
5816 5817 5818 5819 5820 5821 5822 5823
  NoHandleAllocation ha;
  ASSERT(args.length() == 1);

  CONVERT_NUMBER_CHECKED(int32_t, x, Int32, args[0]);
  return Heap::NumberFromInt32(~x);
}


5824
static MaybeObject* Runtime_NumberShl(Arguments args) {
5825 5826 5827 5828 5829 5830 5831 5832 5833
  NoHandleAllocation ha;
  ASSERT(args.length() == 2);

  CONVERT_NUMBER_CHECKED(int32_t, x, Int32, args[0]);
  CONVERT_NUMBER_CHECKED(int32_t, y, Int32, args[1]);
  return Heap::NumberFromInt32(x << (y & 0x1f));
}


5834
static MaybeObject* Runtime_NumberShr(Arguments args) {
5835 5836 5837 5838 5839 5840 5841 5842 5843
  NoHandleAllocation ha;
  ASSERT(args.length() == 2);

  CONVERT_NUMBER_CHECKED(uint32_t, x, Uint32, args[0]);
  CONVERT_NUMBER_CHECKED(int32_t, y, Int32, args[1]);
  return Heap::NumberFromUint32(x >> (y & 0x1f));
}


5844
static MaybeObject* Runtime_NumberSar(Arguments args) {
5845 5846 5847 5848 5849 5850 5851 5852 5853
  NoHandleAllocation ha;
  ASSERT(args.length() == 2);

  CONVERT_NUMBER_CHECKED(int32_t, x, Int32, args[0]);
  CONVERT_NUMBER_CHECKED(int32_t, y, Int32, args[1]);
  return Heap::NumberFromInt32(ArithmeticShiftRight(x, y & 0x1f));
}


5854
static MaybeObject* Runtime_NumberEquals(Arguments args) {
5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872
  NoHandleAllocation ha;
  ASSERT(args.length() == 2);

  CONVERT_DOUBLE_CHECKED(x, args[0]);
  CONVERT_DOUBLE_CHECKED(y, args[1]);
  if (isnan(x)) return Smi::FromInt(NOT_EQUAL);
  if (isnan(y)) return Smi::FromInt(NOT_EQUAL);
  if (x == y) return Smi::FromInt(EQUAL);
  Object* result;
  if ((fpclassify(x) == FP_ZERO) && (fpclassify(y) == FP_ZERO)) {
    result = Smi::FromInt(EQUAL);
  } else {
    result = Smi::FromInt(NOT_EQUAL);
  }
  return result;
}


5873
static MaybeObject* Runtime_StringEquals(Arguments args) {
5874 5875 5876 5877 5878 5879
  NoHandleAllocation ha;
  ASSERT(args.length() == 2);

  CONVERT_CHECKED(String, x, args[0]);
  CONVERT_CHECKED(String, y, args[1]);

5880 5881 5882 5883 5884 5885 5886 5887
  bool not_equal = !x->Equals(y);
  // This is slightly convoluted because the value that signifies
  // equality is 0 and inequality is 1 so we have to negate the result
  // from String::Equals.
  ASSERT(not_equal == 0 || not_equal == 1);
  STATIC_CHECK(EQUAL == 0);
  STATIC_CHECK(NOT_EQUAL == 1);
  return Smi::FromInt(not_equal);
5888 5889 5890
}


5891
static MaybeObject* Runtime_NumberCompare(Arguments args) {
5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903
  NoHandleAllocation ha;
  ASSERT(args.length() == 3);

  CONVERT_DOUBLE_CHECKED(x, args[0]);
  CONVERT_DOUBLE_CHECKED(y, args[1]);
  if (isnan(x) || isnan(y)) return args[2];
  if (x == y) return Smi::FromInt(EQUAL);
  if (isless(x, y)) return Smi::FromInt(LESS);
  return Smi::FromInt(GREATER);
}


5904 5905
// Compare two Smis as if they were converted to strings and then
// compared lexicographically.
5906
static MaybeObject* Runtime_SmiLexicographicCompare(Arguments args) {
5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927
  NoHandleAllocation ha;
  ASSERT(args.length() == 2);

  // Arrays for the individual characters of the two Smis.  Smis are
  // 31 bit integers and 10 decimal digits are therefore enough.
  static int x_elms[10];
  static int y_elms[10];

  // Extract the integer values from the Smis.
  CONVERT_CHECKED(Smi, x, args[0]);
  CONVERT_CHECKED(Smi, y, args[1]);
  int x_value = x->value();
  int y_value = y->value();

  // If the integers are equal so are the string representations.
  if (x_value == y_value) return Smi::FromInt(EQUAL);

  // If one of the integers are zero the normal integer order is the
  // same as the lexicographic order of the string representations.
  if (x_value == 0 || y_value == 0) return Smi::FromInt(x_value - y_value);

5928
  // If only one of the integers is negative the negative number is
5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963
  // smallest because the char code of '-' is less than the char code
  // of any digit.  Otherwise, we make both values positive.
  if (x_value < 0 || y_value < 0) {
    if (y_value >= 0) return Smi::FromInt(LESS);
    if (x_value >= 0) return Smi::FromInt(GREATER);
    x_value = -x_value;
    y_value = -y_value;
  }

  // Convert the integers to arrays of their decimal digits.
  int x_index = 0;
  int y_index = 0;
  while (x_value > 0) {
    x_elms[x_index++] = x_value % 10;
    x_value /= 10;
  }
  while (y_value > 0) {
    y_elms[y_index++] = y_value % 10;
    y_value /= 10;
  }

  // Loop through the arrays of decimal digits finding the first place
  // where they differ.
  while (--x_index >= 0 && --y_index >= 0) {
    int diff = x_elms[x_index] - y_elms[y_index];
    if (diff != 0) return Smi::FromInt(diff);
  }

  // If one array is a suffix of the other array, the longest array is
  // the representation of the largest of the Smis in the
  // lexicographic ordering.
  return Smi::FromInt(x_index - y_index);
}


5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997
static Object* StringInputBufferCompare(String* x, String* y) {
  static StringInputBuffer bufx;
  static StringInputBuffer bufy;
  bufx.Reset(x);
  bufy.Reset(y);
  while (bufx.has_more() && bufy.has_more()) {
    int d = bufx.GetNext() - bufy.GetNext();
    if (d < 0) return Smi::FromInt(LESS);
    else if (d > 0) return Smi::FromInt(GREATER);
  }

  // x is (non-trivial) prefix of y:
  if (bufy.has_more()) return Smi::FromInt(LESS);
  // y is prefix of x:
  return Smi::FromInt(bufx.has_more() ? GREATER : EQUAL);
}


static Object* FlatStringCompare(String* x, String* y) {
  ASSERT(x->IsFlat());
  ASSERT(y->IsFlat());
  Object* equal_prefix_result = Smi::FromInt(EQUAL);
  int prefix_length = x->length();
  if (y->length() < prefix_length) {
    prefix_length = y->length();
    equal_prefix_result = Smi::FromInt(GREATER);
  } else if (y->length() > prefix_length) {
    equal_prefix_result = Smi::FromInt(LESS);
  }
  int r;
  if (x->IsAsciiRepresentation()) {
    Vector<const char> x_chars = x->ToAsciiVector();
    if (y->IsAsciiRepresentation()) {
      Vector<const char> y_chars = y->ToAsciiVector();
5998
      r = CompareChars(x_chars.start(), y_chars.start(), prefix_length);
5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023
    } else {
      Vector<const uc16> y_chars = y->ToUC16Vector();
      r = CompareChars(x_chars.start(), y_chars.start(), prefix_length);
    }
  } else {
    Vector<const uc16> x_chars = x->ToUC16Vector();
    if (y->IsAsciiRepresentation()) {
      Vector<const char> y_chars = y->ToAsciiVector();
      r = CompareChars(x_chars.start(), y_chars.start(), prefix_length);
    } else {
      Vector<const uc16> y_chars = y->ToUC16Vector();
      r = CompareChars(x_chars.start(), y_chars.start(), prefix_length);
    }
  }
  Object* result;
  if (r == 0) {
    result = equal_prefix_result;
  } else {
    result = (r < 0) ? Smi::FromInt(LESS) : Smi::FromInt(GREATER);
  }
  ASSERT(result == StringInputBufferCompare(x, y));
  return result;
}


6024
static MaybeObject* Runtime_StringCompare(Arguments args) {
6025 6026 6027 6028 6029 6030
  NoHandleAllocation ha;
  ASSERT(args.length() == 2);

  CONVERT_CHECKED(String, x, args[0]);
  CONVERT_CHECKED(String, y, args[1]);

6031 6032
  Counters::string_compare_runtime.Increment();

6033 6034
  // A few fast case tests before we flatten.
  if (x == y) return Smi::FromInt(EQUAL);
6035 6036
  if (y->length() == 0) {
    if (x->length() == 0) return Smi::FromInt(EQUAL);
6037
    return Smi::FromInt(GREATER);
6038
  } else if (x->length() == 0) {
6039 6040
    return Smi::FromInt(LESS);
  }
6041

6042
  int d = x->Get(0) - y->Get(0);
6043 6044
  if (d < 0) return Smi::FromInt(LESS);
  else if (d > 0) return Smi::FromInt(GREATER);
6045

6046 6047 6048 6049 6050 6051 6052
  Object* obj;
  { MaybeObject* maybe_obj = Heap::PrepareForCompare(x);
    if (!maybe_obj->ToObject(&obj)) return maybe_obj;
  }
  { MaybeObject* maybe_obj = Heap::PrepareForCompare(y);
    if (!maybe_obj->ToObject(&obj)) return maybe_obj;
  }
6053

6054 6055
  return (x->IsFlat() && y->IsFlat()) ? FlatStringCompare(x, y)
                                      : StringInputBufferCompare(x, y);
6056 6057 6058
}


6059
static MaybeObject* Runtime_Math_acos(Arguments args) {
6060 6061
  NoHandleAllocation ha;
  ASSERT(args.length() == 1);
6062
  Counters::math_acos.Increment();
6063 6064

  CONVERT_DOUBLE_CHECKED(x, args[0]);
6065
  return TranscendentalCache::Get(TranscendentalCache::ACOS, x);
6066 6067 6068
}


6069
static MaybeObject* Runtime_Math_asin(Arguments args) {
6070 6071
  NoHandleAllocation ha;
  ASSERT(args.length() == 1);
6072
  Counters::math_asin.Increment();
6073 6074

  CONVERT_DOUBLE_CHECKED(x, args[0]);
6075
  return TranscendentalCache::Get(TranscendentalCache::ASIN, x);
6076 6077 6078
}


6079
static MaybeObject* Runtime_Math_atan(Arguments args) {
6080 6081
  NoHandleAllocation ha;
  ASSERT(args.length() == 1);
6082
  Counters::math_atan.Increment();
6083 6084

  CONVERT_DOUBLE_CHECKED(x, args[0]);
6085
  return TranscendentalCache::Get(TranscendentalCache::ATAN, x);
6086 6087 6088
}


6089
static MaybeObject* Runtime_Math_atan2(Arguments args) {
6090 6091
  NoHandleAllocation ha;
  ASSERT(args.length() == 2);
6092
  Counters::math_atan2.Increment();
6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112

  CONVERT_DOUBLE_CHECKED(x, args[0]);
  CONVERT_DOUBLE_CHECKED(y, args[1]);
  double result;
  if (isinf(x) && isinf(y)) {
    // Make sure that the result in case of two infinite arguments
    // is a multiple of Pi / 4. The sign of the result is determined
    // by the first argument (x) and the sign of the second argument
    // determines the multiplier: one or three.
    static double kPiDividedBy4 = 0.78539816339744830962;
    int multiplier = (x < 0) ? -1 : 1;
    if (y < 0) multiplier *= 3;
    result = multiplier * kPiDividedBy4;
  } else {
    result = atan2(x, y);
  }
  return Heap::AllocateHeapNumber(result);
}


6113
static MaybeObject* Runtime_Math_ceil(Arguments args) {
6114 6115
  NoHandleAllocation ha;
  ASSERT(args.length() == 1);
6116
  Counters::math_ceil.Increment();
6117 6118 6119 6120 6121 6122

  CONVERT_DOUBLE_CHECKED(x, args[0]);
  return Heap::NumberFromDouble(ceiling(x));
}


6123
static MaybeObject* Runtime_Math_cos(Arguments args) {
6124 6125
  NoHandleAllocation ha;
  ASSERT(args.length() == 1);
6126
  Counters::math_cos.Increment();
6127 6128

  CONVERT_DOUBLE_CHECKED(x, args[0]);
6129
  return TranscendentalCache::Get(TranscendentalCache::COS, x);
6130 6131 6132
}


6133
static MaybeObject* Runtime_Math_exp(Arguments args) {
6134 6135
  NoHandleAllocation ha;
  ASSERT(args.length() == 1);
6136
  Counters::math_exp.Increment();
6137 6138

  CONVERT_DOUBLE_CHECKED(x, args[0]);
6139
  return TranscendentalCache::Get(TranscendentalCache::EXP, x);
6140 6141 6142
}


6143
static MaybeObject* Runtime_Math_floor(Arguments args) {
6144 6145
  NoHandleAllocation ha;
  ASSERT(args.length() == 1);
6146
  Counters::math_floor.Increment();
6147 6148 6149 6150 6151 6152

  CONVERT_DOUBLE_CHECKED(x, args[0]);
  return Heap::NumberFromDouble(floor(x));
}


6153
static MaybeObject* Runtime_Math_log(Arguments args) {
6154 6155
  NoHandleAllocation ha;
  ASSERT(args.length() == 1);
6156
  Counters::math_log.Increment();
6157 6158

  CONVERT_DOUBLE_CHECKED(x, args[0]);
6159
  return TranscendentalCache::Get(TranscendentalCache::LOG, x);
6160 6161 6162
}


6163
static MaybeObject* Runtime_Math_pow(Arguments args) {
6164 6165
  NoHandleAllocation ha;
  ASSERT(args.length() == 2);
6166
  Counters::math_pow.Increment();
6167 6168

  CONVERT_DOUBLE_CHECKED(x, args[0]);
6169 6170 6171 6172 6173

  // If the second argument is a smi, it is much faster to call the
  // custom powi() function than the generic pow().
  if (args[1]->IsSmi()) {
    int y = Smi::cast(args[1])->value();
6174
    return Heap::NumberFromDouble(power_double_int(x, y));
6175 6176
  }

6177
  CONVERT_DOUBLE_CHECKED(y, args[1]);
6178
  return Heap::AllocateHeapNumber(power_double_double(x, y));
6179 6180
}

6181 6182
// Fast version of Math.pow if we know that y is not an integer and
// y is not -0.5 or 0.5. Used as slowcase from codegen.
6183
static MaybeObject* Runtime_Math_pow_cfunction(Arguments args) {
6184 6185 6186 6187 6188
  NoHandleAllocation ha;
  ASSERT(args.length() == 2);
  CONVERT_DOUBLE_CHECKED(x, args[0]);
  CONVERT_DOUBLE_CHECKED(y, args[1]);
  if (y == 0) {
6189
    return Smi::FromInt(1);
6190
  } else if (isnan(y) || ((x == 1 || x == -1) && isinf(y))) {
6191
    return Heap::nan_value();
6192
  } else {
6193
    return Heap::AllocateHeapNumber(pow(x, y));
6194 6195 6196
  }
}

6197

6198
static MaybeObject* Runtime_RoundNumber(Arguments args) {
6199 6200
  NoHandleAllocation ha;
  ASSERT(args.length() == 1);
6201
  Counters::math_round.Increment();
6202

6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228
  if (!args[0]->IsHeapNumber()) {
    // Must be smi. Return the argument unchanged for all the other types
    // to make fuzz-natives test happy.
    return args[0];
  }

  HeapNumber* number = reinterpret_cast<HeapNumber*>(args[0]);

  double value = number->value();
  int exponent = number->get_exponent();
  int sign = number->get_sign();

  // We compare with kSmiValueSize - 3 because (2^30 - 0.1) has exponent 29 and
  // should be rounded to 2^30, which is not smi.
  if (!sign && exponent <= kSmiValueSize - 3) {
    return Smi::FromInt(static_cast<int>(value + 0.5));
  }

  // If the magnitude is big enough, there's no place for fraction part. If we
  // try to add 0.5 to this number, 1.0 will be added instead.
  if (exponent >= 52) {
    return number;
  }

  if (sign && value >= -0.5) return Heap::minus_zero_value();

6229 6230
  // Do not call NumberFromDouble() to avoid extra checks.
  return Heap::AllocateHeapNumber(floor(value + 0.5));
6231 6232 6233
}


6234
static MaybeObject* Runtime_Math_sin(Arguments args) {
6235 6236
  NoHandleAllocation ha;
  ASSERT(args.length() == 1);
6237
  Counters::math_sin.Increment();
6238 6239

  CONVERT_DOUBLE_CHECKED(x, args[0]);
6240
  return TranscendentalCache::Get(TranscendentalCache::SIN, x);
6241 6242 6243
}


6244
static MaybeObject* Runtime_Math_sqrt(Arguments args) {
6245 6246
  NoHandleAllocation ha;
  ASSERT(args.length() == 1);
6247
  Counters::math_sqrt.Increment();
6248 6249 6250 6251 6252 6253

  CONVERT_DOUBLE_CHECKED(x, args[0]);
  return Heap::AllocateHeapNumber(sqrt(x));
}


6254
static MaybeObject* Runtime_Math_tan(Arguments args) {
6255 6256
  NoHandleAllocation ha;
  ASSERT(args.length() == 1);
6257
  Counters::math_tan.Increment();
6258 6259

  CONVERT_DOUBLE_CHECKED(x, args[0]);
6260
  return TranscendentalCache::Get(TranscendentalCache::TAN, x);
6261 6262 6263
}


6264
static int MakeDay(int year, int month, int day) {
6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276
  static const int day_from_month[] = {0, 31, 59, 90, 120, 151,
                                       181, 212, 243, 273, 304, 334};
  static const int day_from_month_leap[] = {0, 31, 60, 91, 121, 152,
                                            182, 213, 244, 274, 305, 335};

  year += month / 12;
  month %= 12;
  if (month < 0) {
    year--;
    month += 12;
  }

6277 6278 6279
  ASSERT(month >= 0);
  ASSERT(month < 12);

6280 6281 6282 6283 6284 6285
  // year_delta is an arbitrary number such that:
  // a) year_delta = -1 (mod 400)
  // b) year + year_delta > 0 for years in the range defined by
  //    ECMA 262 - 15.9.1.1, i.e. upto 100,000,000 days on either side of
  //    Jan 1 1970. This is required so that we don't run into integer
  //    division of negative numbers.
6286
  // c) there shouldn't be an overflow for 32-bit integers in the following
6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298
  //    operations.
  static const int year_delta = 399999;
  static const int base_day = 365 * (1970 + year_delta) +
                              (1970 + year_delta) / 4 -
                              (1970 + year_delta) / 100 +
                              (1970 + year_delta) / 400;

  int year1 = year + year_delta;
  int day_from_year = 365 * year1 +
                      year1 / 4 -
                      year1 / 100 +
                      year1 / 400 -
6299 6300 6301
                      base_day;

  if (year % 4 || (year % 100 == 0 && year % 400 != 0)) {
6302
    return day_from_year + day_from_month[month] + day - 1;
6303
  }
6304

6305 6306 6307 6308
  return day_from_year + day_from_month_leap[month] + day - 1;
}


6309
static MaybeObject* Runtime_DateMakeDay(Arguments args) {
6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534
  NoHandleAllocation ha;
  ASSERT(args.length() == 3);

  CONVERT_SMI_CHECKED(year, args[0]);
  CONVERT_SMI_CHECKED(month, args[1]);
  CONVERT_SMI_CHECKED(date, args[2]);

  return Smi::FromInt(MakeDay(year, month, date));
}


static const int kDays4Years[] = {0, 365, 2 * 365, 3 * 365 + 1};
static const int kDaysIn4Years = 4 * 365 + 1;
static const int kDaysIn100Years = 25 * kDaysIn4Years - 1;
static const int kDaysIn400Years = 4 * kDaysIn100Years + 1;
static const int kDays1970to2000 = 30 * 365 + 7;
static const int kDaysOffset = 1000 * kDaysIn400Years + 5 * kDaysIn400Years -
                               kDays1970to2000;
static const int kYearsOffset = 400000;

static const char kDayInYear[] = {
      1, 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,
      1, 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,
      1, 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,
      1, 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,
      1, 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,
      1, 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,
      1, 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,
      1, 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,
      1, 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,
      1, 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,
      1, 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,
      1, 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,

      1, 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,
      1, 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,
      1, 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,
      1, 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,
      1, 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,
      1, 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,
      1, 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,
      1, 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,
      1, 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,
      1, 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,
      1, 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,
      1, 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,

      1, 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,
      1, 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,
      1, 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,
      1, 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,
      1, 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,
      1, 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,
      1, 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,
      1, 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,
      1, 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,
      1, 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,
      1, 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,
      1, 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,

      1, 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,
      1, 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,
      1, 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,
      1, 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,
      1, 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,
      1, 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,
      1, 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,
      1, 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,
      1, 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,
      1, 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,
      1, 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,
      1, 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};

static const char kMonthInYear[] = {
      0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
      0, 0, 0, 0, 0, 0,
      1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
      1, 1, 1,
      2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
      2, 2, 2, 2, 2, 2,
      3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
      3, 3, 3, 3, 3,
      4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
      4, 4, 4, 4, 4, 4,
      5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
      5, 5, 5, 5, 5,
      6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
      6, 6, 6, 6, 6, 6,
      7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
      7, 7, 7, 7, 7, 7,
      8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
      8, 8, 8, 8, 8,
      9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
      9, 9, 9, 9, 9, 9,
      10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
      10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
      11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
      11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,

      0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
      0, 0, 0, 0, 0, 0,
      1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
      1, 1, 1,
      2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
      2, 2, 2, 2, 2, 2,
      3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
      3, 3, 3, 3, 3,
      4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
      4, 4, 4, 4, 4, 4,
      5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
      5, 5, 5, 5, 5,
      6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
      6, 6, 6, 6, 6, 6,
      7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
      7, 7, 7, 7, 7, 7,
      8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
      8, 8, 8, 8, 8,
      9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
      9, 9, 9, 9, 9, 9,
      10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
      10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
      11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
      11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,

      0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
      0, 0, 0, 0, 0, 0,
      1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
      1, 1, 1, 1,
      2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
      2, 2, 2, 2, 2, 2,
      3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
      3, 3, 3, 3, 3,
      4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
      4, 4, 4, 4, 4, 4,
      5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
      5, 5, 5, 5, 5,
      6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
      6, 6, 6, 6, 6, 6,
      7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
      7, 7, 7, 7, 7, 7,
      8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
      8, 8, 8, 8, 8,
      9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
      9, 9, 9, 9, 9, 9,
      10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
      10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
      11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
      11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,

      0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
      0, 0, 0, 0, 0, 0,
      1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
      1, 1, 1,
      2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
      2, 2, 2, 2, 2, 2,
      3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
      3, 3, 3, 3, 3,
      4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
      4, 4, 4, 4, 4, 4,
      5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
      5, 5, 5, 5, 5,
      6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
      6, 6, 6, 6, 6, 6,
      7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
      7, 7, 7, 7, 7, 7,
      8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
      8, 8, 8, 8, 8,
      9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
      9, 9, 9, 9, 9, 9,
      10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
      10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
      11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
      11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11};


// This function works for dates from 1970 to 2099.
static inline void DateYMDFromTimeAfter1970(int date,
6535
                                            int& year, int& month, int& day) {
6536
#ifdef DEBUG
6537
  int save_date = date;  // Need this for ASSERT in the end.
6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550
#endif

  year = 1970 + (4 * date + 2) / kDaysIn4Years;
  date %= kDaysIn4Years;

  month = kMonthInYear[date];
  day = kDayInYear[date];

  ASSERT(MakeDay(year, month, day) == save_date);
}


static inline void DateYMDFromTimeSlow(int date,
6551
                                       int& year, int& month, int& day) {
6552
#ifdef DEBUG
6553
  int save_date = date;  // Need this for ASSERT in the end.
6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579
#endif

  date += kDaysOffset;
  year = 400 * (date / kDaysIn400Years) - kYearsOffset;
  date %= kDaysIn400Years;

  ASSERT(MakeDay(year, 0, 1) + date == save_date);

  date--;
  int yd1 = date / kDaysIn100Years;
  date %= kDaysIn100Years;
  year += 100 * yd1;

  date++;
  int yd2 = date / kDaysIn4Years;
  date %= kDaysIn4Years;
  year += 4 * yd2;

  date--;
  int yd3 = date / 365;
  date %= 365;
  year += yd3;

  bool is_leap = (!yd1 || yd2) && !yd3;

  ASSERT(date >= -1);
6580 6581 6582 6583 6584
  ASSERT(is_leap || (date >= 0));
  ASSERT((date < 365) || (is_leap && (date < 366)));
  ASSERT(is_leap == ((year % 4 == 0) && (year % 100 || (year % 400 == 0))));
  ASSERT(is_leap || ((MakeDay(year, 0, 1) + date) == save_date));
  ASSERT(!is_leap || ((MakeDay(year, 0, 1) + date + 1) == save_date));
6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598

  if (is_leap) {
    day = kDayInYear[2*365 + 1 + date];
    month = kMonthInYear[2*365 + 1 + date];
  } else {
    day = kDayInYear[date];
    month = kMonthInYear[date];
  }

  ASSERT(MakeDay(year, month, day) == save_date);
}


static inline void DateYMDFromTime(int date,
6599
                                   int& year, int& month, int& day) {
6600 6601 6602 6603 6604 6605 6606 6607
  if (date >= 0 && date < 32 * kDaysIn4Years) {
    DateYMDFromTimeAfter1970(date, year, month, day);
  } else {
    DateYMDFromTimeSlow(date, year, month, day);
  }
}


6608
static MaybeObject* Runtime_DateYMDFromTime(Arguments args) {
6609 6610 6611 6612 6613 6614 6615 6616 6617
  NoHandleAllocation ha;
  ASSERT(args.length() == 2);

  CONVERT_DOUBLE_CHECKED(t, args[0]);
  CONVERT_CHECKED(JSArray, res_array, args[1]);

  int year, month, day;
  DateYMDFromTime(static_cast<int>(floor(t / 86400000)), year, month, day);

6618 6619 6620 6621 6622 6623 6624
  RUNTIME_ASSERT(res_array->elements()->map() == Heap::fixed_array_map());
  FixedArray* elms = FixedArray::cast(res_array->elements());
  RUNTIME_ASSERT(elms->length() == 3);

  elms->set(0, Smi::FromInt(year));
  elms->set(1, Smi::FromInt(month));
  elms->set(2, Smi::FromInt(day));
6625 6626

  return Heap::undefined_value();
6627 6628 6629
}


6630
static MaybeObject* Runtime_NewArgumentsFast(Arguments args) {
6631 6632 6633 6634 6635 6636 6637
  NoHandleAllocation ha;
  ASSERT(args.length() == 3);

  JSFunction* callee = JSFunction::cast(args[0]);
  Object** parameters = reinterpret_cast<Object**>(args[1]);
  const int length = Smi::cast(args[2])->value();

6638 6639 6640 6641
  Object* result;
  { MaybeObject* maybe_result = Heap::AllocateArgumentsObject(callee, length);
    if (!maybe_result->ToObject(&result)) return maybe_result;
  }
6642 6643 6644
  // Allocate the elements if needed.
  if (length > 0) {
    // Allocate the fixed array.
6645 6646 6647 6648
    Object* obj;
    { MaybeObject* maybe_obj = Heap::AllocateRawFixedArray(length);
      if (!maybe_obj->ToObject(&obj)) return maybe_obj;
    }
6649 6650

    AssertNoAllocation no_gc;
6651 6652
    FixedArray* array = reinterpret_cast<FixedArray*>(obj);
    array->set_map(Heap::fixed_array_map());
6653
    array->set_length(length);
6654 6655

    WriteBarrierMode mode = array->GetWriteBarrierMode(no_gc);
6656 6657 6658
    for (int i = 0; i < length; i++) {
      array->set(i, *--parameters, mode);
    }
6659
    JSObject::cast(result)->set_elements(FixedArray::cast(obj));
6660 6661 6662 6663 6664
  }
  return result;
}


6665
static MaybeObject* Runtime_NewClosure(Arguments args) {
6666
  HandleScope scope;
6667
  ASSERT(args.length() == 3);
6668
  CONVERT_ARG_CHECKED(Context, context, 0);
6669
  CONVERT_ARG_CHECKED(SharedFunctionInfo, shared, 1);
6670
  CONVERT_BOOLEAN_CHECKED(pretenure, args[2]);
6671

6672 6673 6674 6675 6676
  // Allocate global closures in old space and allocate local closures
  // in new space. Additionally pretenure closures that are assigned
  // directly to properties.
  pretenure = pretenure || (context->global_context() == *context);
  PretenureFlag pretenure_flag = pretenure ? TENURED : NOT_TENURED;
6677
  Handle<JSFunction> result =
6678 6679 6680
      Factory::NewFunctionFromSharedFunctionInfo(shared,
                                                 context,
                                                 pretenure_flag);
6681 6682 6683
  return *result;
}

6684
static MaybeObject* Runtime_NewObjectFromBound(Arguments args) {
6685 6686 6687 6688
  HandleScope scope;
  ASSERT(args.length() == 2);
  CONVERT_ARG_CHECKED(JSFunction, function, 0);
  CONVERT_ARG_CHECKED(JSArray, params, 1);
6689

6690
  RUNTIME_ASSERT(params->HasFastElements());
6691
  FixedArray* fixed = FixedArray::cast(params->elements());
6692

6693 6694 6695
  int fixed_length = Smi::cast(params->length())->value();
  SmartPointer<Object**> param_data(NewArray<Object**>(fixed_length));
  for (int i = 0; i < fixed_length; i++) {
6696 6697 6698
    Handle<Object> val = Handle<Object>(fixed->get(i));
    param_data[i] = val.location();
  }
6699

6700
  bool exception = false;
6701
  Handle<Object> result = Execution::New(
6702 6703 6704 6705 6706
      function, fixed_length, *param_data, &exception);
  if (exception) {
      return Failure::Exception();
  }
  ASSERT(!result.is_null());
6707
  return *result;
6708 6709
}

6710

6711
static void TrySettingInlineConstructStub(Handle<JSFunction> function) {
6712 6713 6714 6715 6716
  Handle<Object> prototype = Factory::null_value();
  if (function->has_instance_prototype()) {
    prototype = Handle<Object>(function->instance_prototype());
  }
  if (function->shared()->CanGenerateInlineConstructor(*prototype)) {
6717
    ConstructStubCompiler compiler;
6718
    MaybeObject* code = compiler.CompileConstructStub(*function);
6719
    if (!code->IsFailure()) {
6720 6721
      function->shared()->set_construct_stub(
          Code::cast(code->ToObjectUnchecked()));
6722 6723
    }
  }
6724 6725 6726
}


6727
static MaybeObject* Runtime_NewObject(Arguments args) {
6728
  HandleScope scope;
6729 6730
  ASSERT(args.length() == 1);

6731 6732 6733 6734 6735 6736 6737 6738 6739
  Handle<Object> constructor = args.at<Object>(0);

  // If the constructor isn't a proper function we throw a type error.
  if (!constructor->IsJSFunction()) {
    Vector< Handle<Object> > arguments = HandleVector(&constructor, 1);
    Handle<Object> type_error =
        Factory::NewTypeError("not_constructor", arguments);
    return Top::Throw(*type_error);
  }
6740

6741
  Handle<JSFunction> function = Handle<JSFunction>::cast(constructor);
6742 6743 6744 6745 6746 6747 6748 6749 6750 6751

  // If function should not have prototype, construction is not allowed. In this
  // case generated code bailouts here, since function has no initial_map.
  if (!function->should_have_prototype()) {
    Vector< Handle<Object> > arguments = HandleVector(&constructor, 1);
    Handle<Object> type_error =
        Factory::NewTypeError("not_constructor", arguments);
    return Top::Throw(*type_error);
  }

6752
#ifdef ENABLE_DEBUGGER_SUPPORT
6753 6754
  // Handle stepping into constructors if step into is active.
  if (Debug::StepInActive()) {
6755
    Debug::HandleStepIn(function, Handle<Object>::null(), 0, true);
6756
  }
6757
#endif
6758

6759 6760
  if (function->has_initial_map()) {
    if (function->initial_map()->instance_type() == JS_FUNCTION_TYPE) {
6761 6762 6763 6764
      // The 'Function' function ignores the receiver object when
      // called using 'new' and creates a new JSFunction object that
      // is returned.  The receiver object is only used for error
      // reporting if an error occurs when constructing the new
6765 6766 6767 6768 6769 6770 6771
      // JSFunction. Factory::NewJSObject() should not be used to
      // allocate JSFunctions since it does not properly initialize
      // the shared part of the function. Since the receiver is
      // ignored anyway, we use the global object as the receiver
      // instead of a new JSFunction object. This way, errors are
      // reported the same way whether or not 'Function' is called
      // using 'new'.
6772 6773 6774 6775
      return Top::context()->global();
    }
  }

6776 6777 6778 6779
  // The function should be compiled for the optimization hints to be
  // available. We cannot use EnsureCompiled because that forces a
  // compilation through the shared function info which makes it
  // impossible for us to optimize.
6780
  Handle<SharedFunctionInfo> shared(function->shared());
6781
  if (!function->is_compiled()) CompileLazy(function, CLEAR_EXCEPTION);
6782

6783 6784 6785 6786 6787 6788 6789 6790 6791
  if (!function->has_initial_map() &&
      shared->IsInobjectSlackTrackingInProgress()) {
    // The tracking is already in progress for another function. We can only
    // track one initial_map at a time, so we force the completion before the
    // function is called as a constructor for the first time.
    shared->CompleteInobjectSlackTracking();
  }

  bool first_allocation = !shared->live_objects_may_exist();
6792
  Handle<JSObject> result = Factory::NewJSObject(function);
6793 6794 6795
  // Delay setting the stub if inobject slack tracking is in progress.
  if (first_allocation && !shared->IsInobjectSlackTrackingInProgress()) {
    TrySettingInlineConstructStub(function);
6796
  }
6797

6798 6799
  Counters::constructed_objects.Increment();
  Counters::constructed_objects_runtime.Increment();
6800

6801
  return *result;
6802 6803 6804
}


6805
static MaybeObject* Runtime_FinalizeInstanceSize(Arguments args) {
6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816
  HandleScope scope;
  ASSERT(args.length() == 1);

  CONVERT_ARG_CHECKED(JSFunction, function, 0);
  function->shared()->CompleteInobjectSlackTracking();
  TrySettingInlineConstructStub(function);

  return Heap::undefined_value();
}


6817
static MaybeObject* Runtime_LazyCompile(Arguments args) {
6818 6819 6820 6821 6822
  HandleScope scope;
  ASSERT(args.length() == 1);

  Handle<JSFunction> function = args.at<JSFunction>(0);
#ifdef DEBUG
6823
  if (FLAG_trace_lazy && !function->shared()->is_compiled()) {
6824
    PrintF("[lazy: ");
6825
    function->PrintName();
6826 6827 6828 6829
    PrintF("]\n");
  }
#endif

6830 6831 6832 6833 6834 6835 6836
  // Compile the target function.  Here we compile using CompileLazyInLoop in
  // order to get the optimized version.  This helps code like delta-blue
  // that calls performance-critical routines through constructors.  A
  // constructor call doesn't use a CallIC, it uses a LoadIC followed by a
  // direct call.  Since the in-loop tracking takes place through CallICs
  // this means that things called through constructors are never known to
  // be in loops.  We compile them as if they are in loops here just in case.
6837
  ASSERT(!function->is_compiled());
6838
  if (!CompileLazyInLoop(function, KEEP_EXCEPTION)) {
6839 6840 6841
    return Failure::Exception();
  }

6842 6843
  // All done. Return the compiled code.
  ASSERT(function->is_compiled());
6844 6845 6846 6847
  return function->code();
}


6848 6849 6850 6851 6852 6853 6854 6855
static MaybeObject* Runtime_LazyRecompile(Arguments args) {
  HandleScope scope;
  ASSERT(args.length() == 1);
  Handle<JSFunction> function = args.at<JSFunction>(0);
  // If the function is not optimizable or debugger is active continue using the
  // code from the full compiler.
  if (!function->shared()->code()->optimizable() ||
      Debug::has_break_points()) {
6856 6857 6858 6859 6860 6861 6862
    if (FLAG_trace_opt) {
      PrintF("[failed to optimize ");
      function->PrintName();
      PrintF(": is code optimizable: %s, is debugger enabled: %s]\n",
          function->shared()->code()->optimizable() ? "T" : "F",
          Debug::has_break_points() ? "T" : "F");
    }
6863 6864 6865 6866 6867 6868
    function->ReplaceCode(function->shared()->code());
    return function->code();
  }
  if (CompileOptimized(function, AstNode::kNoNumber)) {
    return function->code();
  }
6869 6870 6871 6872 6873
  if (FLAG_trace_opt) {
    PrintF("[failed to optimize ");
    function->PrintName();
    PrintF(": optimized compilation failed]\n");
  }
6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901
  function->ReplaceCode(function->shared()->code());
  return Failure::Exception();
}


static MaybeObject* Runtime_NotifyDeoptimized(Arguments args) {
  HandleScope scope;
  ASSERT(args.length() == 1);
  RUNTIME_ASSERT(args[0]->IsSmi());
  Deoptimizer::BailoutType type =
      static_cast<Deoptimizer::BailoutType>(Smi::cast(args[0])->value());
  Deoptimizer* deoptimizer = Deoptimizer::Grab();
  ASSERT(Heap::IsAllocationAllowed());
  int frames = deoptimizer->output_count();

  JavaScriptFrameIterator it;
  JavaScriptFrame* frame = NULL;
  for (int i = 0; i < frames; i++) {
    if (i != 0) it.Advance();
    frame = it.frame();
    deoptimizer->InsertHeapNumberValues(frames - i - 1, frame);
  }
  delete deoptimizer;

  RUNTIME_ASSERT(frame->function()->IsJSFunction());
  Handle<JSFunction> function(JSFunction::cast(frame->function()));
  Handle<Object> arguments;
  for (int i = frame->ComputeExpressionsCount() - 1; i >= 0; --i) {
6902
    if (frame->GetExpression(i) == Heap::arguments_marker()) {
6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011
      if (arguments.is_null()) {
        // FunctionGetArguments can't throw an exception, so cast away the
        // doubt with an assert.
        arguments = Handle<Object>(
            Accessors::FunctionGetArguments(*function,
                                            NULL)->ToObjectUnchecked());
        ASSERT(*arguments != Heap::null_value());
        ASSERT(*arguments != Heap::undefined_value());
      }
      frame->SetExpression(i, *arguments);
    }
  }

  CompilationCache::MarkForLazyOptimizing(function);
  if (type == Deoptimizer::EAGER) {
    RUNTIME_ASSERT(function->IsOptimized());
  } else {
    RUNTIME_ASSERT(!function->IsOptimized());
  }

  // Avoid doing too much work when running with --always-opt and keep
  // the optimized code around.
  if (FLAG_always_opt || type == Deoptimizer::LAZY) {
    return Heap::undefined_value();
  }

  // Count the number of optimized activations of the function.
  int activations = 0;
  while (!it.done()) {
    JavaScriptFrame* frame = it.frame();
    if (frame->is_optimized() && frame->function() == *function) {
      activations++;
    }
    it.Advance();
  }

  // TODO(kasperl): For now, we cannot support removing the optimized
  // code when we have recursive invocations of the same function.
  if (activations == 0) {
    if (FLAG_trace_deopt) {
      PrintF("[removing optimized code for: ");
      function->PrintName();
      PrintF("]\n");
    }
    function->ReplaceCode(function->shared()->code());
  }
  return Heap::undefined_value();
}


static MaybeObject* Runtime_NotifyOSR(Arguments args) {
  Deoptimizer* deoptimizer = Deoptimizer::Grab();
  delete deoptimizer;
  return Heap::undefined_value();
}


static MaybeObject* Runtime_DeoptimizeFunction(Arguments args) {
  HandleScope scope;
  ASSERT(args.length() == 1);
  CONVERT_ARG_CHECKED(JSFunction, function, 0);
  if (!function->IsOptimized()) return Heap::undefined_value();

  Deoptimizer::DeoptimizeFunction(*function);

  return Heap::undefined_value();
}


static MaybeObject* Runtime_CompileForOnStackReplacement(Arguments args) {
  HandleScope scope;
  ASSERT(args.length() == 1);
  CONVERT_ARG_CHECKED(JSFunction, function, 0);

  // We're not prepared to handle a function with arguments object.
  ASSERT(!function->shared()->scope_info()->HasArgumentsShadow());

  // We have hit a back edge in an unoptimized frame for a function that was
  // selected for on-stack replacement.  Find the unoptimized code object.
  Handle<Code> unoptimized(function->shared()->code());
  // Keep track of whether we've succeeded in optimizing.
  bool succeeded = unoptimized->optimizable();
  if (succeeded) {
    // If we are trying to do OSR when there are already optimized
    // activations of the function, it means (a) the function is directly or
    // indirectly recursive and (b) an optimized invocation has been
    // deoptimized so that we are currently in an unoptimized activation.
    // Check for optimized activations of this function.
    JavaScriptFrameIterator it;
    while (succeeded && !it.done()) {
      JavaScriptFrame* frame = it.frame();
      succeeded = !frame->is_optimized() || frame->function() != *function;
      it.Advance();
    }
  }

  int ast_id = AstNode::kNoNumber;
  if (succeeded) {
    // The top JS function is this one, the PC is somewhere in the
    // unoptimized code.
    JavaScriptFrameIterator it;
    JavaScriptFrame* frame = it.frame();
    ASSERT(frame->function() == *function);
    ASSERT(frame->code() == *unoptimized);
    ASSERT(unoptimized->contains(frame->pc()));

    // Use linear search of the unoptimized code's stack check table to find
    // the AST id matching the PC.
    Address start = unoptimized->instruction_start();
7012
    unsigned target_pc_offset = static_cast<unsigned>(frame->pc() - start);
7013
    Address table_cursor = start + unoptimized->stack_check_table_offset();
7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037
    uint32_t table_length = Memory::uint32_at(table_cursor);
    table_cursor += kIntSize;
    for (unsigned i = 0; i < table_length; ++i) {
      // Table entries are (AST id, pc offset) pairs.
      uint32_t pc_offset = Memory::uint32_at(table_cursor + kIntSize);
      if (pc_offset == target_pc_offset) {
        ast_id = static_cast<int>(Memory::uint32_at(table_cursor));
        break;
      }
      table_cursor += 2 * kIntSize;
    }
    ASSERT(ast_id != AstNode::kNoNumber);
    if (FLAG_trace_osr) {
      PrintF("[replacing on-stack at AST id %d in ", ast_id);
      function->PrintName();
      PrintF("]\n");
    }

    // Try to compile the optimized code.  A true return value from
    // CompileOptimized means that compilation succeeded, not necessarily
    // that optimization succeeded.
    if (CompileOptimized(function, ast_id) && function->IsOptimized()) {
      DeoptimizationInputData* data = DeoptimizationInputData::cast(
          function->code()->deoptimization_data());
7038 7039 7040
      if (data->OsrPcOffset()->value() >= 0) {
        if (FLAG_trace_osr) {
          PrintF("[on-stack replacement offset %d in optimized code]\n",
7041
               data->OsrPcOffset()->value());
7042 7043 7044 7045 7046 7047
        }
        ASSERT(data->OsrAstId()->value() == ast_id);
      } else {
        // We may never generate the desired OSR entry if we emit an
        // early deoptimize.
        succeeded = false;
7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063
      }
    } else {
      succeeded = false;
    }
  }

  // Revert to the original stack checks in the original unoptimized code.
  if (FLAG_trace_osr) {
    PrintF("[restoring original stack checks in ");
    function->PrintName();
    PrintF("]\n");
  }
  StackCheckStub check_stub;
  Handle<Code> check_code = check_stub.GetCode();
  Handle<Code> replacement_code(
      Builtins::builtin(Builtins::OnStackReplacement));
7064 7065 7066
  Deoptimizer::RevertStackCheckCode(*unoptimized,
                                    *check_code,
                                    *replacement_code);
7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082

  // Allow OSR only at nesting level zero again.
  unoptimized->set_allow_osr_at_loop_nesting_level(0);

  // If the optimization attempt succeeded, return the AST id tagged as a
  // smi. This tells the builtin that we need to translate the unoptimized
  // frame to an optimized one.
  if (succeeded) {
    ASSERT(function->code()->kind() == Code::OPTIMIZED_FUNCTION);
    return Smi::FromInt(ast_id);
  } else {
    return Smi::FromInt(-1);
  }
}


7083
static MaybeObject* Runtime_GetFunctionDelegate(Arguments args) {
7084 7085 7086 7087 7088 7089 7090
  HandleScope scope;
  ASSERT(args.length() == 1);
  RUNTIME_ASSERT(!args[0]->IsJSFunction());
  return *Execution::GetFunctionDelegate(args.at<Object>(0));
}


7091
static MaybeObject* Runtime_GetConstructorDelegate(Arguments args) {
7092 7093 7094 7095 7096 7097 7098
  HandleScope scope;
  ASSERT(args.length() == 1);
  RUNTIME_ASSERT(!args[0]->IsJSFunction());
  return *Execution::GetConstructorDelegate(args.at<Object>(0));
}


7099
static MaybeObject* Runtime_NewContext(Arguments args) {
7100
  NoHandleAllocation ha;
7101
  ASSERT(args.length() == 1);
7102

7103
  CONVERT_CHECKED(JSFunction, function, args[0]);
7104
  int length = function->shared()->scope_info()->NumberOfContextSlots();
7105 7106 7107 7108
  Object* result;
  { MaybeObject* maybe_result = Heap::AllocateFunctionContext(length, function);
    if (!maybe_result->ToObject(&result)) return maybe_result;
  }
7109 7110 7111

  Top::set_context(Context::cast(result));

7112
  return result;  // non-failure
7113 7114
}

7115 7116 7117

MUST_USE_RESULT static MaybeObject* PushContextHelper(Object* object,
                                                      bool is_catch_context) {
7118
  // Convert the object to a proper JavaScript object.
7119 7120
  Object* js_object = object;
  if (!js_object->IsJSObject()) {
7121 7122 7123 7124 7125
    MaybeObject* maybe_js_object = js_object->ToObject();
    if (!maybe_js_object->ToObject(&js_object)) {
      if (!Failure::cast(maybe_js_object)->IsInternalError()) {
        return maybe_js_object;
      }
7126
      HandleScope scope;
7127
      Handle<Object> handle(object);
7128 7129 7130 7131 7132 7133
      Handle<Object> result =
          Factory::NewTypeError("with_expression", HandleVector(&handle, 1));
      return Top::Throw(*result);
    }
  }

7134 7135 7136 7137 7138 7139 7140
  Object* result;
  { MaybeObject* maybe_result =
        Heap::AllocateWithContext(Top::context(),
                                  JSObject::cast(js_object),
                                  is_catch_context);
    if (!maybe_result->ToObject(&result)) return maybe_result;
  }
7141

7142 7143
  Context* context = Context::cast(result);
  Top::set_context(context);
7144

7145
  return result;
7146 7147 7148
}


7149
static MaybeObject* Runtime_PushContext(Arguments args) {
7150 7151 7152 7153 7154 7155
  NoHandleAllocation ha;
  ASSERT(args.length() == 1);
  return PushContextHelper(args[0], false);
}


7156
static MaybeObject* Runtime_PushCatchContext(Arguments args) {
7157 7158 7159 7160 7161 7162
  NoHandleAllocation ha;
  ASSERT(args.length() == 1);
  return PushContextHelper(args[0], true);
}


7163
static MaybeObject* Runtime_DeleteContextSlot(Arguments args) {
7164 7165 7166 7167 7168 7169 7170 7171 7172
  HandleScope scope;
  ASSERT(args.length() == 2);

  CONVERT_ARG_CHECKED(Context, context, 0);
  CONVERT_ARG_CHECKED(String, name, 1);

  int index;
  PropertyAttributes attributes;
  ContextLookupFlags flags = FOLLOW_CHAINS;
7173 7174 7175 7176 7177 7178
  Handle<Object> holder = context->Lookup(name, flags, &index, &attributes);

  // If the slot was not found the result is true.
  if (holder.is_null()) {
    return Heap::true_value();
  }
7179

7180 7181 7182
  // If the slot was found in a context, it should be DONT_DELETE.
  if (holder->IsContext()) {
    return Heap::false_value();
7183 7184
  }

7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197
  // The slot was found in a JSObject, either a context extension object,
  // the global object, or an arguments object.  Try to delete it
  // (respecting DONT_DELETE).  For consistency with V8's usual behavior,
  // which allows deleting all parameters in functions that mention
  // 'arguments', we do this even for the case of slots found on an
  // arguments object.  The slot was found on an arguments object if the
  // index is non-negative.
  Handle<JSObject> object = Handle<JSObject>::cast(holder);
  if (index >= 0) {
    return object->DeleteElement(index, JSObject::NORMAL_DELETION);
  } else {
    return object->DeleteProperty(*name, JSObject::NORMAL_DELETION);
  }
7198 7199 7200
}


7201 7202 7203 7204 7205 7206
// A mechanism to return a pair of Object pointers in registers (if possible).
// How this is achieved is calling convention-dependent.
// All currently supported x86 compiles uses calling conventions that are cdecl
// variants where a 64-bit value is returned in two 32-bit registers
// (edx:eax on ia32, r1:r0 on ARM).
// In AMD-64 calling convention a struct of two pointers is returned in rdx:rax.
whesse@chromium.org's avatar
whesse@chromium.org committed
7207 7208
// In Win64 calling convention, a struct of two pointers is returned in memory,
// allocated by the caller, and passed as a pointer in a hidden first parameter.
7209 7210
#ifdef V8_HOST_ARCH_64_BIT
struct ObjectPair {
7211 7212
  MaybeObject* x;
  MaybeObject* y;
7213
};
7214

7215
static inline ObjectPair MakePair(MaybeObject* x, MaybeObject* y) {
7216
  ObjectPair result = {x, y};
7217 7218 7219
  // Pointers x and y returned in rax and rdx, in AMD-x64-abi.
  // In Win64 they are assigned to a hidden first argument.
  return result;
7220
}
7221
#else
7222
typedef uint64_t ObjectPair;
7223
static inline ObjectPair MakePair(MaybeObject* x, MaybeObject* y) {
7224
  return reinterpret_cast<uint32_t>(x) |
7225
      (reinterpret_cast<ObjectPair>(y) << 32);
7226
}
7227 7228 7229
#endif


7230 7231
static inline MaybeObject* Unhole(MaybeObject* x,
                                  PropertyAttributes attributes) {
7232 7233 7234 7235 7236 7237
  ASSERT(!x->IsTheHole() || (attributes & READ_ONLY) != 0);
  USE(attributes);
  return x->IsTheHole() ? Heap::undefined_value() : x;
}


7238 7239
static JSObject* ComputeReceiverForNonGlobal(JSObject* holder) {
  ASSERT(!holder->IsGlobalObject());
7240
  Context* top = Top::context();
7241
  // Get the context extension function.
7242 7243
  JSFunction* context_extension_function =
      top->global_context()->context_extension_function();
7244 7245 7246 7247 7248 7249 7250 7251 7252 7253
  // If the holder isn't a context extension object, we just return it
  // as the receiver. This allows arguments objects to be used as
  // receivers, but only if they are put in the context scope chain
  // explicitly via a with-statement.
  Object* constructor = holder->map()->constructor();
  if (constructor != context_extension_function) return holder;
  // Fall back to using the global object as the receiver if the
  // property turns out to be a local variable allocated in a context
  // extension object - introduced via eval.
  return top->global()->global_receiver();
7254 7255 7256
}


7257
static ObjectPair LoadContextSlotHelper(Arguments args, bool throw_error) {
7258
  HandleScope scope;
7259
  ASSERT_EQ(2, args.length());
7260

7261
  if (!args[0]->IsContext() || !args[1]->IsString()) {
7262
    return MakePair(Top::ThrowIllegalOperation(), NULL);
7263
  }
7264
  Handle<Context> context = args.at<Context>(0);
7265
  Handle<String> name = args.at<String>(1);
7266 7267 7268 7269

  int index;
  PropertyAttributes attributes;
  ContextLookupFlags flags = FOLLOW_CHAINS;
7270
  Handle<Object> holder = context->Lookup(name, flags, &index, &attributes);
7271

7272 7273 7274
  // If the index is non-negative, the slot has been found in a local
  // variable or a parameter. Read it from the context object or the
  // arguments object.
7275
  if (index >= 0) {
7276 7277 7278 7279
    // If the "property" we were looking for is a local variable or an
    // argument in a context, the receiver is the global object; see
    // ECMA-262, 3rd., 10.1.6 and 10.2.3.
    JSObject* receiver = Top::context()->global()->global_receiver();
7280
    MaybeObject* value = (holder->IsContext())
7281 7282 7283 7284 7285 7286 7287
        ? Context::cast(*holder)->get(index)
        : JSObject::cast(*holder)->GetElement(index);
    return MakePair(Unhole(value, attributes), receiver);
  }

  // If the holder is found, we read the property from it.
  if (!holder.is_null() && holder->IsJSObject()) {
7288
    ASSERT(Handle<JSObject>::cast(holder)->HasProperty(*name));
7289
    JSObject* object = JSObject::cast(*holder);
7290 7291 7292 7293 7294 7295 7296 7297
    JSObject* receiver;
    if (object->IsGlobalObject()) {
      receiver = GlobalObject::cast(object)->global_receiver();
    } else if (context->is_exception_holder(*holder)) {
      receiver = Top::context()->global()->global_receiver();
    } else {
      receiver = ComputeReceiverForNonGlobal(object);
    }
7298 7299
    // No need to unhole the value here. This is taken care of by the
    // GetProperty function.
7300
    MaybeObject* value = object->GetProperty(*name);
7301
    return MakePair(value, receiver);
7302 7303 7304 7305 7306
  }

  if (throw_error) {
    // The property doesn't exist - throw exception.
    Handle<Object> reference_error =
7307
        Factory::NewReferenceError("not_defined", HandleVector(&name, 1));
7308 7309 7310 7311 7312 7313 7314 7315
    return MakePair(Top::Throw(*reference_error), NULL);
  } else {
    // The property doesn't exist - return undefined
    return MakePair(Heap::undefined_value(), Heap::undefined_value());
  }
}


7316
static ObjectPair Runtime_LoadContextSlot(Arguments args) {
7317 7318 7319 7320
  return LoadContextSlotHelper(args, true);
}


7321
static ObjectPair Runtime_LoadContextSlotNoReferenceError(Arguments args) {
7322 7323 7324 7325
  return LoadContextSlotHelper(args, false);
}


7326
static MaybeObject* Runtime_StoreContextSlot(Arguments args) {
7327 7328 7329 7330 7331
  HandleScope scope;
  ASSERT(args.length() == 3);

  Handle<Object> value(args[0]);
  CONVERT_ARG_CHECKED(Context, context, 1);
7332
  CONVERT_ARG_CHECKED(String, name, 2);
7333 7334 7335 7336

  int index;
  PropertyAttributes attributes;
  ContextLookupFlags flags = FOLLOW_CHAINS;
7337
  Handle<Object> holder = context->Lookup(name, flags, &index, &attributes);
7338 7339

  if (index >= 0) {
7340
    if (holder->IsContext()) {
7341 7342
      // Ignore if read_only variable.
      if ((attributes & READ_ONLY) == 0) {
7343
        Handle<Context>::cast(holder)->set(index, *value);
7344 7345 7346
      }
    } else {
      ASSERT((attributes & READ_ONLY) == 0);
7347 7348
      Handle<JSObject>::cast(holder)->SetElement(index, *value)->
          ToObjectUnchecked();
7349 7350 7351 7352 7353 7354 7355 7356
    }
    return *value;
  }

  // Slow case: The property is not in a FixedArray context.
  // It is either in an JSObject extension context or it was not found.
  Handle<JSObject> context_ext;

7357
  if (!holder.is_null()) {
7358
    // The property exists in the extension context.
7359
    context_ext = Handle<JSObject>::cast(holder);
7360 7361 7362 7363 7364 7365 7366
  } else {
    // The property was not found. It needs to be stored in the global context.
    ASSERT(attributes == ABSENT);
    attributes = NONE;
    context_ext = Handle<JSObject>(Top::context()->global());
  }

7367 7368 7369 7370
  // Set the property, but ignore if read_only variable on the context
  // extension object itself.
  if ((attributes & READ_ONLY) == 0 ||
      (context_ext->GetLocalPropertyAttribute(*name) == ABSENT)) {
7371
    Handle<Object> set = SetProperty(context_ext, name, value, NONE);
7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383
    if (set.is_null()) {
      // Failure::Exception is converted to a null handle in the
      // handle-based methods such as SetProperty.  We therefore need
      // to convert null handles back to exceptions.
      ASSERT(Top::has_pending_exception());
      return Failure::Exception();
    }
  }
  return *value;
}


7384
static MaybeObject* Runtime_Throw(Arguments args) {
7385 7386 7387 7388 7389 7390 7391
  HandleScope scope;
  ASSERT(args.length() == 1);

  return Top::Throw(args[0]);
}


7392
static MaybeObject* Runtime_ReThrow(Arguments args) {
7393 7394 7395 7396 7397 7398 7399
  HandleScope scope;
  ASSERT(args.length() == 1);

  return Top::ReThrow(args[0]);
}


7400
static MaybeObject* Runtime_PromoteScheduledException(Arguments args) {
7401 7402 7403 7404 7405
  ASSERT_EQ(0, args.length());
  return Top::PromoteScheduledException();
}


7406
static MaybeObject* Runtime_ThrowReferenceError(Arguments args) {
7407 7408 7409 7410 7411 7412 7413 7414 7415 7416
  HandleScope scope;
  ASSERT(args.length() == 1);

  Handle<Object> name(args[0]);
  Handle<Object> reference_error =
    Factory::NewReferenceError("not_defined", HandleVector(&name, 1));
  return Top::Throw(*reference_error);
}


7417
static MaybeObject* Runtime_StackOverflow(Arguments args) {
7418 7419 7420 7421 7422
  NoHandleAllocation na;
  return Top::StackOverflow();
}


7423
static MaybeObject* Runtime_StackGuard(Arguments args) {
7424
  ASSERT(args.length() == 0);
7425 7426

  // First check if this is a real stack overflow.
7427 7428 7429
  if (StackGuard::IsStackOverflow()) {
    return Runtime_StackOverflow(args);
  }
7430

7431
  return Execution::HandleStackGuardInterrupt();
7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465
}


// NOTE: These PrintXXX functions are defined for all builds (not just
// DEBUG builds) because we may want to be able to trace function
// calls in all modes.
static void PrintString(String* str) {
  // not uncommon to have empty strings
  if (str->length() > 0) {
    SmartPointer<char> s =
        str->ToCString(DISALLOW_NULLS, ROBUST_STRING_TRAVERSAL);
    PrintF("%s", *s);
  }
}


static void PrintObject(Object* obj) {
  if (obj->IsSmi()) {
    PrintF("%d", Smi::cast(obj)->value());
  } else if (obj->IsString() || obj->IsSymbol()) {
    PrintString(String::cast(obj));
  } else if (obj->IsNumber()) {
    PrintF("%g", obj->Number());
  } else if (obj->IsFailure()) {
    PrintF("<failure>");
  } else if (obj->IsUndefined()) {
    PrintF("<undefined>");
  } else if (obj->IsNull()) {
    PrintF("<null>");
  } else if (obj->IsTrue()) {
    PrintF("<true>");
  } else if (obj->IsFalse()) {
    PrintF("<false>");
  } else {
7466
    PrintF("%p", reinterpret_cast<void*>(obj));
7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520
  }
}


static int StackSize() {
  int n = 0;
  for (JavaScriptFrameIterator it; !it.done(); it.Advance()) n++;
  return n;
}


static void PrintTransition(Object* result) {
  // indentation
  { const int nmax = 80;
    int n = StackSize();
    if (n <= nmax)
      PrintF("%4d:%*s", n, n, "");
    else
      PrintF("%4d:%*s", n, nmax, "...");
  }

  if (result == NULL) {
    // constructor calls
    JavaScriptFrameIterator it;
    JavaScriptFrame* frame = it.frame();
    if (frame->IsConstructor()) PrintF("new ");
    // function name
    Object* fun = frame->function();
    if (fun->IsJSFunction()) {
      PrintObject(JSFunction::cast(fun)->shared()->name());
    } else {
      PrintObject(fun);
    }
    // function arguments
    // (we are intentionally only printing the actually
    // supplied parameters, not all parameters required)
    PrintF("(this=");
    PrintObject(frame->receiver());
    const int length = frame->GetProvidedParametersCount();
    for (int i = 0; i < length; i++) {
      PrintF(", ");
      PrintObject(frame->GetParameter(i));
    }
    PrintF(") {\n");

  } else {
    // function result
    PrintF("} -> ");
    PrintObject(result);
    PrintF("\n");
  }
}


7521
static MaybeObject* Runtime_TraceEnter(Arguments args) {
7522
  ASSERT(args.length() == 0);
7523 7524
  NoHandleAllocation ha;
  PrintTransition(NULL);
7525
  return Heap::undefined_value();
7526 7527 7528
}


7529
static MaybeObject* Runtime_TraceExit(Arguments args) {
7530 7531 7532 7533 7534 7535
  NoHandleAllocation ha;
  PrintTransition(args[0]);
  return args[0];  // return TOS
}


7536
static MaybeObject* Runtime_DebugPrint(Arguments args) {
7537 7538 7539 7540 7541 7542 7543 7544 7545
  NoHandleAllocation ha;
  ASSERT(args.length() == 1);

#ifdef DEBUG
  if (args[0]->IsString()) {
    // If we have a string, assume it's a code "marker"
    // and print some interesting cpu debugging info.
    JavaScriptFrameIterator it;
    JavaScriptFrame* frame = it.frame();
7546 7547
    PrintF("fp = %p, sp = %p, caller_sp = %p: ",
           frame->fp(), frame->sp(), frame->caller_sp());
7548 7549 7550 7551
  } else {
    PrintF("DebugPrint: ");
  }
  args[0]->Print();
7552
  if (args[0]->IsHeapObject()) {
7553
    PrintF("\n");
7554 7555
    HeapObject::cast(args[0])->map()->Print();
  }
7556
#else
7557 7558
  // ShortPrint is available in release mode. Print is not.
  args[0]->ShortPrint();
7559 7560
#endif
  PrintF("\n");
7561
  Flush();
7562 7563 7564 7565 7566

  return args[0];  // return TOS
}


7567
static MaybeObject* Runtime_DebugTrace(Arguments args) {
7568
  ASSERT(args.length() == 0);
7569 7570
  NoHandleAllocation ha;
  Top::PrintStack();
7571
  return Heap::undefined_value();
7572 7573 7574
}


7575
static MaybeObject* Runtime_DateCurrentTime(Arguments args) {
7576
  NoHandleAllocation ha;
7577
  ASSERT(args.length() == 0);
7578 7579 7580 7581 7582 7583 7584 7585 7586 7587

  // According to ECMA-262, section 15.9.1, page 117, the precision of
  // the number in a Date object representing a particular instant in
  // time is milliseconds. Therefore, we floor the result of getting
  // the OS time.
  double millis = floor(OS::TimeCurrentMillis());
  return Heap::NumberFromDouble(millis);
}


7588
static MaybeObject* Runtime_DateParseString(Arguments args) {
7589
  HandleScope scope;
7590
  ASSERT(args.length() == 2);
7591

7592
  CONVERT_ARG_CHECKED(String, str, 0);
7593
  FlattenString(str);
7594 7595 7596 7597 7598 7599

  CONVERT_ARG_CHECKED(JSArray, output, 1);
  RUNTIME_ASSERT(output->HasFastElements());

  AssertNoAllocation no_allocation;

7600
  FixedArray* output_array = FixedArray::cast(output->elements());
7601
  RUNTIME_ASSERT(output_array->length() >= DateParser::OUTPUT_SIZE);
7602
  bool result;
7603
  if (str->IsAsciiRepresentation()) {
7604 7605
    result = DateParser::Parse(str->ToAsciiVector(), output_array);
  } else {
7606
    ASSERT(str->IsTwoByteRepresentation());
7607
    result = DateParser::Parse(str->ToUC16Vector(), output_array);
7608
  }
7609

7610
  if (result) {
7611
    return *output;
7612
  } else {
7613
    return Heap::null_value();
7614 7615 7616 7617
  }
}


7618
static MaybeObject* Runtime_DateLocalTimezone(Arguments args) {
7619 7620 7621 7622
  NoHandleAllocation ha;
  ASSERT(args.length() == 1);

  CONVERT_DOUBLE_CHECKED(x, args[0]);
7623
  const char* zone = OS::LocalTimezone(x);
7624 7625 7626 7627
  return Heap::AllocateStringFromUtf8(CStrVector(zone));
}


7628
static MaybeObject* Runtime_DateLocalTimeOffset(Arguments args) {
7629
  NoHandleAllocation ha;
7630
  ASSERT(args.length() == 0);
7631 7632 7633 7634 7635

  return Heap::NumberFromDouble(OS::LocalTimeOffset());
}


7636
static MaybeObject* Runtime_DateDaylightSavingsOffset(Arguments args) {
7637 7638 7639 7640 7641 7642 7643 7644
  NoHandleAllocation ha;
  ASSERT(args.length() == 1);

  CONVERT_DOUBLE_CHECKED(x, args[0]);
  return Heap::NumberFromDouble(OS::DaylightSavingsOffset(x));
}


7645
static MaybeObject* Runtime_GlobalReceiver(Arguments args) {
7646 7647 7648 7649
  ASSERT(args.length() == 1);
  Object* global = args[0];
  if (!global->IsJSGlobalObject()) return Heap::null_value();
  return JSGlobalObject::cast(global)->global_receiver();
7650 7651 7652
}


7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667
static MaybeObject* Runtime_ParseJson(Arguments args) {
  HandleScope scope;
  ASSERT_EQ(1, args.length());
  CONVERT_ARG_CHECKED(String, source, 0);

  Handle<Object> result = JsonParser::Parse(source);
  if (result.is_null()) {
    // Syntax error or stack overflow in scanner.
    ASSERT(Top::has_pending_exception());
    return Failure::Exception();
  }
  return *result;
}


7668
static MaybeObject* Runtime_CompileString(Arguments args) {
7669
  HandleScope scope;
7670
  ASSERT_EQ(1, args.length());
7671 7672
  CONVERT_ARG_CHECKED(String, source, 0);

7673 7674
  // Compile source string in the global context.
  Handle<Context> context(Top::context()->global_context());
7675 7676
  Handle<SharedFunctionInfo> shared = Compiler::CompileEval(source,
                                                            context,
7677
                                                            true);
7678
  if (shared.is_null()) return Failure::Exception();
7679
  Handle<JSFunction> fun =
7680
      Factory::NewFunctionFromSharedFunctionInfo(shared, context, NOT_TENURED);
7681
  return *fun;
7682 7683 7684
}


7685 7686 7687 7688 7689 7690 7691
static ObjectPair CompileGlobalEval(Handle<String> source,
                                    Handle<Object> receiver) {
  // Deal with a normal eval call with a string argument. Compile it
  // and return the compiled function bound in the local context.
  Handle<SharedFunctionInfo> shared = Compiler::CompileEval(
      source,
      Handle<Context>(Top::context()),
7692
      Top::context()->IsGlobalContext());
7693 7694 7695 7696 7697 7698 7699 7700 7701
  if (shared.is_null()) return MakePair(Failure::Exception(), NULL);
  Handle<JSFunction> compiled = Factory::NewFunctionFromSharedFunctionInfo(
      shared,
      Handle<Context>(Top::context()),
      NOT_TENURED);
  return MakePair(*compiled, *receiver);
}


7702 7703 7704 7705 7706
static ObjectPair Runtime_ResolvePossiblyDirectEval(Arguments args) {
  ASSERT(args.length() == 3);
  if (!args[0]->IsJSFunction()) {
    return MakePair(Top::ThrowIllegalOperation(), NULL);
  }
7707 7708

  HandleScope scope;
7709 7710 7711 7712 7713 7714 7715 7716
  Handle<JSFunction> callee = args.at<JSFunction>(0);
  Handle<Object> receiver;  // Will be overwritten.

  // Compute the calling context.
  Handle<Context> context = Handle<Context>(Top::context());
#ifdef DEBUG
  // Make sure Top::context() agrees with the old code that traversed
  // the stack frames to compute the context.
7717 7718
  StackFrameLocator locator;
  JavaScriptFrame* frame = locator.FindJavaScriptFrame(0);
7719 7720
  ASSERT(Context::cast(frame->context()) == *context);
#endif
7721 7722 7723

  // Find where the 'eval' symbol is bound. It is unaliased only if
  // it is bound in the global context.
7724 7725 7726
  int index = -1;
  PropertyAttributes attributes = ABSENT;
  while (true) {
7727 7728
    receiver = context->Lookup(Factory::eval_symbol(), FOLLOW_PROTOTYPE_CHAIN,
                               &index, &attributes);
ager@chromium.org's avatar
ager@chromium.org committed
7729 7730 7731
    // Stop search when eval is found or when the global context is
    // reached.
    if (attributes != ABSENT || context->IsGlobalContext()) break;
7732 7733 7734 7735 7736 7737 7738
    if (context->is_function_context()) {
      context = Handle<Context>(Context::cast(context->closure()->context()));
    } else {
      context = Handle<Context>(context->previous());
    }
  }

ager@chromium.org's avatar
ager@chromium.org committed
7739 7740 7741 7742 7743 7744
  // If eval could not be resolved, it has been deleted and we need to
  // throw a reference error.
  if (attributes == ABSENT) {
    Handle<Object> name = Factory::eval_symbol();
    Handle<Object> reference_error =
        Factory::NewReferenceError("not_defined", HandleVector(&name, 1));
7745 7746 7747 7748
    return MakePair(Top::Throw(*reference_error), NULL);
  }

  if (!context->IsGlobalContext()) {
7749 7750 7751 7752 7753
    // 'eval' is not bound in the global context. Just call the function
    // with the given arguments. This is not necessarily the global eval.
    if (receiver->IsContext()) {
      context = Handle<Context>::cast(receiver);
      receiver = Handle<Object>(context->get(index));
7754 7755
    } else if (receiver->IsJSContextExtensionObject()) {
      receiver = Handle<JSObject>(Top::context()->global()->global_receiver());
7756
    }
7757
    return MakePair(*callee, *receiver);
7758 7759
  }

7760 7761 7762 7763 7764 7765 7766
  // 'eval' is bound in the global context, but it may have been overwritten.
  // Compare it to the builtin 'GlobalEval' function to make sure.
  if (*callee != Top::global_context()->global_eval_fun() ||
      !args[1]->IsString()) {
    return MakePair(*callee, Top::context()->global()->global_receiver());
  }

7767 7768 7769 7770 7771 7772 7773 7774 7775 7776 7777 7778 7779 7780 7781 7782 7783 7784 7785 7786 7787
  return CompileGlobalEval(args.at<String>(1), args.at<Object>(2));
}


static ObjectPair Runtime_ResolvePossiblyDirectEvalNoLookup(Arguments args) {
  ASSERT(args.length() == 3);
  if (!args[0]->IsJSFunction()) {
    return MakePair(Top::ThrowIllegalOperation(), NULL);
  }

  HandleScope scope;
  Handle<JSFunction> callee = args.at<JSFunction>(0);

  // 'eval' is bound in the global context, but it may have been overwritten.
  // Compare it to the builtin 'GlobalEval' function to make sure.
  if (*callee != Top::global_context()->global_eval_fun() ||
      !args[1]->IsString()) {
    return MakePair(*callee, Top::context()->global()->global_receiver());
  }

  return CompileGlobalEval(args.at<String>(1), args.at<Object>(2));
7788 7789 7790
}


7791
static MaybeObject* Runtime_SetNewFunctionAttributes(Arguments args) {
7792 7793 7794 7795 7796 7797 7798 7799 7800 7801 7802 7803 7804 7805 7806 7807
  // This utility adjusts the property attributes for newly created Function
  // object ("new Function(...)") by changing the map.
  // All it does is changing the prototype property to enumerable
  // as specified in ECMA262, 15.3.5.2.
  HandleScope scope;
  ASSERT(args.length() == 1);
  CONVERT_ARG_CHECKED(JSFunction, func, 0);
  ASSERT(func->map()->instance_type() ==
         Top::function_instance_map()->instance_type());
  ASSERT(func->map()->instance_size() ==
         Top::function_instance_map()->instance_size());
  func->set_map(*Top::function_instance_map());
  return *func;
}


7808
static MaybeObject* Runtime_AllocateInNewSpace(Arguments args) {
7809 7810 7811 7812 7813 7814 7815 7816 7817 7818 7819
  // Allocate a block of memory in NewSpace (filled with a filler).
  // Use as fallback for allocation in generated code when NewSpace
  // is full.
  ASSERT(args.length() == 1);
  CONVERT_ARG_CHECKED(Smi, size_smi, 0);
  int size = size_smi->value();
  RUNTIME_ASSERT(IsAligned(size, kPointerSize));
  RUNTIME_ASSERT(size > 0);
  static const int kMinFreeNewSpaceAfterGC =
      Heap::InitialSemiSpaceSize() * 3/4;
  RUNTIME_ASSERT(size <= kMinFreeNewSpaceAfterGC);
7820 7821 7822 7823 7824 7825
  Object* allocation;
  { MaybeObject* maybe_allocation = Heap::new_space()->AllocateRaw(size);
    if (maybe_allocation->ToObject(&allocation)) {
      Heap::CreateFillerObjectAt(HeapObject::cast(allocation)->address(), size);
    }
    return maybe_allocation;
7826 7827 7828 7829
  }
}


7830
// Push an object unto an array of objects if it is not already in the
7831 7832
// array.  Returns true if the element was pushed on the stack and
// false otherwise.
7833
static MaybeObject* Runtime_PushIfAbsent(Arguments args) {
ager@chromium.org's avatar
ager@chromium.org committed
7834
  ASSERT(args.length() == 2);
7835
  CONVERT_CHECKED(JSArray, array, args[0]);
7836
  CONVERT_CHECKED(JSObject, element, args[1]);
7837
  RUNTIME_ASSERT(array->HasFastElements());
7838 7839 7840 7841 7842
  int length = Smi::cast(array->length())->value();
  FixedArray* elements = FixedArray::cast(array->elements());
  for (int i = 0; i < length; i++) {
    if (elements->get(i) == element) return Heap::false_value();
  }
7843 7844 7845 7846
  Object* obj;
  { MaybeObject* maybe_obj = array->SetFastElement(length, element);
    if (!maybe_obj->ToObject(&obj)) return maybe_obj;
  }
7847 7848 7849 7850
  return Heap::true_value();
}


7851 7852 7853 7854 7855 7856 7857
/**
 * A simple visitor visits every element of Array's.
 * The backend storage can be a fixed array for fast elements case,
 * or a dictionary for sparse array. Since Dictionary is a subtype
 * of FixedArray, the class can be used by both fast and slow cases.
 * The second parameter of the constructor, fast_elements, specifies
 * whether the storage is a FixedArray or Dictionary.
7858 7859 7860
 *
 * An index limit is used to deal with the situation that a result array
 * length overflows 32-bit non-negative integer.
7861 7862 7863
 */
class ArrayConcatVisitor {
 public:
7864 7865 7866 7867
  ArrayConcatVisitor(Handle<FixedArray> storage,
                     uint32_t index_limit,
                     bool fast_elements) :
      storage_(storage), index_limit_(index_limit),
7868
      index_offset_(0), fast_elements_(fast_elements) { }
7869 7870

  void visit(uint32_t i, Handle<Object> elm) {
7871 7872
    if (i >= index_limit_ - index_offset_) return;
    uint32_t index = index_offset_ + i;
feng@chromium.org's avatar
feng@chromium.org committed
7873

7874 7875 7876 7877 7878
    if (fast_elements_) {
      ASSERT(index < static_cast<uint32_t>(storage_->length()));
      storage_->set(index, *elm);

    } else {
7879 7880
      Handle<NumberDictionary> dict = Handle<NumberDictionary>::cast(storage_);
      Handle<NumberDictionary> result =
7881 7882 7883 7884 7885 7886 7887
          Factory::DictionaryAtNumberPut(dict, index, elm);
      if (!result.is_identical_to(dict))
        storage_ = result;
    }
  }

  void increase_index_offset(uint32_t delta) {
7888 7889 7890 7891 7892
    if (index_limit_ - index_offset_ < delta) {
      index_offset_ = index_limit_;
    } else {
      index_offset_ += delta;
    }
7893 7894
  }

7895 7896
  Handle<FixedArray> storage() { return storage_; }

7897 7898
 private:
  Handle<FixedArray> storage_;
7899 7900
  // Limit on the accepted indices. Elements with indices larger than the
  // limit are ignored by the visitor.
7901
  uint32_t index_limit_;
7902
  // Index after last seen index. Always less than or equal to index_limit_.
7903
  uint32_t index_offset_;
7904
  const bool fast_elements_;
7905 7906 7907
};


7908 7909 7910 7911 7912 7913 7914 7915 7916 7917 7918 7919 7920 7921 7922 7923 7924 7925 7926 7927 7928 7929 7930 7931
template<class ExternalArrayClass, class ElementType>
static uint32_t IterateExternalArrayElements(Handle<JSObject> receiver,
                                             bool elements_are_ints,
                                             bool elements_are_guaranteed_smis,
                                             uint32_t range,
                                             ArrayConcatVisitor* visitor) {
  Handle<ExternalArrayClass> array(
      ExternalArrayClass::cast(receiver->elements()));
  uint32_t len = Min(static_cast<uint32_t>(array->length()), range);

  if (visitor != NULL) {
    if (elements_are_ints) {
      if (elements_are_guaranteed_smis) {
        for (uint32_t j = 0; j < len; j++) {
          Handle<Smi> e(Smi::FromInt(static_cast<int>(array->get(j))));
          visitor->visit(j, e);
        }
      } else {
        for (uint32_t j = 0; j < len; j++) {
          int64_t val = static_cast<int64_t>(array->get(j));
          if (Smi::IsValid(static_cast<intptr_t>(val))) {
            Handle<Smi> e(Smi::FromInt(static_cast<int>(val)));
            visitor->visit(j, e);
          } else {
7932 7933
            Handle<Object> e =
                Factory::NewNumber(static_cast<ElementType>(val));
7934 7935 7936 7937 7938 7939
            visitor->visit(j, e);
          }
        }
      }
    } else {
      for (uint32_t j = 0; j < len; j++) {
7940
        Handle<Object> e = Factory::NewNumber(array->get(j));
7941 7942 7943 7944 7945 7946 7947 7948
        visitor->visit(j, e);
      }
    }
  }

  return len;
}

7949 7950 7951 7952 7953 7954 7955 7956 7957 7958 7959 7960 7961 7962
/**
 * A helper function that visits elements of a JSObject. Only elements
 * whose index between 0 and range (exclusive) are visited.
 *
 * If the third parameter, visitor, is not NULL, the visitor is called
 * with parameters, 'visitor_index_offset + element index' and the element.
 *
 * It returns the number of visisted elements.
 */
static uint32_t IterateElements(Handle<JSObject> receiver,
                                uint32_t range,
                                ArrayConcatVisitor* visitor) {
  uint32_t num_of_elements = 0;

7963 7964 7965 7966 7967 7968 7969
  switch (receiver->GetElementsKind()) {
    case JSObject::FAST_ELEMENTS: {
      Handle<FixedArray> elements(FixedArray::cast(receiver->elements()));
      uint32_t len = elements->length();
      if (range < len) {
        len = range;
      }
7970

7971 7972 7973 7974 7975 7976 7977 7978 7979 7980 7981 7982 7983 7984 7985 7986 7987
      for (uint32_t j = 0; j < len; j++) {
        Handle<Object> e(elements->get(j));
        if (!e->IsTheHole()) {
          num_of_elements++;
          if (visitor) {
            visitor->visit(j, e);
          }
        }
      }
      break;
    }
    case JSObject::PIXEL_ELEMENTS: {
      Handle<PixelArray> pixels(PixelArray::cast(receiver->elements()));
      uint32_t len = pixels->length();
      if (range < len) {
        len = range;
      }
7988

7989
      for (uint32_t j = 0; j < len; j++) {
7990
        num_of_elements++;
7991 7992
        if (visitor != NULL) {
          Handle<Smi> e(Smi::FromInt(pixels->get(j)));
7993
          visitor->visit(j, e);
7994
        }
7995
      }
7996
      break;
7997
    }
7998 7999 8000 8001 8002 8003 8004 8005 8006 8007 8008 8009 8010 8011 8012 8013 8014 8015 8016 8017 8018 8019 8020 8021 8022 8023 8024 8025 8026 8027 8028 8029 8030 8031 8032 8033 8034 8035 8036 8037 8038 8039
    case JSObject::EXTERNAL_BYTE_ELEMENTS: {
      num_of_elements =
          IterateExternalArrayElements<ExternalByteArray, int8_t>(
              receiver, true, true, range, visitor);
      break;
    }
    case JSObject::EXTERNAL_UNSIGNED_BYTE_ELEMENTS: {
      num_of_elements =
          IterateExternalArrayElements<ExternalUnsignedByteArray, uint8_t>(
              receiver, true, true, range, visitor);
      break;
    }
    case JSObject::EXTERNAL_SHORT_ELEMENTS: {
      num_of_elements =
          IterateExternalArrayElements<ExternalShortArray, int16_t>(
              receiver, true, true, range, visitor);
      break;
    }
    case JSObject::EXTERNAL_UNSIGNED_SHORT_ELEMENTS: {
      num_of_elements =
          IterateExternalArrayElements<ExternalUnsignedShortArray, uint16_t>(
              receiver, true, true, range, visitor);
      break;
    }
    case JSObject::EXTERNAL_INT_ELEMENTS: {
      num_of_elements =
          IterateExternalArrayElements<ExternalIntArray, int32_t>(
              receiver, true, false, range, visitor);
      break;
    }
    case JSObject::EXTERNAL_UNSIGNED_INT_ELEMENTS: {
      num_of_elements =
          IterateExternalArrayElements<ExternalUnsignedIntArray, uint32_t>(
              receiver, true, false, range, visitor);
      break;
    }
    case JSObject::EXTERNAL_FLOAT_ELEMENTS: {
      num_of_elements =
          IterateExternalArrayElements<ExternalFloatArray, float>(
              receiver, false, false, range, visitor);
      break;
    }
8040 8041 8042 8043 8044 8045 8046 8047 8048 8049 8050 8051 8052
    case JSObject::DICTIONARY_ELEMENTS: {
      Handle<NumberDictionary> dict(receiver->element_dictionary());
      uint32_t capacity = dict->Capacity();
      for (uint32_t j = 0; j < capacity; j++) {
        Handle<Object> k(dict->KeyAt(j));
        if (dict->IsKey(*k)) {
          ASSERT(k->IsNumber());
          uint32_t index = static_cast<uint32_t>(k->Number());
          if (index < range) {
            num_of_elements++;
            if (visitor) {
              visitor->visit(index, Handle<Object>(dict->ValueAt(j)));
            }
8053 8054 8055
          }
        }
      }
8056
      break;
8057
    }
8058 8059 8060
    default:
      UNREACHABLE();
      break;
8061 8062 8063 8064 8065 8066 8067 8068 8069 8070 8071 8072 8073
  }

  return num_of_elements;
}


/**
 * A helper function that visits elements of an Array object, and elements
 * on its prototypes.
 *
 * Elements on prototypes are visited first, and only elements whose indices
 * less than Array length are visited.
 *
kasperl@chromium.org's avatar
kasperl@chromium.org committed
8074
 * If a ArrayConcatVisitor object is given, the visitor is called with
8075
 * parameters, element's index + visitor_index_offset and the element.
8076 8077 8078 8079 8080
 *
 * The returned number of elements is an upper bound on the actual number
 * of elements added. If the same element occurs in more than one object
 * in the array's prototype chain, it will be counted more than once, but
 * will only occur once in the result.
8081 8082 8083 8084 8085 8086 8087 8088 8089 8090 8091 8092 8093 8094
 */
static uint32_t IterateArrayAndPrototypeElements(Handle<JSArray> array,
                                                 ArrayConcatVisitor* visitor) {
  uint32_t range = static_cast<uint32_t>(array->length()->Number());
  Handle<Object> obj = array;

  static const int kEstimatedPrototypes = 3;
  List< Handle<JSObject> > objects(kEstimatedPrototypes);

  // Visit prototype first. If an element on the prototype is shadowed by
  // the inheritor using the same index, the ArrayConcatVisitor visits
  // the prototype element before the shadowing element.
  // The visitor can simply overwrite the old value by new value using
  // the same index.  This follows Array::concat semantics.
kasperl@chromium.org's avatar
kasperl@chromium.org committed
8095
  while (!obj->IsNull()) {
8096
    objects.Add(Handle<JSObject>::cast(obj));
8097 8098 8099 8100 8101 8102
    obj = Handle<Object>(obj->GetPrototype());
  }

  uint32_t nof_elements = 0;
  for (int i = objects.length() - 1; i >= 0; i--) {
    Handle<JSObject> obj = objects[i];
8103
    uint32_t encountered_elements =
8104
        IterateElements(Handle<JSObject>::cast(obj), range, visitor);
8105 8106 8107 8108 8109 8110

    if (encountered_elements > JSObject::kMaxElementCount - nof_elements) {
      nof_elements = JSObject::kMaxElementCount;
    } else {
      nof_elements += encountered_elements;
    }
8111 8112
  }

kasperl@chromium.org's avatar
kasperl@chromium.org committed
8113
  return nof_elements;
8114 8115 8116 8117 8118 8119
}


/**
 * A helper function of Runtime_ArrayConcat.
 *
8120 8121
 * The first argument is an Array of arrays and objects. It is the
 * same as the arguments array of Array::concat JS function.
8122
 *
8123 8124 8125
 * If an argument is an Array object, the function visits array
 * elements.  If an argument is not an Array object, the function
 * visits the object as if it is an one-element array.
8126
 *
8127
 * If the result array index overflows 32-bit unsigned integer, the rounded
8128 8129 8130
 * non-negative number is used as new length. For example, if one
 * array length is 2^32 - 1, second array length is 1, the
 * concatenated array length is 0.
8131 8132
 * TODO(lrn) Change length behavior to ECMAScript 5 specification (length
 * is one more than the last array index to get a value assigned).
8133 8134 8135 8136 8137 8138 8139
 */
static uint32_t IterateArguments(Handle<JSArray> arguments,
                                 ArrayConcatVisitor* visitor) {
  uint32_t visited_elements = 0;
  uint32_t num_of_args = static_cast<uint32_t>(arguments->length()->Number());

  for (uint32_t i = 0; i < num_of_args; i++) {
8140 8141 8142 8143 8144 8145 8146 8147 8148 8149 8150 8151 8152 8153 8154 8155 8156 8157 8158 8159 8160 8161
    Object *element;
    MaybeObject* maybe_element = arguments->GetElement(i);
    // This if() is not expected to fail, but we have the check in the
    // interest of hardening the runtime calls.
    if (maybe_element->ToObject(&element)) {
      Handle<Object> obj(element);
      if (obj->IsJSArray()) {
        Handle<JSArray> array = Handle<JSArray>::cast(obj);
        uint32_t len = static_cast<uint32_t>(array->length()->Number());
        uint32_t nof_elements =
            IterateArrayAndPrototypeElements(array, visitor);
        // Total elements of array and its prototype chain can be more than
        // the array length, but ArrayConcat can only concatenate at most
        // the array length number of elements. We use the length as an estimate
        // for the actual number of elements added.
        uint32_t added_elements = (nof_elements > len) ? len : nof_elements;
        if (JSArray::kMaxElementCount - visited_elements < added_elements) {
          visited_elements = JSArray::kMaxElementCount;
        } else {
          visited_elements += added_elements;
        }
        if (visitor) visitor->increase_index_offset(len);
8162
      } else {
8163 8164 8165 8166 8167 8168 8169
        if (visitor) {
          visitor->visit(0, obj);
          visitor->increase_index_offset(1);
        }
        if (visited_elements < JSArray::kMaxElementCount) {
          visited_elements++;
        }
8170
      }
kasperl@chromium.org's avatar
kasperl@chromium.org committed
8171
    }
8172 8173 8174 8175 8176 8177 8178 8179
  }
  return visited_elements;
}


/**
 * Array::concat implementation.
 * See ECMAScript 262, 15.4.4.4.
8180 8181
 * TODO(lrn): Fix non-compliance for very large concatenations and update to
 * following the ECMAScript 5 specification.
8182
 */
8183
static MaybeObject* Runtime_ArrayConcat(Arguments args) {
8184 8185 8186 8187 8188 8189 8190 8191 8192 8193 8194 8195 8196
  ASSERT(args.length() == 1);
  HandleScope handle_scope;

  CONVERT_CHECKED(JSArray, arg_arrays, args[0]);
  Handle<JSArray> arguments(arg_arrays);

  // Pass 1: estimate the number of elements of the result
  // (it could be more than real numbers if prototype has elements).
  uint32_t result_length = 0;
  uint32_t num_of_args = static_cast<uint32_t>(arguments->length()->Number());

  { AssertNoAllocation nogc;
    for (uint32_t i = 0; i < num_of_args; i++) {
8197 8198 8199 8200 8201 8202 8203 8204 8205 8206 8207 8208 8209 8210 8211 8212 8213
      Object* obj;
      MaybeObject* maybe_object = arguments->GetElement(i);
      // This if() is not expected to fail, but we have the check in the
      // interest of hardening the runtime calls.
      if (maybe_object->ToObject(&obj)) {
        uint32_t length_estimate;
        if (obj->IsJSArray()) {
          length_estimate =
              static_cast<uint32_t>(JSArray::cast(obj)->length()->Number());
        } else {
          length_estimate = 1;
        }
        if (JSObject::kMaxElementCount - result_length < length_estimate) {
          result_length = JSObject::kMaxElementCount;
          break;
        }
        result_length += length_estimate;
8214 8215 8216 8217 8218 8219 8220 8221
      }
    }
  }

  // Allocate an empty array, will set length and content later.
  Handle<JSArray> result = Factory::NewJSArray(0);

  uint32_t estimate_nof_elements = IterateArguments(arguments, NULL);
8222 8223 8224
  // If estimated number of elements is more than half of length, a
  // fixed array (fast case) is more time and space-efficient than a
  // dictionary.
8225 8226 8227 8228
  bool fast_case = (estimate_nof_elements * 2) >= result_length;

  Handle<FixedArray> storage;
  if (fast_case) {
8229 8230 8231
    // The backing storage array must have non-existing elements to
    // preserve holes across concat operations.
    storage = Factory::NewFixedArrayWithHoles(result_length);
8232 8233 8234
    Handle<Map> fast_map =
        Factory::GetFastElementsMap(Handle<Map>(result->map()));
    result->set_map(*fast_map);
8235 8236 8237 8238 8239
  } else {
    // TODO(126): move 25% pre-allocation logic into Dictionary::Allocate
    uint32_t at_least_space_for = estimate_nof_elements +
                                  (estimate_nof_elements >> 2);
    storage = Handle<FixedArray>::cast(
8240
                  Factory::NewNumberDictionary(at_least_space_for));
8241 8242 8243
    Handle<Map> slow_map =
        Factory::GetSlowElementsMap(Handle<Map>(result->map()));
    result->set_map(*slow_map);
8244 8245 8246 8247
  }

  Handle<Object> len = Factory::NewNumber(static_cast<double>(result_length));

8248
  ArrayConcatVisitor visitor(storage, result_length, fast_case);
8249 8250 8251 8252

  IterateArguments(arguments, &visitor);

  result->set_length(*len);
8253 8254
  // Please note the storage might have changed in the visitor.
  result->set_elements(*visitor.storage());
8255 8256 8257 8258 8259

  return *result;
}


8260 8261
// This will not allocate (flatten the string), but it may run
// very slowly for very deeply nested ConsStrings.  For debugging use only.
8262
static MaybeObject* Runtime_GlobalPrint(Arguments args) {
8263 8264 8265 8266 8267 8268 8269 8270 8271 8272 8273 8274
  NoHandleAllocation ha;
  ASSERT(args.length() == 1);

  CONVERT_CHECKED(String, string, args[0]);
  StringInputBuffer buffer(string);
  while (buffer.has_more()) {
    uint16_t character = buffer.GetNext();
    PrintF("%c", character);
  }
  return string;
}

8275 8276 8277 8278 8279
// Moves all own elements of an object, that are below a limit, to positions
// starting at zero. All undefined values are placed after non-undefined values,
// and are followed by non-existing element. Does not change the length
// property.
// Returns the number of non-undefined elements collected.
8280
static MaybeObject* Runtime_RemoveArrayHoles(Arguments args) {
8281 8282 8283 8284
  ASSERT(args.length() == 2);
  CONVERT_CHECKED(JSObject, object, args[0]);
  CONVERT_NUMBER_CHECKED(uint32_t, limit, Uint32, args[1]);
  return object->PrepareElementsForSort(limit);
8285 8286 8287 8288
}


// Move contents of argument 0 (an array) to argument 1 (an array)
8289
static MaybeObject* Runtime_MoveArrayContents(Arguments args) {
8290 8291 8292
  ASSERT(args.length() == 2);
  CONVERT_CHECKED(JSArray, from, args[0]);
  CONVERT_CHECKED(JSArray, to, args[1]);
8293
  HeapObject* new_elements = from->elements();
8294
  MaybeObject* maybe_new_map;
8295 8296
  if (new_elements->map() == Heap::fixed_array_map() ||
      new_elements->map() == Heap::fixed_cow_array_map()) {
8297
    maybe_new_map = to->map()->GetFastElementsMap();
8298
  } else {
8299
    maybe_new_map = to->map()->GetSlowElementsMap();
8300
  }
8301 8302
  Object* new_map;
  if (!maybe_new_map->ToObject(&new_map)) return maybe_new_map;
8303 8304
  to->set_map(Map::cast(new_map));
  to->set_elements(new_elements);
8305
  to->set_length(from->length());
8306 8307 8308 8309
  Object* obj;
  { MaybeObject* maybe_obj = from->ResetElements();
    if (!maybe_obj->ToObject(&obj)) return maybe_obj;
  }
8310
  from->set_length(Smi::FromInt(0));
8311 8312 8313 8314
  return to;
}


8315
// How many elements does this object/array have?
8316
static MaybeObject* Runtime_EstimateNumberOfElements(Arguments args) {
8317
  ASSERT(args.length() == 1);
8318 8319
  CONVERT_CHECKED(JSObject, object, args[0]);
  HeapObject* elements = object->elements();
8320
  if (elements->IsDictionary()) {
8321
    return Smi::FromInt(NumberDictionary::cast(elements)->NumberOfElements());
8322 8323
  } else if (object->IsJSArray()) {
    return JSArray::cast(object)->length();
8324
  } else {
8325
    return Smi::FromInt(FixedArray::cast(elements)->length());
8326 8327 8328 8329
  }
}


8330
static MaybeObject* Runtime_SwapElements(Arguments args) {
8331 8332 8333 8334
  HandleScope handle_scope;

  ASSERT_EQ(3, args.length());

8335
  CONVERT_ARG_CHECKED(JSObject, object, 0);
8336 8337 8338 8339
  Handle<Object> key1 = args.at<Object>(1);
  Handle<Object> key2 = args.at<Object>(2);

  uint32_t index1, index2;
8340 8341
  if (!key1->ToArrayIndex(&index1)
      || !key2->ToArrayIndex(&index2)) {
8342
    return Top::ThrowIllegalOperation();
8343 8344
  }

8345 8346 8347 8348 8349 8350 8351
  Handle<JSObject> jsobject = Handle<JSObject>::cast(object);
  Handle<Object> tmp1 = GetElement(jsobject, index1);
  Handle<Object> tmp2 = GetElement(jsobject, index2);

  SetElement(jsobject, index1, tmp2);
  SetElement(jsobject, index2, tmp1);

8352 8353 8354 8355
  return Heap::undefined_value();
}


8356
// Returns an array that tells you where in the [0, length) interval an array
8357 8358 8359 8360
// might have elements.  Can either return keys (positive integers) or
// intervals (pair of a negative integer (-start-1) followed by a
// positive (length)) or undefined values.
// Intervals can span over some keys that are not in the object.
8361
static MaybeObject* Runtime_GetArrayKeys(Arguments args) {
8362 8363
  ASSERT(args.length() == 2);
  HandleScope scope;
8364
  CONVERT_ARG_CHECKED(JSObject, array, 0);
8365
  CONVERT_NUMBER_CHECKED(uint32_t, length, Uint32, args[1]);
8366
  if (array->elements()->IsDictionary()) {
8367 8368
    // Create an array and get all the keys into it, then remove all the
    // keys that are not integers in the range 0 to length-1.
8369
    Handle<FixedArray> keys = GetKeysInFixedArrayFor(array, INCLUDE_PROTOS);
8370 8371 8372
    int keys_length = keys->length();
    for (int i = 0; i < keys_length; i++) {
      Object* key = keys->get(i);
8373
      uint32_t index = 0;
8374
      if (!key->ToArrayIndex(&index) || index >= length) {
8375 8376 8377 8378 8379 8380
        // Zap invalid keys.
        keys->set_undefined(i);
      }
    }
    return *Factory::NewJSArrayWithElements(keys);
  } else {
8381
    ASSERT(array->HasFastElements());
8382 8383
    Handle<FixedArray> single_interval = Factory::NewFixedArray(2);
    // -1 means start of array.
8384
    single_interval->set(0, Smi::FromInt(-1));
8385 8386
    uint32_t actual_length =
        static_cast<uint32_t>(FixedArray::cast(array->elements())->length());
8387
    uint32_t min_length = actual_length < length ? actual_length : length;
8388
    Handle<Object> length_object =
8389
        Factory::NewNumber(static_cast<double>(min_length));
8390 8391 8392 8393 8394 8395 8396 8397 8398 8399 8400
    single_interval->set(1, *length_object);
    return *Factory::NewJSArrayWithElements(single_interval);
  }
}


// DefineAccessor takes an optional final argument which is the
// property attributes (eg, DONT_ENUM, DONT_DELETE).  IMPORTANT: due
// to the way accessors are implemented, it is set for both the getter
// and setter on the first call to DefineAccessor and ignored on
// subsequent calls.
8401
static MaybeObject* Runtime_DefineAccessor(Arguments args) {
8402
  RUNTIME_ASSERT(args.length() == 4 || args.length() == 5);
8403 8404
  // Compute attributes.
  PropertyAttributes attributes = NONE;
8405
  if (args.length() == 5) {
8406 8407 8408 8409 8410 8411 8412 8413 8414 8415 8416
    CONVERT_CHECKED(Smi, attrs, args[4]);
    int value = attrs->value();
    // Only attribute bits should be set.
    ASSERT((value & ~(READ_ONLY | DONT_ENUM | DONT_DELETE)) == 0);
    attributes = static_cast<PropertyAttributes>(value);
  }

  CONVERT_CHECKED(JSObject, obj, args[0]);
  CONVERT_CHECKED(String, name, args[1]);
  CONVERT_CHECKED(Smi, flag, args[2]);
  CONVERT_CHECKED(JSFunction, fun, args[3]);
8417
  return obj->DefineAccessor(name, flag->value() == 0, fun, attributes);
8418 8419 8420
}


8421
static MaybeObject* Runtime_LookupAccessor(Arguments args) {
8422 8423 8424 8425 8426 8427 8428 8429
  ASSERT(args.length() == 3);
  CONVERT_CHECKED(JSObject, obj, args[0]);
  CONVERT_CHECKED(String, name, args[1]);
  CONVERT_CHECKED(Smi, flag, args[2]);
  return obj->LookupAccessor(name, flag->value() == 0);
}


8430
#ifdef ENABLE_DEBUGGER_SUPPORT
8431
static MaybeObject* Runtime_DebugBreak(Arguments args) {
8432 8433 8434 8435 8436
  ASSERT(args.length() == 0);
  return Execution::DebugBreakHelper();
}


8437 8438
// Helper functions for wrapping and unwrapping stack frame ids.
static Smi* WrapFrameId(StackFrame::Id id) {
8439
  ASSERT(IsAligned(OffsetFrom(id), static_cast<intptr_t>(4)));
8440 8441 8442 8443 8444 8445 8446 8447 8448 8449
  return Smi::FromInt(id >> 2);
}


static StackFrame::Id UnwrapFrameId(Smi* wrapped) {
  return static_cast<StackFrame::Id>(wrapped->value() << 2);
}


// Adds a JavaScript function as a debug event listener.
8450 8451
// args[0]: debug event listener function to set or null or undefined for
//          clearing the event listener function
8452
// args[1]: object supplied during callback
8453
static MaybeObject* Runtime_SetDebugEventListener(Arguments args) {
8454
  ASSERT(args.length() == 2);
8455 8456 8457 8458 8459 8460
  RUNTIME_ASSERT(args[0]->IsJSFunction() ||
                 args[0]->IsUndefined() ||
                 args[0]->IsNull());
  Handle<Object> callback = args.at<Object>(0);
  Handle<Object> data = args.at<Object>(1);
  Debugger::SetEventListener(callback, data);
8461 8462 8463 8464 8465

  return Heap::undefined_value();
}


8466
static MaybeObject* Runtime_Break(Arguments args) {
8467
  ASSERT(args.length() == 0);
8468 8469 8470 8471 8472
  StackGuard::DebugBreak();
  return Heap::undefined_value();
}


8473 8474 8475
static MaybeObject* DebugLookupResultValue(Object* receiver, String* name,
                                           LookupResult* result,
                                           bool* caught_exception) {
8476
  Object* value;
8477
  switch (result->type()) {
8478 8479
    case NORMAL:
      value = result->holder()->GetNormalizedProperty(result);
8480 8481 8482 8483
      if (value->IsTheHole()) {
        return Heap::undefined_value();
      }
      return value;
8484
    case FIELD:
8485 8486 8487 8488 8489 8490 8491
      value =
          JSObject::cast(
              result->holder())->FastPropertyAt(result->GetFieldIndex());
      if (value->IsTheHole()) {
        return Heap::undefined_value();
      }
      return value;
8492
    case CONSTANT_FUNCTION:
8493
      return result->GetConstantFunction();
8494
    case CALLBACKS: {
8495
      Object* structure = result->GetCallbackObject();
8496
      if (structure->IsProxy() || structure->IsAccessorInfo()) {
8497
        MaybeObject* maybe_value = receiver->GetPropertyWithCallback(
8498
            receiver, structure, name, result->holder());
8499
        if (!maybe_value->ToObject(&value)) {
8500
          if (maybe_value->IsRetryAfterGC()) return maybe_value;
8501 8502
          ASSERT(maybe_value->IsException());
          maybe_value = Top::pending_exception();
8503 8504 8505 8506
          Top::clear_pending_exception();
          if (caught_exception != NULL) {
            *caught_exception = true;
          }
8507
          return maybe_value;
8508
        }
8509 8510 8511
        return value;
      } else {
        return Heap::undefined_value();
8512
      }
8513
    }
8514
    case INTERCEPTOR:
8515 8516 8517
    case MAP_TRANSITION:
    case CONSTANT_TRANSITION:
    case NULL_DESCRIPTOR:
8518 8519 8520 8521
      return Heap::undefined_value();
    default:
      UNREACHABLE();
  }
8522
  UNREACHABLE();
8523 8524 8525 8526
  return Heap::undefined_value();
}


8527 8528 8529 8530 8531 8532 8533 8534 8535 8536 8537 8538
// Get debugger related details for an object property.
// args[0]: object holding property
// args[1]: name of the property
//
// The array returned contains the following information:
// 0: Property value
// 1: Property details
// 2: Property value is exception
// 3: Getter function if defined
// 4: Setter function if defined
// Items 2-4 are only filled if the property has either a getter or a setter
// defined through __defineGetter__ and/or __defineSetter__.
8539
static MaybeObject* Runtime_DebugGetPropertyDetails(Arguments args) {
8540 8541 8542 8543 8544 8545 8546
  HandleScope scope;

  ASSERT(args.length() == 2);

  CONVERT_ARG_CHECKED(JSObject, obj, 0);
  CONVERT_ARG_CHECKED(String, name, 1);

8547 8548 8549 8550 8551 8552 8553 8554 8555 8556 8557
  // Make sure to set the current context to the context before the debugger was
  // entered (if the debugger is entered). The reason for switching context here
  // is that for some property lookups (accessors and interceptors) callbacks
  // into the embedding application can occour, and the embedding application
  // could have the assumption that its own global context is the current
  // context and not some internal debugger context.
  SaveContext save;
  if (Debug::InDebugger()) {
    Top::set_context(*Debug::debugger_entry()->GetContext());
  }

8558 8559 8560 8561 8562 8563 8564
  // Skip the global proxy as it has no properties and always delegates to the
  // real global object.
  if (obj->IsJSGlobalProxy()) {
    obj = Handle<JSObject>(JSObject::cast(obj->GetPrototype()));
  }


8565 8566 8567 8568 8569
  // Check if the name is trivially convertible to an index and get the element
  // if so.
  uint32_t index;
  if (name->AsArrayIndex(&index)) {
    Handle<FixedArray> details = Factory::NewFixedArray(2);
8570 8571 8572 8573 8574 8575 8576
    Object* element_or_char;
    { MaybeObject* maybe_element_or_char =
          Runtime::GetElementOrCharAt(obj, index);
      if (!maybe_element_or_char->ToObject(&element_or_char)) {
        return maybe_element_or_char;
      }
    }
8577
    details->set(0, element_or_char);
8578 8579 8580 8581
    details->set(1, PropertyDetails(NONE, NORMAL).AsSmi());
    return *Factory::NewJSArrayWithElements(details);
  }

8582 8583 8584 8585 8586 8587
  // Find the number of objects making up this.
  int length = LocalPrototypeChainLength(*obj);

  // Try local lookup on each of the objects.
  Handle<JSObject> jsproto = obj;
  for (int i = 0; i < length; i++) {
8588
    LookupResult result;
8589 8590
    jsproto->LocalLookup(*name, &result);
    if (result.IsProperty()) {
8591 8592 8593 8594 8595 8596 8597 8598 8599 8600 8601 8602
      // LookupResult is not GC safe as it holds raw object pointers.
      // GC can happen later in this code so put the required fields into
      // local variables using handles when required for later use.
      PropertyType result_type = result.type();
      Handle<Object> result_callback_obj;
      if (result_type == CALLBACKS) {
        result_callback_obj = Handle<Object>(result.GetCallbackObject());
      }
      Smi* property_details = result.GetPropertyDetails().AsSmi();
      // DebugLookupResultValue can cause GC so details from LookupResult needs
      // to be copied to handles before this.
      bool caught_exception = false;
8603 8604 8605 8606 8607
      Object* raw_value;
      { MaybeObject* maybe_raw_value =
            DebugLookupResultValue(*obj, *name, &result, &caught_exception);
        if (!maybe_raw_value->ToObject(&raw_value)) return maybe_raw_value;
      }
8608 8609 8610 8611 8612 8613 8614 8615 8616 8617 8618 8619 8620 8621 8622 8623 8624 8625 8626
      Handle<Object> value(raw_value);

      // If the callback object is a fixed array then it contains JavaScript
      // getter and/or setter.
      bool hasJavaScriptAccessors = result_type == CALLBACKS &&
                                    result_callback_obj->IsFixedArray();
      Handle<FixedArray> details =
          Factory::NewFixedArray(hasJavaScriptAccessors ? 5 : 2);
      details->set(0, *value);
      details->set(1, property_details);
      if (hasJavaScriptAccessors) {
        details->set(2,
                     caught_exception ? Heap::true_value()
                                      : Heap::false_value());
        details->set(3, FixedArray::cast(*result_callback_obj)->get(0));
        details->set(4, FixedArray::cast(*result_callback_obj)->get(1));
      }

      return *Factory::NewJSArrayWithElements(details);
8627 8628 8629 8630 8631 8632
    }
    if (i < length - 1) {
      jsproto = Handle<JSObject>(JSObject::cast(jsproto->GetPrototype()));
    }
  }

8633 8634 8635 8636
  return Heap::undefined_value();
}


8637
static MaybeObject* Runtime_DebugGetProperty(Arguments args) {
8638 8639 8640 8641 8642 8643 8644 8645 8646 8647
  HandleScope scope;

  ASSERT(args.length() == 2);

  CONVERT_ARG_CHECKED(JSObject, obj, 0);
  CONVERT_ARG_CHECKED(String, name, 1);

  LookupResult result;
  obj->Lookup(*name, &result);
  if (result.IsProperty()) {
8648
    return DebugLookupResultValue(*obj, *name, &result, NULL);
8649 8650 8651 8652 8653 8654 8655
  }
  return Heap::undefined_value();
}


// Return the property type calculated from the property details.
// args[0]: smi with property details.
8656
static MaybeObject* Runtime_DebugPropertyTypeFromDetails(Arguments args) {
8657 8658 8659 8660 8661 8662 8663 8664 8665
  ASSERT(args.length() == 1);
  CONVERT_CHECKED(Smi, details, args[0]);
  PropertyType type = PropertyDetails(details).type();
  return Smi::FromInt(static_cast<int>(type));
}


// Return the property attribute calculated from the property details.
// args[0]: smi with property details.
8666
static MaybeObject* Runtime_DebugPropertyAttributesFromDetails(Arguments args) {
8667 8668 8669 8670 8671 8672 8673 8674 8675
  ASSERT(args.length() == 1);
  CONVERT_CHECKED(Smi, details, args[0]);
  PropertyAttributes attributes = PropertyDetails(details).attributes();
  return Smi::FromInt(static_cast<int>(attributes));
}


// Return the property insertion index calculated from the property details.
// args[0]: smi with property details.
8676
static MaybeObject* Runtime_DebugPropertyIndexFromDetails(Arguments args) {
8677 8678 8679 8680 8681 8682 8683 8684 8685 8686
  ASSERT(args.length() == 1);
  CONVERT_CHECKED(Smi, details, args[0]);
  int index = PropertyDetails(details).index();
  return Smi::FromInt(index);
}


// Return property value from named interceptor.
// args[0]: object
// args[1]: property name
8687
static MaybeObject* Runtime_DebugNamedInterceptorPropertyValue(Arguments args) {
8688 8689 8690 8691 8692 8693 8694
  HandleScope scope;
  ASSERT(args.length() == 2);
  CONVERT_ARG_CHECKED(JSObject, obj, 0);
  RUNTIME_ASSERT(obj->HasNamedInterceptor());
  CONVERT_ARG_CHECKED(String, name, 1);

  PropertyAttributes attributes;
8695
  return obj->GetPropertyWithInterceptor(*obj, *name, &attributes);
8696 8697 8698 8699 8700 8701
}


// Return element value from indexed interceptor.
// args[0]: object
// args[1]: index
8702 8703
static MaybeObject* Runtime_DebugIndexedInterceptorElementValue(
    Arguments args) {
8704 8705 8706 8707 8708 8709
  HandleScope scope;
  ASSERT(args.length() == 2);
  CONVERT_ARG_CHECKED(JSObject, obj, 0);
  RUNTIME_ASSERT(obj->HasIndexedInterceptor());
  CONVERT_NUMBER_CHECKED(uint32_t, index, Uint32, args[1]);

8710
  return obj->GetElementWithInterceptor(*obj, index);
8711 8712 8713
}


8714
static MaybeObject* Runtime_CheckExecutionState(Arguments args) {
8715 8716
  ASSERT(args.length() >= 1);
  CONVERT_NUMBER_CHECKED(int, break_id, Int32, args[0]);
8717
  // Check that the break id is valid.
8718
  if (Debug::break_id() == 0 || break_id != Debug::break_id()) {
8719 8720 8721 8722 8723 8724 8725
    return Top::Throw(Heap::illegal_execution_state_symbol());
  }

  return Heap::true_value();
}


8726
static MaybeObject* Runtime_GetFrameCount(Arguments args) {
8727 8728 8729 8730
  HandleScope scope;
  ASSERT(args.length() == 1);

  // Check arguments.
8731 8732 8733 8734
  Object* result;
  { MaybeObject* maybe_result = Runtime_CheckExecutionState(args);
    if (!maybe_result->ToObject(&result)) return maybe_result;
  }
8735 8736 8737

  // Count all frames which are relevant to debugging stack trace.
  int n = 0;
8738
  StackFrame::Id id = Debug::break_frame_id();
8739 8740 8741 8742
  if (id == StackFrame::NO_ID) {
    // If there is no JavaScript stack frame count is 0.
    return Smi::FromInt(0);
  }
8743 8744 8745 8746 8747 8748 8749 8750 8751 8752 8753 8754
  for (JavaScriptFrameIterator it(id); !it.done(); it.Advance()) n++;
  return Smi::FromInt(n);
}


static const int kFrameDetailsFrameIdIndex = 0;
static const int kFrameDetailsReceiverIndex = 1;
static const int kFrameDetailsFunctionIndex = 2;
static const int kFrameDetailsArgumentCountIndex = 3;
static const int kFrameDetailsLocalCountIndex = 4;
static const int kFrameDetailsSourcePositionIndex = 5;
static const int kFrameDetailsConstructCallIndex = 6;
8755 8756 8757
static const int kFrameDetailsAtReturnIndex = 7;
static const int kFrameDetailsDebuggerFrameIndex = 8;
static const int kFrameDetailsFirstDynamicIndex = 9;
8758 8759 8760 8761 8762 8763 8764 8765 8766 8767 8768 8769 8770

// Return an array with frame details
// args[0]: number: break id
// args[1]: number: frame index
//
// The array returned contains the following information:
// 0: Frame id
// 1: Receiver
// 2: Function
// 3: Argument count
// 4: Local count
// 5: Source position
// 6: Constructor call
8771 8772
// 7: Is at return
// 8: Debugger frame
8773 8774
// Arguments name, value
// Locals name, value
8775
// Return value if any
8776
static MaybeObject* Runtime_GetFrameDetails(Arguments args) {
8777 8778 8779 8780
  HandleScope scope;
  ASSERT(args.length() == 2);

  // Check arguments.
8781 8782 8783 8784
  Object* check;
  { MaybeObject* maybe_check = Runtime_CheckExecutionState(args);
    if (!maybe_check->ToObject(&check)) return maybe_check;
  }
8785 8786 8787
  CONVERT_NUMBER_CHECKED(int, index, Int32, args[1]);

  // Find the relevant frame with the requested index.
8788
  StackFrame::Id id = Debug::break_frame_id();
8789 8790 8791 8792
  if (id == StackFrame::NO_ID) {
    // If there are no JavaScript stack frames return undefined.
    return Heap::undefined_value();
  }
8793 8794 8795 8796 8797 8798 8799 8800
  int count = 0;
  JavaScriptFrameIterator it(id);
  for (; !it.done(); it.Advance()) {
    if (count == index) break;
    count++;
  }
  if (it.done()) return Heap::undefined_value();

8801 8802 8803
  bool is_optimized_frame =
      it.frame()->code()->kind() == Code::OPTIMIZED_FUNCTION;

8804 8805 8806
  // Traverse the saved contexts chain to find the active context for the
  // selected frame.
  SaveContext* save = Top::save_context();
8807
  while (save != NULL && !save->below(it.frame())) {
8808 8809
    save = save->prev();
  }
8810
  ASSERT(save != NULL);
8811 8812 8813 8814 8815

  // Get the frame id.
  Handle<Object> frame_id(WrapFrameId(it.frame()->id()));

  // Find source position.
8816
  int position = it.frame()->code()->SourcePosition(it.frame()->pc());
8817 8818 8819 8820

  // Check for constructor frame.
  bool constructor = it.frame()->IsConstructor();

8821 8822
  // Get scope info and read from it for local variable information.
  Handle<JSFunction> function(JSFunction::cast(it.frame()->function()));
8823
  Handle<SerializedScopeInfo> scope_info(function->shared()->scope_info());
8824
  ScopeInfo<> info(*scope_info);
8825 8826 8827 8828 8829 8830 8831 8832 8833 8834

  // Get the context.
  Handle<Context> context(Context::cast(it.frame()->context()));

  // Get the locals names and values into a temporary array.
  //
  // TODO(1240907): Hide compiler-introduced stack variables
  // (e.g. .result)?  For users of the debugger, they will probably be
  // confusing.
  Handle<FixedArray> locals = Factory::NewFixedArray(info.NumberOfLocals() * 2);
8835 8836

  // Fill in the names of the locals.
8837 8838
  for (int i = 0; i < info.NumberOfLocals(); i++) {
    locals->set(i * 2, *info.LocalName(i));
8839
  }
8840

8841 8842 8843 8844 8845 8846 8847 8848 8849 8850 8851
  // Fill in the values of the locals.
  for (int i = 0; i < info.NumberOfLocals(); i++) {
    if (is_optimized_frame) {
      // If we are inspecting an optimized frame use undefined as the
      // value for all locals.
      //
      // TODO(3141533): We should be able to get the correct values
      // for locals in optimized frames.
      locals->set(i * 2 + 1, Heap::undefined_value());
    } else if (i < info.number_of_stack_slots()) {
      // Get the value from the stack.
8852 8853 8854 8855
      locals->set(i * 2 + 1, it.frame()->GetExpression(i));
    } else {
      // Traverse the context chain to the function context as all local
      // variables stored in the context will be on the function context.
8856
      Handle<String> name = info.LocalName(i);
8857
      while (!context->is_function_context()) {
8858 8859 8860 8861
        context = Handle<Context>(context->previous());
      }
      ASSERT(context->is_function_context());
      locals->set(i * 2 + 1,
8862
                  context->get(scope_info->ContextSlotIndex(*name, NULL)));
8863 8864 8865
    }
  }

8866 8867 8868 8869 8870 8871
  // Check whether this frame is positioned at return. If not top
  // frame or if the frame is optimized it cannot be at a return.
  bool at_return = false;
  if (!is_optimized_frame && index == 0) {
    at_return = Debug::IsBreakAtReturn(it.frame());
  }
8872 8873 8874 8875 8876 8877 8878 8879 8880 8881 8882 8883 8884 8885 8886 8887 8888 8889 8890 8891 8892 8893 8894 8895 8896 8897 8898 8899 8900 8901 8902

  // If positioned just before return find the value to be returned and add it
  // to the frame information.
  Handle<Object> return_value = Factory::undefined_value();
  if (at_return) {
    StackFrameIterator it2;
    Address internal_frame_sp = NULL;
    while (!it2.done()) {
      if (it2.frame()->is_internal()) {
        internal_frame_sp = it2.frame()->sp();
      } else {
        if (it2.frame()->is_java_script()) {
          if (it2.frame()->id() == it.frame()->id()) {
            // The internal frame just before the JavaScript frame contains the
            // value to return on top. A debug break at return will create an
            // internal frame to store the return value (eax/rax/r0) before
            // entering the debug break exit frame.
            if (internal_frame_sp != NULL) {
              return_value =
                  Handle<Object>(Memory::Object_at(internal_frame_sp));
              break;
            }
          }
        }

        // Indicate that the previous frame was not an internal frame.
        internal_frame_sp = NULL;
      }
      it2.Advance();
    }
  }
8903 8904 8905 8906 8907 8908 8909 8910 8911 8912 8913 8914 8915 8916 8917 8918

  // Now advance to the arguments adapter frame (if any). It contains all
  // the provided parameters whereas the function frame always have the number
  // of arguments matching the functions parameters. The rest of the
  // information (except for what is collected above) is the same.
  it.AdvanceToArgumentsFrame();

  // Find the number of arguments to fill. At least fill the number of
  // parameters for the function and fill more if more parameters are provided.
  int argument_count = info.number_of_parameters();
  if (argument_count < it.frame()->GetProvidedParametersCount()) {
    argument_count = it.frame()->GetProvidedParametersCount();
  }

  // Calculate the size of the result.
  int details_size = kFrameDetailsFirstDynamicIndex +
8919 8920
                     2 * (argument_count + info.NumberOfLocals()) +
                     (at_return ? 1 : 0);
8921 8922 8923 8924 8925 8926 8927 8928 8929 8930 8931 8932 8933 8934 8935 8936
  Handle<FixedArray> details = Factory::NewFixedArray(details_size);

  // Add the frame id.
  details->set(kFrameDetailsFrameIdIndex, *frame_id);

  // Add the function (same as in function frame).
  details->set(kFrameDetailsFunctionIndex, it.frame()->function());

  // Add the arguments count.
  details->set(kFrameDetailsArgumentCountIndex, Smi::FromInt(argument_count));

  // Add the locals count
  details->set(kFrameDetailsLocalCountIndex,
               Smi::FromInt(info.NumberOfLocals()));

  // Add the source position.
8937
  if (position != RelocInfo::kNoPosition) {
8938 8939 8940 8941 8942 8943 8944 8945
    details->set(kFrameDetailsSourcePositionIndex, Smi::FromInt(position));
  } else {
    details->set(kFrameDetailsSourcePositionIndex, Heap::undefined_value());
  }

  // Add the constructor information.
  details->set(kFrameDetailsConstructCallIndex, Heap::ToBoolean(constructor));

8946 8947 8948
  // Add the at return information.
  details->set(kFrameDetailsAtReturnIndex, Heap::ToBoolean(at_return));

8949 8950 8951 8952 8953 8954 8955 8956 8957 8958 8959 8960 8961 8962 8963 8964
  // Add information on whether this frame is invoked in the debugger context.
  details->set(kFrameDetailsDebuggerFrameIndex,
               Heap::ToBoolean(*save->context() == *Debug::debug_context()));

  // Fill the dynamic part.
  int details_index = kFrameDetailsFirstDynamicIndex;

  // Add arguments name and value.
  for (int i = 0; i < argument_count; i++) {
    // Name of the argument.
    if (i < info.number_of_parameters()) {
      details->set(details_index++, *info.parameter_name(i));
    } else {
      details->set(details_index++, Heap::undefined_value());
    }

8965 8966 8967 8968 8969 8970 8971
    // Parameter value. If we are inspecting an optimized frame, use
    // undefined as the value.
    //
    // TODO(3141533): We should be able to get the actual parameter
    // value for optimized frames.
    if (!is_optimized_frame &&
        (i < it.frame()->GetProvidedParametersCount())) {
8972 8973 8974 8975 8976 8977 8978 8979 8980 8981 8982
      details->set(details_index++, it.frame()->GetParameter(i));
    } else {
      details->set(details_index++, Heap::undefined_value());
    }
  }

  // Add locals name and value from the temporary copy from the function frame.
  for (int i = 0; i < info.NumberOfLocals() * 2; i++) {
    details->set(details_index++, locals->get(i));
  }

8983 8984 8985 8986 8987
  // Add the value being returned.
  if (at_return) {
    details->set(details_index++, *return_value);
  }

8988 8989 8990 8991 8992 8993 8994 8995 8996 8997 8998 8999 9000 9001 9002 9003 9004 9005 9006 9007 9008 9009
  // Add the receiver (same as in function frame).
  // THIS MUST BE DONE LAST SINCE WE MIGHT ADVANCE
  // THE FRAME ITERATOR TO WRAP THE RECEIVER.
  Handle<Object> receiver(it.frame()->receiver());
  if (!receiver->IsJSObject()) {
    // If the receiver is NOT a JSObject we have hit an optimization
    // where a value object is not converted into a wrapped JS objects.
    // To hide this optimization from the debugger, we wrap the receiver
    // by creating correct wrapper object based on the calling frame's
    // global context.
    it.Advance();
    Handle<Context> calling_frames_global_context(
        Context::cast(Context::cast(it.frame()->context())->global_context()));
    receiver = Factory::ToObject(receiver, calling_frames_global_context);
  }
  details->set(kFrameDetailsReceiverIndex, *receiver);

  ASSERT_EQ(details_size, details_index);
  return *Factory::NewJSArrayWithElements(details);
}


9010
// Copy all the context locals into an object used to materialize a scope.
9011 9012 9013 9014 9015
static void CopyContextLocalsToScopeObject(
    Handle<SerializedScopeInfo> serialized_scope_info,
    ScopeInfo<>& scope_info,
    Handle<Context> context,
    Handle<JSObject> scope_object) {
9016 9017 9018 9019
  // Fill all context locals to the context extension.
  for (int i = Context::MIN_CONTEXT_SLOTS;
       i < scope_info.number_of_context_slots();
       i++) {
9020 9021
    int context_index = serialized_scope_info->ContextSlotIndex(
        *scope_info.context_slot_name(i), NULL);
9022 9023 9024 9025 9026 9027 9028 9029 9030 9031 9032 9033 9034 9035 9036

    // Don't include the arguments shadow (.arguments) context variable.
    if (*scope_info.context_slot_name(i) != Heap::arguments_shadow_symbol()) {
      SetProperty(scope_object,
                  scope_info.context_slot_name(i),
                  Handle<Object>(context->get(context_index)), NONE);
    }
  }
}


// Create a plain JSObject which materializes the local scope for the specified
// frame.
static Handle<JSObject> MaterializeLocalScope(JavaScriptFrame* frame) {
  Handle<JSFunction> function(JSFunction::cast(frame->function()));
9037
  Handle<SharedFunctionInfo> shared(function->shared());
9038 9039
  Handle<SerializedScopeInfo> serialized_scope_info(shared->scope_info());
  ScopeInfo<> scope_info(*serialized_scope_info);
9040 9041 9042 9043 9044 9045 9046 9047 9048 9049 9050 9051 9052 9053 9054 9055 9056 9057 9058 9059 9060 9061

  // Allocate and initialize a JSObject with all the arguments, stack locals
  // heap locals and extension properties of the debugged function.
  Handle<JSObject> local_scope = Factory::NewJSObject(Top::object_function());

  // First fill all parameters.
  for (int i = 0; i < scope_info.number_of_parameters(); ++i) {
    SetProperty(local_scope,
                scope_info.parameter_name(i),
                Handle<Object>(frame->GetParameter(i)), NONE);
  }

  // Second fill all stack locals.
  for (int i = 0; i < scope_info.number_of_stack_slots(); i++) {
    SetProperty(local_scope,
                scope_info.stack_slot_name(i),
                Handle<Object>(frame->GetExpression(i)), NONE);
  }

  // Third fill all context locals.
  Handle<Context> frame_context(Context::cast(frame->context()));
  Handle<Context> function_context(frame_context->fcontext());
9062
  CopyContextLocalsToScopeObject(serialized_scope_info, scope_info,
9063 9064 9065 9066 9067 9068 9069 9070
                                 function_context, local_scope);

  // Finally copy any properties from the function context extension. This will
  // be variables introduced by eval.
  if (function_context->closure() == *function) {
    if (function_context->has_extension() &&
        !function_context->IsGlobalContext()) {
      Handle<JSObject> ext(JSObject::cast(function_context->extension()));
9071
      Handle<FixedArray> keys = GetKeysInFixedArrayFor(ext, INCLUDE_PROTOS);
9072 9073 9074 9075 9076 9077 9078 9079 9080 9081 9082 9083 9084 9085 9086 9087 9088
      for (int i = 0; i < keys->length(); i++) {
        // Names of variables introduced by eval are strings.
        ASSERT(keys->get(i)->IsString());
        Handle<String> key(String::cast(keys->get(i)));
        SetProperty(local_scope, key, GetProperty(ext, key), NONE);
      }
    }
  }
  return local_scope;
}


// Create a plain JSObject which materializes the closure content for the
// context.
static Handle<JSObject> MaterializeClosure(Handle<Context> context) {
  ASSERT(context->is_function_context());

9089
  Handle<SharedFunctionInfo> shared(context->closure()->shared());
9090 9091
  Handle<SerializedScopeInfo> serialized_scope_info(shared->scope_info());
  ScopeInfo<> scope_info(*serialized_scope_info);
9092 9093 9094 9095 9096 9097 9098

  // Allocate and initialize a JSObject with all the content of theis function
  // closure.
  Handle<JSObject> closure_scope = Factory::NewJSObject(Top::object_function());

  // Check whether the arguments shadow object exists.
  int arguments_shadow_index =
9099 9100
      shared->scope_info()->ContextSlotIndex(Heap::arguments_shadow_symbol(),
                                             NULL);
9101 9102 9103 9104 9105 9106
  if (arguments_shadow_index >= 0) {
    // In this case all the arguments are available in the arguments shadow
    // object.
    Handle<JSObject> arguments_shadow(
        JSObject::cast(context->get(arguments_shadow_index)));
    for (int i = 0; i < scope_info.number_of_parameters(); ++i) {
9107 9108
      // We don't expect exception-throwing getters on the arguments shadow.
      Object* element = arguments_shadow->GetElement(i)->ToObjectUnchecked();
9109 9110
      SetProperty(closure_scope,
                  scope_info.parameter_name(i),
9111 9112
                  Handle<Object>(element),
                  NONE);
9113 9114 9115 9116
    }
  }

  // Fill all context locals to the context extension.
9117 9118
  CopyContextLocalsToScopeObject(serialized_scope_info, scope_info,
                                 context, closure_scope);
9119 9120 9121 9122 9123

  // Finally copy any properties from the function context extension. This will
  // be variables introduced by eval.
  if (context->has_extension()) {
    Handle<JSObject> ext(JSObject::cast(context->extension()));
9124
    Handle<FixedArray> keys = GetKeysInFixedArrayFor(ext, INCLUDE_PROTOS);
9125 9126 9127 9128 9129 9130 9131 9132 9133 9134 9135 9136 9137 9138 9139 9140 9141 9142 9143 9144 9145
    for (int i = 0; i < keys->length(); i++) {
      // Names of variables introduced by eval are strings.
      ASSERT(keys->get(i)->IsString());
      Handle<String> key(String::cast(keys->get(i)));
      SetProperty(closure_scope, key, GetProperty(ext, key), NONE);
    }
  }

  return closure_scope;
}


// Iterate over the actual scopes visible from a stack frame. All scopes are
// backed by an actual context except the local scope, which is inserted
// "artifically" in the context chain.
class ScopeIterator {
 public:
  enum ScopeType {
    ScopeTypeGlobal = 0,
    ScopeTypeLocal,
    ScopeTypeWith,
9146 9147 9148 9149 9150 9151
    ScopeTypeClosure,
    // Every catch block contains an implicit with block (its parameter is
    // a JSContextExtensionObject) that extends current scope with a variable
    // holding exception object. Such with blocks are treated as scopes of their
    // own type.
    ScopeTypeCatch
9152 9153 9154 9155 9156 9157 9158 9159 9160 9161 9162 9163 9164 9165 9166
  };

  explicit ScopeIterator(JavaScriptFrame* frame)
    : frame_(frame),
      function_(JSFunction::cast(frame->function())),
      context_(Context::cast(frame->context())),
      local_done_(false),
      at_local_(false) {

    // Check whether the first scope is actually a local scope.
    if (context_->IsGlobalContext()) {
      // If there is a stack slot for .result then this local scope has been
      // created for evaluating top level code and it is not a real local scope.
      // Checking for the existence of .result seems fragile, but the scope info
      // saved with the code object does not otherwise have that information.
9167 9168
      int index = function_->shared()->scope_info()->
          StackSlotIndex(Heap::result_symbol());
9169 9170 9171 9172 9173 9174 9175 9176 9177 9178 9179 9180 9181 9182 9183 9184 9185 9186 9187 9188 9189 9190 9191 9192 9193 9194 9195 9196 9197 9198 9199 9200 9201 9202 9203 9204 9205 9206 9207 9208 9209 9210 9211 9212 9213 9214 9215 9216 9217 9218 9219 9220 9221 9222 9223 9224 9225 9226
      at_local_ = index < 0;
    } else if (context_->is_function_context()) {
      at_local_ = true;
    }
  }

  // More scopes?
  bool Done() { return context_.is_null(); }

  // Move to the next scope.
  void Next() {
    // If at a local scope mark the local scope as passed.
    if (at_local_) {
      at_local_ = false;
      local_done_ = true;

      // If the current context is not associated with the local scope the
      // current context is the next real scope, so don't move to the next
      // context in this case.
      if (context_->closure() != *function_) {
        return;
      }
    }

    // The global scope is always the last in the chain.
    if (context_->IsGlobalContext()) {
      context_ = Handle<Context>();
      return;
    }

    // Move to the next context.
    if (context_->is_function_context()) {
      context_ = Handle<Context>(Context::cast(context_->closure()->context()));
    } else {
      context_ = Handle<Context>(context_->previous());
    }

    // If passing the local scope indicate that the current scope is now the
    // local scope.
    if (!local_done_ &&
        (context_->IsGlobalContext() || (context_->is_function_context()))) {
      at_local_ = true;
    }
  }

  // Return the type of the current scope.
  int Type() {
    if (at_local_) {
      return ScopeTypeLocal;
    }
    if (context_->IsGlobalContext()) {
      ASSERT(context_->global()->IsGlobalObject());
      return ScopeTypeGlobal;
    }
    if (context_->is_function_context()) {
      return ScopeTypeClosure;
    }
    ASSERT(context_->has_extension());
9227 9228 9229 9230 9231 9232 9233 9234
    // Current scope is either an explicit with statement or a with statement
    // implicitely generated for a catch block.
    // If the extension object here is a JSContextExtensionObject then
    // current with statement is one frome a catch block otherwise it's a
    // regular with statement.
    if (context_->extension()->IsJSContextExtensionObject()) {
      return ScopeTypeCatch;
    }
9235 9236 9237 9238 9239 9240 9241 9242 9243 9244 9245 9246 9247 9248
    return ScopeTypeWith;
  }

  // Return the JavaScript object with the content of the current scope.
  Handle<JSObject> ScopeObject() {
    switch (Type()) {
      case ScopeIterator::ScopeTypeGlobal:
        return Handle<JSObject>(CurrentContext()->global());
        break;
      case ScopeIterator::ScopeTypeLocal:
        // Materialize the content of the local scope into a JSObject.
        return MaterializeLocalScope(frame_);
        break;
      case ScopeIterator::ScopeTypeWith:
9249
      case ScopeIterator::ScopeTypeCatch:
9250 9251 9252 9253 9254 9255 9256 9257
        // Return the with object.
        return Handle<JSObject>(CurrentContext()->extension());
        break;
      case ScopeIterator::ScopeTypeClosure:
        // Materialize the content of the closure scope into a JSObject.
        return MaterializeClosure(CurrentContext());
        break;
    }
9258 9259
    UNREACHABLE();
    return Handle<JSObject>();
9260 9261 9262 9263 9264 9265 9266 9267 9268 9269 9270 9271 9272 9273 9274 9275 9276 9277 9278 9279 9280 9281
  }

  // Return the context for this scope. For the local context there might not
  // be an actual context.
  Handle<Context> CurrentContext() {
    if (at_local_ && context_->closure() != *function_) {
      return Handle<Context>();
    }
    return context_;
  }

#ifdef DEBUG
  // Debug print of the content of the current scope.
  void DebugPrint() {
    switch (Type()) {
      case ScopeIterator::ScopeTypeGlobal:
        PrintF("Global:\n");
        CurrentContext()->Print();
        break;

      case ScopeIterator::ScopeTypeLocal: {
        PrintF("Local:\n");
9282
        ScopeInfo<> scope_info(function_->shared()->scope_info());
9283 9284 9285 9286 9287 9288 9289 9290 9291 9292 9293 9294 9295 9296 9297 9298 9299 9300 9301 9302 9303 9304
        scope_info.Print();
        if (!CurrentContext().is_null()) {
          CurrentContext()->Print();
          if (CurrentContext()->has_extension()) {
            Handle<JSObject> extension =
                Handle<JSObject>(CurrentContext()->extension());
            if (extension->IsJSContextExtensionObject()) {
              extension->Print();
            }
          }
        }
        break;
      }

      case ScopeIterator::ScopeTypeWith: {
        PrintF("With:\n");
        Handle<JSObject> extension =
            Handle<JSObject>(CurrentContext()->extension());
        extension->Print();
        break;
      }

9305 9306 9307 9308 9309 9310 9311 9312
      case ScopeIterator::ScopeTypeCatch: {
        PrintF("Catch:\n");
        Handle<JSObject> extension =
            Handle<JSObject>(CurrentContext()->extension());
        extension->Print();
        break;
      }

9313 9314 9315 9316 9317 9318 9319 9320 9321 9322 9323 9324 9325 9326 9327 9328 9329 9330 9331 9332 9333 9334 9335 9336 9337 9338 9339 9340 9341 9342 9343
      case ScopeIterator::ScopeTypeClosure: {
        PrintF("Closure:\n");
        CurrentContext()->Print();
        if (CurrentContext()->has_extension()) {
          Handle<JSObject> extension =
              Handle<JSObject>(CurrentContext()->extension());
          if (extension->IsJSContextExtensionObject()) {
            extension->Print();
          }
        }
        break;
      }

      default:
        UNREACHABLE();
    }
    PrintF("\n");
  }
#endif

 private:
  JavaScriptFrame* frame_;
  Handle<JSFunction> function_;
  Handle<Context> context_;
  bool local_done_;
  bool at_local_;

  DISALLOW_IMPLICIT_CONSTRUCTORS(ScopeIterator);
};


9344
static MaybeObject* Runtime_GetScopeCount(Arguments args) {
9345 9346 9347 9348
  HandleScope scope;
  ASSERT(args.length() == 2);

  // Check arguments.
9349 9350 9351 9352
  Object* check;
  { MaybeObject* maybe_check = Runtime_CheckExecutionState(args);
    if (!maybe_check->ToObject(&check)) return maybe_check;
  }
9353 9354 9355 9356 9357 9358 9359 9360 9361 9362 9363 9364 9365 9366 9367 9368 9369 9370 9371 9372 9373 9374 9375 9376 9377 9378 9379 9380 9381
  CONVERT_CHECKED(Smi, wrapped_id, args[1]);

  // Get the frame where the debugging is performed.
  StackFrame::Id id = UnwrapFrameId(wrapped_id);
  JavaScriptFrameIterator it(id);
  JavaScriptFrame* frame = it.frame();

  // Count the visible scopes.
  int n = 0;
  for (ScopeIterator it(frame); !it.Done(); it.Next()) {
    n++;
  }

  return Smi::FromInt(n);
}


static const int kScopeDetailsTypeIndex = 0;
static const int kScopeDetailsObjectIndex = 1;
static const int kScopeDetailsSize = 2;

// Return an array with scope details
// args[0]: number: break id
// args[1]: number: frame index
// args[2]: number: scope index
//
// The array returned contains the following information:
// 0: Scope type
// 1: Scope object
9382
static MaybeObject* Runtime_GetScopeDetails(Arguments args) {
9383 9384 9385 9386
  HandleScope scope;
  ASSERT(args.length() == 3);

  // Check arguments.
9387 9388 9389 9390
  Object* check;
  { MaybeObject* maybe_check = Runtime_CheckExecutionState(args);
    if (!maybe_check->ToObject(&check)) return maybe_check;
  }
9391 9392 9393 9394 9395 9396 9397 9398 9399 9400 9401 9402 9403 9404 9405 9406 9407 9408 9409 9410 9411 9412 9413 9414
  CONVERT_CHECKED(Smi, wrapped_id, args[1]);
  CONVERT_NUMBER_CHECKED(int, index, Int32, args[2]);

  // Get the frame where the debugging is performed.
  StackFrame::Id id = UnwrapFrameId(wrapped_id);
  JavaScriptFrameIterator frame_it(id);
  JavaScriptFrame* frame = frame_it.frame();

  // Find the requested scope.
  int n = 0;
  ScopeIterator it(frame);
  for (; !it.Done() && n < index; it.Next()) {
    n++;
  }
  if (it.Done()) {
    return Heap::undefined_value();
  }

  // Calculate the size of the result.
  int details_size = kScopeDetailsSize;
  Handle<FixedArray> details = Factory::NewFixedArray(details_size);

  // Fill in scope details.
  details->set(kScopeDetailsTypeIndex, Smi::FromInt(it.Type()));
9415 9416
  Handle<JSObject> scope_object = it.ScopeObject();
  details->set(kScopeDetailsObjectIndex, *scope_object);
9417 9418 9419 9420 9421

  return *Factory::NewJSArrayWithElements(details);
}


9422
static MaybeObject* Runtime_DebugPrintScopes(Arguments args) {
9423 9424 9425 9426 9427 9428 9429 9430 9431 9432 9433 9434 9435 9436 9437
  HandleScope scope;
  ASSERT(args.length() == 0);

#ifdef DEBUG
  // Print the scopes for the top frame.
  StackFrameLocator locator;
  JavaScriptFrame* frame = locator.FindJavaScriptFrame(0);
  for (ScopeIterator it(frame); !it.Done(); it.Next()) {
    it.DebugPrint();
  }
#endif
  return Heap::undefined_value();
}


9438
static MaybeObject* Runtime_GetThreadCount(Arguments args) {
9439 9440 9441 9442
  HandleScope scope;
  ASSERT(args.length() == 1);

  // Check arguments.
9443 9444 9445 9446
  Object* result;
  { MaybeObject* maybe_result = Runtime_CheckExecutionState(args);
    if (!maybe_result->ToObject(&result)) return maybe_result;
  }
9447 9448 9449 9450 9451 9452 9453 9454 9455 9456 9457 9458 9459 9460 9461 9462 9463 9464 9465 9466 9467 9468 9469 9470 9471

  // Count all archived V8 threads.
  int n = 0;
  for (ThreadState* thread = ThreadState::FirstInUse();
       thread != NULL;
       thread = thread->Next()) {
    n++;
  }

  // Total number of threads is current thread and archived threads.
  return Smi::FromInt(n + 1);
}


static const int kThreadDetailsCurrentThreadIndex = 0;
static const int kThreadDetailsThreadIdIndex = 1;
static const int kThreadDetailsSize = 2;

// Return an array with thread details
// args[0]: number: break id
// args[1]: number: thread index
//
// The array returned contains the following information:
// 0: Is current thread?
// 1: Thread id
9472
static MaybeObject* Runtime_GetThreadDetails(Arguments args) {
9473 9474 9475 9476
  HandleScope scope;
  ASSERT(args.length() == 2);

  // Check arguments.
9477 9478 9479 9480
  Object* check;
  { MaybeObject* maybe_check = Runtime_CheckExecutionState(args);
    if (!maybe_check->ToObject(&check)) return maybe_check;
  }
9481 9482 9483 9484 9485 9486 9487 9488 9489 9490 9491 9492 9493 9494 9495 9496 9497 9498 9499 9500 9501 9502 9503 9504 9505 9506 9507 9508 9509 9510 9511 9512 9513
  CONVERT_NUMBER_CHECKED(int, index, Int32, args[1]);

  // Allocate array for result.
  Handle<FixedArray> details = Factory::NewFixedArray(kThreadDetailsSize);

  // Thread index 0 is current thread.
  if (index == 0) {
    // Fill the details.
    details->set(kThreadDetailsCurrentThreadIndex, Heap::true_value());
    details->set(kThreadDetailsThreadIdIndex,
                 Smi::FromInt(ThreadManager::CurrentId()));
  } else {
    // Find the thread with the requested index.
    int n = 1;
    ThreadState* thread = ThreadState::FirstInUse();
    while (index != n && thread != NULL) {
      thread = thread->Next();
      n++;
    }
    if (thread == NULL) {
      return Heap::undefined_value();
    }

    // Fill the details.
    details->set(kThreadDetailsCurrentThreadIndex, Heap::false_value());
    details->set(kThreadDetailsThreadIdIndex, Smi::FromInt(thread->id()));
  }

  // Convert to JS array and return.
  return *Factory::NewJSArrayWithElements(details);
}


9514 9515
// Sets the disable break state
// args[0]: disable break state
9516
static MaybeObject* Runtime_SetDisableBreak(Arguments args) {
9517 9518 9519 9520 9521 9522 9523 9524
  HandleScope scope;
  ASSERT(args.length() == 1);
  CONVERT_BOOLEAN_CHECKED(disable_break, args[0]);
  Debug::set_disable_break(disable_break);
  return  Heap::undefined_value();
}


9525
static MaybeObject* Runtime_GetBreakLocations(Arguments args) {
9526 9527 9528
  HandleScope scope;
  ASSERT(args.length() == 1);

9529 9530
  CONVERT_ARG_CHECKED(JSFunction, fun, 0);
  Handle<SharedFunctionInfo> shared(fun->shared());
9531 9532 9533 9534 9535 9536 9537 9538 9539 9540 9541 9542 9543
  // Find the number of break points
  Handle<Object> break_locations = Debug::GetSourceBreakLocations(shared);
  if (break_locations->IsUndefined()) return Heap::undefined_value();
  // Return array as JS array
  return *Factory::NewJSArrayWithElements(
      Handle<FixedArray>::cast(break_locations));
}


// Set a break point in a function
// args[0]: function
// args[1]: number: break source position (within the function source)
// args[2]: number: break point object
9544
static MaybeObject* Runtime_SetFunctionBreakPoint(Arguments args) {
9545 9546
  HandleScope scope;
  ASSERT(args.length() == 3);
9547 9548
  CONVERT_ARG_CHECKED(JSFunction, fun, 0);
  Handle<SharedFunctionInfo> shared(fun->shared());
9549 9550 9551 9552 9553
  CONVERT_NUMBER_CHECKED(int32_t, source_position, Int32, args[1]);
  RUNTIME_ASSERT(source_position >= 0);
  Handle<Object> break_point_object_arg = args.at<Object>(2);

  // Set break point.
9554
  Debug::SetBreakPoint(shared, break_point_object_arg, &source_position);
9555

9556
  return Smi::FromInt(source_position);
9557 9558 9559
}


9560 9561
Object* Runtime::FindSharedFunctionInfoInScript(Handle<Script> script,
                                                int position) {
9562 9563 9564
  // Iterate the heap looking for SharedFunctionInfo generated from the
  // script. The inner most SharedFunctionInfo containing the source position
  // for the requested break point is found.
9565
  // NOTE: This might require several heap iterations. If the SharedFunctionInfo
9566 9567 9568 9569 9570 9571
  // which is found is not compiled it is compiled and the heap is iterated
  // again as the compilation might create inner functions from the newly
  // compiled function and the actual requested break point might be in one of
  // these functions.
  bool done = false;
  // The current candidate for the source position:
9572
  int target_start_position = RelocInfo::kNoPosition;
9573 9574 9575
  Handle<SharedFunctionInfo> target;
  while (!done) {
    HeapIterator iterator;
9576 9577
    for (HeapObject* obj = iterator.next();
         obj != NULL; obj = iterator.next()) {
9578 9579 9580 9581 9582 9583
      if (obj->IsSharedFunctionInfo()) {
        Handle<SharedFunctionInfo> shared(SharedFunctionInfo::cast(obj));
        if (shared->script() == *script) {
          // If the SharedFunctionInfo found has the requested script data and
          // contains the source position it is a candidate.
          int start_position = shared->function_token_position();
9584
          if (start_position == RelocInfo::kNoPosition) {
9585 9586 9587 9588
            start_position = shared->start_position();
          }
          if (start_position <= position &&
              position <= shared->end_position()) {
9589
            // If there is no candidate or this function is within the current
9590 9591 9592 9593 9594
            // candidate this is the new candidate.
            if (target.is_null()) {
              target_start_position = start_position;
              target = shared;
            } else {
9595 9596 9597 9598 9599 9600 9601 9602 9603 9604 9605 9606 9607 9608
              if (target_start_position == start_position &&
                  shared->end_position() == target->end_position()) {
                  // If a top-level function contain only one function
                  // declartion the source for the top-level and the function is
                  // the same. In that case prefer the non top-level function.
                if (!shared->is_toplevel()) {
                  target_start_position = start_position;
                  target = shared;
                }
              } else if (target_start_position <= start_position &&
                         shared->end_position() <= target->end_position()) {
                // This containment check includes equality as a function inside
                // a top-level function can share either start or end position
                // with the top-level function.
9609 9610 9611 9612 9613 9614 9615 9616 9617 9618
                target_start_position = start_position;
                target = shared;
              }
            }
          }
        }
      }
    }

    if (target.is_null()) {
9619
      return Heap::undefined_value();
9620 9621 9622 9623 9624 9625 9626 9627 9628
    }

    // If the candidate found is compiled we are done. NOTE: when lazy
    // compilation of inner functions is introduced some additional checking
    // needs to be done here to compile inner functions.
    done = target->is_compiled();
    if (!done) {
      // If the candidate is not compiled compile it to reveal any inner
      // functions which might contain the requested source position.
9629
      CompileLazyShared(target, KEEP_EXCEPTION);
9630 9631 9632 9633 9634 9635 9636
    }
  }

  return *target;
}


9637 9638 9639
// Changes the state of a break point in a script and returns source position
// where break point was set. NOTE: Regarding performance see the NOTE for
// GetScriptFromScriptData.
9640 9641 9642
// args[0]: script to set break point in
// args[1]: number: break source position (within the script source)
// args[2]: number: break point object
9643
static MaybeObject* Runtime_SetScriptBreakPoint(Arguments args) {
9644 9645 9646 9647 9648 9649 9650 9651 9652 9653 9654
  HandleScope scope;
  ASSERT(args.length() == 3);
  CONVERT_ARG_CHECKED(JSValue, wrapper, 0);
  CONVERT_NUMBER_CHECKED(int32_t, source_position, Int32, args[1]);
  RUNTIME_ASSERT(source_position >= 0);
  Handle<Object> break_point_object_arg = args.at<Object>(2);

  // Get the script from the script wrapper.
  RUNTIME_ASSERT(wrapper->value()->IsScript());
  Handle<Script> script(Script::cast(wrapper->value()));

9655 9656
  Object* result = Runtime::FindSharedFunctionInfoInScript(
      script, source_position);
9657 9658 9659 9660 9661 9662 9663 9664 9665 9666
  if (!result->IsUndefined()) {
    Handle<SharedFunctionInfo> shared(SharedFunctionInfo::cast(result));
    // Find position within function. The script position might be before the
    // source position of the first function.
    int position;
    if (shared->start_position() > source_position) {
      position = 0;
    } else {
      position = source_position - shared->start_position();
    }
9667 9668 9669
    Debug::SetBreakPoint(shared, break_point_object_arg, &position);
    position += shared->start_position();
    return Smi::FromInt(position);
9670 9671 9672 9673 9674 9675 9676
  }
  return  Heap::undefined_value();
}


// Clear a break point
// args[0]: number: break point object
9677
static MaybeObject* Runtime_ClearBreakPoint(Arguments args) {
9678 9679 9680 9681 9682 9683 9684 9685 9686 9687 9688
  HandleScope scope;
  ASSERT(args.length() == 1);
  Handle<Object> break_point_object_arg = args.at<Object>(0);

  // Clear break point.
  Debug::ClearBreakPoint(break_point_object_arg);

  return Heap::undefined_value();
}


9689 9690 9691
// Change the state of break on exceptions.
// args[0]: Enum value indicating whether to affect caught/uncaught exceptions.
// args[1]: Boolean indicating on/off.
9692
static MaybeObject* Runtime_ChangeBreakOnException(Arguments args) {
9693 9694
  HandleScope scope;
  ASSERT(args.length() == 2);
9695 9696
  RUNTIME_ASSERT(args[0]->IsNumber());
  CONVERT_BOOLEAN_CHECKED(enable, args[1]);
9697

9698 9699
  // If the number doesn't match an enum value, the ChangeBreakOnException
  // function will default to affecting caught exceptions.
9700 9701
  ExceptionBreakType type =
      static_cast<ExceptionBreakType>(NumberToUint32(args[0]));
9702
  // Update break point state.
9703 9704 9705 9706 9707
  Debug::ChangeBreakOnException(type, enable);
  return Heap::undefined_value();
}


9708 9709
// Returns the state of break on exceptions
// args[0]: boolean indicating uncaught exceptions
9710
static MaybeObject* Runtime_IsBreakOnException(Arguments args) {
9711 9712
  HandleScope scope;
  ASSERT(args.length() == 1);
9713
  RUNTIME_ASSERT(args[0]->IsNumber());
9714 9715 9716 9717 9718 9719 9720 9721

  ExceptionBreakType type =
      static_cast<ExceptionBreakType>(NumberToUint32(args[0]));
  bool result = Debug::IsBreakOnException(type);
  return Smi::FromInt(result);
}


9722 9723 9724
// Prepare for stepping
// args[0]: break id for checking execution state
// args[1]: step action from the enumeration StepAction
9725 9726
// args[2]: number of times to perform the step, for step out it is the number
//          of frames to step down.
9727
static MaybeObject* Runtime_PrepareStep(Arguments args) {
9728 9729 9730
  HandleScope scope;
  ASSERT(args.length() == 3);
  // Check arguments.
9731 9732 9733 9734
  Object* check;
  { MaybeObject* maybe_check = Runtime_CheckExecutionState(args);
    if (!maybe_check->ToObject(&check)) return maybe_check;
  }
9735 9736 9737 9738 9739 9740 9741 9742 9743 9744 9745 9746 9747 9748 9749 9750 9751 9752 9753 9754
  if (!args[1]->IsNumber() || !args[2]->IsNumber()) {
    return Top::Throw(Heap::illegal_argument_symbol());
  }

  // Get the step action and check validity.
  StepAction step_action = static_cast<StepAction>(NumberToInt32(args[1]));
  if (step_action != StepIn &&
      step_action != StepNext &&
      step_action != StepOut &&
      step_action != StepInMin &&
      step_action != StepMin) {
    return Top::Throw(Heap::illegal_argument_symbol());
  }

  // Get the number of steps.
  int step_count = NumberToInt32(args[2]);
  if (step_count < 1) {
    return Top::Throw(Heap::illegal_argument_symbol());
  }

9755 9756 9757
  // Clear all current stepping setup.
  Debug::ClearStepping();

9758 9759 9760 9761 9762 9763 9764
  // Prepare step.
  Debug::PrepareStep(static_cast<StepAction>(step_action), step_count);
  return Heap::undefined_value();
}


// Clear all stepping set by PrepareStep.
9765
static MaybeObject* Runtime_ClearStepping(Arguments args) {
9766
  HandleScope scope;
9767
  ASSERT(args.length() == 0);
9768 9769 9770 9771 9772 9773 9774 9775 9776 9777 9778 9779 9780 9781 9782 9783 9784
  Debug::ClearStepping();
  return Heap::undefined_value();
}


// Creates a copy of the with context chain. The copy of the context chain is
// is linked to the function context supplied.
static Handle<Context> CopyWithContextChain(Handle<Context> context_chain,
                                            Handle<Context> function_context) {
  // At the bottom of the chain. Return the function context to link to.
  if (context_chain->is_function_context()) {
    return function_context;
  }

  // Recursively copy the with contexts.
  Handle<Context> previous(context_chain->previous());
  Handle<JSObject> extension(JSObject::cast(context_chain->extension()));
9785 9786 9787 9788
  Handle<Context> context = CopyWithContextChain(function_context, previous);
  return Factory::NewWithContext(context,
                                 extension,
                                 context_chain->IsCatchContext());
9789 9790 9791 9792 9793 9794 9795
}


// Helper function to find or create the arguments object for
// Runtime_DebugEvaluate.
static Handle<Object> GetArgumentsObject(JavaScriptFrame* frame,
                                         Handle<JSFunction> function,
9796
                                         Handle<SerializedScopeInfo> scope_info,
9797 9798 9799 9800 9801 9802 9803
                                         const ScopeInfo<>* sinfo,
                                         Handle<Context> function_context) {
  // Try to find the value of 'arguments' to pass as parameter. If it is not
  // found (that is the debugged function does not reference 'arguments' and
  // does not support eval) then create an 'arguments' object.
  int index;
  if (sinfo->number_of_stack_slots() > 0) {
9804
    index = scope_info->StackSlotIndex(Heap::arguments_symbol());
9805 9806 9807 9808 9809 9810
    if (index != -1) {
      return Handle<Object>(frame->GetExpression(index));
    }
  }

  if (sinfo->number_of_context_slots() > Context::MIN_CONTEXT_SLOTS) {
9811
    index = scope_info->ContextSlotIndex(Heap::arguments_symbol(), NULL);
9812 9813 9814 9815 9816 9817
    if (index != -1) {
      return Handle<Object>(function_context->get(index));
    }
  }

  const int length = frame->GetProvidedParametersCount();
9818 9819
  Handle<JSObject> arguments = Factory::NewArgumentsObject(function, length);
  Handle<FixedArray> array = Factory::NewFixedArray(length);
9820 9821 9822

  AssertNoAllocation no_gc;
  WriteBarrierMode mode = array->GetWriteBarrierMode(no_gc);
9823
  for (int i = 0; i < length; i++) {
9824
    array->set(i, frame->GetParameter(i), mode);
9825
  }
9826
  arguments->set_elements(*array);
9827 9828 9829 9830 9831
  return arguments;
}


// Evaluate a piece of JavaScript in the context of a stack frame for
9832
// debugging. This is accomplished by creating a new context which in its
9833 9834 9835 9836 9837 9838 9839 9840 9841
// extension part has all the parameters and locals of the function on the
// stack frame. A function which calls eval with the code to evaluate is then
// compiled in this context and called in this context. As this context
// replaces the context of the function on the stack frame a new (empty)
// function is created as well to be used as the closure for the context.
// This function and the context acts as replacements for the function on the
// stack frame presenting the same view of the values of parameters and
// local variables as if the piece of JavaScript was evaluated at the point
// where the function on the stack frame is currently stopped.
9842
static MaybeObject* Runtime_DebugEvaluate(Arguments args) {
9843 9844 9845 9846
  HandleScope scope;

  // Check the execution state and decode arguments frame and source to be
  // evaluated.
9847
  ASSERT(args.length() == 5);
9848 9849 9850 9851 9852 9853
  Object* check_result;
  { MaybeObject* maybe_check_result = Runtime_CheckExecutionState(args);
    if (!maybe_check_result->ToObject(&check_result)) {
      return maybe_check_result;
    }
  }
9854 9855
  CONVERT_CHECKED(Smi, wrapped_id, args[1]);
  CONVERT_ARG_CHECKED(String, source, 2);
9856
  CONVERT_BOOLEAN_CHECKED(disable_break, args[3]);
9857
  Handle<Object> additional_context(args[4]);
9858 9859 9860

  // Handle the processing of break.
  DisableBreak disable_break_save(disable_break);
9861 9862 9863 9864 9865 9866

  // Get the frame where the debugging is performed.
  StackFrame::Id id = UnwrapFrameId(wrapped_id);
  JavaScriptFrameIterator it(id);
  JavaScriptFrame* frame = it.frame();
  Handle<JSFunction> function(JSFunction::cast(frame->function()));
9867
  Handle<SerializedScopeInfo> scope_info(function->shared()->scope_info());
9868
  ScopeInfo<> sinfo(*scope_info);
9869 9870 9871 9872

  // Traverse the saved contexts chain to find the active context for the
  // selected frame.
  SaveContext* save = Top::save_context();
9873
  while (save != NULL && !save->below(frame)) {
9874 9875 9876 9877 9878 9879 9880 9881 9882 9883 9884 9885 9886 9887 9888 9889
    save = save->prev();
  }
  ASSERT(save != NULL);
  SaveContext savex;
  Top::set_context(*(save->context()));

  // Create the (empty) function replacing the function on the stack frame for
  // the purpose of evaluating in the context created below. It is important
  // that this function does not describe any parameters and local variables
  // in the context. If it does then this will cause problems with the lookup
  // in Context::Lookup, where context slots for parameters and local variables
  // are looked at before the extension object.
  Handle<JSFunction> go_between =
      Factory::NewFunction(Factory::empty_string(), Factory::undefined_value());
  go_between->set_context(function->context());
#ifdef DEBUG
9890
  ScopeInfo<> go_between_sinfo(go_between->shared()->scope_info());
9891 9892 9893 9894
  ASSERT(go_between_sinfo.number_of_parameters() == 0);
  ASSERT(go_between_sinfo.number_of_context_slots() == 0);
#endif

9895 9896
  // Materialize the content of the local scope into a JSObject.
  Handle<JSObject> local_scope = MaterializeLocalScope(frame);
9897 9898 9899 9900 9901

  // Allocate a new context for the debug evaluation and set the extension
  // object build.
  Handle<Context> context =
      Factory::NewFunctionContext(Context::MIN_CONTEXT_SLOTS, go_between);
9902
  context->set_extension(*local_scope);
9903
  // Copy any with contexts present and chain them in front of this context.
9904 9905
  Handle<Context> frame_context(Context::cast(frame->context()));
  Handle<Context> function_context(frame_context->fcontext());
9906 9907
  context = CopyWithContextChain(frame_context, context);

9908 9909 9910 9911 9912
  if (additional_context->IsJSObject()) {
    context = Factory::NewWithContext(context,
        Handle<JSObject>::cast(additional_context), false);
  }

9913 9914 9915
  // Wrap the evaluation statement in a new function compiled in the newly
  // created context. The function has one parameter which has to be called
  // 'arguments'. This it to have access to what would have been 'arguments' in
9916
  // the function being debugged.
9917 9918
  // function(arguments,__source__) {return eval(__source__);}
  static const char* source_str =
9919
      "(function(arguments,__source__){return eval(__source__);})";
9920
  static const int source_str_length = StrLength(source_str);
9921 9922 9923
  Handle<String> function_source =
      Factory::NewStringFromAscii(Vector<const char>(source_str,
                                                     source_str_length));
9924
  Handle<SharedFunctionInfo> shared =
9925 9926
      Compiler::CompileEval(function_source,
                            context,
9927
                            context->IsGlobalContext());
9928
  if (shared.is_null()) return Failure::Exception();
9929
  Handle<JSFunction> compiled_function =
9930
      Factory::NewFunctionFromSharedFunctionInfo(shared, context);
9931 9932 9933 9934 9935 9936 9937

  // Invoke the result of the compilation to get the evaluation function.
  bool has_pending_exception;
  Handle<Object> receiver(frame->receiver());
  Handle<Object> evaluation_function =
      Execution::Call(compiled_function, receiver, 0, NULL,
                      &has_pending_exception);
9938
  if (has_pending_exception) return Failure::Exception();
9939

9940 9941
  Handle<Object> arguments = GetArgumentsObject(frame, function, scope_info,
                                                &sinfo, function_context);
9942 9943 9944 9945 9946 9947 9948 9949

  // Invoke the evaluation function and return the result.
  const int argc = 2;
  Object** argv[argc] = { arguments.location(),
                          Handle<Object>::cast(source).location() };
  Handle<Object> result =
      Execution::Call(Handle<JSFunction>::cast(evaluation_function), receiver,
                      argc, argv, &has_pending_exception);
9950
  if (has_pending_exception) return Failure::Exception();
9951 9952 9953 9954 9955 9956 9957

  // Skip the global proxy as it has no properties and always delegates to the
  // real global object.
  if (result->IsJSGlobalProxy()) {
    result = Handle<JSObject>(JSObject::cast(result->GetPrototype()));
  }

9958 9959 9960 9961
  return *result;
}


9962
static MaybeObject* Runtime_DebugEvaluateGlobal(Arguments args) {
9963 9964 9965 9966
  HandleScope scope;

  // Check the execution state and decode arguments frame and source to be
  // evaluated.
9967
  ASSERT(args.length() == 4);
9968 9969 9970 9971 9972 9973
  Object* check_result;
  { MaybeObject* maybe_check_result = Runtime_CheckExecutionState(args);
    if (!maybe_check_result->ToObject(&check_result)) {
      return maybe_check_result;
    }
  }
9974
  CONVERT_ARG_CHECKED(String, source, 1);
9975
  CONVERT_BOOLEAN_CHECKED(disable_break, args[2]);
9976
  Handle<Object> additional_context(args[3]);
9977 9978 9979

  // Handle the processing of break.
  DisableBreak disable_break_save(disable_break);
9980 9981 9982 9983 9984 9985 9986 9987 9988 9989 9990 9991 9992 9993 9994

  // Enter the top context from before the debugger was invoked.
  SaveContext save;
  SaveContext* top = &save;
  while (top != NULL && *top->context() == *Debug::debug_context()) {
    top = top->prev();
  }
  if (top != NULL) {
    Top::set_context(*top->context());
  }

  // Get the global context now set to the top context from before the
  // debugger was invoked.
  Handle<Context> context = Top::global_context();

9995 9996 9997 9998 9999 10000 10001 10002 10003 10004 10005 10006 10007
  bool is_global = true;

  if (additional_context->IsJSObject()) {
    // Create a function context first, than put 'with' context on top of it.
    Handle<JSFunction> go_between = Factory::NewFunction(
        Factory::empty_string(), Factory::undefined_value());
    go_between->set_context(*context);
    context =
        Factory::NewFunctionContext(Context::MIN_CONTEXT_SLOTS, go_between);
    context->set_extension(JSObject::cast(*additional_context));
    is_global = false;
  }

10008
  // Compile the source to be evaluated.
10009 10010 10011
  Handle<SharedFunctionInfo> shared =
      Compiler::CompileEval(source,
                            context,
10012
                            is_global);
10013
  if (shared.is_null()) return Failure::Exception();
10014
  Handle<JSFunction> compiled_function =
10015 10016
      Handle<JSFunction>(Factory::NewFunctionFromSharedFunctionInfo(shared,
                                                                    context));
10017 10018 10019 10020 10021 10022 10023

  // Invoke the result of the compilation to get the evaluation function.
  bool has_pending_exception;
  Handle<Object> receiver = Top::global();
  Handle<Object> result =
    Execution::Call(compiled_function, receiver, 0, NULL,
                    &has_pending_exception);
10024
  if (has_pending_exception) return Failure::Exception();
10025 10026 10027 10028
  return *result;
}


10029
static MaybeObject* Runtime_DebugGetLoadedScripts(Arguments args) {
10030
  HandleScope scope;
10031
  ASSERT(args.length() == 0);
10032 10033

  // Fill the script objects.
10034
  Handle<FixedArray> instances = Debug::GetLoadedScripts();
10035 10036

  // Convert the script objects to proper JS objects.
10037
  for (int i = 0; i < instances->length(); i++) {
10038 10039 10040
    Handle<Script> script = Handle<Script>(Script::cast(instances->get(i)));
    // Get the script wrapper in a local handle before calling GetScriptWrapper,
    // because using
kasperl@chromium.org's avatar
kasperl@chromium.org committed
10041
    //   instances->set(i, *GetScriptWrapper(script))
10042
    // is unsafe as GetScriptWrapper might call GC and the C++ compiler might
kasperl@chromium.org's avatar
kasperl@chromium.org committed
10043
    // already have deferenced the instances handle.
10044 10045
    Handle<JSValue> wrapper = GetScriptWrapper(script);
    instances->set(i, *wrapper);
10046 10047 10048 10049 10050 10051 10052 10053 10054 10055 10056 10057 10058 10059 10060 10061 10062 10063 10064 10065 10066
  }

  // Return result as a JS array.
  Handle<JSObject> result = Factory::NewJSObject(Top::array_function());
  Handle<JSArray>::cast(result)->SetContent(*instances);
  return *result;
}


// Helper function used by Runtime_DebugReferencedBy below.
static int DebugReferencedBy(JSObject* target,
                             Object* instance_filter, int max_references,
                             FixedArray* instances, int instances_size,
                             JSFunction* arguments_function) {
  NoHandleAllocation ha;
  AssertNoAllocation no_alloc;

  // Iterate the heap.
  int count = 0;
  JSObject* last = NULL;
  HeapIterator iterator;
10067 10068
  HeapObject* heap_obj = NULL;
  while (((heap_obj = iterator.next()) != NULL) &&
10069 10070 10071 10072 10073 10074
         (max_references == 0 || count < max_references)) {
    // Only look at all JSObjects.
    if (heap_obj->IsJSObject()) {
      // Skip context extension objects and argument arrays as these are
      // checked in the context of functions using them.
      JSObject* obj = JSObject::cast(heap_obj);
10075
      if (obj->IsJSContextExtensionObject() ||
10076 10077 10078 10079 10080 10081 10082 10083 10084 10085 10086 10087 10088 10089 10090 10091 10092 10093 10094 10095 10096 10097 10098 10099 10100 10101 10102 10103 10104 10105 10106 10107 10108 10109 10110 10111 10112 10113 10114 10115 10116 10117 10118 10119 10120 10121 10122 10123 10124 10125 10126 10127 10128
          obj->map()->constructor() == arguments_function) {
        continue;
      }

      // Check if the JS object has a reference to the object looked for.
      if (obj->ReferencesObject(target)) {
        // Check instance filter if supplied. This is normally used to avoid
        // references from mirror objects (see Runtime_IsInPrototypeChain).
        if (!instance_filter->IsUndefined()) {
          Object* V = obj;
          while (true) {
            Object* prototype = V->GetPrototype();
            if (prototype->IsNull()) {
              break;
            }
            if (instance_filter == prototype) {
              obj = NULL;  // Don't add this object.
              break;
            }
            V = prototype;
          }
        }

        if (obj != NULL) {
          // Valid reference found add to instance array if supplied an update
          // count.
          if (instances != NULL && count < instances_size) {
            instances->set(count, obj);
          }
          last = obj;
          count++;
        }
      }
    }
  }

  // Check for circular reference only. This can happen when the object is only
  // referenced from mirrors and has a circular reference in which case the
  // object is not really alive and would have been garbage collected if not
  // referenced from the mirror.
  if (count == 1 && last == target) {
    count = 0;
  }

  // Return the number of referencing objects found.
  return count;
}


// Scan the heap for objects with direct references to an object
// args[0]: the object to find references to
// args[1]: constructor function for instances to exclude (Mirror)
// args[2]: the the maximum number of objects to return
10129
static MaybeObject* Runtime_DebugReferencedBy(Arguments args) {
10130 10131 10132
  ASSERT(args.length() == 3);

  // First perform a full GC in order to avoid references from dead objects.
10133
  Heap::CollectAllGarbage(false);
10134 10135 10136 10137 10138 10139 10140 10141 10142 10143 10144 10145 10146 10147 10148 10149 10150 10151

  // Check parameters.
  CONVERT_CHECKED(JSObject, target, args[0]);
  Object* instance_filter = args[1];
  RUNTIME_ASSERT(instance_filter->IsUndefined() ||
                 instance_filter->IsJSObject());
  CONVERT_NUMBER_CHECKED(int32_t, max_references, Int32, args[2]);
  RUNTIME_ASSERT(max_references >= 0);

  // Get the constructor function for context extension and arguments array.
  JSObject* arguments_boilerplate =
      Top::context()->global_context()->arguments_boilerplate();
  JSFunction* arguments_function =
      JSFunction::cast(arguments_boilerplate->map()->constructor());

  // Get the number of referencing objects.
  int count;
  count = DebugReferencedBy(target, instance_filter, max_references,
10152
                            NULL, 0, arguments_function);
10153 10154

  // Allocate an array to hold the result.
10155 10156 10157 10158
  Object* object;
  { MaybeObject* maybe_object = Heap::AllocateFixedArray(count);
    if (!maybe_object->ToObject(&object)) return maybe_object;
  }
10159 10160 10161 10162
  FixedArray* instances = FixedArray::cast(object);

  // Fill the referencing objects.
  count = DebugReferencedBy(target, instance_filter, max_references,
10163
                            instances, count, arguments_function);
10164 10165

  // Return result as JS array.
10166 10167 10168 10169 10170 10171
  Object* result;
  { MaybeObject* maybe_result = Heap::AllocateJSObject(
        Top::context()->global_context()->array_function());
    if (!maybe_result->ToObject(&result)) return maybe_result;
  }
  JSArray::cast(result)->SetContent(instances);
10172 10173 10174 10175 10176 10177 10178 10179 10180 10181 10182 10183
  return result;
}


// Helper function used by Runtime_DebugConstructedBy below.
static int DebugConstructedBy(JSFunction* constructor, int max_references,
                              FixedArray* instances, int instances_size) {
  AssertNoAllocation no_alloc;

  // Iterate the heap.
  int count = 0;
  HeapIterator iterator;
10184 10185
  HeapObject* heap_obj = NULL;
  while (((heap_obj = iterator.next()) != NULL) &&
10186 10187 10188 10189 10190 10191 10192 10193 10194 10195 10196 10197 10198 10199 10200 10201 10202 10203 10204 10205 10206 10207 10208
         (max_references == 0 || count < max_references)) {
    // Only look at all JSObjects.
    if (heap_obj->IsJSObject()) {
      JSObject* obj = JSObject::cast(heap_obj);
      if (obj->map()->constructor() == constructor) {
        // Valid reference found add to instance array if supplied an update
        // count.
        if (instances != NULL && count < instances_size) {
          instances->set(count, obj);
        }
        count++;
      }
    }
  }

  // Return the number of referencing objects found.
  return count;
}


// Scan the heap for objects constructed by a specific function.
// args[0]: the constructor to find instances of
// args[1]: the the maximum number of objects to return
10209
static MaybeObject* Runtime_DebugConstructedBy(Arguments args) {
10210 10211 10212
  ASSERT(args.length() == 2);

  // First perform a full GC in order to avoid dead objects.
10213
  Heap::CollectAllGarbage(false);
10214 10215 10216 10217 10218 10219 10220 10221 10222 10223 10224

  // Check parameters.
  CONVERT_CHECKED(JSFunction, constructor, args[0]);
  CONVERT_NUMBER_CHECKED(int32_t, max_references, Int32, args[1]);
  RUNTIME_ASSERT(max_references >= 0);

  // Get the number of referencing objects.
  int count;
  count = DebugConstructedBy(constructor, max_references, NULL, 0);

  // Allocate an array to hold the result.
10225 10226 10227 10228
  Object* object;
  { MaybeObject* maybe_object = Heap::AllocateFixedArray(count);
    if (!maybe_object->ToObject(&object)) return maybe_object;
  }
10229 10230 10231 10232 10233 10234
  FixedArray* instances = FixedArray::cast(object);

  // Fill the referencing objects.
  count = DebugConstructedBy(constructor, max_references, instances, count);

  // Return result as JS array.
10235 10236 10237 10238 10239 10240
  Object* result;
  { MaybeObject* maybe_result = Heap::AllocateJSObject(
        Top::context()->global_context()->array_function());
    if (!maybe_result->ToObject(&result)) return maybe_result;
  }
  JSArray::cast(result)->SetContent(instances);
10241 10242 10243 10244
  return result;
}


10245 10246
// Find the effective prototype object as returned by __proto__.
// args[0]: the object to find the prototype for.
10247
static MaybeObject* Runtime_DebugGetPrototype(Arguments args) {
10248 10249 10250 10251
  ASSERT(args.length() == 1);

  CONVERT_CHECKED(JSObject, obj, args[0]);

10252 10253
  // Use the __proto__ accessor.
  return Accessors::ObjectPrototype.getter(obj, NULL);
10254 10255 10256
}


10257
static MaybeObject* Runtime_SystemBreak(Arguments args) {
10258
  ASSERT(args.length() == 0);
10259 10260 10261 10262 10263
  CPU::DebugBreak();
  return Heap::undefined_value();
}


10264
static MaybeObject* Runtime_DebugDisassembleFunction(Arguments args) {
10265 10266 10267 10268 10269
#ifdef DEBUG
  HandleScope scope;
  ASSERT(args.length() == 1);
  // Get the function and make sure it is compiled.
  CONVERT_ARG_CHECKED(JSFunction, func, 0);
10270 10271
  Handle<SharedFunctionInfo> shared(func->shared());
  if (!EnsureCompiled(shared, KEEP_EXCEPTION)) {
10272 10273 10274
    return Failure::Exception();
  }
  func->code()->PrintLn();
10275 10276 10277 10278 10279
#endif  // DEBUG
  return Heap::undefined_value();
}


10280
static MaybeObject* Runtime_DebugDisassembleConstructor(Arguments args) {
10281 10282 10283 10284 10285
#ifdef DEBUG
  HandleScope scope;
  ASSERT(args.length() == 1);
  // Get the function and make sure it is compiled.
  CONVERT_ARG_CHECKED(JSFunction, func, 0);
10286 10287
  Handle<SharedFunctionInfo> shared(func->shared());
  if (!EnsureCompiled(shared, KEEP_EXCEPTION)) {
10288 10289
    return Failure::Exception();
  }
10290
  shared->construct_stub()->PrintLn();
10291 10292 10293
#endif  // DEBUG
  return Heap::undefined_value();
}
10294 10295


10296
static MaybeObject* Runtime_FunctionGetInferredName(Arguments args) {
10297 10298 10299 10300 10301 10302
  NoHandleAllocation ha;
  ASSERT(args.length() == 1);

  CONVERT_CHECKED(JSFunction, f, args[0]);
  return f->shared()->inferred_name();
}
10303

10304 10305 10306 10307 10308 10309 10310 10311 10312 10313 10314 10315 10316 10317 10318 10319 10320 10321 10322 10323 10324 10325 10326 10327 10328 10329 10330 10331

static int FindSharedFunctionInfosForScript(Script* script,
                                     FixedArray* buffer) {
  AssertNoAllocation no_allocations;

  int counter = 0;
  int buffer_size = buffer->length();
  HeapIterator iterator;
  for (HeapObject* obj = iterator.next(); obj != NULL; obj = iterator.next()) {
    ASSERT(obj != NULL);
    if (!obj->IsSharedFunctionInfo()) {
      continue;
    }
    SharedFunctionInfo* shared = SharedFunctionInfo::cast(obj);
    if (shared->script() != script) {
      continue;
    }
    if (counter < buffer_size) {
      buffer->set(counter, shared);
    }
    counter++;
  }
  return counter;
}

// For a script finds all SharedFunctionInfo's in the heap that points
// to this script. Returns JSArray of SharedFunctionInfo wrapped
// in OpaqueReferences.
10332
static MaybeObject* Runtime_LiveEditFindSharedFunctionInfosForScript(
10333 10334 10335 10336 10337 10338 10339 10340 10341 10342 10343 10344 10345 10346 10347 10348 10349 10350 10351 10352 10353 10354 10355 10356 10357 10358 10359 10360 10361 10362 10363 10364
    Arguments args) {
  ASSERT(args.length() == 1);
  HandleScope scope;
  CONVERT_CHECKED(JSValue, script_value, args[0]);

  Handle<Script> script = Handle<Script>(Script::cast(script_value->value()));

  const int kBufferSize = 32;

  Handle<FixedArray> array;
  array = Factory::NewFixedArray(kBufferSize);
  int number = FindSharedFunctionInfosForScript(*script, *array);
  if (number > kBufferSize) {
    array = Factory::NewFixedArray(number);
    FindSharedFunctionInfosForScript(*script, *array);
  }

  Handle<JSArray> result = Factory::NewJSArrayWithElements(array);
  result->set_length(Smi::FromInt(number));

  LiveEdit::WrapSharedFunctionInfos(result);

  return *result;
}

// For a script calculates compilation information about all its functions.
// The script source is explicitly specified by the second argument.
// The source of the actual script is not used, however it is important that
// all generated code keeps references to this particular instance of script.
// Returns a JSArray of compilation infos. The array is ordered so that
// each function with all its descendant is always stored in a continues range
// with the function itself going first. The root function is a script function.
10365
static MaybeObject* Runtime_LiveEditGatherCompileInfo(Arguments args) {
10366 10367 10368 10369 10370 10371 10372 10373 10374 10375 10376 10377 10378 10379 10380
  ASSERT(args.length() == 2);
  HandleScope scope;
  CONVERT_CHECKED(JSValue, script, args[0]);
  CONVERT_ARG_CHECKED(String, source, 1);
  Handle<Script> script_handle = Handle<Script>(Script::cast(script->value()));

  JSArray* result =  LiveEdit::GatherCompileInfo(script_handle, source);

  if (Top::has_pending_exception()) {
    return Failure::Exception();
  }

  return result;
}

10381 10382 10383
// Changes the source of the script to a new_source.
// If old_script_name is provided (i.e. is a String), also creates a copy of
// the script with its original source and sends notification to debugger.
10384
static MaybeObject* Runtime_LiveEditReplaceScript(Arguments args) {
10385 10386 10387 10388
  ASSERT(args.length() == 3);
  HandleScope scope;
  CONVERT_CHECKED(JSValue, original_script_value, args[0]);
  CONVERT_ARG_CHECKED(String, new_source, 1);
10389
  Handle<Object> old_script_name(args[2]);
10390

10391 10392 10393
  CONVERT_CHECKED(Script, original_script_pointer,
                  original_script_value->value());
  Handle<Script> original_script(original_script_pointer);
10394

10395 10396 10397
  Object* old_script = LiveEdit::ChangeScriptSource(original_script,
                                                    new_source,
                                                    old_script_name);
10398

10399 10400 10401 10402 10403 10404
  if (old_script->IsScript()) {
    Handle<Script> script_handle(Script::cast(old_script));
    return *(GetScriptWrapper(script_handle));
  } else {
    return Heap::null_value();
  }
10405 10406
}

10407 10408 10409 10410 10411 10412 10413 10414 10415

static MaybeObject* Runtime_LiveEditFunctionSourceUpdated(Arguments args) {
  ASSERT(args.length() == 1);
  HandleScope scope;
  CONVERT_ARG_CHECKED(JSArray, shared_info, 0);
  return LiveEdit::FunctionSourceUpdated(shared_info);
}


10416
// Replaces code of SharedFunctionInfo with a new one.
10417
static MaybeObject* Runtime_LiveEditReplaceFunctionCode(Arguments args) {
10418 10419 10420 10421 10422
  ASSERT(args.length() == 2);
  HandleScope scope;
  CONVERT_ARG_CHECKED(JSArray, new_compile_info, 0);
  CONVERT_ARG_CHECKED(JSArray, shared_info, 1);

10423
  return LiveEdit::ReplaceFunctionCode(new_compile_info, shared_info);
10424 10425 10426
}

// Connects SharedFunctionInfo to another script.
10427
static MaybeObject* Runtime_LiveEditFunctionSetScript(Arguments args) {
10428 10429
  ASSERT(args.length() == 2);
  HandleScope scope;
10430 10431
  Handle<Object> function_object(args[0]);
  Handle<Object> script_object(args[1]);
10432

10433 10434 10435 10436 10437 10438 10439 10440 10441 10442 10443 10444
  if (function_object->IsJSValue()) {
    Handle<JSValue> function_wrapper = Handle<JSValue>::cast(function_object);
    if (script_object->IsJSValue()) {
      CONVERT_CHECKED(Script, script, JSValue::cast(*script_object)->value());
      script_object = Handle<Object>(script);
    }

    LiveEdit::SetFunctionScript(function_wrapper, script_object);
  } else {
    // Just ignore this. We may not have a SharedFunctionInfo for some functions
    // and we check it in this function.
  }
10445 10446 10447 10448

  return Heap::undefined_value();
}

10449 10450 10451

// In a code of a parent function replaces original function as embedded object
// with a substitution one.
10452
static MaybeObject* Runtime_LiveEditReplaceRefToNestedFunction(Arguments args) {
10453 10454 10455 10456 10457 10458 10459 10460 10461 10462 10463 10464 10465 10466
  ASSERT(args.length() == 3);
  HandleScope scope;

  CONVERT_ARG_CHECKED(JSValue, parent_wrapper, 0);
  CONVERT_ARG_CHECKED(JSValue, orig_wrapper, 1);
  CONVERT_ARG_CHECKED(JSValue, subst_wrapper, 2);

  LiveEdit::ReplaceRefToNestedFunction(parent_wrapper, orig_wrapper,
                                       subst_wrapper);

  return Heap::undefined_value();
}


10467 10468 10469 10470 10471
// Updates positions of a shared function info (first parameter) according
// to script source change. Text change is described in second parameter as
// array of groups of 3 numbers:
// (change_begin, change_end, change_end_new_position).
// Each group describes a change in text; groups are sorted by change_begin.
10472
static MaybeObject* Runtime_LiveEditPatchFunctionPositions(Arguments args) {
10473 10474 10475 10476 10477
  ASSERT(args.length() == 2);
  HandleScope scope;
  CONVERT_ARG_CHECKED(JSArray, shared_array, 0);
  CONVERT_ARG_CHECKED(JSArray, position_change_array, 1);

10478
  return LiveEdit::PatchFunctionPositions(shared_array, position_change_array);
10479 10480 10481
}


10482 10483 10484 10485
// For array of SharedFunctionInfo's (each wrapped in JSValue)
// checks that none of them have activations on stacks (of any thread).
// Returns array of the same length with corresponding results of
// LiveEdit::FunctionPatchabilityStatus type.
10486
static MaybeObject* Runtime_LiveEditCheckAndDropActivations(Arguments args) {
10487
  ASSERT(args.length() == 2);
10488 10489
  HandleScope scope;
  CONVERT_ARG_CHECKED(JSArray, shared_array, 0);
10490
  CONVERT_BOOLEAN_CHECKED(do_drop, args[1]);
10491

10492
  return *LiveEdit::CheckAndDropActivations(shared_array, do_drop);
10493 10494
}

10495 10496 10497 10498
// Compares 2 strings line-by-line, then token-wise and returns diff in form
// of JSArray of triplets (pos1, pos1_end, pos2_end) describing list
// of diff chunks.
static MaybeObject* Runtime_LiveEditCompareStrings(Arguments args) {
10499 10500 10501 10502 10503
  ASSERT(args.length() == 2);
  HandleScope scope;
  CONVERT_ARG_CHECKED(String, s1, 0);
  CONVERT_ARG_CHECKED(String, s2, 1);

10504
  return *LiveEdit::CompareStrings(s1, s2);
10505 10506 10507
}


10508

10509 10510
// A testing entry. Returns statement position which is the closest to
// source_position.
10511
static MaybeObject* Runtime_GetFunctionCodePositionFromSource(Arguments args) {
10512 10513 10514 10515 10516 10517 10518
  ASSERT(args.length() == 2);
  HandleScope scope;
  CONVERT_ARG_CHECKED(JSFunction, function, 0);
  CONVERT_NUMBER_CHECKED(int32_t, source_position, Int32, args[1]);

  Handle<Code> code(function->code());

10519 10520 10521 10522 10523
  if (code->kind() != Code::FUNCTION &&
      code->kind() != Code::OPTIMIZED_FUNCTION) {
    return Heap::undefined_value();
  }

10524
  RelocIterator it(*code, RelocInfo::ModeMask(RelocInfo::STATEMENT_POSITION));
10525 10526 10527 10528 10529 10530 10531
  int closest_pc = 0;
  int distance = kMaxInt;
  while (!it.done()) {
    int statement_position = static_cast<int>(it.rinfo()->data());
    // Check if this break point is closer that what was previously found.
    if (source_position <= statement_position &&
        statement_position - source_position < distance) {
10532 10533
      closest_pc =
          static_cast<int>(it.rinfo()->pc() - code->instruction_start());
10534 10535 10536 10537 10538 10539 10540 10541 10542 10543 10544
      distance = statement_position - source_position;
      // Check whether we can't get any closer.
      if (distance == 0) break;
    }
    it.next();
  }

  return Smi::FromInt(closest_pc);
}


10545 10546 10547
// Calls specified function with or without entering the debugger.
// This is used in unit tests to run code as if debugger is entered or simply
// to have a stack with C++ frame in the middle.
10548
static MaybeObject* Runtime_ExecuteInDebugContext(Arguments args) {
10549 10550 10551 10552 10553 10554 10555 10556 10557 10558 10559 10560 10561 10562 10563 10564 10565 10566 10567 10568 10569 10570 10571 10572 10573
  ASSERT(args.length() == 2);
  HandleScope scope;
  CONVERT_ARG_CHECKED(JSFunction, function, 0);
  CONVERT_BOOLEAN_CHECKED(without_debugger, args[1]);

  Handle<Object> result;
  bool pending_exception;
  {
    if (without_debugger) {
      result = Execution::Call(function, Top::global(), 0, NULL,
                               &pending_exception);
    } else {
      EnterDebugger enter_debugger;
      result = Execution::Call(function, Top::global(), 0, NULL,
                               &pending_exception);
    }
  }
  if (!pending_exception) {
    return *result;
  } else {
    return Failure::Exception();
  }
}


10574 10575 10576 10577 10578
// Sets a v8 flag.
static MaybeObject* Runtime_SetFlags(Arguments args) {
  CONVERT_CHECKED(String, arg, args[0]);
  SmartPointer<char> flags =
      arg->ToCString(DISALLOW_NULLS, ROBUST_STRING_TRAVERSAL);
10579
  FlagList::SetFlagsFromString(*flags, StrLength(*flags));
10580 10581 10582 10583 10584 10585 10586 10587 10588 10589 10590 10591 10592 10593
  return Heap::undefined_value();
}


// Performs a GC.
// Presently, it only does a full GC.
static MaybeObject* Runtime_CollectGarbage(Arguments args) {
  Heap::CollectAllGarbage(true);
  return Heap::undefined_value();
}


// Gets the current heap usage.
static MaybeObject* Runtime_GetHeapUsage(Arguments args) {
10594
  int usage = static_cast<int>(Heap::SizeOfObjects());
10595 10596 10597 10598 10599
  if (!Smi::IsValid(usage)) {
    return *Factory::NewNumberFromInt(usage);
  }
  return Smi::FromInt(usage);
}
10600 10601
#endif  // ENABLE_DEBUGGER_SUPPORT

10602

10603
#ifdef ENABLE_LOGGING_AND_PROFILING
10604
static MaybeObject* Runtime_ProfilerResume(Arguments args) {
10605
  NoHandleAllocation ha;
10606
  ASSERT(args.length() == 2);
10607 10608

  CONVERT_CHECKED(Smi, smi_modules, args[0]);
10609 10610
  CONVERT_CHECKED(Smi, smi_tag, args[1]);
  v8::V8::ResumeProfilerEx(smi_modules->value(), smi_tag->value());
10611 10612 10613 10614
  return Heap::undefined_value();
}


10615
static MaybeObject* Runtime_ProfilerPause(Arguments args) {
10616
  NoHandleAllocation ha;
10617
  ASSERT(args.length() == 2);
10618 10619

  CONVERT_CHECKED(Smi, smi_modules, args[0]);
10620 10621
  CONVERT_CHECKED(Smi, smi_tag, args[1]);
  v8::V8::PauseProfilerEx(smi_modules->value(), smi_tag->value());
10622 10623 10624 10625
  return Heap::undefined_value();
}

#endif  // ENABLE_LOGGING_AND_PROFILING
10626

10627 10628 10629 10630 10631 10632 10633 10634 10635 10636 10637 10638
// Finds the script object from the script data. NOTE: This operation uses
// heap traversal to find the function generated for the source position
// for the requested break point. For lazily compiled functions several heap
// traversals might be required rendering this operation as a rather slow
// operation. However for setting break points which is normally done through
// some kind of user interaction the performance is not crucial.
static Handle<Object> Runtime_GetScriptFromScriptName(
    Handle<String> script_name) {
  // Scan the heap for Script objects to find the script with the requested
  // script data.
  Handle<Script> script;
  HeapIterator iterator;
10639 10640
  HeapObject* obj = NULL;
  while (script.is_null() && ((obj = iterator.next()) != NULL)) {
10641 10642 10643 10644 10645 10646 10647 10648 10649 10650 10651 10652 10653 10654 10655 10656 10657 10658 10659 10660 10661
    // If a script is found check if it has the script data requested.
    if (obj->IsScript()) {
      if (Script::cast(obj)->name()->IsString()) {
        if (String::cast(Script::cast(obj)->name())->Equals(*script_name)) {
          script = Handle<Script>(Script::cast(obj));
        }
      }
    }
  }

  // If no script with the requested script data is found return undefined.
  if (script.is_null()) return Factory::undefined_value();

  // Return the script found.
  return GetScriptWrapper(script);
}


// Get the script object from script data. NOTE: Regarding performance
// see the NOTE for GetScriptFromScriptData.
// args[0]: script data for the script to find the source for
10662
static MaybeObject* Runtime_GetScript(Arguments args) {
10663 10664 10665 10666 10667 10668 10669 10670 10671 10672 10673 10674 10675
  HandleScope scope;

  ASSERT(args.length() == 1);

  CONVERT_CHECKED(String, script_name, args[0]);

  // Find the requested script.
  Handle<Object> result =
      Runtime_GetScriptFromScriptName(Handle<String>(script_name));
  return *result;
}


10676 10677 10678 10679 10680 10681 10682 10683 10684 10685 10686 10687 10688 10689 10690 10691
// Determines whether the given stack frame should be displayed in
// a stack trace.  The caller is the error constructor that asked
// for the stack trace to be collected.  The first time a construct
// call to this function is encountered it is skipped.  The seen_caller
// in/out parameter is used to remember if the caller has been seen
// yet.
static bool ShowFrameInStackTrace(StackFrame* raw_frame, Object* caller,
    bool* seen_caller) {
  // Only display JS frames.
  if (!raw_frame->is_java_script())
    return false;
  JavaScriptFrame* frame = JavaScriptFrame::cast(raw_frame);
  Object* raw_fun = frame->function();
  // Not sure when this can happen but skip it just in case.
  if (!raw_fun->IsJSFunction())
    return false;
10692
  if ((raw_fun == caller) && !(*seen_caller)) {
10693 10694 10695
    *seen_caller = true;
    return false;
  }
10696 10697 10698 10699 10700
  // Skip all frames until we've seen the caller.  Also, skip the most
  // obvious builtin calls.  Some builtin calls (such as Number.ADD
  // which is invoked using 'call') are very difficult to recognize
  // so we're leaving them in for now.
  return *seen_caller && !frame->receiver()->IsJSBuiltinsObject();
10701 10702 10703
}


10704 10705 10706
// Collect the raw data for a stack trace.  Returns an array of 4
// element segments each containing a receiver, function, code and
// native code offset.
10707
static MaybeObject* Runtime_CollectStackTrace(Arguments args) {
10708
  ASSERT_EQ(args.length(), 2);
10709
  Handle<Object> caller = args.at<Object>(0);
10710 10711 10712 10713
  CONVERT_NUMBER_CHECKED(int32_t, limit, Int32, args[1]);

  HandleScope scope;

10714 10715
  limit = Max(limit, 0);  // Ensure that limit is not negative.
  int initial_size = Min(limit, 10);
10716
  Handle<JSArray> result = Factory::NewJSArray(initial_size * 4);
10717 10718

  StackFrameIterator iter;
10719 10720 10721
  // If the caller parameter is a function we skip frames until we're
  // under it before starting to collect.
  bool seen_caller = !caller->IsJSFunction();
10722 10723 10724
  int cursor = 0;
  int frames_seen = 0;
  while (!iter.done() && frames_seen < limit) {
10725
    StackFrame* raw_frame = iter.frame();
10726
    if (ShowFrameInStackTrace(raw_frame, *caller, &seen_caller)) {
10727
      frames_seen++;
10728
      JavaScriptFrame* frame = JavaScriptFrame::cast(raw_frame);
10729 10730 10731 10732 10733 10734 10735 10736 10737 10738 10739 10740 10741 10742 10743 10744 10745 10746 10747
      List<FrameSummary> frames(3);  // Max 2 levels of inlining.
      frame->Summarize(&frames);
      for (int i = frames.length() - 1; i >= 0; i--) {
        Handle<Object> recv = frames[i].receiver();
        Handle<JSFunction> fun = frames[i].function();
        Handle<Code> code = frames[i].code();
        Handle<Smi> offset(Smi::FromInt(frames[i].offset()));
        FixedArray* elements = FixedArray::cast(result->elements());
        if (cursor + 3 < elements->length()) {
          elements->set(cursor++, *recv);
          elements->set(cursor++, *fun);
          elements->set(cursor++, *code);
          elements->set(cursor++, *offset);
        } else {
          SetElement(result, cursor++, recv);
          SetElement(result, cursor++, fun);
          SetElement(result, cursor++, code);
          SetElement(result, cursor++, offset);
        }
10748
      }
10749
    }
10750
    iter.Advance();
10751
  }
10752

10753
  result->set_length(Smi::FromInt(cursor));
10754 10755 10756 10757
  return *result;
}


10758
// Returns V8 version as a string.
10759
static MaybeObject* Runtime_GetV8Version(Arguments args) {
10760 10761 10762 10763 10764 10765 10766 10767 10768 10769
  ASSERT_EQ(args.length(), 0);

  NoHandleAllocation ha;

  const char* version_string = v8::V8::GetVersion();

  return Heap::AllocateStringFromAscii(CStrVector(version_string), NOT_TENURED);
}


10770
static MaybeObject* Runtime_Abort(Arguments args) {
10771 10772 10773 10774 10775 10776 10777 10778 10779 10780
  ASSERT(args.length() == 2);
  OS::PrintError("abort: %s\n", reinterpret_cast<char*>(args[0]) +
                                    Smi::cast(args[1])->value());
  Top::PrintStack();
  OS::Abort();
  UNREACHABLE();
  return NULL;
}


10781
static MaybeObject* Runtime_GetFromCache(Arguments args) {
10782
  // This is only called from codegen, so checks might be more lax.
10783
  CONVERT_CHECKED(JSFunctionResultCache, cache, args[0]);
10784 10785
  Object* key = args[1];

10786
  int finger_index = cache->finger_index();
10787 10788 10789 10790 10791 10792 10793 10794 10795 10796 10797
  Object* o = cache->get(finger_index);
  if (o == key) {
    // The fastest case: hit the same place again.
    return cache->get(finger_index + 1);
  }

  for (int i = finger_index - 2;
       i >= JSFunctionResultCache::kEntriesIndex;
       i -= 2) {
    o = cache->get(i);
    if (o == key) {
10798
      cache->set_finger_index(i);
10799 10800 10801 10802
      return cache->get(i + 1);
    }
  }

10803
  int size = cache->size();
10804 10805 10806 10807 10808
  ASSERT(size <= cache->length());

  for (int i = size - 2; i > finger_index; i -= 2) {
    o = cache->get(i);
    if (o == key) {
10809
      cache->set_finger_index(i);
10810 10811 10812 10813
      return cache->get(i + 1);
    }
  }

10814 10815 10816 10817 10818 10819 10820 10821 10822 10823 10824 10825 10826 10827 10828 10829 10830 10831 10832 10833 10834 10835 10836 10837 10838 10839 10840 10841 10842 10843 10844 10845 10846 10847 10848 10849
  // There is no value in the cache.  Invoke the function and cache result.
  HandleScope scope;

  Handle<JSFunctionResultCache> cache_handle(cache);
  Handle<Object> key_handle(key);
  Handle<Object> value;
  {
    Handle<JSFunction> factory(JSFunction::cast(
          cache_handle->get(JSFunctionResultCache::kFactoryIndex)));
    // TODO(antonm): consider passing a receiver when constructing a cache.
    Handle<Object> receiver(Top::global_context()->global());
    // This handle is nor shared, nor used later, so it's safe.
    Object** argv[] = { key_handle.location() };
    bool pending_exception = false;
    value = Execution::Call(factory,
                            receiver,
                            1,
                            argv,
                            &pending_exception);
    if (pending_exception) return Failure::Exception();
  }

#ifdef DEBUG
  cache_handle->JSFunctionResultCacheVerify();
#endif

  // Function invocation may have cleared the cache.  Reread all the data.
  finger_index = cache_handle->finger_index();
  size = cache_handle->size();

  // If we have spare room, put new data into it, otherwise evict post finger
  // entry which is likely to be the least recently used.
  int index = -1;
  if (size < cache_handle->length()) {
    cache_handle->set_size(size + JSFunctionResultCache::kEntrySize);
    index = size;
10850
  } else {
10851 10852 10853
    index = finger_index + JSFunctionResultCache::kEntrySize;
    if (index == cache_handle->length()) {
      index = JSFunctionResultCache::kEntriesIndex;
antonm@chromium.org's avatar
antonm@chromium.org committed
10854
    }
10855
  }
10856 10857 10858 10859 10860 10861 10862 10863 10864 10865 10866 10867 10868 10869

  ASSERT(index % 2 == 0);
  ASSERT(index >= JSFunctionResultCache::kEntriesIndex);
  ASSERT(index < cache_handle->length());

  cache_handle->set(index, *key_handle);
  cache_handle->set(index + 1, *value);
  cache_handle->set_finger_index(index);

#ifdef DEBUG
  cache_handle->JSFunctionResultCacheVerify();
#endif

  return *value;
10870 10871
}

10872 10873 10874 10875 10876 10877 10878 10879 10880 10881 10882 10883 10884 10885 10886 10887 10888 10889 10890 10891 10892 10893 10894 10895 10896 10897 10898 10899 10900 10901 10902 10903 10904 10905 10906 10907 10908 10909 10910

static MaybeObject* Runtime_NewMessageObject(Arguments args) {
  HandleScope scope;
  CONVERT_ARG_CHECKED(String, type, 0);
  CONVERT_ARG_CHECKED(JSArray, arguments, 1);
  return *Factory::NewJSMessageObject(type,
                                      arguments,
                                      0,
                                      0,
                                      Factory::undefined_value(),
                                      Factory::undefined_value(),
                                      Factory::undefined_value());
}


static MaybeObject* Runtime_MessageGetType(Arguments args) {
  CONVERT_CHECKED(JSMessageObject, message, args[0]);
  return message->type();
}


static MaybeObject* Runtime_MessageGetArguments(Arguments args) {
  CONVERT_CHECKED(JSMessageObject, message, args[0]);
  return message->arguments();
}


static MaybeObject* Runtime_MessageGetStartPosition(Arguments args) {
  CONVERT_CHECKED(JSMessageObject, message, args[0]);
  return Smi::FromInt(message->start_position());
}


static MaybeObject* Runtime_MessageGetScript(Arguments args) {
  CONVERT_CHECKED(JSMessageObject, message, args[0]);
  return message->script();
}


10911 10912 10913
#ifdef DEBUG
// ListNatives is ONLY used by the fuzz-natives.js in debug mode
// Exclude the code in release mode.
10914
static MaybeObject* Runtime_ListNatives(Arguments args) {
10915
  ASSERT(args.length() == 0);
10916 10917 10918
  HandleScope scope;
  Handle<JSArray> result = Factory::NewJSArray(0);
  int index = 0;
10919
  bool inline_runtime_functions = false;
10920
#define ADD_ENTRY(Name, argc, ressize)                                       \
10921 10922
  {                                                                          \
    HandleScope inner;                                                       \
10923 10924 10925 10926 10927 10928 10929 10930 10931
    Handle<String> name;                                                     \
    /* Inline runtime functions have an underscore in front of the name. */  \
    if (inline_runtime_functions) {                                          \
      name = Factory::NewStringFromAscii(                                    \
          Vector<const char>("_" #Name, StrLength("_" #Name)));              \
    } else {                                                                 \
      name = Factory::NewStringFromAscii(                                    \
          Vector<const char>(#Name, StrLength(#Name)));                      \
    }                                                                        \
10932 10933 10934 10935 10936
    Handle<JSArray> pair = Factory::NewJSArray(0);                           \
    SetElement(pair, 0, name);                                               \
    SetElement(pair, 1, Handle<Smi>(Smi::FromInt(argc)));                    \
    SetElement(result, index++, pair);                                       \
  }
10937
  inline_runtime_functions = false;
10938
  RUNTIME_FUNCTION_LIST(ADD_ENTRY)
10939
  inline_runtime_functions = true;
10940
  INLINE_FUNCTION_LIST(ADD_ENTRY)
10941
  INLINE_RUNTIME_FUNCTION_LIST(ADD_ENTRY)
10942 10943 10944
#undef ADD_ENTRY
  return *result;
}
10945
#endif
10946 10947


10948
static MaybeObject* Runtime_Log(Arguments args) {
10949
  ASSERT(args.length() == 2);
10950 10951
  CONVERT_CHECKED(String, format, args[0]);
  CONVERT_CHECKED(JSArray, elms, args[1]);
10952 10953 10954 10955 10956 10957
  Vector<const char> chars = format->ToAsciiVector();
  Logger::LogRuntime(chars, elms);
  return Heap::undefined_value();
}


10958
static MaybeObject* Runtime_IS_VAR(Arguments args) {
10959 10960 10961 10962 10963 10964 10965 10966
  UNREACHABLE();  // implemented as macro in the parser
  return NULL;
}


// ----------------------------------------------------------------------------
// Implementation of Runtime

10967 10968 10969 10970 10971 10972 10973 10974
#define F(name, number_of_args, result_size)                             \
  { Runtime::k##name, Runtime::RUNTIME, #name,   \
    FUNCTION_ADDR(Runtime_##name), number_of_args, result_size },


#define I(name, number_of_args, result_size)                             \
  { Runtime::kInline##name, Runtime::INLINE,     \
    "_" #name, NULL, number_of_args, result_size },
10975

10976
Runtime::Function kIntrinsicFunctions[] = {
10977
  RUNTIME_FUNCTION_LIST(F)
10978 10979
  INLINE_FUNCTION_LIST(I)
  INLINE_RUNTIME_FUNCTION_LIST(I)
10980 10981 10982
};


10983
MaybeObject* Runtime::InitializeIntrinsicFunctionNames(Object* dictionary) {
10984 10985 10986
  ASSERT(dictionary != NULL);
  ASSERT(StringDictionary::cast(dictionary)->NumberOfElements() == 0);
  for (int i = 0; i < kNumFunctions; ++i) {
10987 10988 10989 10990 10991
    Object* name_symbol;
    { MaybeObject* maybe_name_symbol =
          Heap::LookupAsciiSymbol(kIntrinsicFunctions[i].name);
      if (!maybe_name_symbol->ToObject(&name_symbol)) return maybe_name_symbol;
    }
10992
    StringDictionary* string_dictionary = StringDictionary::cast(dictionary);
10993 10994 10995 10996 10997 10998 10999 11000 11001 11002
    { MaybeObject* maybe_dictionary = string_dictionary->Add(
          String::cast(name_symbol),
          Smi::FromInt(i),
          PropertyDetails(NONE, NORMAL));
      if (!maybe_dictionary->ToObject(&dictionary)) {
        // Non-recoverable failure.  Calling code must restart heap
        // initialization.
        return maybe_dictionary;
      }
    }
11003 11004
  }
  return dictionary;
11005 11006 11007
}


11008 11009 11010 11011 11012 11013
Runtime::Function* Runtime::FunctionForSymbol(Handle<String> name) {
  int entry = Heap::intrinsic_function_names()->FindEntry(*name);
  if (entry != kNotFound) {
    Object* smi_index = Heap::intrinsic_function_names()->ValueAt(entry);
    int function_index = Smi::cast(smi_index)->value();
    return &(kIntrinsicFunctions[function_index]);
11014 11015 11016 11017 11018
  }
  return NULL;
}


11019 11020 11021 11022 11023
Runtime::Function* Runtime::FunctionForId(Runtime::FunctionId id) {
  return &(kIntrinsicFunctions[static_cast<int>(id)]);
}


11024 11025
void Runtime::PerformGC(Object* result) {
  Failure* failure = Failure::cast(result);
11026 11027 11028
  if (failure->IsRetryAfterGC()) {
    // Try to do a garbage collection; ignore it if it fails. The C
    // entry stub will throw an out-of-memory exception in that case.
11029
    Heap::CollectGarbage(failure->allocation_space());
11030 11031 11032
  } else {
    // Handle last resort GC and make sure to allow future allocations
    // to grow the heap without causing GCs (if possible).
11033
    Counters::gc_last_resort_from_js.Increment();
11034
    Heap::CollectAllGarbage(false);
11035
  }
11036 11037 11038 11039
}


} }  // namespace v8::internal