runtime-scopes.cc 40.3 KB
Newer Older
1 2 3 4
// Copyright 2014 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5
#include "src/runtime/runtime-utils.h"
6 7 8

#include "src/accessors.h"
#include "src/arguments.h"
9 10
#include "src/ast/scopeinfo.h"
#include "src/ast/scopes.h"
11
#include "src/deoptimizer.h"
12
#include "src/frames-inl.h"
13
#include "src/isolate-inl.h"
14
#include "src/messages.h"
15 16 17 18 19 20 21

namespace v8 {
namespace internal {

static Object* ThrowRedeclarationError(Isolate* isolate, Handle<String> name) {
  HandleScope scope(isolate);
  THROW_NEW_ERROR_RETURN_FAILURE(
22
      isolate, NewTypeError(MessageTemplate::kVarRedeclaration, name));
23 24 25
}


26 27
RUNTIME_FUNCTION(Runtime_ThrowConstAssignError) {
  HandleScope scope(isolate);
28 29
  THROW_NEW_ERROR_RETURN_FAILURE(isolate,
                                 NewTypeError(MessageTemplate::kConstAssign));
30 31 32
}


33
// May throw a RedeclarationError.
34
static Object* DeclareGlobals(Isolate* isolate, Handle<JSGlobalObject> global,
35 36 37
                              Handle<String> name, Handle<Object> value,
                              PropertyAttributes attr, bool is_var,
                              bool is_const, bool is_function) {
38 39
  Handle<ScriptContextTable> script_contexts(
      global->native_context()->script_context_table());
40 41 42
  ScriptContextTable::LookupResult lookup;
  if (ScriptContextTable::Lookup(script_contexts, name, &lookup) &&
      IsLexicalVariableMode(lookup.mode)) {
43 44 45
    return ThrowRedeclarationError(isolate, name);
  }

46 47 48
  // Do the lookup own properties only, see ES5 erratum.
  LookupIterator it(global, name, LookupIterator::HIDDEN_SKIP_INTERCEPTOR);
  Maybe<PropertyAttributes> maybe = JSReceiver::GetPropertyAttributes(&it);
49
  if (!maybe.IsJust()) return isolate->heap()->exception();
50 51

  if (it.IsFound()) {
52
    PropertyAttributes old_attributes = maybe.FromJust();
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
    // The name was declared before; check for conflicting re-declarations.
    if (is_const) return ThrowRedeclarationError(isolate, name);

    // Skip var re-declarations.
    if (is_var) return isolate->heap()->undefined_value();

    DCHECK(is_function);
    if ((old_attributes & DONT_DELETE) != 0) {
      // Only allow reconfiguring globals to functions in user code (no
      // natives, which are marked as read-only).
      DCHECK((attr & READ_ONLY) == 0);

      // Check whether we can reconfigure the existing property into a
      // function.
      PropertyDetails old_details = it.property_details();
      if (old_details.IsReadOnly() || old_details.IsDontEnum() ||
69 70
          (it.state() == LookupIterator::ACCESSOR &&
           it.GetAccessors()->IsAccessorPair())) {
71 72 73 74 75
        return ThrowRedeclarationError(isolate, name);
      }
      // If the existing property is not configurable, keep its attributes. Do
      attr = old_attributes;
    }
76 77 78 79 80 81 82 83

    // If the current state is ACCESSOR, this could mean it's an AccessorInfo
    // type property. We are not allowed to call into such setters during global
    // function declaration since this would break e.g., onload. Meaning
    // 'function onload() {}' would invalidly register that function as the
    // onload callback. To avoid this situation, we first delete the property
    // before readding it as a regular data property below.
    if (it.state() == LookupIterator::ACCESSOR) it.Delete();
84 85 86
  }

  // Define or redefine own property.
87 88
  RETURN_FAILURE_ON_EXCEPTION(
      isolate, JSObject::DefineOwnPropertyIgnoreAttributes(&it, value, attr));
89 90 91 92 93 94 95

  return isolate->heap()->undefined_value();
}


RUNTIME_FUNCTION(Runtime_DeclareGlobals) {
  HandleScope scope(isolate);
96
  DCHECK_EQ(2, args.length());
97
  Handle<JSGlobalObject> global(isolate->global_object());
98
  Handle<Context> context(isolate->context());
99

100 101
  CONVERT_ARG_HANDLE_CHECKED(FixedArray, pairs, 0);
  CONVERT_SMI_ARG_CHECKED(flags, 1);
102 103 104 105 106 107 108 109 110 111 112 113 114 115

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

    // 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_var = initial_value->IsUndefined();
    bool is_const = initial_value->IsTheHole();
    bool is_function = initial_value->IsSharedFunctionInfo();
116 117
    DCHECK_EQ(1,
              BoolToInt(is_var) + BoolToInt(is_const) + BoolToInt(is_function));
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161

    Handle<Object> value;
    if (is_function) {
      // Copy the function and update its context. Use it as value.
      Handle<SharedFunctionInfo> shared =
          Handle<SharedFunctionInfo>::cast(initial_value);
      Handle<JSFunction> function =
          isolate->factory()->NewFunctionFromSharedFunctionInfo(shared, context,
                                                                TENURED);
      value = function;
    } else {
      value = isolate->factory()->undefined_value();
    }

    // Compute the property attributes. According to ECMA-262,
    // the property must be non-configurable except in eval.
    bool is_native = DeclareGlobalsNativeFlag::decode(flags);
    bool is_eval = DeclareGlobalsEvalFlag::decode(flags);
    int attr = NONE;
    if (is_const) attr |= READ_ONLY;
    if (is_function && is_native) attr |= READ_ONLY;
    if (!is_const && !is_eval) attr |= DONT_DELETE;

    Object* result = DeclareGlobals(isolate, global, name, value,
                                    static_cast<PropertyAttributes>(attr),
                                    is_var, is_const, is_function);
    if (isolate->has_pending_exception()) return result;
  }

  return isolate->heap()->undefined_value();
}


RUNTIME_FUNCTION(Runtime_InitializeVarGlobal) {
  HandleScope scope(isolate);
  // args[0] == name
  // args[1] == language_mode
  // args[2] == value (optional)

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

  CONVERT_ARG_HANDLE_CHECKED(String, name, 0);
162
  CONVERT_LANGUAGE_MODE_ARG_CHECKED(language_mode, 1);
163 164
  CONVERT_ARG_HANDLE_CHECKED(Object, value, 2);

165
  Handle<JSGlobalObject> global(isolate->context()->global_object());
166 167
  Handle<Object> result;
  ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
168
      isolate, result, Object::SetProperty(global, name, value, language_mode));
169 170 171 172 173 174 175 176 177 178 179 180 181
  return *result;
}


RUNTIME_FUNCTION(Runtime_InitializeConstGlobal) {
  HandleScope handle_scope(isolate);
  // 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_HANDLE_CHECKED(String, name, 0);
  CONVERT_ARG_HANDLE_CHECKED(Object, value, 1);

182
  Handle<JSGlobalObject> global = isolate->global_object();
183 184 185 186

  // Lookup the property as own on the global object.
  LookupIterator it(global, name, LookupIterator::HIDDEN_SKIP_INTERCEPTOR);
  Maybe<PropertyAttributes> maybe = JSReceiver::GetPropertyAttributes(&it);
187 188
  DCHECK(maybe.IsJust());
  PropertyAttributes old_attributes = maybe.FromJust();
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204

  PropertyAttributes attr =
      static_cast<PropertyAttributes>(DONT_DELETE | READ_ONLY);
  // Set the value if the property is either missing, or the property attributes
  // allow setting the value without invoking an accessor.
  if (it.IsFound()) {
    // Ignore if we can't reconfigure the value.
    if ((old_attributes & DONT_DELETE) != 0) {
      if ((old_attributes & READ_ONLY) != 0 ||
          it.state() == LookupIterator::ACCESSOR) {
        return *value;
      }
      attr = static_cast<PropertyAttributes>(old_attributes | READ_ONLY);
    }
  }

205 206
  RETURN_FAILURE_ON_EXCEPTION(
      isolate, JSObject::DefineOwnPropertyIgnoreAttributes(&it, value, attr));
207 208 209 210 211

  return *value;
}


212
namespace {
213

214 215 216
Object* DeclareLookupSlot(Isolate* isolate, Handle<String> name,
                          Handle<Object> initial_value,
                          PropertyAttributes attr) {
217 218 219
  // Declarations are always made in a function, eval or script context, or
  // a declaration block scope.
  // In the case of eval code, the context passed is the context of the caller,
220
  // which may be some nested context and not the declaration context.
221 222
  Handle<Context> context_arg(isolate->context(), isolate);
  Handle<Context> context(context_arg->declaration_context(), isolate);
223 224 225 226 227

  // TODO(verwaest): Unify the encoding indicating "var" with DeclareGlobals.
  bool is_var = *initial_value == NULL;
  bool is_const = initial_value->IsTheHole();
  bool is_function = initial_value->IsJSFunction();
228 229
  DCHECK_EQ(1,
            BoolToInt(is_var) + BoolToInt(is_const) + BoolToInt(is_function));
230 231 232 233

  int index;
  PropertyAttributes attributes;
  BindingFlags binding_flags;
234 235 236 237 238 239 240

  if ((attr & EVAL_DECLARED) != 0) {
    // Check for a conflict with a lexically scoped variable
    context_arg->Lookup(name, LEXICAL_TEST, &index, &attributes,
                        &binding_flags);
    if (attributes != ABSENT &&
        (binding_flags == MUTABLE_CHECK_INITIALIZED ||
241 242
         binding_flags == IMMUTABLE_CHECK_INITIALIZED ||
         binding_flags == IMMUTABLE_CHECK_INITIALIZED_HARMONY)) {
243 244 245 246 247 248 249
      return ThrowRedeclarationError(isolate, name);
    }
    attr = static_cast<PropertyAttributes>(attr & ~EVAL_DECLARED);
  }

  Handle<Object> holder = context->Lookup(name, DONT_FOLLOW_CHAINS, &index,
                                          &attributes, &binding_flags);
250 251 252 253
  if (holder.is_null()) {
    // In case of JSProxy, an exception might have been thrown.
    if (isolate->has_pending_exception()) return isolate->heap()->exception();
  }
254 255 256 257 258 259 260 261

  Handle<JSObject> object;
  Handle<Object> value =
      is_function ? initial_value
                  : Handle<Object>::cast(isolate->factory()->undefined_value());

  // TODO(verwaest): This case should probably not be covered by this function,
  // but by DeclareGlobals instead.
262
  if (attributes != ABSENT && holder->IsJSGlobalObject()) {
263 264 265
    return DeclareGlobals(isolate, Handle<JSGlobalObject>::cast(holder), name,
                          value, attr, is_var, is_const, is_function);
  }
266
  if (context_arg->extension()->IsJSGlobalObject()) {
267 268 269 270
    Handle<JSGlobalObject> global(
        JSGlobalObject::cast(context_arg->extension()), isolate);
    return DeclareGlobals(isolate, global, name, value, attr, is_var, is_const,
                          is_function);
271 272 273 274 275 276
  } else if (context->IsScriptContext()) {
    DCHECK(context->global_object()->IsJSGlobalObject());
    Handle<JSGlobalObject> global(
        JSGlobalObject::cast(context->global_object()), isolate);
    return DeclareGlobals(isolate, global, name, value, attr, is_var, is_const,
                          is_function);
277
  }
278 279 280 281 282 283 284 285 286 287 288

  if (attributes != ABSENT) {
    // The name was declared before; check for conflicting re-declarations.
    if (is_const || (attributes & READ_ONLY) != 0) {
      return ThrowRedeclarationError(isolate, name);
    }

    // Skip var re-declarations.
    if (is_var) return isolate->heap()->undefined_value();

    DCHECK(is_function);
289
    if (index != Context::kNotFound) {
290 291 292 293 294 295 296 297
      DCHECK(holder.is_identical_to(context));
      context->set(index, *initial_value);
      return isolate->heap()->undefined_value();
    }

    object = Handle<JSObject>::cast(holder);

  } else if (context->has_extension()) {
298 299 300 301 302 303
    // Sloppy varblock contexts might not have an extension object yet,
    // in which case their extension is a ScopeInfo.
    if (context->extension()->IsScopeInfo()) {
      DCHECK(context->IsBlockContext());
      object = isolate->factory()->NewJSObject(
          isolate->context_extension_function());
304
      Handle<HeapObject> extension =
305 306 307 308 309 310
          isolate->factory()->NewSloppyBlockWithEvalContextExtension(
              handle(context->scope_info()), object);
      context->set_extension(*extension);
    } else {
      object = handle(context->extension_object(), isolate);
    }
311 312 313 314 315 316 317 318 319 320 321 322 323 324
    DCHECK(object->IsJSContextExtensionObject() || object->IsJSGlobalObject());
  } else {
    DCHECK(context->IsFunctionContext());
    object =
        isolate->factory()->NewJSObject(isolate->context_extension_function());
    context->set_extension(*object);
  }

  RETURN_FAILURE_ON_EXCEPTION(isolate, JSObject::SetOwnPropertyIgnoreAttributes(
                                           object, name, value, attr));

  return isolate->heap()->undefined_value();
}

325 326 327 328 329
}  // namespace


RUNTIME_FUNCTION(Runtime_DeclareLookupSlot) {
  HandleScope scope(isolate);
330
  DCHECK_EQ(3, args.length());
331 332
  CONVERT_ARG_HANDLE_CHECKED(String, name, 0);
  CONVERT_ARG_HANDLE_CHECKED(Object, initial_value, 1);
333
  CONVERT_ARG_HANDLE_CHECKED(Smi, property_attributes, 2);
334

335 336 337
  PropertyAttributes attributes =
      static_cast<PropertyAttributes>(property_attributes->value());
  return DeclareLookupSlot(isolate, name, initial_value, attributes);
338 339
}

340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357

RUNTIME_FUNCTION(Runtime_InitializeLegacyConstLookupSlot) {
  HandleScope scope(isolate);
  DCHECK(args.length() == 3);

  CONVERT_ARG_HANDLE_CHECKED(Object, value, 0);
  DCHECK(!value->IsTheHole());
  // Initializations are always done in a function or native context.
  CONVERT_ARG_HANDLE_CHECKED(Context, context_arg, 1);
  Handle<Context> context(context_arg->declaration_context());
  CONVERT_ARG_HANDLE_CHECKED(String, name, 2);

  int index;
  PropertyAttributes attributes;
  ContextLookupFlags flags = DONT_FOLLOW_CHAINS;
  BindingFlags binding_flags;
  Handle<Object> holder =
      context->Lookup(name, flags, &index, &attributes, &binding_flags);
358 359 360 361
  if (holder.is_null()) {
    // In case of JSProxy, an exception might have been thrown.
    if (isolate->has_pending_exception()) return isolate->heap()->exception();
  }
362

363
  if (index != Context::kNotFound) {
364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381
    DCHECK(holder->IsContext());
    // Property was found in a context.  Perform the assignment if the constant
    // was uninitialized.
    Handle<Context> context = Handle<Context>::cast(holder);
    DCHECK((attributes & READ_ONLY) != 0);
    if (context->get(index)->IsTheHole()) context->set(index, *value);
    return *value;
  }

  PropertyAttributes attr =
      static_cast<PropertyAttributes>(DONT_DELETE | READ_ONLY);

  // Strict mode handling not needed (legacy const is disallowed in strict
  // mode).

  // The declared const was configurable, and may have been deleted in the
  // meanwhile. If so, re-introduce the variable in the context extension.
  if (attributes == ABSENT) {
382
    Handle<Context> declaration_context(context_arg->declaration_context());
383 384 385
    if (declaration_context->IsScriptContext()) {
      holder = handle(declaration_context->global_object(), isolate);
    } else {
386 387
      holder = handle(declaration_context->extension_object(), isolate);
      DCHECK(!holder.is_null());
388
    }
389
    CHECK(holder->IsJSObject());
390 391 392 393 394 395 396 397 398
  } else {
    // For JSContextExtensionObjects, the initializer can be run multiple times
    // if in a for loop: for (var i = 0; i < 2; i++) { const x = i; }. Only the
    // first assignment should go through. For JSGlobalObjects, additionally any
    // code can run in between that modifies the declared property.
    DCHECK(holder->IsJSGlobalObject() || holder->IsJSContextExtensionObject());

    LookupIterator it(holder, name, LookupIterator::HIDDEN_SKIP_INTERCEPTOR);
    Maybe<PropertyAttributes> maybe = JSReceiver::GetPropertyAttributes(&it);
399 400
    if (!maybe.IsJust()) return isolate->heap()->exception();
    PropertyAttributes old_attributes = maybe.FromJust();
401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419

    // Ignore if we can't reconfigure the value.
    if ((old_attributes & DONT_DELETE) != 0) {
      if ((old_attributes & READ_ONLY) != 0 ||
          it.state() == LookupIterator::ACCESSOR) {
        return *value;
      }
      attr = static_cast<PropertyAttributes>(old_attributes | READ_ONLY);
    }
  }

  RETURN_FAILURE_ON_EXCEPTION(
      isolate, JSObject::SetOwnPropertyIgnoreAttributes(
                   Handle<JSObject>::cast(holder), name, value, attr));

  return *value;
}


420 421
namespace {

422
// Find the arguments of the JavaScript function invocation that called
423
// into C++ code. Collect these in a newly allocated array of handles.
424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448
base::SmartArrayPointer<Handle<Object>> GetCallerArguments(Isolate* isolate,
                                                           int* total_argc) {
  // Find frame containing arguments passed to the caller.
  JavaScriptFrameIterator it(isolate);
  JavaScriptFrame* frame = it.frame();
  List<JSFunction*> functions(2);
  frame->GetFunctions(&functions);
  if (functions.length() > 1) {
    int inlined_jsframe_index = functions.length() - 1;
    TranslatedState translated_values(frame);
    translated_values.Prepare(false, frame->fp());

    int argument_count = 0;
    TranslatedFrame* translated_frame =
        translated_values.GetArgumentsInfoFromJSFrameIndex(
            inlined_jsframe_index, &argument_count);
    TranslatedFrame::iterator iter = translated_frame->begin();

    // Skip the function.
    iter++;

    // Skip the receiver.
    iter++;
    argument_count--;

449
    *total_argc = argument_count;
450 451 452 453 454 455
    base::SmartArrayPointer<Handle<Object>> param_data(
        NewArray<Handle<Object>>(*total_argc));
    bool should_deoptimize = false;
    for (int i = 0; i < argument_count; i++) {
      should_deoptimize = should_deoptimize || iter->IsMaterializedObject();
      Handle<Object> value = iter->GetValue();
456
      param_data[i] = value;
457 458 459 460 461 462 463 464 465 466 467 468 469
      iter++;
    }

    if (should_deoptimize) {
      translated_values.StoreMaterializedValuesAndDeopt();
    }

    return param_data;
  } else {
    it.AdvanceToArgumentsFrame();
    frame = it.frame();
    int args_count = frame->ComputeParametersCount();

470
    *total_argc = args_count;
471 472 473 474
    base::SmartArrayPointer<Handle<Object>> param_data(
        NewArray<Handle<Object>>(*total_argc));
    for (int i = 0; i < args_count; i++) {
      Handle<Object> val = Handle<Object>(frame->GetParameter(i), isolate);
475
      param_data[i] = val;
476 477 478 479 480 481
    }
    return param_data;
  }
}


482 483 484
template <typename T>
Handle<JSObject> NewSloppyArguments(Isolate* isolate, Handle<JSFunction> callee,
                                    T parameters, int argument_count) {
485
  CHECK(!IsSubclassConstructor(callee->shared()->kind()));
486
  DCHECK(callee->shared()->has_simple_parameters());
487 488 489 490
  Handle<JSObject> result =
      isolate->factory()->NewArgumentsObject(callee, argument_count);

  // Allocate the elements if needed.
491
  int parameter_count = callee->shared()->internal_formal_parameter_count();
492 493 494 495 496 497
  if (argument_count > 0) {
    if (parameter_count > 0) {
      int mapped_count = Min(argument_count, parameter_count);
      Handle<FixedArray> parameter_map =
          isolate->factory()->NewFixedArray(mapped_count + 2, NOT_TENURED);
      parameter_map->set_map(isolate->heap()->sloppy_arguments_elements_map());
498
      result->set_map(isolate->native_context()->fast_aliased_arguments_map());
499 500 501 502 503 504 505 506 507 508 509 510 511 512 513
      result->set_elements(*parameter_map);

      // Store the context and the arguments array at the beginning of the
      // parameter map.
      Handle<Context> context(isolate->context());
      Handle<FixedArray> arguments =
          isolate->factory()->NewFixedArray(argument_count, NOT_TENURED);
      parameter_map->set(0, *context);
      parameter_map->set(1, *arguments);

      // Loop over the actual parameters backwards.
      int index = argument_count - 1;
      while (index >= mapped_count) {
        // These go directly in the arguments array and have no
        // corresponding slot in the parameter map.
514
        arguments->set(index, parameters[index]);
515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533
        --index;
      }

      Handle<ScopeInfo> scope_info(callee->shared()->scope_info());
      while (index >= 0) {
        // Detect duplicate names to the right in the parameter list.
        Handle<String> name(scope_info->ParameterName(index));
        int context_local_count = scope_info->ContextLocalCount();
        bool duplicate = false;
        for (int j = index + 1; j < parameter_count; ++j) {
          if (scope_info->ParameterName(j) == *name) {
            duplicate = true;
            break;
          }
        }

        if (duplicate) {
          // This goes directly in the arguments array with a hole in the
          // parameter map.
534
          arguments->set(index, parameters[index]);
535 536 537 538 539 540 541 542 543 544 545
          parameter_map->set_the_hole(index + 2);
        } else {
          // The context index goes in the parameter map with a hole in the
          // arguments array.
          int context_index = -1;
          for (int j = 0; j < context_local_count; ++j) {
            if (scope_info->ContextLocalName(j) == *name) {
              context_index = j;
              break;
            }
          }
546

547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562
          DCHECK(context_index >= 0);
          arguments->set_the_hole(index);
          parameter_map->set(
              index + 2,
              Smi::FromInt(Context::MIN_CONTEXT_SLOTS + context_index));
        }

        --index;
      }
    } else {
      // If there is no aliasing, the arguments object elements are not
      // special in any way.
      Handle<FixedArray> elements =
          isolate->factory()->NewFixedArray(argument_count, NOT_TENURED);
      result->set_elements(*elements);
      for (int i = 0; i < argument_count; ++i) {
563
        elements->set(i, parameters[i]);
564 565 566 567 568 569 570
      }
    }
  }
  return result;
}


571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593
class HandleArguments BASE_EMBEDDED {
 public:
  explicit HandleArguments(Handle<Object>* array) : array_(array) {}
  Object* operator[](int index) { return *array_[index]; }

 private:
  Handle<Object>* array_;
};


class ParameterArguments BASE_EMBEDDED {
 public:
  explicit ParameterArguments(Object** parameters) : parameters_(parameters) {}
  Object*& operator[](int index) { return *(parameters_ - index - 1); }

 private:
  Object** parameters_;
};

}  // namespace


RUNTIME_FUNCTION(Runtime_NewSloppyArguments_Generic) {
594 595 596
  HandleScope scope(isolate);
  DCHECK(args.length() == 1);
  CONVERT_ARG_HANDLE_CHECKED(JSFunction, callee, 0);
597
  // This generic runtime function can also be used when the caller has been
598
  // inlined, we use the slow but accurate {GetCallerArguments}.
599 600
  int argument_count = 0;
  base::SmartArrayPointer<Handle<Object>> arguments =
601
      GetCallerArguments(isolate, &argument_count);
602 603 604
  HandleArguments argument_getter(arguments.get());
  return *NewSloppyArguments(isolate, callee, argument_getter, argument_count);
}
605

606

607
RUNTIME_FUNCTION(Runtime_NewStrictArguments) {
608
  HandleScope scope(isolate);
609
  DCHECK_EQ(1, args.length());
610 611
  CONVERT_ARG_HANDLE_CHECKED(JSFunction, callee, 0);
  // This generic runtime function can also be used when the caller has been
612
  // inlined, we use the slow but accurate {GetCallerArguments}.
613 614
  int argument_count = 0;
  base::SmartArrayPointer<Handle<Object>> arguments =
615
      GetCallerArguments(isolate, &argument_count);
616 617 618 619 620 621 622 623 624 625 626 627 628
  Handle<JSObject> result =
      isolate->factory()->NewArgumentsObject(callee, argument_count);
  if (argument_count) {
    Handle<FixedArray> array =
        isolate->factory()->NewUninitializedFixedArray(argument_count);
    DisallowHeapAllocation no_gc;
    WriteBarrierMode mode = array->GetWriteBarrierMode(no_gc);
    for (int i = 0; i < argument_count; i++) {
      array->set(i, *arguments[i], mode);
    }
    result->set_elements(*array);
  }
  return *result;
629 630 631
}


632
RUNTIME_FUNCTION(Runtime_NewRestParameter) {
633
  HandleScope scope(isolate);
634
  DCHECK_EQ(1, args.length());
635
  CONVERT_ARG_HANDLE_CHECKED(JSFunction, callee, 0)
636
  int start_index = callee->shared()->internal_formal_parameter_count();
637
  // This generic runtime function can also be used when the caller has been
638
  // inlined, we use the slow but accurate {GetCallerArguments}.
639 640
  int argument_count = 0;
  base::SmartArrayPointer<Handle<Object>> arguments =
641
      GetCallerArguments(isolate, &argument_count);
642 643 644 645 646 647 648 649 650 651 652 653 654
  int num_elements = std::max(0, argument_count - start_index);
  Handle<JSObject> result = isolate->factory()->NewJSArray(
      FAST_ELEMENTS, num_elements, num_elements, Strength::WEAK,
      DONT_INITIALIZE_ARRAY_ELEMENTS);
  {
    DisallowHeapAllocation no_gc;
    FixedArray* elements = FixedArray::cast(result->elements());
    WriteBarrierMode mode = result->GetWriteBarrierMode(no_gc);
    for (int i = 0; i < num_elements; i++) {
      elements->set(i, *arguments[i + start_index], mode);
    }
  }
  return *result;
655 656 657
}


658 659 660 661 662 663
RUNTIME_FUNCTION(Runtime_NewSloppyArguments) {
  HandleScope scope(isolate);
  DCHECK(args.length() == 3);
  CONVERT_ARG_HANDLE_CHECKED(JSFunction, callee, 0);
  Object** parameters = reinterpret_cast<Object**>(args[1]);
  CONVERT_SMI_ARG_CHECKED(argument_count, 2);
664 665 666 667 668 669
#ifdef DEBUG
  // This runtime function does not materialize the correct arguments when the
  // caller has been inlined, better make sure we are not hitting that case.
  JavaScriptFrameIterator it(isolate);
  DCHECK(!it.frame()->HasInlinedFrames());
#endif  // DEBUG
670 671
  ParameterArguments argument_getter(parameters);
  return *NewSloppyArguments(isolate, callee, argument_getter, argument_count);
672 673 674
}


675
RUNTIME_FUNCTION(Runtime_NewClosure) {
676
  HandleScope scope(isolate);
677
  DCHECK_EQ(1, args.length());
678
  CONVERT_ARG_HANDLE_CHECKED(SharedFunctionInfo, shared, 0);
679
  Handle<Context> context(isolate->context(), isolate);
680
  return *isolate->factory()->NewFunctionFromSharedFunctionInfo(shared, context,
681
                                                                NOT_TENURED);
682 683 684
}


685
RUNTIME_FUNCTION(Runtime_NewClosure_Tenured) {
686
  HandleScope scope(isolate);
687 688 689
  DCHECK_EQ(1, args.length());
  CONVERT_ARG_HANDLE_CHECKED(SharedFunctionInfo, shared, 0);
  Handle<Context> context(isolate->context(), isolate);
690 691 692
  // The caller ensures that we pretenure closures that are assigned
  // directly to properties.
  return *isolate->factory()->NewFunctionFromSharedFunctionInfo(shared, context,
693
                                                                TENURED);
694 695
}

696
static Object* FindNameClash(Handle<ScopeInfo> scope_info,
697
                             Handle<JSGlobalObject> global_object,
698
                             Handle<ScriptContextTable> script_context) {
699 700 701 702
  Isolate* isolate = scope_info->GetIsolate();
  for (int var = 0; var < scope_info->ContextLocalCount(); var++) {
    Handle<String> name(scope_info->ContextLocalName(var));
    VariableMode mode = scope_info->ContextLocalMode(var);
703 704 705
    ScriptContextTable::LookupResult lookup;
    if (ScriptContextTable::Lookup(script_context, name, &lookup)) {
      if (IsLexicalVariableMode(mode) || IsLexicalVariableMode(lookup.mode)) {
706 707 708 709 710 711 712 713
        return ThrowRedeclarationError(isolate, name);
      }
    }

    if (IsLexicalVariableMode(mode)) {
      LookupIterator it(global_object, name,
                        LookupIterator::HIDDEN_SKIP_INTERCEPTOR);
      Maybe<PropertyAttributes> maybe = JSReceiver::GetPropertyAttributes(&it);
714 715
      if (!maybe.IsJust()) return isolate->heap()->exception();
      if ((maybe.FromJust() & DONT_DELETE) != 0) {
716 717 718
        return ThrowRedeclarationError(isolate, name);
      }

719
      JSGlobalObject::InvalidatePropertyCell(global_object, name);
720 721 722 723 724
    }
  }
  return isolate->heap()->undefined_value();
}

725

726
RUNTIME_FUNCTION(Runtime_NewScriptContext) {
727 728 729 730 731
  HandleScope scope(isolate);
  DCHECK(args.length() == 2);

  CONVERT_ARG_HANDLE_CHECKED(JSFunction, function, 0);
  CONVERT_ARG_HANDLE_CHECKED(ScopeInfo, scope_info, 1);
732
  Handle<JSGlobalObject> global_object(function->context()->global_object());
733
  Handle<Context> native_context(global_object->native_context());
734 735
  Handle<ScriptContextTable> script_context_table(
      native_context->script_context_table());
736 737

  Object* name_clash_result =
738
      FindNameClash(scope_info, global_object, script_context_table);
739 740
  if (isolate->has_pending_exception()) return name_clash_result;

741 742 743
  // Script contexts have a canonical empty function as their closure, not the
  // anonymous closure containing the global code.  See
  // FullCodeGenerator::PushFunctionArgumentForContextAllocation.
744 745
  Handle<JSFunction> closure(
      function->shared()->IsBuiltin() ? *function : native_context->closure());
746
  Handle<Context> result =
747
      isolate->factory()->NewScriptContext(closure, scope_info);
748

749 750
  result->InitializeGlobalSlots();

751
  DCHECK(function->context() == isolate->context());
752
  DCHECK(*global_object == result->global_object());
753

754 755 756
  Handle<ScriptContextTable> new_script_context_table =
      ScriptContextTable::Extend(script_context_table, result);
  native_context->set_script_context_table(*new_script_context_table);
757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774
  return *result;
}


RUNTIME_FUNCTION(Runtime_NewFunctionContext) {
  HandleScope scope(isolate);
  DCHECK(args.length() == 1);

  CONVERT_ARG_HANDLE_CHECKED(JSFunction, function, 0);

  DCHECK(function->context() == isolate->context());
  int length = function->shared()->scope_info()->ContextLength();
  return *isolate->factory()->NewFunctionContext(length, function);
}


RUNTIME_FUNCTION(Runtime_PushWithContext) {
  HandleScope scope(isolate);
775
  DCHECK_EQ(2, args.length());
776
  CONVERT_ARG_HANDLE_CHECKED(JSReceiver, extension_object, 0);
777
  CONVERT_ARG_HANDLE_CHECKED(JSFunction, function, 1);
778 779 780 781 782 783 784 785 786 787
  Handle<Context> current(isolate->context());
  Handle<Context> context =
      isolate->factory()->NewWithContext(function, current, extension_object);
  isolate->set_context(*context);
  return *context;
}


RUNTIME_FUNCTION(Runtime_PushCatchContext) {
  HandleScope scope(isolate);
788
  DCHECK_EQ(3, args.length());
789 790
  CONVERT_ARG_HANDLE_CHECKED(String, name, 0);
  CONVERT_ARG_HANDLE_CHECKED(Object, thrown_object, 1);
791
  CONVERT_ARG_HANDLE_CHECKED(JSFunction, function, 2);
792 793 794 795 796 797 798 799 800 801
  Handle<Context> current(isolate->context());
  Handle<Context> context = isolate->factory()->NewCatchContext(
      function, current, name, thrown_object);
  isolate->set_context(*context);
  return *context;
}


RUNTIME_FUNCTION(Runtime_PushBlockContext) {
  HandleScope scope(isolate);
802
  DCHECK_EQ(2, args.length());
803
  CONVERT_ARG_HANDLE_CHECKED(ScopeInfo, scope_info, 0);
804
  CONVERT_ARG_HANDLE_CHECKED(JSFunction, function, 1);
805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827
  Handle<Context> current(isolate->context());
  Handle<Context> context =
      isolate->factory()->NewBlockContext(function, current, scope_info);
  isolate->set_context(*context);
  return *context;
}


RUNTIME_FUNCTION(Runtime_IsJSModule) {
  SealHandleScope shs(isolate);
  DCHECK(args.length() == 1);
  CONVERT_ARG_CHECKED(Object, obj, 0);
  return isolate->heap()->ToBoolean(obj->IsJSModule());
}


RUNTIME_FUNCTION(Runtime_PushModuleContext) {
  SealHandleScope shs(isolate);
  DCHECK(args.length() == 2);
  CONVERT_SMI_ARG_CHECKED(index, 0);

  if (!args[1]->IsScopeInfo()) {
    // Module already initialized. Find hosting context and retrieve context.
828
    Context* host = Context::cast(isolate->context())->script_context();
829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845
    Context* context = Context::cast(host->get(index));
    DCHECK(context->previous() == isolate->context());
    isolate->set_context(context);
    return context;
  }

  CONVERT_ARG_HANDLE_CHECKED(ScopeInfo, scope_info, 1);

  // Allocate module context.
  HandleScope scope(isolate);
  Factory* factory = isolate->factory();
  Handle<Context> context = factory->NewModuleContext(scope_info);
  Handle<JSModule> module = factory->NewJSModule(context, scope_info);
  context->set_module(*module);
  Context* previous = isolate->context();
  context->set_previous(previous);
  context->set_closure(previous->closure());
846
  context->set_native_context(previous->native_context());
847 848 849
  isolate->set_context(*context);

  // Find hosting scope and initialize internal variable holding module there.
850
  previous->script_context()->set(index, *context);
851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875

  return *context;
}


RUNTIME_FUNCTION(Runtime_DeclareModules) {
  HandleScope scope(isolate);
  DCHECK(args.length() == 1);
  CONVERT_ARG_HANDLE_CHECKED(FixedArray, descriptions, 0);
  Context* host_context = isolate->context();

  for (int i = 0; i < descriptions->length(); ++i) {
    Handle<ModuleInfo> description(ModuleInfo::cast(descriptions->get(i)));
    int host_index = description->host_index();
    Handle<Context> context(Context::cast(host_context->get(host_index)));
    Handle<JSModule> module(context->module());

    for (int j = 0; j < description->length(); ++j) {
      Handle<String> name(description->name(j));
      VariableMode mode = description->mode(j);
      int index = description->index(j);
      switch (mode) {
        case VAR:
        case LET:
        case CONST:
876 877
        case CONST_LEGACY:
        case IMPORT: {
878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895
          PropertyAttributes attr =
              IsImmutableVariableMode(mode) ? FROZEN : SEALED;
          Handle<AccessorInfo> info =
              Accessors::MakeModuleExport(name, index, attr);
          Handle<Object> result =
              JSObject::SetAccessor(module, info).ToHandleChecked();
          DCHECK(!result->IsUndefined());
          USE(result);
          break;
        }
        case TEMPORARY:
        case DYNAMIC:
        case DYNAMIC_GLOBAL:
        case DYNAMIC_LOCAL:
          UNREACHABLE();
      }
    }

896 897
    if (JSObject::PreventExtensions(module, Object::THROW_ON_ERROR)
            .IsNothing()) {
898
      DCHECK(false);
899
    }
900 901 902 903 904 905 906 907 908
  }

  DCHECK(!isolate->has_pending_exception());
  return isolate->heap()->undefined_value();
}


RUNTIME_FUNCTION(Runtime_DeleteLookupSlot) {
  HandleScope scope(isolate);
909 910
  DCHECK_EQ(1, args.length());
  CONVERT_ARG_HANDLE_CHECKED(String, name, 0);
911 912 913

  int index;
  PropertyAttributes attributes;
914 915 916
  BindingFlags flags;
  Handle<Object> holder = isolate->context()->Lookup(
      name, FOLLOW_CHAINS, &index, &attributes, &flags);
917 918 919

  // If the slot was not found the result is true.
  if (holder.is_null()) {
920 921
    // In case of JSProxy, an exception might have been thrown.
    if (isolate->has_pending_exception()) return isolate->heap()->exception();
922 923 924 925 926 927 928 929
    return isolate->heap()->true_value();
  }

  // If the slot was found in a context, it should be DONT_DELETE.
  if (holder->IsContext()) {
    return isolate->heap()->false_value();
  }

930
  // The slot was found in a JSReceiver, either a context extension object,
931 932
  // the global object, or the subject of a with.  Try to delete it
  // (respecting DONT_DELETE).
933
  Handle<JSReceiver> object = Handle<JSReceiver>::cast(holder);
neis's avatar
neis committed
934 935 936
  Maybe<bool> result = JSReceiver::DeleteProperty(object, name);
  MAYBE_RETURN(result, isolate->heap()->exception());
  return isolate->heap()->ToBoolean(result.FromJust());
937 938 939
}


940
namespace {
941

942 943 944 945
MaybeHandle<Object> LoadLookupSlot(Handle<String> name,
                                   Object::ShouldThrow should_throw,
                                   Handle<Object>* receiver_return = nullptr) {
  Isolate* const isolate = name->GetIsolate();
946 947 948

  int index;
  PropertyAttributes attributes;
949 950 951 952
  BindingFlags flags;
  Handle<Object> holder = isolate->context()->Lookup(
      name, FOLLOW_CHAINS, &index, &attributes, &flags);
  if (isolate->has_pending_exception()) return MaybeHandle<Object>();
953

954
  if (index != Context::kNotFound) {
955 956 957 958
    DCHECK(holder->IsContext());
    // If the "property" we were looking for is a local variable, the
    // receiver is the global object; see ECMA-262, 3rd., 10.1.6 and 10.2.3.
    Handle<Object> receiver = isolate->factory()->undefined_value();
959
    Handle<Object> value = handle(Context::cast(*holder)->get(index), isolate);
960
    // Check for uninitialized bindings.
961
    switch (flags) {
962 963 964
      case MUTABLE_CHECK_INITIALIZED:
      case IMMUTABLE_CHECK_INITIALIZED_HARMONY:
        if (value->IsTheHole()) {
965 966 967 968 969 970 971 972 973
          THROW_NEW_ERROR(isolate,
                          NewReferenceError(MessageTemplate::kNotDefined, name),
                          Object);
        }
      // FALLTHROUGH
      case IMMUTABLE_CHECK_INITIALIZED:
        if (value->IsTheHole()) {
          DCHECK(attributes & READ_ONLY);
          value = isolate->factory()->undefined_value();
974 975 976 977 978 979
        }
      // FALLTHROUGH
      case MUTABLE_IS_INITIALIZED:
      case IMMUTABLE_IS_INITIALIZED:
      case IMMUTABLE_IS_INITIALIZED_HARMONY:
        DCHECK(!value->IsTheHole());
980 981
        if (receiver_return) *receiver_return = receiver;
        return value;
982
      case MISSING_BINDING:
983
        break;
984
    }
985
    UNREACHABLE();
986 987 988 989 990 991 992 993 994
  }

  // Otherwise, if the slot was found the holder is a context extension
  // object, subject of a with, or a global object.  We read the named
  // property from it.
  if (!holder.is_null()) {
    // No need to unhole the value here.  This is taken care of by the
    // GetProperty function.
    Handle<Object> value;
995 996 997 998 999 1000 1001 1002 1003 1004
    ASSIGN_RETURN_ON_EXCEPTION(
        isolate, value, Object::GetProperty(holder, name),
        Object);
    if (receiver_return) {
      *receiver_return =
          (holder->IsJSGlobalObject() || holder->IsJSContextExtensionObject())
              ? Handle<Object>::cast(isolate->factory()->undefined_value())
              : holder;
    }
    return value;
1005 1006
  }

1007
  if (should_throw == Object::THROW_ON_ERROR) {
1008
    // The property doesn't exist - throw exception.
1009 1010
    THROW_NEW_ERROR(
        isolate, NewReferenceError(MessageTemplate::kNotDefined, name), Object);
1011
  }
1012 1013 1014 1015

  // The property doesn't exist - return undefined.
  if (receiver_return) *receiver_return = isolate->factory()->undefined_value();
  return isolate->factory()->undefined_value();
1016 1017
}

1018
}  // namespace
1019

1020 1021 1022 1023 1024 1025 1026 1027 1028

RUNTIME_FUNCTION(Runtime_LoadLookupSlot) {
  HandleScope scope(isolate);
  DCHECK_EQ(1, args.length());
  CONVERT_ARG_HANDLE_CHECKED(String, name, 0);
  Handle<Object> value;
  ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
      isolate, value, LoadLookupSlot(name, Object::THROW_ON_ERROR));
  return *value;
1029 1030 1031
}


1032 1033 1034 1035 1036 1037 1038 1039
RUNTIME_FUNCTION(Runtime_LoadLookupSlotInsideTypeof) {
  HandleScope scope(isolate);
  DCHECK_EQ(1, args.length());
  CONVERT_ARG_HANDLE_CHECKED(String, name, 0);
  Handle<Object> value;
  ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
      isolate, value, LoadLookupSlot(name, Object::DONT_THROW));
  return *value;
1040 1041 1042
}


1043
RUNTIME_FUNCTION_RETURN_PAIR(Runtime_LoadLookupSlotForCall) {
1044
  HandleScope scope(isolate);
1045 1046 1047 1048 1049 1050 1051 1052 1053 1054
  DCHECK_EQ(1, args.length());
  DCHECK(args[0]->IsString());
  Handle<String> name = args.at<String>(0);
  Handle<Object> value;
  Handle<Object> receiver;
  ASSIGN_RETURN_ON_EXCEPTION_VALUE(
      isolate, value, LoadLookupSlot(name, Object::THROW_ON_ERROR, &receiver),
      MakePair(isolate->heap()->exception(), nullptr));
  return MakePair(*value, *receiver);
}
1055

1056 1057 1058 1059 1060 1061 1062

namespace {

MaybeHandle<Object> StoreLookupSlot(Handle<String> name, Handle<Object> value,
                                    LanguageMode language_mode) {
  Isolate* const isolate = name->GetIsolate();
  Handle<Context> context(isolate->context(), isolate);
1063 1064 1065

  int index;
  PropertyAttributes attributes;
1066
  BindingFlags flags;
1067
  Handle<Object> holder =
1068
      context->Lookup(name, FOLLOW_CHAINS, &index, &attributes, &flags);
1069 1070
  if (holder.is_null()) {
    // In case of JSProxy, an exception might have been thrown.
1071
    if (isolate->has_pending_exception()) return MaybeHandle<Object>();
1072
  }
1073 1074

  // The property was found in a context slot.
1075
  if (index != Context::kNotFound) {
1076 1077
    if ((flags == MUTABLE_CHECK_INITIALIZED ||
         flags == IMMUTABLE_CHECK_INITIALIZED_HARMONY) &&
1078
        Handle<Context>::cast(holder)->is_the_hole(index)) {
1079 1080 1081
      THROW_NEW_ERROR(isolate,
                      NewReferenceError(MessageTemplate::kNotDefined, name),
                      Object);
1082
    }
1083 1084
    if ((attributes & READ_ONLY) == 0) {
      Handle<Context>::cast(holder)->set(index, *value);
1085
    } else if (is_strict(language_mode)) {
1086
      // Setting read only property in strict mode.
1087 1088 1089
      THROW_NEW_ERROR(isolate,
                      NewTypeError(MessageTemplate::kStrictCannotAssign, name),
                      Object);
1090
    }
1091
    return value;
1092 1093 1094 1095 1096 1097 1098 1099 1100
  }

  // Slow case: The property is not in a context slot.  It is either in a
  // context extension object, a property of the subject of a with, or a
  // property of the global object.
  Handle<JSReceiver> object;
  if (attributes != ABSENT) {
    // The property exists on the holder.
    object = Handle<JSReceiver>::cast(holder);
1101
  } else if (is_strict(language_mode)) {
1102
    // If absent in strict mode: throw.
1103 1104
    THROW_NEW_ERROR(
        isolate, NewReferenceError(MessageTemplate::kNotDefined, name), Object);
1105 1106 1107 1108 1109
  } else {
    // If absent in sloppy mode: add the property to the global object.
    object = Handle<JSReceiver>(context->global_object());
  }

1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128
  ASSIGN_RETURN_ON_EXCEPTION(
      isolate, value, Object::SetProperty(object, name, value, language_mode),
      Object);
  return value;
}

}  // namespace


RUNTIME_FUNCTION(Runtime_StoreLookupSlot_Sloppy) {
  HandleScope scope(isolate);
  DCHECK_EQ(2, args.length());
  CONVERT_ARG_HANDLE_CHECKED(String, name, 0);
  CONVERT_ARG_HANDLE_CHECKED(Object, value, 1);
  ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, value,
                                     StoreLookupSlot(name, value, SLOPPY));
  return *value;
}

1129

1130 1131 1132 1133 1134 1135 1136
RUNTIME_FUNCTION(Runtime_StoreLookupSlot_Strict) {
  HandleScope scope(isolate);
  DCHECK_EQ(2, args.length());
  CONVERT_ARG_HANDLE_CHECKED(String, name, 0);
  CONVERT_ARG_HANDLE_CHECKED(Object, value, 1);
  ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, value,
                                     StoreLookupSlot(name, value, STRICT));
1137 1138 1139
  return *value;
}

1140 1141
}  // namespace internal
}  // namespace v8