runtime-scopes.cc 37.6 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 6
#include <memory>

7
#include "src/accessors.h"
8
#include "src/arguments-inl.h"
9
#include "src/ast/scopes.h"
10
#include "src/bootstrapper.h"
11
#include "src/counters.h"
12
#include "src/deoptimizer.h"
13
#include "src/frames-inl.h"
14
#include "src/isolate-inl.h"
15
#include "src/message-template.h"
16
#include "src/objects/heap-object-inl.h"
17
#include "src/objects/module-inl.h"
18
#include "src/objects/smi.h"
19
#include "src/runtime/runtime-utils.h"
20 21 22 23

namespace v8 {
namespace internal {

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

namespace {

32 33
enum class RedeclarationType { kSyntaxError = 0, kTypeError = 1 };

34 35
Object* ThrowRedeclarationError(Isolate* isolate, Handle<String> name,
                                RedeclarationType redeclaration_type) {
36
  HandleScope scope(isolate);
37 38 39 40 41 42 43
  if (redeclaration_type == RedeclarationType::kSyntaxError) {
    THROW_NEW_ERROR_RETURN_FAILURE(
        isolate, NewSyntaxError(MessageTemplate::kVarRedeclaration, name));
  } else {
    THROW_NEW_ERROR_RETURN_FAILURE(
        isolate, NewTypeError(MessageTemplate::kVarRedeclaration, name));
  }
44 45 46 47
}


// May throw a RedeclarationError.
48 49 50
Object* DeclareGlobal(
    Isolate* isolate, Handle<JSGlobalObject> global, Handle<String> name,
    Handle<Object> value, PropertyAttributes attr, bool is_var,
51
    bool is_function_declaration, RedeclarationType redeclaration_type,
52
    Handle<FeedbackVector> feedback_vector = Handle<FeedbackVector>(),
53
    FeedbackSlot slot = FeedbackSlot::Invalid()) {
54
  Handle<ScriptContextTable> script_contexts(
55
      global->native_context()->script_context_table(), isolate);
56
  ScriptContextTable::LookupResult lookup;
57
  if (ScriptContextTable::Lookup(isolate, script_contexts, name, &lookup) &&
58
      IsLexicalVariableMode(lookup.mode)) {
59 60 61 62 63
    // ES#sec-globaldeclarationinstantiation 6.a:
    // If envRec.HasLexicalDeclaration(name) is true, throw a SyntaxError
    // exception.
    return ThrowRedeclarationError(isolate, name,
                                   RedeclarationType::kSyntaxError);
64 65
  }

66
  // Do the lookup own properties only, see ES5 erratum.
67 68 69 70 71 72 73 74
  LookupIterator::Configuration lookup_config(
      LookupIterator::Configuration::OWN_SKIP_INTERCEPTOR);
  if (is_function_declaration) {
    // For function declarations, use the interceptor on the declaration. For
    // non-functions, use it only on initialization.
    lookup_config = LookupIterator::Configuration::OWN;
  }
  LookupIterator it(global, name, global, lookup_config);
75
  Maybe<PropertyAttributes> maybe = JSReceiver::GetPropertyAttributes(&it);
76
  if (maybe.IsNothing()) return ReadOnlyRoots(isolate).exception();
77 78

  if (it.IsFound()) {
79
    PropertyAttributes old_attributes = maybe.FromJust();
80 81 82
    // The name was declared before; check for conflicting re-declarations.

    // Skip var re-declarations.
83
    if (is_var) return ReadOnlyRoots(isolate).undefined_value();
84

85
    DCHECK(is_function_declaration);
86 87 88
    if ((old_attributes & DONT_DELETE) != 0) {
      // Only allow reconfiguring globals to functions in user code (no
      // natives, which are marked as read-only).
89
      DCHECK_EQ(attr & READ_ONLY, 0);
90 91 92

      // Check whether we can reconfigure the existing property into a
      // function.
93
      if (old_attributes & READ_ONLY || old_attributes & DONT_ENUM ||
94
          (it.state() == LookupIterator::ACCESSOR)) {
95
        // ECMA-262 section 15.1.11 GlobalDeclarationInstantiation 5.d:
96
        // If hasRestrictedGlobal is true, throw a SyntaxError exception.
97
        // ECMA-262 section 18.2.1.3 EvalDeclarationInstantiation 8.a.iv.1.b:
98 99
        // If fnDefinable is false, throw a TypeError exception.
        return ThrowRedeclarationError(isolate, name, redeclaration_type);
100 101 102 103
      }
      // If the existing property is not configurable, keep its attributes. Do
      attr = old_attributes;
    }
104 105 106 107 108 109 110 111

    // 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();
112 113
  }

114 115 116 117
  if (is_function_declaration) {
    it.Restart();
  }

118
  // Define or redefine own property.
119 120
  RETURN_FAILURE_ON_EXCEPTION(
      isolate, JSObject::DefineOwnPropertyIgnoreAttributes(&it, value, attr));
121

122 123
  if (!feedback_vector.is_null() &&
      it.state() != LookupIterator::State::INTERCEPTOR) {
124 125 126 127 128
    DCHECK_EQ(*global, *it.GetHolder<Object>());
    // Preinitialize the feedback slot if the global object does not have
    // named interceptor or the interceptor is not masking.
    if (!global->HasNamedInterceptor() ||
        global->GetNamedInterceptor()->non_masking()) {
129
      FeedbackNexus nexus(feedback_vector, slot);
130 131 132
      nexus.ConfigurePropertyCellMode(it.GetPropertyCell());
    }
  }
133
  return ReadOnlyRoots(isolate).undefined_value();
134 135
}

136
Object* DeclareGlobals(Isolate* isolate, Handle<FixedArray> declarations,
137
                       int flags, Handle<FeedbackVector> feedback_vector) {
138
  HandleScope scope(isolate);
139
  Handle<JSGlobalObject> global(isolate->global_object());
140
  Handle<Context> context(isolate->context(), isolate);
141 142

  // Traverse the name/value pairs and set the properties.
143
  int length = declarations->length();
144
  FOR_WITH_HANDLE_SCOPE(isolate, int, i = 0, i, i < length, i += 4, {
145
    Handle<String> name(String::cast(declarations->get(i)), isolate);
jgruber's avatar
jgruber committed
146
    FeedbackSlot slot(Smi::ToInt(declarations->get(i + 1)));
147 148
    Handle<Object> possibly_feedback_cell_slot(declarations->get(i + 2),
                                               isolate);
149
    Handle<Object> initial_value(declarations->get(i + 3), isolate);
150

151
    bool is_var = initial_value->IsUndefined(isolate);
152
    bool is_function = initial_value->IsSharedFunctionInfo();
153
    DCHECK_EQ(1, BoolToInt(is_var) + BoolToInt(is_function));
154 155 156

    Handle<Object> value;
    if (is_function) {
157 158 159 160 161 162 163 164 165 166 167 168 169 170
      // If feedback vector was not allocated for this function, then we don't
      // have any information about number of closures. Use NoFeedbackCell to
      // indicate that.
      Handle<FeedbackCell> feedback_cell =
          isolate->factory()->no_feedback_cell();
      if (!feedback_vector.is_null()) {
        DCHECK(possibly_feedback_cell_slot->IsSmi());
        FeedbackSlot feedback_cells_slot(
            Smi::ToInt(*possibly_feedback_cell_slot));
        feedback_cell = Handle<FeedbackCell>(
            FeedbackCell::cast(feedback_vector->Get(feedback_cells_slot)
                                   ->GetHeapObjectAssumeStrong()),
            isolate);
      }
171 172 173 174
      // Copy the function and update its context. Use it as value.
      Handle<SharedFunctionInfo> shared =
          Handle<SharedFunctionInfo>::cast(initial_value);
      Handle<JSFunction> function =
175
          isolate->factory()->NewFunctionFromSharedFunctionInfo(
176
              shared, context, feedback_cell, TENURED);
177 178 179 180 181 182 183 184 185 186 187
      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_function && is_native) attr |= READ_ONLY;
188
    if (!is_eval) attr |= DONT_DELETE;
189

190 191
    // ES#sec-globaldeclarationinstantiation 5.d:
    // If hasRestrictedGlobal is true, throw a SyntaxError exception.
192
    Object* result = DeclareGlobal(
193
        isolate, global, name, value, static_cast<PropertyAttributes>(attr),
194 195
        is_var, is_function, RedeclarationType::kSyntaxError, feedback_vector,
        slot);
196
    if (isolate->has_pending_exception()) return result;
197
  });
198

199
  return ReadOnlyRoots(isolate).undefined_value();
200 201
}

202 203 204 205 206 207
}  // namespace

RUNTIME_FUNCTION(Runtime_DeclareGlobals) {
  HandleScope scope(isolate);
  DCHECK_EQ(3, args.length());

208
  CONVERT_ARG_HANDLE_CHECKED(FixedArray, declarations, 0);
209 210 211
  CONVERT_SMI_ARG_CHECKED(flags, 1);
  CONVERT_ARG_HANDLE_CHECKED(JSFunction, closure, 2);

212 213 214 215 216
  Handle<FeedbackVector> feedback_vector = Handle<FeedbackVector>();
  if (closure->has_feedback_vector()) {
    feedback_vector =
        Handle<FeedbackVector>(closure->feedback_vector(), isolate);
  }
217
  return DeclareGlobals(isolate, declarations, flags, feedback_vector);
218
}
219

220
namespace {
221

222 223
Object* DeclareEvalHelper(Isolate* isolate, Handle<String> name,
                          Handle<Object> value) {
224 225 226 227
  // Declarations are always made in a function, native, eval, or script
  // context, or a declaration block scope. Since this is called from eval, the
  // context passed is the context of the caller, which may be some nested
  // context and not the declaration context.
228 229
  Handle<Context> context_arg(isolate->context(), isolate);
  Handle<Context> context(context_arg->declaration_context(), isolate);
230

231
  DCHECK(context->IsFunctionContext() || context->IsNativeContext() ||
232
         context->IsScriptContext() || context->IsEvalContext() ||
233 234
         (context->IsBlockContext() &&
          context->scope_info()->is_declaration_scope()));
235 236 237 238

  bool is_function = value->IsJSFunction();
  bool is_var = !is_function;
  DCHECK(!is_var || value->IsUndefined(isolate));
239 240 241

  int index;
  PropertyAttributes attributes;
242
  InitializationFlag init_flag;
243
  VariableMode mode;
244

245
  // Check for a conflict with a lexically scoped variable
246 247 248
  const ContextLookupFlags lookup_flags = static_cast<ContextLookupFlags>(
      FOLLOW_CONTEXT_CHAIN | STOP_AT_DECLARATION_SCOPE | SKIP_WITH_CONTEXT);
  context_arg->Lookup(name, lookup_flags, &index, &attributes, &init_flag,
249 250
                      &mode);
  if (attributes != ABSENT && IsLexicalVariableMode(mode)) {
251 252 253 254 255 256 257
    // ES#sec-evaldeclarationinstantiation 5.a.i.1:
    // If varEnvRec.HasLexicalDeclaration(name) is true, throw a SyntaxError
    // exception.
    // ES#sec-evaldeclarationinstantiation 5.d.ii.2.a.i:
    // Throw a SyntaxError exception.
    return ThrowRedeclarationError(isolate, name,
                                   RedeclarationType::kSyntaxError);
258 259 260
  }

  Handle<Object> holder = context->Lookup(name, DONT_FOLLOW_CHAINS, &index,
261
                                          &attributes, &init_flag, &mode);
262
  DCHECK(holder.is_null() || !holder->IsModule());
263
  DCHECK(!isolate->has_pending_exception());
264 265 266

  Handle<JSObject> object;

267
  if (attributes != ABSENT && holder->IsJSGlobalObject()) {
268 269
    // ES#sec-evaldeclarationinstantiation 8.a.iv.1.b:
    // If fnDefinable is false, throw a TypeError exception.
270 271 272
    return DeclareGlobal(isolate, Handle<JSGlobalObject>::cast(holder), name,
                         value, NONE, is_var, is_function,
                         RedeclarationType::kTypeError);
273
  }
274
  if (context_arg->extension()->IsJSGlobalObject()) {
275 276
    Handle<JSGlobalObject> global(
        JSGlobalObject::cast(context_arg->extension()), isolate);
277 278
    return DeclareGlobal(isolate, global, name, value, NONE, is_var,
                         is_function, RedeclarationType::kTypeError);
279 280 281 282
  } else if (context->IsScriptContext()) {
    DCHECK(context->global_object()->IsJSGlobalObject());
    Handle<JSGlobalObject> global(
        JSGlobalObject::cast(context->global_object()), isolate);
283 284
    return DeclareGlobal(isolate, global, name, value, NONE, is_var,
                         is_function, RedeclarationType::kTypeError);
285
  }
286 287

  if (attributes != ABSENT) {
288
    DCHECK_EQ(NONE, attributes);
289 290

    // Skip var re-declarations.
291
    if (is_var) return ReadOnlyRoots(isolate).undefined_value();
292 293

    DCHECK(is_function);
294
    if (index != Context::kNotFound) {
295
      DCHECK(holder.is_identical_to(context));
296
      context->set(index, *value);
297
      return ReadOnlyRoots(isolate).undefined_value();
298 299 300 301 302
    }

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

  } else if (context->has_extension()) {
303
    object = handle(context->extension_object(), isolate);
304 305
    DCHECK(object->IsJSContextExtensionObject() || object->IsJSGlobalObject());
  } else {
306 307 308 309 310 311
    // Sloppy varblock and function contexts might not have an extension object
    // yet. Sloppy eval will never have an extension object, as vars are hoisted
    // out, and lets are known statically.
    DCHECK((context->IsBlockContext() &&
            context->scope_info()->is_declaration_scope()) ||
           context->IsFunctionContext());
312 313
    object =
        isolate->factory()->NewJSObject(isolate->context_extension_function());
314

315
    context->set_extension(*object);
316 317 318
  }

  RETURN_FAILURE_ON_EXCEPTION(isolate, JSObject::SetOwnPropertyIgnoreAttributes(
319
                                           object, name, value, NONE));
320

321
  return ReadOnlyRoots(isolate).undefined_value();
322 323
}

324 325
}  // namespace

326
RUNTIME_FUNCTION(Runtime_DeclareEvalFunction) {
327
  HandleScope scope(isolate);
328
  DCHECK_EQ(2, args.length());
329
  CONVERT_ARG_HANDLE_CHECKED(String, name, 0);
330 331
  CONVERT_ARG_HANDLE_CHECKED(Object, value, 1);
  return DeclareEvalHelper(isolate, name, value);
332 333
}

334 335 336 337 338 339 340
RUNTIME_FUNCTION(Runtime_DeclareEvalVar) {
  HandleScope scope(isolate);
  DCHECK_EQ(1, args.length());
  CONVERT_ARG_HANDLE_CHECKED(String, name, 0);
  return DeclareEvalHelper(isolate, name,
                           isolate->factory()->undefined_value());
}
341

342 343
namespace {

344
// Find the arguments of the JavaScript function invocation that called
345
// into C++ code. Collect these in a newly allocated array of handles.
346 347
std::unique_ptr<Handle<Object>[]> GetCallerArguments(Isolate* isolate,
                                                     int* total_argc) {
348 349 350
  // Find frame containing arguments passed to the caller.
  JavaScriptFrameIterator it(isolate);
  JavaScriptFrame* frame = it.frame();
351
  std::vector<SharedFunctionInfo> functions;
352
  frame->GetFunctions(&functions);
353 354
  if (functions.size() > 1) {
    int inlined_jsframe_index = static_cast<int>(functions.size()) - 1;
355
    TranslatedState translated_values(frame);
356
    translated_values.Prepare(frame->fp());
357 358 359 360 361 362 363 364 365 366 367 368 369 370

    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--;

371
    *total_argc = argument_count;
372
    std::unique_ptr<Handle<Object>[]> param_data(
373 374 375
        NewArray<Handle<Object>>(*total_argc));
    bool should_deoptimize = false;
    for (int i = 0; i < argument_count; i++) {
376 377
      // If we materialize any object, we should deoptimize the frame because we
      // might alias an object that was eliminated by escape analysis.
378 379
      should_deoptimize = should_deoptimize || iter->IsMaterializedObject();
      Handle<Object> value = iter->GetValue();
380
      param_data[i] = value;
381 382 383 384
      iter++;
    }

    if (should_deoptimize) {
385
      translated_values.StoreMaterializedValuesAndDeopt(frame);
386 387 388 389
    }

    return param_data;
  } else {
390 391 392 393
    if (it.frame()->has_adapted_arguments()) {
      it.AdvanceOneFrame();
      DCHECK(it.frame()->is_arguments_adaptor());
    }
394 395 396
    frame = it.frame();
    int args_count = frame->ComputeParametersCount();

397
    *total_argc = args_count;
398
    std::unique_ptr<Handle<Object>[]> param_data(
399 400 401
        NewArray<Handle<Object>>(*total_argc));
    for (int i = 0; i < args_count; i++) {
      Handle<Object> val = Handle<Object>(frame->GetParameter(i), isolate);
402
      param_data[i] = val;
403 404 405 406 407
    }
    return param_data;
  }
}

408 409 410
template <typename T>
Handle<JSObject> NewSloppyArguments(Isolate* isolate, Handle<JSFunction> callee,
                                    T parameters, int argument_count) {
411
  CHECK(!IsDerivedConstructor(callee->shared()->kind()));
412
  DCHECK(callee->shared()->has_simple_parameters());
413 414 415 416
  Handle<JSObject> result =
      isolate->factory()->NewArgumentsObject(callee, argument_count);

  // Allocate the elements if needed.
417
  int parameter_count = callee->shared()->internal_formal_parameter_count();
418 419 420 421 422
  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);
423 424
      parameter_map->set_map(
          ReadOnlyRoots(isolate).sloppy_arguments_elements_map());
425
      result->set_map(isolate->native_context()->fast_aliased_arguments_map());
426 427 428 429
      result->set_elements(*parameter_map);

      // Store the context and the arguments array at the beginning of the
      // parameter map.
430
      Handle<Context> context(isolate->context(), isolate);
431 432 433 434 435 436 437 438 439 440
      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.
441
        arguments->set(index, parameters[index]);
442 443 444
        --index;
      }

445
      Handle<ScopeInfo> scope_info(callee->shared()->scope_info(), isolate);
446

447 448 449 450 451 452 453 454 455 456 457 458 459 460
      // First mark all mappable slots as unmapped and copy the values into the
      // arguments object.
      for (int i = 0; i < mapped_count; i++) {
        arguments->set(i, parameters[i]);
        parameter_map->set_the_hole(i + 2);
      }

      // Walk all context slots to find context allocated parameters. Mark each
      // found parameter as mapped.
      for (int i = 0; i < scope_info->ContextLocalCount(); i++) {
        if (!scope_info->ContextLocalIsParameter(i)) continue;
        int parameter = scope_info->ContextLocalParameterNumber(i);
        if (parameter >= mapped_count) continue;
        arguments->set_the_hole(parameter);
461
        Smi slot = Smi::FromInt(Context::MIN_CONTEXT_SLOTS + i);
462
        parameter_map->set(parameter + 2, slot);
463 464 465 466 467 468 469 470
      }
    } 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) {
471
        elements->set(i, parameters[i]);
472 473 474 475 476 477
      }
    }
  }
  return result;
}

478
class HandleArguments {
479 480 481 482 483 484 485 486
 public:
  explicit HandleArguments(Handle<Object>* array) : array_(array) {}
  Object* operator[](int index) { return *array_[index]; }

 private:
  Handle<Object>* array_;
};

487
class ParameterArguments {
488
 public:
489 490 491 492
  explicit ParameterArguments(Address parameters) : parameters_(parameters) {}
  Object* operator[](int index) {
    return *ObjectSlot(parameters_ - (index + 1) * kPointerSize);
  }
493 494

 private:
495
  Address parameters_;
496 497 498 499 500 501
};

}  // namespace


RUNTIME_FUNCTION(Runtime_NewSloppyArguments_Generic) {
502
  HandleScope scope(isolate);
503
  DCHECK_EQ(1, args.length());
504
  CONVERT_ARG_HANDLE_CHECKED(JSFunction, callee, 0);
505
  // This generic runtime function can also be used when the caller has been
506
  // inlined, we use the slow but accurate {GetCallerArguments}.
507
  int argument_count = 0;
508
  std::unique_ptr<Handle<Object>[]> arguments =
509
      GetCallerArguments(isolate, &argument_count);
510 511 512
  HandleArguments argument_getter(arguments.get());
  return *NewSloppyArguments(isolate, callee, argument_getter, argument_count);
}
513

514

515
RUNTIME_FUNCTION(Runtime_NewStrictArguments) {
516
  HandleScope scope(isolate);
517
  DCHECK_EQ(1, args.length());
518 519
  CONVERT_ARG_HANDLE_CHECKED(JSFunction, callee, 0);
  // This generic runtime function can also be used when the caller has been
520
  // inlined, we use the slow but accurate {GetCallerArguments}.
521
  int argument_count = 0;
522
  std::unique_ptr<Handle<Object>[]> arguments =
523
      GetCallerArguments(isolate, &argument_count);
524 525 526 527 528 529 530 531 532 533 534 535 536
  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;
537 538 539
}


540
RUNTIME_FUNCTION(Runtime_NewRestParameter) {
541
  HandleScope scope(isolate);
542
  DCHECK_EQ(1, args.length());
543
  CONVERT_ARG_HANDLE_CHECKED(JSFunction, callee, 0)
544
  int start_index = callee->shared()->internal_formal_parameter_count();
545
  // This generic runtime function can also be used when the caller has been
546
  // inlined, we use the slow but accurate {GetCallerArguments}.
547
  int argument_count = 0;
548
  std::unique_ptr<Handle<Object>[]> arguments =
549
      GetCallerArguments(isolate, &argument_count);
550
  int num_elements = std::max(0, argument_count - start_index);
551 552 553
  Handle<JSObject> result = isolate->factory()->NewJSArray(
      PACKED_ELEMENTS, num_elements, num_elements,
      DONT_INITIALIZE_ARRAY_ELEMENTS);
554 555
  {
    DisallowHeapAllocation no_gc;
556
    FixedArray elements = FixedArray::cast(result->elements());
557
    WriteBarrierMode mode = elements->GetWriteBarrierMode(no_gc);
558 559 560 561 562
    for (int i = 0; i < num_elements; i++) {
      elements->set(i, *arguments[i + start_index], mode);
    }
  }
  return *result;
563 564 565
}


566 567
RUNTIME_FUNCTION(Runtime_NewSloppyArguments) {
  HandleScope scope(isolate);
568
  DCHECK_EQ(1, args.length());
569
  CONVERT_ARG_HANDLE_CHECKED(JSFunction, callee, 0);
570 571 572 573 574 575 576 577 578 579
  StackFrameIterator iterator(isolate);

  // Stub/interpreter handler frame
  iterator.Advance();
  DCHECK(iterator.frame()->type() == StackFrame::STUB);

  // Function frame
  iterator.Advance();
  JavaScriptFrame* function_frame = JavaScriptFrame::cast(iterator.frame());
  DCHECK(function_frame->is_java_script());
580
  int argc = function_frame->ComputeParametersCount();
581 582 583
  Address fp = function_frame->fp();
  if (function_frame->has_adapted_arguments()) {
    iterator.Advance();
584 585 586 587
    ArgumentsAdaptorFrame* adaptor_frame =
        ArgumentsAdaptorFrame::cast(iterator.frame());
    argc = adaptor_frame->ComputeParametersCount();
    fp = adaptor_frame->fp();
588 589
  }

590 591
  Address parameters =
      fp + argc * kPointerSize + StandardFrameConstants::kCallerSPOffset;
592
  ParameterArguments argument_getter(parameters);
593
  return *NewSloppyArguments(isolate, callee, argument_getter, argc);
594 595
}

596 597
RUNTIME_FUNCTION(Runtime_NewArgumentsElements) {
  HandleScope scope(isolate);
598
  DCHECK_EQ(3, args.length());
599 600 601 602
  // Note that args[0] is the address of an array of object pointers (a.k.a.
  // an ObjectSlot), which looks like a Smi because it's aligned.
  DCHECK(args[0].IsSmi());
  ObjectSlot frame(args[0]->ptr());
603
  CONVERT_SMI_ARG_CHECKED(length, 1);
604
  CONVERT_SMI_ARG_CHECKED(mapped_count, 2);
605 606 607 608 609
  Handle<FixedArray> result =
      isolate->factory()->NewUninitializedFixedArray(length);
  int const offset = length + 1;
  DisallowHeapAllocation no_gc;
  WriteBarrierMode mode = result->GetWriteBarrierMode(no_gc);
610 611 612 613 614
  int number_of_holes = Min(mapped_count, length);
  for (int index = 0; index < number_of_holes; ++index) {
    result->set_the_hole(isolate, index);
  }
  for (int index = number_of_holes; index < length; ++index) {
615
    result->set(index, *(frame + (offset - index)), mode);
616 617 618
  }
  return *result;
}
619

620
RUNTIME_FUNCTION(Runtime_NewClosure) {
621
  HandleScope scope(isolate);
622
  DCHECK_EQ(2, args.length());
623
  CONVERT_ARG_HANDLE_CHECKED(SharedFunctionInfo, shared, 0);
624
  CONVERT_ARG_HANDLE_CHECKED(FeedbackCell, feedback_cell, 1);
625
  Handle<Context> context(isolate->context(), isolate);
626
  Handle<JSFunction> function =
627
      isolate->factory()->NewFunctionFromSharedFunctionInfo(
628
          shared, context, feedback_cell, NOT_TENURED);
629
  return *function;
630 631
}

632
RUNTIME_FUNCTION(Runtime_NewClosure_Tenured) {
633
  HandleScope scope(isolate);
634
  DCHECK_EQ(2, args.length());
635
  CONVERT_ARG_HANDLE_CHECKED(SharedFunctionInfo, shared, 0);
636
  CONVERT_ARG_HANDLE_CHECKED(FeedbackCell, feedback_cell, 1);
637
  Handle<Context> context(isolate->context(), isolate);
638 639
  // The caller ensures that we pretenure closures that are assigned
  // directly to properties.
640
  Handle<JSFunction> function =
641
      isolate->factory()->NewFunctionFromSharedFunctionInfo(
642
          shared, context, feedback_cell, TENURED);
643
  return *function;
644 645
}

646
static Object* FindNameClash(Isolate* isolate, Handle<ScopeInfo> scope_info,
647
                             Handle<JSGlobalObject> global_object,
648
                             Handle<ScriptContextTable> script_context) {
649
  for (int var = 0; var < scope_info->ContextLocalCount(); var++) {
650
    Handle<String> name(scope_info->ContextLocalName(var), isolate);
651
    VariableMode mode = scope_info->ContextLocalMode(var);
652
    ScriptContextTable::LookupResult lookup;
653
    if (ScriptContextTable::Lookup(isolate, script_context, name, &lookup)) {
654
      if (IsLexicalVariableMode(mode) || IsLexicalVariableMode(lookup.mode)) {
655 656 657 658 659
        // ES#sec-globaldeclarationinstantiation 5.b:
        // If envRec.HasLexicalDeclaration(name) is true, throw a SyntaxError
        // exception.
        return ThrowRedeclarationError(isolate, name,
                                       RedeclarationType::kSyntaxError);
660 661 662 663
      }
    }

    if (IsLexicalVariableMode(mode)) {
664
      LookupIterator it(global_object, name, global_object,
665
                        LookupIterator::OWN_SKIP_INTERCEPTOR);
666
      Maybe<PropertyAttributes> maybe = JSReceiver::GetPropertyAttributes(&it);
667
      if (maybe.IsNothing()) return ReadOnlyRoots(isolate).exception();
668
      if ((maybe.FromJust() & DONT_DELETE) != 0) {
669 670 671 672 673 674 675
        // ES#sec-globaldeclarationinstantiation 5.a:
        // If envRec.HasVarDeclaration(name) is true, throw a SyntaxError
        // exception.
        // ES#sec-globaldeclarationinstantiation 5.d:
        // If hasRestrictedGlobal is true, throw a SyntaxError exception.
        return ThrowRedeclarationError(isolate, name,
                                       RedeclarationType::kSyntaxError);
676 677
      }

678
      JSGlobalObject::InvalidatePropertyCell(global_object, name);
679 680
    }
  }
681
  return ReadOnlyRoots(isolate).undefined_value();
682 683
}

684

685
RUNTIME_FUNCTION(Runtime_NewScriptContext) {
686
  HandleScope scope(isolate);
687
  DCHECK_EQ(1, args.length());
688

689
  CONVERT_ARG_HANDLE_CHECKED(ScopeInfo, scope_info, 0);
690 691
  Handle<NativeContext> native_context(NativeContext::cast(isolate->context()),
                                       isolate);
692 693
  Handle<JSGlobalObject> global_object(native_context->global_object(),
                                       isolate);
694
  Handle<ScriptContextTable> script_context_table(
695
      native_context->script_context_table(), isolate);
696 697

  Object* name_clash_result =
698
      FindNameClash(isolate, scope_info, global_object, script_context_table);
699 700
  if (isolate->has_pending_exception()) return name_clash_result;

701 702
  // We do not need script contexts here during bootstrap.
  DCHECK(!isolate->bootstrapper()->IsActive());
703

704 705
  Handle<Context> result =
      isolate->factory()->NewScriptContext(native_context, scope_info);
706

707 708 709
  Handle<ScriptContextTable> new_script_context_table =
      ScriptContextTable::Extend(script_context_table, result);
  native_context->set_script_context_table(*new_script_context_table);
710 711 712 713 714
  return *result;
}

RUNTIME_FUNCTION(Runtime_NewFunctionContext) {
  HandleScope scope(isolate);
715
  DCHECK_EQ(1, args.length());
716

717
  CONVERT_ARG_HANDLE_CHECKED(ScopeInfo, scope_info, 0);
718

719 720
  Handle<Context> outer(isolate->context(), isolate);
  return *isolate->factory()->NewFunctionContext(outer, scope_info);
721 722 723 724
}

RUNTIME_FUNCTION(Runtime_PushWithContext) {
  HandleScope scope(isolate);
725
  DCHECK_EQ(2, args.length());
726
  CONVERT_ARG_HANDLE_CHECKED(JSReceiver, extension_object, 0);
727
  CONVERT_ARG_HANDLE_CHECKED(ScopeInfo, scope_info, 1);
728
  Handle<Context> current(isolate->context(), isolate);
729 730
  Handle<Context> context =
      isolate->factory()->NewWithContext(current, scope_info, extension_object);
731 732 733 734
  isolate->set_context(*context);
  return *context;
}

735 736
RUNTIME_FUNCTION(Runtime_PushModuleContext) {
  HandleScope scope(isolate);
737
  DCHECK_EQ(2, args.length());
738
  CONVERT_ARG_HANDLE_CHECKED(Module, module, 0);
739
  CONVERT_ARG_HANDLE_CHECKED(ScopeInfo, scope_info, 1);
740

741
  Handle<NativeContext> outer(NativeContext::cast(isolate->context()), isolate);
742
  Handle<Context> context =
743
      isolate->factory()->NewModuleContext(module, outer, scope_info);
744 745 746
  isolate->set_context(*context);
  return *context;
}
747 748 749

RUNTIME_FUNCTION(Runtime_PushCatchContext) {
  HandleScope scope(isolate);
750 751 752
  DCHECK_EQ(2, args.length());
  CONVERT_ARG_HANDLE_CHECKED(Object, thrown_object, 0);
  CONVERT_ARG_HANDLE_CHECKED(ScopeInfo, scope_info, 1);
753
  Handle<Context> current(isolate->context(), isolate);
754 755
  Handle<Context> context =
      isolate->factory()->NewCatchContext(current, scope_info, thrown_object);
756 757 758 759 760 761 762
  isolate->set_context(*context);
  return *context;
}


RUNTIME_FUNCTION(Runtime_PushBlockContext) {
  HandleScope scope(isolate);
763
  DCHECK_EQ(1, args.length());
764
  CONVERT_ARG_HANDLE_CHECKED(ScopeInfo, scope_info, 0);
765
  Handle<Context> current(isolate->context(), isolate);
766
  Handle<Context> context =
767
      isolate->factory()->NewBlockContext(current, scope_info);
768 769 770 771 772 773 774
  isolate->set_context(*context);
  return *context;
}


RUNTIME_FUNCTION(Runtime_DeleteLookupSlot) {
  HandleScope scope(isolate);
775 776
  DCHECK_EQ(1, args.length());
  CONVERT_ARG_HANDLE_CHECKED(String, name, 0);
777 778 779

  int index;
  PropertyAttributes attributes;
780
  InitializationFlag flag;
781
  VariableMode mode;
782
  Handle<Object> holder = isolate->context()->Lookup(
783
      name, FOLLOW_CHAINS, &index, &attributes, &flag, &mode);
784 785 786

  // If the slot was not found the result is true.
  if (holder.is_null()) {
787
    // In case of JSProxy, an exception might have been thrown.
788 789 790
    if (isolate->has_pending_exception())
      return ReadOnlyRoots(isolate).exception();
    return ReadOnlyRoots(isolate).true_value();
791 792
  }

793 794 795
  // If the slot was found in a context or in module imports and exports it
  // should be DONT_DELETE.
  if (holder->IsContext() || holder->IsModule()) {
796
    return ReadOnlyRoots(isolate).false_value();
797 798
  }

799
  // The slot was found in a JSReceiver, either a context extension object,
800 801
  // the global object, or the subject of a with.  Try to delete it
  // (respecting DONT_DELETE).
802
  Handle<JSReceiver> object = Handle<JSReceiver>::cast(holder);
neis's avatar
neis committed
803
  Maybe<bool> result = JSReceiver::DeleteProperty(object, name);
804
  MAYBE_RETURN(result, ReadOnlyRoots(isolate).exception());
neis's avatar
neis committed
805
  return isolate->heap()->ToBoolean(result.FromJust());
806 807 808
}


809
namespace {
810

811
MaybeHandle<Object> LoadLookupSlot(Isolate* isolate, Handle<String> name,
812
                                   ShouldThrow should_throw,
813
                                   Handle<Object>* receiver_return = nullptr) {
814 815
  int index;
  PropertyAttributes attributes;
816
  InitializationFlag flag;
817
  VariableMode mode;
818
  Handle<Object> holder = isolate->context()->Lookup(
819
      name, FOLLOW_CHAINS, &index, &attributes, &flag, &mode);
820
  if (isolate->has_pending_exception()) return MaybeHandle<Object>();
821

822
  if (!holder.is_null() && holder->IsModule()) {
823 824
    Handle<Object> receiver = isolate->factory()->undefined_value();
    if (receiver_return) *receiver_return = receiver;
825
    return Module::LoadVariable(isolate, Handle<Module>::cast(holder), index);
826
  }
827
  if (index != Context::kNotFound) {
828 829 830 831
    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();
832
    Handle<Object> value = handle(Context::cast(*holder)->get(index), isolate);
833
    // Check for uninitialized bindings.
834 835 836 837
    if (flag == kNeedsInitialization && value->IsTheHole(isolate)) {
      THROW_NEW_ERROR(isolate,
                      NewReferenceError(MessageTemplate::kNotDefined, name),
                      Object);
838
    }
839 840 841
    DCHECK(!value->IsTheHole(isolate));
    if (receiver_return) *receiver_return = receiver;
    return value;
842 843 844 845 846 847 848 849 850
  }

  // 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;
851
    ASSIGN_RETURN_ON_EXCEPTION(
852
        isolate, value, Object::GetProperty(isolate, holder, name), Object);
853 854 855 856 857 858 859
    if (receiver_return) {
      *receiver_return =
          (holder->IsJSGlobalObject() || holder->IsJSContextExtensionObject())
              ? Handle<Object>::cast(isolate->factory()->undefined_value())
              : holder;
    }
    return value;
860 861
  }

862
  if (should_throw == kThrowOnError) {
863
    // The property doesn't exist - throw exception.
864 865
    THROW_NEW_ERROR(
        isolate, NewReferenceError(MessageTemplate::kNotDefined, name), Object);
866
  }
867 868 869 870

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

873
}  // namespace
874

875 876 877 878 879

RUNTIME_FUNCTION(Runtime_LoadLookupSlot) {
  HandleScope scope(isolate);
  DCHECK_EQ(1, args.length());
  CONVERT_ARG_HANDLE_CHECKED(String, name, 0);
880 881
  RETURN_RESULT_OR_FAILURE(isolate,
                           LoadLookupSlot(isolate, name, kThrowOnError));
882 883 884
}


885 886 887 888
RUNTIME_FUNCTION(Runtime_LoadLookupSlotInsideTypeof) {
  HandleScope scope(isolate);
  DCHECK_EQ(1, args.length());
  CONVERT_ARG_HANDLE_CHECKED(String, name, 0);
889
  RETURN_RESULT_OR_FAILURE(isolate, LoadLookupSlot(isolate, name, kDontThrow));
890 891 892
}


893
RUNTIME_FUNCTION_RETURN_PAIR(Runtime_LoadLookupSlotForCall) {
894
  HandleScope scope(isolate);
895 896 897 898 899 900
  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(
901
      isolate, value, LoadLookupSlot(isolate, name, kThrowOnError, &receiver),
902
      MakePair(ReadOnlyRoots(isolate).exception(), nullptr));
903 904
  return MakePair(*value, *receiver);
}
905

906 907 908

namespace {

909
MaybeHandle<Object> StoreLookupSlot(
910 911
    Isolate* isolate, Handle<String> name, Handle<Object> value,
    LanguageMode language_mode,
912
    ContextLookupFlags context_lookup_flags = FOLLOW_CHAINS) {
913
  Handle<Context> context(isolate->context(), isolate);
914 915 916

  int index;
  PropertyAttributes attributes;
917
  InitializationFlag flag;
918
  VariableMode mode;
919 920 921 922
  bool is_sloppy_function_name;
  Handle<Object> holder =
      context->Lookup(name, context_lookup_flags, &index, &attributes, &flag,
                      &mode, &is_sloppy_function_name);
923 924
  if (holder.is_null()) {
    // In case of JSProxy, an exception might have been thrown.
925
    if (isolate->has_pending_exception()) return MaybeHandle<Object>();
926 927 928
  } else if (holder->IsModule()) {
    if ((attributes & READ_ONLY) == 0) {
      Module::StoreVariable(Handle<Module>::cast(holder), index, value);
929 930 931
    } else {
      THROW_NEW_ERROR(
          isolate, NewTypeError(MessageTemplate::kConstAssign, name), Object);
932 933
    }
    return value;
934
  }
935
  // The property was found in a context slot.
936
  if (index != Context::kNotFound) {
937
    if (flag == kNeedsInitialization &&
938
        Handle<Context>::cast(holder)->get(index)->IsTheHole(isolate)) {
939 940 941
      THROW_NEW_ERROR(isolate,
                      NewReferenceError(MessageTemplate::kNotDefined, name),
                      Object);
942
    }
943 944
    if ((attributes & READ_ONLY) == 0) {
      Handle<Context>::cast(holder)->set(index, *value);
945 946 947
    } else if (!is_sloppy_function_name || is_strict(language_mode)) {
      THROW_NEW_ERROR(
          isolate, NewTypeError(MessageTemplate::kConstAssign, name), Object);
948
    }
949
    return value;
950 951 952 953 954 955 956 957 958
  }

  // 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);
959
  } else if (is_strict(language_mode)) {
960
    // If absent in strict mode: throw.
961 962
    THROW_NEW_ERROR(
        isolate, NewReferenceError(MessageTemplate::kNotDefined, name), Object);
963 964
  } else {
    // If absent in sloppy mode: add the property to the global object.
965
    object = handle(context->global_object(), isolate);
966 967
  }

968
  ASSIGN_RETURN_ON_EXCEPTION(
969 970
      isolate, value,
      Object::SetProperty(isolate, object, name, value, language_mode), Object);
971 972 973 974 975 976 977 978 979 980 981
  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);
982 983
  RETURN_RESULT_OR_FAILURE(
      isolate, StoreLookupSlot(isolate, name, value, LanguageMode::kSloppy));
984 985
}

986 987 988 989 990 991 992 993 994 995
// Store into a dynamic context for sloppy-mode block-scoped function hoisting
// which leaks out of an eval. In particular, with-scopes are be skipped to
// reach the appropriate var-like declaration.
RUNTIME_FUNCTION(Runtime_StoreLookupSlot_SloppyHoisting) {
  HandleScope scope(isolate);
  DCHECK_EQ(2, args.length());
  CONVERT_ARG_HANDLE_CHECKED(String, name, 0);
  CONVERT_ARG_HANDLE_CHECKED(Object, value, 1);
  const ContextLookupFlags lookup_flags = static_cast<ContextLookupFlags>(
      FOLLOW_CONTEXT_CHAIN | STOP_AT_DECLARATION_SCOPE | SKIP_WITH_CONTEXT);
996
  RETURN_RESULT_OR_FAILURE(
997 998
      isolate, StoreLookupSlot(isolate, name, value, LanguageMode::kSloppy,
                               lookup_flags));
999
}
1000

1001 1002 1003 1004 1005
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);
1006 1007
  RETURN_RESULT_OR_FAILURE(
      isolate, StoreLookupSlot(isolate, name, value, LanguageMode::kStrict));
1008 1009
}

1010 1011
}  // namespace internal
}  // namespace v8