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


6
#include "src/v8.h"
7

8
#include "src/liveedit.h"
9

10 11 12 13 14 15 16 17 18 19 20
#include "src/code-stubs.h"
#include "src/compilation-cache.h"
#include "src/compiler.h"
#include "src/debug.h"
#include "src/deoptimizer.h"
#include "src/global-handles.h"
#include "src/messages.h"
#include "src/parser.h"
#include "src/scopeinfo.h"
#include "src/scopes.h"
#include "src/v8memory.h"
21 22 23 24

namespace v8 {
namespace internal {

25 26 27
void SetElementSloppy(Handle<JSObject> object,
                      uint32_t index,
                      Handle<Object> value) {
28 29 30
  // Ignore return value from SetElement. It can only be a failure if there
  // are element setters causing exceptions and the debugger context has none
  // of these.
31
  JSObject::SetElement(object, index, value, NONE, SLOPPY).Assert();
32 33
}

34

35
// A simple implementation of dynamic programming algorithm. It solves
36 37
// the problem of finding the difference of 2 arrays. It uses a table of results
// of subproblems. Each cell contains a number together with 2-bit flag
38 39 40
// that helps building the chunk list.
class Differencer {
 public:
41 42 43
  explicit Differencer(Comparator::Input* input)
      : input_(input), len1_(input->GetLength1()), len2_(input->GetLength2()) {
    buffer_ = NewArray<int>(len1_ * len2_);
44 45
  }
  ~Differencer() {
46
    DeleteArray(buffer_);
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
  }

  void Initialize() {
    int array_size = len1_ * len2_;
    for (int i = 0; i < array_size; i++) {
      buffer_[i] = kEmptyCellValue;
    }
  }

  // Makes sure that result for the full problem is calculated and stored
  // in the table together with flags showing a path through subproblems.
  void FillTable() {
    CompareUpToTail(0, 0);
  }

62
  void SaveResult(Comparator::Output* chunk_writer) {
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
    ResultWriter writer(chunk_writer);

    int pos1 = 0;
    int pos2 = 0;
    while (true) {
      if (pos1 < len1_) {
        if (pos2 < len2_) {
          Direction dir = get_direction(pos1, pos2);
          switch (dir) {
            case EQ:
              writer.eq();
              pos1++;
              pos2++;
              break;
            case SKIP1:
              writer.skip1(1);
              pos1++;
              break;
            case SKIP2:
            case SKIP_ANY:
              writer.skip2(1);
              pos2++;
              break;
            default:
              UNREACHABLE();
          }
        } else {
          writer.skip1(len1_ - pos1);
          break;
        }
      } else {
        if (len2_ != pos2) {
          writer.skip2(len2_ - pos2);
        }
        break;
      }
    }
    writer.close();
  }

 private:
104
  Comparator::Input* input_;
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
  int* buffer_;
  int len1_;
  int len2_;

  enum Direction {
    EQ = 0,
    SKIP1,
    SKIP2,
    SKIP_ANY,

    MAX_DIRECTION_FLAG_VALUE = SKIP_ANY
  };

  // Computes result for a subtask and optionally caches it in the buffer table.
  // All results values are shifted to make space for flags in the lower bits.
  int CompareUpToTail(int pos1, int pos2) {
    if (pos1 < len1_) {
      if (pos2 < len2_) {
        int cached_res = get_value4(pos1, pos2);
        if (cached_res == kEmptyCellValue) {
          Direction dir;
          int res;
127
          if (input_->Equals(pos1, pos2)) {
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 162 163
            res = CompareUpToTail(pos1 + 1, pos2 + 1);
            dir = EQ;
          } else {
            int res1 = CompareUpToTail(pos1 + 1, pos2) +
                (1 << kDirectionSizeBits);
            int res2 = CompareUpToTail(pos1, pos2 + 1) +
                (1 << kDirectionSizeBits);
            if (res1 == res2) {
              res = res1;
              dir = SKIP_ANY;
            } else if (res1 < res2) {
              res = res1;
              dir = SKIP1;
            } else {
              res = res2;
              dir = SKIP2;
            }
          }
          set_value4_and_dir(pos1, pos2, res, dir);
          cached_res = res;
        }
        return cached_res;
      } else {
        return (len1_ - pos1) << kDirectionSizeBits;
      }
    } else {
      return (len2_ - pos2) << kDirectionSizeBits;
    }
  }

  inline int& get_cell(int i1, int i2) {
    return buffer_[i1 + i2 * len1_];
  }

  // Each cell keeps a value plus direction. Value is multiplied by 4.
  void set_value4_and_dir(int i1, int i2, int value4, Direction dir) {
164
    DCHECK((value4 & kDirectionMask) == 0);
165 166 167 168 169 170 171 172 173 174 175 176
    get_cell(i1, i2) = value4 | dir;
  }

  int get_value4(int i1, int i2) {
    return get_cell(i1, i2) & (kMaxUInt32 ^ kDirectionMask);
  }
  Direction get_direction(int i1, int i2) {
    return static_cast<Direction>(get_cell(i1, i2) & kDirectionMask);
  }

  static const int kDirectionSizeBits = 2;
  static const int kDirectionMask = (1 << kDirectionSizeBits) - 1;
177
  static const int kEmptyCellValue = ~0u << kDirectionSizeBits;
178 179 180 181 182 183 184 185 186

  // This method only holds static assert statement (unfortunately you cannot
  // place one in class scope).
  void StaticAssertHolder() {
    STATIC_ASSERT(MAX_DIRECTION_FLAG_VALUE < (1 << kDirectionSizeBits));
  }

  class ResultWriter {
   public:
187
    explicit ResultWriter(Comparator::Output* chunk_writer)
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208
        : chunk_writer_(chunk_writer), pos1_(0), pos2_(0),
          pos1_begin_(-1), pos2_begin_(-1), has_open_chunk_(false) {
    }
    void eq() {
      FlushChunk();
      pos1_++;
      pos2_++;
    }
    void skip1(int len1) {
      StartChunk();
      pos1_ += len1;
    }
    void skip2(int len2) {
      StartChunk();
      pos2_ += len2;
    }
    void close() {
      FlushChunk();
    }

   private:
209
    Comparator::Output* chunk_writer_;
210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
    int pos1_;
    int pos2_;
    int pos1_begin_;
    int pos2_begin_;
    bool has_open_chunk_;

    void StartChunk() {
      if (!has_open_chunk_) {
        pos1_begin_ = pos1_;
        pos2_begin_ = pos2_;
        has_open_chunk_ = true;
      }
    }

    void FlushChunk() {
      if (has_open_chunk_) {
        chunk_writer_->AddChunk(pos1_begin_, pos2_begin_,
                                pos1_ - pos1_begin_, pos2_ - pos2_begin_);
        has_open_chunk_ = false;
      }
    }
  };
};


235 236 237
void Comparator::CalculateDifference(Comparator::Input* input,
                                     Comparator::Output* result_writer) {
  Differencer differencer(input);
238 239 240 241 242 243
  differencer.Initialize();
  differencer.FillTable();
  differencer.SaveResult(result_writer);
}


244
static bool CompareSubstrings(Handle<String> s1, int pos1,
245 246
                              Handle<String> s2, int pos2, int len) {
  for (int i = 0; i < len; i++) {
247
    if (s1->Get(i + pos1) != s2->Get(i + pos2)) {
248 249 250 251 252 253 254
      return false;
    }
  }
  return true;
}


255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318
// Additional to Input interface. Lets switch Input range to subrange.
// More elegant way would be to wrap one Input as another Input object
// and translate positions there, but that would cost us additional virtual
// call per comparison.
class SubrangableInput : public Comparator::Input {
 public:
  virtual void SetSubrange1(int offset, int len) = 0;
  virtual void SetSubrange2(int offset, int len) = 0;
};


class SubrangableOutput : public Comparator::Output {
 public:
  virtual void SetSubrange1(int offset, int len) = 0;
  virtual void SetSubrange2(int offset, int len) = 0;
};


static int min(int a, int b) {
  return a < b ? a : b;
}


// Finds common prefix and suffix in input. This parts shouldn't take space in
// linear programming table. Enable subranging in input and output.
static void NarrowDownInput(SubrangableInput* input,
    SubrangableOutput* output) {
  const int len1 = input->GetLength1();
  const int len2 = input->GetLength2();

  int common_prefix_len;
  int common_suffix_len;

  {
    common_prefix_len = 0;
    int prefix_limit = min(len1, len2);
    while (common_prefix_len < prefix_limit &&
        input->Equals(common_prefix_len, common_prefix_len)) {
      common_prefix_len++;
    }

    common_suffix_len = 0;
    int suffix_limit = min(len1 - common_prefix_len, len2 - common_prefix_len);

    while (common_suffix_len < suffix_limit &&
        input->Equals(len1 - common_suffix_len - 1,
        len2 - common_suffix_len - 1)) {
      common_suffix_len++;
    }
  }

  if (common_prefix_len > 0 || common_suffix_len > 0) {
    int new_len1 = len1 - common_suffix_len - common_prefix_len;
    int new_len2 = len2 - common_suffix_len - common_prefix_len;

    input->SetSubrange1(common_prefix_len, new_len1);
    input->SetSubrange2(common_prefix_len, new_len2);

    output->SetSubrange1(common_prefix_len, new_len1);
    output->SetSubrange2(common_prefix_len, new_len2);
  }
}


319 320 321 322
// A helper class that writes chunk numbers into JSArray.
// Each chunk is stored as 3 array elements: (pos1_begin, pos1_end, pos2_end).
class CompareOutputArrayWriter {
 public:
323 324
  explicit CompareOutputArrayWriter(Isolate* isolate)
      : array_(isolate->factory()->NewJSArray(10)), current_size_(0) {}
325 326 327 328 329 330

  Handle<JSArray> GetResult() {
    return array_;
  }

  void WriteChunk(int char_pos1, int char_pos2, int char_len1, int char_len2) {
331
    Isolate* isolate = array_->GetIsolate();
332 333 334 335 336 337 338 339 340 341 342
    SetElementSloppy(array_,
                     current_size_,
                     Handle<Object>(Smi::FromInt(char_pos1), isolate));
    SetElementSloppy(array_,
                     current_size_ + 1,
                     Handle<Object>(Smi::FromInt(char_pos1 + char_len1),
                                    isolate));
    SetElementSloppy(array_,
                     current_size_ + 2,
                     Handle<Object>(Smi::FromInt(char_pos2 + char_len2),
                                    isolate));
343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361
    current_size_ += 3;
  }

 private:
  Handle<JSArray> array_;
  int current_size_;
};


// Represents 2 strings as 2 arrays of tokens.
// TODO(LiveEdit): Currently it's actually an array of charactres.
//     Make array of tokens instead.
class TokensCompareInput : public Comparator::Input {
 public:
  TokensCompareInput(Handle<String> s1, int offset1, int len1,
                       Handle<String> s2, int offset2, int len2)
      : s1_(s1), offset1_(offset1), len1_(len1),
        s2_(s2), offset2_(offset2), len2_(len2) {
  }
362
  virtual int GetLength1() {
363 364
    return len1_;
  }
365
  virtual int GetLength2() {
366 367
    return len2_;
  }
368
  bool Equals(int index1, int index2) {
369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401
    return s1_->Get(offset1_ + index1) == s2_->Get(offset2_ + index2);
  }

 private:
  Handle<String> s1_;
  int offset1_;
  int len1_;
  Handle<String> s2_;
  int offset2_;
  int len2_;
};


// Stores compare result in JSArray. Converts substring positions
// to absolute positions.
class TokensCompareOutput : public Comparator::Output {
 public:
  TokensCompareOutput(CompareOutputArrayWriter* array_writer,
                      int offset1, int offset2)
        : array_writer_(array_writer), offset1_(offset1), offset2_(offset2) {
  }

  void AddChunk(int pos1, int pos2, int len1, int len2) {
    array_writer_->WriteChunk(pos1 + offset1_, pos2 + offset2_, len1, len2);
  }

 private:
  CompareOutputArrayWriter* array_writer_;
  int offset1_;
  int offset2_;
};


402 403 404 405 406
// Wraps raw n-elements line_ends array as a list of n+1 lines. The last line
// never has terminating new line character.
class LineEndsWrapper {
 public:
  explicit LineEndsWrapper(Handle<String> string)
407
      : ends_array_(String::CalculateLineEnds(string, false)),
408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443
        string_len_(string->length()) {
  }
  int length() {
    return ends_array_->length() + 1;
  }
  // Returns start for any line including start of the imaginary line after
  // the last line.
  int GetLineStart(int index) {
    if (index == 0) {
      return 0;
    } else {
      return GetLineEnd(index - 1);
    }
  }
  int GetLineEnd(int index) {
    if (index == ends_array_->length()) {
      // End of the last line is always an end of the whole string.
      // If the string ends with a new line character, the last line is an
      // empty string after this character.
      return string_len_;
    } else {
      return GetPosAfterNewLine(index);
    }
  }

 private:
  Handle<FixedArray> ends_array_;
  int string_len_;

  int GetPosAfterNewLine(int index) {
    return Smi::cast(ends_array_->get(index))->value() + 1;
  }
};


// Represents 2 strings as 2 arrays of lines.
444
class LineArrayCompareInput : public SubrangableInput {
445
 public:
446
  LineArrayCompareInput(Handle<String> s1, Handle<String> s2,
447
                        LineEndsWrapper line_ends1, LineEndsWrapper line_ends2)
448
      : s1_(s1), s2_(s2), line_ends1_(line_ends1),
449 450 451 452
        line_ends2_(line_ends2),
        subrange_offset1_(0), subrange_offset2_(0),
        subrange_len1_(line_ends1_.length()),
        subrange_len2_(line_ends2_.length()) {
453
  }
454 455
  int GetLength1() {
    return subrange_len1_;
456
  }
457 458
  int GetLength2() {
    return subrange_len2_;
459
  }
460 461 462 463
  bool Equals(int index1, int index2) {
    index1 += subrange_offset1_;
    index2 += subrange_offset2_;

464 465 466 467 468 469 470 471 472
    int line_start1 = line_ends1_.GetLineStart(index1);
    int line_start2 = line_ends2_.GetLineStart(index2);
    int line_end1 = line_ends1_.GetLineEnd(index1);
    int line_end2 = line_ends2_.GetLineEnd(index2);
    int len1 = line_end1 - line_start1;
    int len2 = line_end2 - line_start2;
    if (len1 != len2) {
      return false;
    }
473
    return CompareSubstrings(s1_, line_start1, s2_, line_start2,
474
                             len1);
475
  }
476 477 478 479 480 481 482 483
  void SetSubrange1(int offset, int len) {
    subrange_offset1_ = offset;
    subrange_len1_ = len;
  }
  void SetSubrange2(int offset, int len) {
    subrange_offset2_ = offset;
    subrange_len2_ = len;
  }
484 485 486 487 488 489

 private:
  Handle<String> s1_;
  Handle<String> s2_;
  LineEndsWrapper line_ends1_;
  LineEndsWrapper line_ends2_;
490 491 492 493
  int subrange_offset1_;
  int subrange_offset2_;
  int subrange_len1_;
  int subrange_len2_;
494 495 496
};


497 498
// Stores compare result in JSArray. For each chunk tries to conduct
// a fine-grained nested diff token-wise.
499
class TokenizingLineArrayCompareOutput : public SubrangableOutput {
500
 public:
501 502
  TokenizingLineArrayCompareOutput(LineEndsWrapper line_ends1,
                                   LineEndsWrapper line_ends2,
503
                                   Handle<String> s1, Handle<String> s2)
504 505
      : array_writer_(s1->GetIsolate()),
        line_ends1_(line_ends1), line_ends2_(line_ends2), s1_(s1), s2_(s2),
506
        subrange_offset1_(0), subrange_offset2_(0) {
507 508 509
  }

  void AddChunk(int line_pos1, int line_pos2, int line_len1, int line_len2) {
510 511 512
    line_pos1 += subrange_offset1_;
    line_pos2 += subrange_offset2_;

513 514 515 516 517
    int char_pos1 = line_ends1_.GetLineStart(line_pos1);
    int char_pos2 = line_ends2_.GetLineStart(line_pos2);
    int char_len1 = line_ends1_.GetLineStart(line_pos1 + line_len1) - char_pos1;
    int char_len2 = line_ends2_.GetLineStart(line_pos2 + line_len2) - char_pos2;

518 519
    if (char_len1 < CHUNK_LEN_LIMIT && char_len2 < CHUNK_LEN_LIMIT) {
      // Chunk is small enough to conduct a nested token-level diff.
520
      HandleScope subTaskScope(s1_->GetIsolate());
521 522 523 524 525 526

      TokensCompareInput tokens_input(s1_, char_pos1, char_len1,
                                      s2_, char_pos2, char_len2);
      TokensCompareOutput tokens_output(&array_writer_, char_pos1,
                                          char_pos2);

527
      Comparator::CalculateDifference(&tokens_input, &tokens_output);
528 529 530
    } else {
      array_writer_.WriteChunk(char_pos1, char_pos2, char_len1, char_len2);
    }
531
  }
532 533 534 535 536 537
  void SetSubrange1(int offset, int len) {
    subrange_offset1_ = offset;
  }
  void SetSubrange2(int offset, int len) {
    subrange_offset2_ = offset;
  }
538 539

  Handle<JSArray> GetResult() {
540
    return array_writer_.GetResult();
541 542 543
  }

 private:
544 545 546
  static const int CHUNK_LEN_LIMIT = 800;

  CompareOutputArrayWriter array_writer_;
547 548
  LineEndsWrapper line_ends1_;
  LineEndsWrapper line_ends2_;
549 550
  Handle<String> s1_;
  Handle<String> s2_;
551 552
  int subrange_offset1_;
  int subrange_offset2_;
553 554 555
};


556 557
Handle<JSArray> LiveEdit::CompareStrings(Handle<String> s1,
                                         Handle<String> s2) {
558 559
  s1 = String::Flatten(s1);
  s2 = String::Flatten(s2);
560

561 562 563
  LineEndsWrapper line_ends1(s1);
  LineEndsWrapper line_ends2(s2);

564
  LineArrayCompareInput input(s1, s2, line_ends1, line_ends2);
565
  TokenizingLineArrayCompareOutput output(line_ends1, line_ends2, s1, s2);
566

567 568
  NarrowDownInput(&input, &output);

569
  Comparator::CalculateDifference(&input, &output);
570

571
  return output.GetResult();
572 573 574
}


575 576
// Unwraps JSValue object, returning its field "value"
static Handle<Object> UnwrapJSValue(Handle<JSValue> jsValue) {
577
  return Handle<Object>(jsValue->value(), jsValue->GetIsolate());
578 579
}

580

581 582
// Wraps any object into a OpaqueReference, that will hide the object
// from JavaScript.
583 584
static Handle<JSValue> WrapInJSValue(Handle<HeapObject> object) {
  Isolate* isolate = object->GetIsolate();
585
  Handle<JSFunction> constructor = isolate->opaque_reference_function();
586
  Handle<JSValue> result =
587
      Handle<JSValue>::cast(isolate->factory()->NewJSObject(constructor));
588
  result->set_value(*object);
589 590 591
  return result;
}

592

593 594 595 596 597 598 599 600 601 602 603 604 605 606 607
static Handle<SharedFunctionInfo> UnwrapSharedFunctionInfoFromJSValue(
    Handle<JSValue> jsValue) {
  Object* shared = jsValue->value();
  CHECK(shared->IsSharedFunctionInfo());
  return Handle<SharedFunctionInfo>(SharedFunctionInfo::cast(shared));
}


static int GetArrayLength(Handle<JSArray> array) {
  Object* length = array->length();
  CHECK(length->IsSmi());
  return Smi::cast(length)->value();
}


608 609 610 611 612
void FunctionInfoWrapper::SetInitialProperties(Handle<String> name,
                                               int start_position,
                                               int end_position,
                                               int param_num,
                                               int literal_count,
613
                                               int slot_count,
614 615 616 617 618 619 620
                                               int parent_index) {
  HandleScope scope(isolate());
  this->SetField(kFunctionNameOffset_, name);
  this->SetSmiValueField(kStartPositionOffset_, start_position);
  this->SetSmiValueField(kEndPositionOffset_, end_position);
  this->SetSmiValueField(kParamNumOffset_, param_num);
  this->SetSmiValueField(kLiteralNumOffset_, literal_count);
621
  this->SetSmiValueField(kSlotNumOffset_, slot_count);
622 623
  this->SetSmiValueField(kParentIndexOffset_, parent_index);
}
624 625


626 627 628 629
void FunctionInfoWrapper::SetFunctionCode(Handle<Code> function_code,
                                          Handle<HeapObject> code_scope_info) {
  Handle<JSValue> code_wrapper = WrapInJSValue(function_code);
  this->SetField(kCodeOffset_, code_wrapper);
630

631 632 633
  Handle<JSValue> scope_wrapper = WrapInJSValue(code_scope_info);
  this->SetField(kCodeScopeInfoOffset_, scope_wrapper);
}
634

635

636 637 638 639 640
void FunctionInfoWrapper::SetSharedFunctionInfo(
    Handle<SharedFunctionInfo> info) {
  Handle<JSValue> info_holder = WrapInJSValue(info);
  this->SetField(kSharedFunctionInfoOffset_, info_holder);
}
641 642


643 644 645 646 647 648 649
Handle<Code> FunctionInfoWrapper::GetFunctionCode() {
  Handle<Object> element = this->GetField(kCodeOffset_);
  Handle<JSValue> value_wrapper = Handle<JSValue>::cast(element);
  Handle<Object> raw_result = UnwrapJSValue(value_wrapper);
  CHECK(raw_result->IsCode());
  return Handle<Code>::cast(raw_result);
}
650

651

652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671
Handle<FixedArray> FunctionInfoWrapper::GetFeedbackVector() {
  Handle<Object> element = this->GetField(kSharedFunctionInfoOffset_);
  Handle<FixedArray> result;
  if (element->IsJSValue()) {
    Handle<JSValue> value_wrapper = Handle<JSValue>::cast(element);
    Handle<Object> raw_result = UnwrapJSValue(value_wrapper);
    Handle<SharedFunctionInfo> shared =
        Handle<SharedFunctionInfo>::cast(raw_result);
    result = Handle<FixedArray>(shared->feedback_vector(), isolate());
    CHECK_EQ(result->length(), GetSlotCount());
  } else {
    // Scripts may never have a SharedFunctionInfo created, so
    // create a type feedback vector here.
    int slot_count = GetSlotCount();
    result = isolate()->factory()->NewTypeFeedbackVector(slot_count);
  }
  return result;
}


672 673 674 675
Handle<Object> FunctionInfoWrapper::GetCodeScopeInfo() {
  Handle<Object> element = this->GetField(kCodeScopeInfoOffset_);
  return UnwrapJSValue(Handle<JSValue>::cast(element));
}
676 677


678 679 680 681 682 683 684 685 686 687 688
void SharedInfoWrapper::SetProperties(Handle<String> name,
                                      int start_position,
                                      int end_position,
                                      Handle<SharedFunctionInfo> info) {
  HandleScope scope(isolate());
  this->SetField(kFunctionNameOffset_, name);
  Handle<JSValue> info_holder = WrapInJSValue(info);
  this->SetField(kSharedInfoOffset_, info_holder);
  this->SetSmiValueField(kStartPositionOffset_, start_position);
  this->SetSmiValueField(kEndPositionOffset_, end_position);
}
689

690 691 692 693 694 695

Handle<SharedFunctionInfo> SharedInfoWrapper::GetInfo() {
  Handle<Object> element = this->GetField(kSharedInfoOffset_);
  Handle<JSValue> value_wrapper = Handle<JSValue>::cast(element);
  return UnwrapSharedFunctionInfoFromJSValue(value_wrapper);
}
696

697

698 699
class FunctionInfoListener {
 public:
700
  explicit FunctionInfoListener(Isolate* isolate) {
701 702
    current_parent_index_ = -1;
    len_ = 0;
703
    result_ = isolate->factory()->NewJSArray(10);
704 705 706
  }

  void FunctionStarted(FunctionLiteral* fun) {
707
    HandleScope scope(isolate());
708
    FunctionInfoWrapper info = FunctionInfoWrapper::Create(isolate());
709
    info.SetInitialProperties(fun->name(), fun->start_position(),
710
                              fun->end_position(), fun->parameter_count(),
711
                              fun->materialized_literal_count(),
712
                              fun->slot_count(),
713 714
                              current_parent_index_);
    current_parent_index_ = len_;
715
    SetElementSloppy(result_, len_, info.GetJSArray());
716 717 718 719
    len_++;
  }

  void FunctionDone() {
720
    HandleScope scope(isolate());
721 722
    FunctionInfoWrapper info =
        FunctionInfoWrapper::cast(
723 724
            *Object::GetElement(
                isolate(), result_, current_parent_index_).ToHandleChecked());
725 726 727
    current_parent_index_ = info.GetParentIndex();
  }

728 729 730
  // Saves only function code, because for a script function we
  // may never create a SharedFunctionInfo object.
  void FunctionCode(Handle<Code> function_code) {
731 732
    FunctionInfoWrapper info =
        FunctionInfoWrapper::cast(
733 734
            *Object::GetElement(
                isolate(), result_, current_parent_index_).ToHandleChecked());
735
    info.SetFunctionCode(function_code,
736
                         Handle<HeapObject>(isolate()->heap()->null_value()));
737 738 739 740
  }

  // Saves full information about a function: its code, its scope info
  // and a SharedFunctionInfo object.
741 742
  void FunctionInfo(Handle<SharedFunctionInfo> shared, Scope* scope,
                    Zone* zone) {
743 744 745
    if (!shared->IsSharedFunctionInfo()) {
      return;
    }
746 747
    FunctionInfoWrapper info =
        FunctionInfoWrapper::cast(
748 749
            *Object::GetElement(
                isolate(), result_, current_parent_index_).ToHandleChecked());
750
    info.SetFunctionCode(Handle<Code>(shared->code()),
751
                         Handle<HeapObject>(shared->scope_info()));
752 753
    info.SetSharedFunctionInfo(shared);

754
    Handle<Object> scope_info_list = SerializeFunctionScope(scope, zone);
755
    info.SetFunctionScopeInfo(scope_info_list);
756 757 758 759
  }

  Handle<JSArray> GetResult() { return result_; }

760
 private:
761 762
  Isolate* isolate() const { return result_->GetIsolate(); }

763
  Handle<Object> SerializeFunctionScope(Scope* scope, Zone* zone) {
764
    Handle<JSArray> scope_info_list = isolate()->factory()->NewJSArray(10);
765 766 767 768 769
    int scope_info_length = 0;

    // Saves some description of scope. It stores name and indexes of
    // variables in the whole scope chain. Null-named slots delimit
    // scopes of this chain.
770 771
    Scope* current_scope = scope;
    while (current_scope != NULL) {
772
      HandleScope handle_scope(isolate());
773 774 775 776
      ZoneList<Variable*> stack_list(current_scope->StackLocalCount(), zone);
      ZoneList<Variable*> context_list(
          current_scope->ContextLocalCount(), zone);
      current_scope->CollectStackAndContextLocals(&stack_list, &context_list);
777
      context_list.Sort(&Variable::CompareIndex);
778

779
      for (int i = 0; i < context_list.length(); i++) {
780 781 782
        SetElementSloppy(scope_info_list,
                         scope_info_length,
                         context_list[i]->name());
783
        scope_info_length++;
784
        SetElementSloppy(
785 786
            scope_info_list,
            scope_info_length,
787
            Handle<Smi>(Smi::FromInt(context_list[i]->index()), isolate()));
788 789
        scope_info_length++;
      }
790 791 792 793
      SetElementSloppy(scope_info_list,
                       scope_info_length,
                       Handle<Object>(isolate()->heap()->null_value(),
                                      isolate()));
794 795
      scope_info_length++;

796 797
      current_scope = current_scope->outer_scope();
    }
798

799
    return scope_info_list;
800 801 802 803 804 805 806
  }

  Handle<JSArray> result_;
  int len_;
  int current_parent_index_;
};

807

808 809 810 811 812 813
void LiveEdit::InitializeThreadLocal(Debug* debug) {
  debug->thread_local_.frame_drop_mode_ = LiveEdit::FRAMES_UNTOUCHED;
}


bool LiveEdit::SetAfterBreakTarget(Debug* debug) {
814
  Code* code = NULL;
815 816
  Isolate* isolate = debug->isolate_;
  switch (debug->thread_local_.frame_drop_mode_) {
817
    case FRAMES_UNTOUCHED:
818
      return false;
819 820 821 822 823 824 825 826 827 828 829
    case FRAME_DROPPED_IN_IC_CALL:
      // We must have been calling IC stub. Do not go there anymore.
      code = isolate->builtins()->builtin(Builtins::kPlainReturn_LiveEdit);
      break;
    case FRAME_DROPPED_IN_DEBUG_SLOT_CALL:
      // Debug break slot stub does not return normally, instead it manually
      // cleans the stack and jumps. We should patch the jump address.
      code = isolate->builtins()->builtin(Builtins::kFrameDropper_LiveEdit);
      break;
    case FRAME_DROPPED_IN_DIRECT_CALL:
      // Nothing to do, after_break_target is not used here.
830
      return true;
831 832 833 834 835 836 837
    case FRAME_DROPPED_IN_RETURN_CALL:
      code = isolate->builtins()->builtin(Builtins::kFrameDropper_LiveEdit);
      break;
    case CURRENTLY_SET_MODE:
      UNREACHABLE();
      break;
  }
838 839
  debug->after_break_target_ = code->entry();
  return true;
840 841 842
}


843 844
MaybeHandle<JSArray> LiveEdit::GatherCompileInfo(Handle<Script> script,
                                                 Handle<String> source) {
845
  Isolate* isolate = script->GetIsolate();
846

847 848 849
  FunctionInfoListener listener(isolate);
  Handle<Object> original_source =
      Handle<Object>(script->source(), isolate);
850
  script->set_source(*source);
851
  isolate->set_active_function_info_listener(&listener);
852 853 854 855 856 857 858 859

  {
    // Creating verbose TryCatch from public API is currently the only way to
    // force code save location. We do not use this the object directly.
    v8::TryCatch try_catch;
    try_catch.SetVerbose(true);

    // A logical 'try' section.
860
    Compiler::CompileForLiveEdit(script);
861 862 863
  }

  // A logical 'catch' section.
864
  Handle<JSObject> rethrow_exception;
865
  if (isolate->has_pending_exception()) {
866
    Handle<Object> exception(isolate->pending_exception(), isolate);
867 868 869 870 871 872 873
    MessageLocation message_location = isolate->GetMessageLocation();

    isolate->clear_pending_message();
    isolate->clear_pending_exception();

    // If possible, copy positions from message object to exception object.
    if (exception->IsJSObject() && !message_location.script().is_null()) {
874
      rethrow_exception = Handle<JSObject>::cast(exception);
875 876

      Factory* factory = isolate->factory();
877
      Handle<String> start_pos_key = factory->InternalizeOneByteString(
878 879 880 881 882
          STATIC_CHAR_VECTOR("startPosition"));
      Handle<String> end_pos_key =
          factory->InternalizeOneByteString(STATIC_CHAR_VECTOR("endPosition"));
      Handle<String> script_obj_key =
          factory->InternalizeOneByteString(STATIC_CHAR_VECTOR("scriptObject"));
883 884
      Handle<Smi> start_pos(
          Smi::FromInt(message_location.start_pos()), isolate);
885
      Handle<Smi> end_pos(Smi::FromInt(message_location.end_pos()), isolate);
886 887
      Handle<JSObject> script_obj =
          Script::GetWrapper(message_location.script());
888 889 890 891 892
      Object::SetProperty(rethrow_exception, start_pos_key, start_pos, SLOPPY)
          .Assert();
      Object::SetProperty(rethrow_exception, end_pos_key, end_pos, SLOPPY)
          .Assert();
      Object::SetProperty(rethrow_exception, script_obj_key, script_obj, SLOPPY)
893
          .Assert();
894 895 896 897
    }
  }

  // A logical 'finally' section.
898
  isolate->set_active_function_info_listener(NULL);
899 900
  script->set_source(*original_source);

901
  if (rethrow_exception.is_null()) {
902
    return listener.GetResult();
903
  } else {
904
    return isolate->Throw<JSArray>(rethrow_exception);
905
  }
906 907 908 909
}


void LiveEdit::WrapSharedFunctionInfos(Handle<JSArray> array) {
910 911
  Isolate* isolate = array->GetIsolate();
  HandleScope scope(isolate);
912
  int len = GetArrayLength(array);
913 914
  for (int i = 0; i < len; i++) {
    Handle<SharedFunctionInfo> info(
915
        SharedFunctionInfo::cast(
916
            *Object::GetElement(isolate, array, i).ToHandleChecked()));
917
    SharedInfoWrapper info_wrapper = SharedInfoWrapper::Create(isolate);
918 919 920
    Handle<String> name_handle(String::cast(info->name()));
    info_wrapper.SetProperties(name_handle, info->start_position(),
                               info->end_position(), info);
921
    SetElementSloppy(array, i, info_wrapper.GetJSArray());
922 923 924 925
  }
}


926 927 928 929
// Visitor that finds all references to a particular code object,
// including "CODE_TARGET" references in other code objects and replaces
// them on the fly.
class ReplacingVisitor : public ObjectVisitor {
930
 public:
931 932
  explicit ReplacingVisitor(Code* original, Code* substitution)
    : original_(original), substitution_(substitution) {
933 934 935 936 937
  }

  virtual void VisitPointers(Object** start, Object** end) {
    for (Object** p = start; p < end; p++) {
      if (*p == original_) {
938
        *p = substitution_;
939 940 941 942
      }
    }
  }

943 944
  virtual void VisitCodeEntry(Address entry) {
    if (Code::GetObjectFromEntryAddress(entry) == original_) {
945 946
      Address substitution_entry = substitution_->instruction_start();
      Memory::Address_at(entry) = substitution_entry;
947 948 949 950
    }
  }

  virtual void VisitCodeTarget(RelocInfo* rinfo) {
951 952
    if (RelocInfo::IsCodeTarget(rinfo->rmode()) &&
        Code::GetCodeFromTargetAddress(rinfo->target_address()) == original_) {
953 954
      Address substitution_entry = substitution_->instruction_start();
      rinfo->set_target_address(substitution_entry);
955 956 957 958 959 960 961 962 963
    }
  }

  virtual void VisitDebugTarget(RelocInfo* rinfo) {
    VisitCodeTarget(rinfo);
  }

 private:
  Code* original_;
964
  Code* substitution_;
965 966
};

967

968
// Finds all references to original and replaces them with substitution.
969 970 971 972 973 974 975
static void ReplaceCodeObject(Handle<Code> original,
                              Handle<Code> substitution) {
  // Perform a full GC in order to ensure that we are not in the middle of an
  // incremental marking phase when we are replacing the code object.
  // Since we are not in an incremental marking phase we can write pointers
  // to code objects (that are never in new space) without worrying about
  // write barriers.
976
  Heap* heap = original->GetHeap();
977
  HeapIterator iterator(heap);
978

979
  DCHECK(!heap->InNewSpace(*substitution));
980

981
  ReplacingVisitor visitor(*original, *substitution);
982 983 984 985

  // Iterate over all roots. Stack frames may have pointer into original code,
  // so temporary replace the pointers with offset numbers
  // in prologue/epilogue.
986
  heap->IterateRoots(&visitor, VISIT_ALL);
987 988 989 990 991 992 993 994 995

  // Now iterate over all pointers of all objects, including code_target
  // implicit pointers.
  for (HeapObject* obj = iterator.next(); obj != NULL; obj = iterator.next()) {
    obj->Iterate(&visitor);
  }
}


996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015
// Patch function literals.
// Name 'literals' is a misnomer. Rather it's a cache for complex object
// boilerplates and for a native context. We must clean cached values.
// Additionally we may need to allocate a new array if number of literals
// changed.
class LiteralFixer {
 public:
  static void PatchLiterals(FunctionInfoWrapper* compile_info_wrapper,
                            Handle<SharedFunctionInfo> shared_info,
                            Isolate* isolate) {
    int new_literal_count = compile_info_wrapper->GetLiteralCount();
    if (new_literal_count > 0) {
      new_literal_count += JSFunction::kLiteralsPrefixSize;
    }
    int old_literal_count = shared_info->num_literals();

    if (old_literal_count == new_literal_count) {
      // If literal count didn't change, simply go over all functions
      // and clear literal arrays.
      ClearValuesVisitor visitor;
1016
      IterateJSFunctions(shared_info, &visitor);
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
    } else {
      // When literal count changes, we have to create new array instances.
      // Since we cannot create instances when iterating heap, we should first
      // collect all functions and fix their literal arrays.
      Handle<FixedArray> function_instances =
          CollectJSFunctions(shared_info, isolate);
      for (int i = 0; i < function_instances->length(); i++) {
        Handle<JSFunction> fun(JSFunction::cast(function_instances->get(i)));
        Handle<FixedArray> old_literals(fun->literals());
        Handle<FixedArray> new_literals =
            isolate->factory()->NewFixedArray(new_literal_count);
        if (new_literal_count > 0) {
          Handle<Context> native_context;
          if (old_literals->length() >
              JSFunction::kLiteralNativeContextIndex) {
            native_context = Handle<Context>(
                JSFunction::NativeContextFromLiterals(fun->literals()));
          } else {
            native_context = Handle<Context>(fun->context()->native_context());
          }
          new_literals->set(JSFunction::kLiteralNativeContextIndex,
              *native_context);
        }
        fun->set_literals(*new_literals);
      }

      shared_info->set_num_literals(new_literal_count);
    }
  }

 private:
  // Iterates all function instances in the HEAP that refers to the
  // provided shared_info.
  template<typename Visitor>
1051
  static void IterateJSFunctions(Handle<SharedFunctionInfo> shared_info,
1052
                                 Visitor* visitor) {
1053
    HeapIterator iterator(shared_info->GetHeap());
1054 1055 1056 1057
    for (HeapObject* obj = iterator.next(); obj != NULL;
        obj = iterator.next()) {
      if (obj->IsJSFunction()) {
        JSFunction* function = JSFunction::cast(obj);
1058
        if (function->shared() == *shared_info) {
1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070
          visitor->visit(function);
        }
      }
    }
  }

  // Finds all instances of JSFunction that refers to the provided shared_info
  // and returns array with them.
  static Handle<FixedArray> CollectJSFunctions(
      Handle<SharedFunctionInfo> shared_info, Isolate* isolate) {
    CountVisitor count_visitor;
    count_visitor.count = 0;
1071
    IterateJSFunctions(shared_info, &count_visitor);
1072 1073 1074 1075 1076
    int size = count_visitor.count;

    Handle<FixedArray> result = isolate->factory()->NewFixedArray(size);
    if (size > 0) {
      CollectVisitor collect_visitor(result);
1077
      IterateJSFunctions(shared_info, &collect_visitor);
1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116
    }
    return result;
  }

  class ClearValuesVisitor {
   public:
    void visit(JSFunction* fun) {
      FixedArray* literals = fun->literals();
      int len = literals->length();
      for (int j = JSFunction::kLiteralsPrefixSize; j < len; j++) {
        literals->set_undefined(j);
      }
    }
  };

  class CountVisitor {
   public:
    void visit(JSFunction* fun) {
      count++;
    }
    int count;
  };

  class CollectVisitor {
   public:
    explicit CollectVisitor(Handle<FixedArray> output)
        : m_output(output), m_pos(0) {}

    void visit(JSFunction* fun) {
      m_output->set(m_pos, fun);
      m_pos++;
    }
   private:
    Handle<FixedArray> m_output;
    int m_pos;
  };
};


1117 1118 1119 1120 1121 1122 1123
// Check whether the code is natural function code (not a lazy-compile stub
// code).
static bool IsJSFunctionCode(Code* code) {
  return code->kind() == Code::FUNCTION;
}


1124 1125
// Returns true if an instance of candidate were inlined into function's code.
static bool IsInlined(JSFunction* function, SharedFunctionInfo* candidate) {
1126
  DisallowHeapAllocation no_gc;
1127 1128 1129 1130 1131 1132

  if (function->code()->kind() != Code::OPTIMIZED_FUNCTION) return false;

  DeoptimizationInputData* data =
      DeoptimizationInputData::cast(function->code()->deoptimization_data());

1133 1134 1135
  if (data == function->GetIsolate()->heap()->empty_fixed_array()) {
    return false;
  }
1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148

  FixedArray* literals = data->LiteralArray();

  int inlined_count = data->InlinedFunctionCount()->value();
  for (int i = 0; i < inlined_count; ++i) {
    JSFunction* inlined = JSFunction::cast(literals->get(i));
    if (inlined->shared() == candidate) return true;
  }

  return false;
}


1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162
// Marks code that shares the same shared function info or has inlined
// code that shares the same function info.
class DependentFunctionMarker: public OptimizedFunctionVisitor {
 public:
  SharedFunctionInfo* shared_info_;
  bool found_;

  explicit DependentFunctionMarker(SharedFunctionInfo* shared_info)
    : shared_info_(shared_info), found_(false) { }

  virtual void EnterContext(Context* context) { }  // Don't care.
  virtual void LeaveContext(Context* context)  { }  // Don't care.
  virtual void VisitFunction(JSFunction* function) {
    // It should be guaranteed by the iterator that everything is optimized.
1163
    DCHECK(function->code()->kind() == Code::OPTIMIZED_FUNCTION);
1164 1165 1166 1167 1168
    if (shared_info_ == function->shared() ||
        IsInlined(function, shared_info_)) {
      // Mark the code for deoptimization.
      function->code()->set_marked_for_deoptimization(true);
      found_ = true;
1169
    }
1170 1171
  }
};
1172 1173


1174
static void DeoptimizeDependentFunctions(SharedFunctionInfo* function_info) {
1175
  DisallowHeapAllocation no_allocation;
1176 1177 1178
  DependentFunctionMarker marker(function_info);
  // TODO(titzer): need to traverse all optimized code to find OSR code here.
  Deoptimizer::VisitAllOptimizedFunctions(function_info->GetIsolate(), &marker);
1179

1180 1181 1182 1183
  if (marker.found_) {
    // Only go through with the deoptimization if something was found.
    Deoptimizer::DeoptimizeMarkedCode(function_info->GetIsolate());
  }
1184 1185 1186
}


1187
void LiveEdit::ReplaceFunctionCode(
1188 1189
    Handle<JSArray> new_compile_info_array,
    Handle<JSArray> shared_info_array) {
1190
  Isolate* isolate = new_compile_info_array->GetIsolate();
1191

1192 1193 1194 1195 1196
  FunctionInfoWrapper compile_info_wrapper(new_compile_info_array);
  SharedInfoWrapper shared_info_wrapper(shared_info_array);

  Handle<SharedFunctionInfo> shared_info = shared_info_wrapper.GetInfo();

1197
  if (IsJSFunctionCode(shared_info->code())) {
1198
    Handle<Code> code = compile_info_wrapper.GetFunctionCode();
1199 1200
    ReplaceCodeObject(Handle<Code>(shared_info->code()), code);
    Handle<Object> code_scope_info = compile_info_wrapper.GetCodeScopeInfo();
1201
    if (code_scope_info->IsFixedArray()) {
1202
      shared_info->set_scope_info(ScopeInfo::cast(*code_scope_info));
1203
    }
1204
    shared_info->DisableOptimization(kLiveEdit);
1205 1206 1207 1208
    // Update the type feedback vector
    Handle<FixedArray> feedback_vector =
        compile_info_wrapper.GetFeedbackVector();
    shared_info->set_feedback_vector(*feedback_vector);
1209 1210 1211 1212 1213
  }

  if (shared_info->debug_info()->IsDebugInfo()) {
    Handle<DebugInfo> debug_info(DebugInfo::cast(shared_info->debug_info()));
    Handle<Code> new_original_code =
1214
        isolate->factory()->CopyCode(compile_info_wrapper.GetFunctionCode());
1215 1216
    debug_info->set_original_code(*new_original_code);
  }
1217

1218 1219 1220 1221
  int start_position = compile_info_wrapper.GetStartPosition();
  int end_position = compile_info_wrapper.GetEndPosition();
  shared_info->set_start_position(start_position);
  shared_info->set_end_position(end_position);
1222

1223 1224
  LiteralFixer::PatchLiterals(&compile_info_wrapper, shared_info, isolate);

1225
  shared_info->set_construct_stub(
1226
      isolate->builtins()->builtin(Builtins::kJSConstructStubGeneric));
1227

1228
  DeoptimizeDependentFunctions(*shared_info);
1229
  isolate->compilation_cache()->Remove(shared_info);
1230 1231 1232
}


1233
void LiveEdit::FunctionSourceUpdated(Handle<JSArray> shared_info_array) {
1234 1235 1236 1237
  SharedInfoWrapper shared_info_wrapper(shared_info_array);
  Handle<SharedFunctionInfo> shared_info = shared_info_wrapper.GetInfo();

  DeoptimizeDependentFunctions(*shared_info);
1238
  shared_info_array->GetIsolate()->compilation_cache()->Remove(shared_info);
1239 1240 1241
}


1242 1243 1244
void LiveEdit::SetFunctionScript(Handle<JSValue> function_wrapper,
                                 Handle<Object> script_handle) {
  Handle<SharedFunctionInfo> shared_info =
1245
      UnwrapSharedFunctionInfoFromJSValue(function_wrapper);
1246
  CHECK(script_handle->IsScript() || script_handle->IsUndefined());
1247
  shared_info->set_script(*script_handle);
1248

1249
  function_wrapper->GetIsolate()->compilation_cache()->Remove(shared_info);
1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264
}


// For a script text change (defined as position_change_array), translates
// position in unchanged text to position in changed text.
// Text change is a set of non-overlapping regions in text, that have changed
// their contents and length. It is specified 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.
// Only position in text beyond any changes may be successfully translated.
// If a positions is inside some region that changed, result is currently
// undefined.
static int TranslatePosition(int original_position,
                             Handle<JSArray> position_change_array) {
  int position_diff = 0;
1265
  int array_len = GetArrayLength(position_change_array);
1266
  Isolate* isolate = position_change_array->GetIsolate();
1267
  // TODO(635): binary search may be used here
1268
  for (int i = 0; i < array_len; i += 3) {
1269
    HandleScope scope(isolate);
1270 1271
    Handle<Object> element = Object::GetElement(
        isolate, position_change_array, i).ToHandleChecked();
1272
    CHECK(element->IsSmi());
1273
    int chunk_start = Handle<Smi>::cast(element)->value();
1274 1275 1276
    if (original_position < chunk_start) {
      break;
    }
1277 1278
    element = Object::GetElement(
        isolate, position_change_array, i + 1).ToHandleChecked();
1279
    CHECK(element->IsSmi());
1280
    int chunk_end = Handle<Smi>::cast(element)->value();
1281
    // Position mustn't be inside a chunk.
1282
    DCHECK(original_position >= chunk_end);
1283 1284
    element = Object::GetElement(
        isolate, position_change_array, i + 2).ToHandleChecked();
1285
    CHECK(element->IsSmi());
1286
    int chunk_changed_end = Handle<Smi>::cast(element)->value();
1287
    position_diff = chunk_changed_end - chunk_end;
1288 1289 1290 1291 1292 1293
  }

  return original_position + position_diff;
}


1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322
// Auto-growing buffer for writing relocation info code section. This buffer
// is a simplified version of buffer from Assembler. Unlike Assembler, this
// class is platform-independent and it works without dealing with instructions.
// As specified by RelocInfo format, the buffer is filled in reversed order:
// from upper to lower addresses.
// It uses NewArray/DeleteArray for memory management.
class RelocInfoBuffer {
 public:
  RelocInfoBuffer(int buffer_initial_capicity, byte* pc) {
    buffer_size_ = buffer_initial_capicity + kBufferGap;
    buffer_ = NewArray<byte>(buffer_size_);

    reloc_info_writer_.Reposition(buffer_ + buffer_size_, pc);
  }
  ~RelocInfoBuffer() {
    DeleteArray(buffer_);
  }

  // As specified by RelocInfo format, the buffer is filled in reversed order:
  // from upper to lower addresses.
  void Write(const RelocInfo* rinfo) {
    if (buffer_ + kBufferGap >= reloc_info_writer_.pos()) {
      Grow();
    }
    reloc_info_writer_.Write(rinfo);
  }

  Vector<byte> GetResult() {
    // Return the bytes from pos up to end of buffer.
1323 1324 1325
    int result_size =
        static_cast<int>((buffer_ + buffer_size_) - reloc_info_writer_.pos());
    return Vector<byte>(reloc_info_writer_.pos(), result_size);
1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342
  }

 private:
  void Grow() {
    // Compute new buffer size.
    int new_buffer_size;
    if (buffer_size_ < 2 * KB) {
      new_buffer_size = 4 * KB;
    } else {
      new_buffer_size = 2 * buffer_size_;
    }
    // Some internal data structures overflow for very large buffers,
    // they must ensure that kMaximalBufferSize is not too large.
    if (new_buffer_size > kMaximalBufferSize) {
      V8::FatalProcessOutOfMemory("RelocInfoBuffer::GrowBuffer");
    }

1343
    // Set up new buffer.
1344 1345 1346
    byte* new_buffer = NewArray<byte>(new_buffer_size);

    // Copy the data.
1347 1348
    int curently_used_size =
        static_cast<int>(buffer_ + buffer_size_ - reloc_info_writer_.pos());
1349 1350
    MemMove(new_buffer + new_buffer_size - curently_used_size,
            reloc_info_writer_.pos(), curently_used_size);
1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364

    reloc_info_writer_.Reposition(
        new_buffer + new_buffer_size - curently_used_size,
        reloc_info_writer_.last_pc());

    DeleteArray(buffer_);
    buffer_ = new_buffer;
    buffer_size_ = new_buffer_size;
  }

  RelocInfoWriter reloc_info_writer_;
  byte* buffer_;
  int buffer_size_;

1365
  static const int kBufferGap = RelocInfoWriter::kMaxSize;
1366 1367 1368
  static const int kMaximalBufferSize = 512*MB;
};

1369

1370 1371
// Patch positions in code (changes relocation info section) and possibly
// returns new instance of code.
1372 1373
static Handle<Code> PatchPositionsInCode(
    Handle<Code> code,
1374
    Handle<JSArray> position_change_array) {
1375
  Isolate* isolate = code->GetIsolate();
1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387

  RelocInfoBuffer buffer_writer(code->relocation_size(),
                                code->instruction_start());

  {
    for (RelocIterator it(*code); !it.done(); it.next()) {
      RelocInfo* rinfo = it.rinfo();
      if (RelocInfo::IsPosition(rinfo->rmode())) {
        int position = static_cast<int>(rinfo->data());
        int new_position = TranslatePosition(position,
                                             position_change_array);
        if (position != new_position) {
1388
          RelocInfo info_copy(rinfo->pc(), rinfo->rmode(), new_position, NULL);
1389 1390 1391 1392
          buffer_writer.Write(&info_copy);
          continue;
        }
      }
1393 1394 1395
      if (RelocInfo::IsRealRelocMode(rinfo->rmode())) {
        buffer_writer.Write(it.rinfo());
      }
1396 1397 1398 1399 1400 1401 1402
    }
  }

  Vector<byte> buffer = buffer_writer.GetResult();

  if (buffer.length() == code->relocation_size()) {
    // Simply patch relocation area of code.
1403
    MemCopy(code->relocation_start(), buffer.start(), buffer.length());
1404 1405 1406 1407 1408
    return code;
  } else {
    // Relocation info section now has different size. We cannot simply
    // rewrite it inside code object. Instead we have to create a new
    // code object.
1409
    Handle<Code> result(isolate->factory()->CopyCode(code, buffer));
1410 1411 1412 1413 1414
    return result;
  }
}


1415 1416
void LiveEdit::PatchFunctionPositions(Handle<JSArray> shared_info_array,
                                      Handle<JSArray> position_change_array) {
1417 1418 1419
  SharedInfoWrapper shared_info_wrapper(shared_info_array);
  Handle<SharedFunctionInfo> info = shared_info_wrapper.GetInfo();

1420 1421 1422
  int old_function_start = info->start_position();
  int new_function_start = TranslatePosition(old_function_start,
                                             position_change_array);
1423 1424 1425 1426
  int new_function_end = TranslatePosition(info->end_position(),
                                           position_change_array);
  int new_function_token_pos =
      TranslatePosition(info->function_token_position(), position_change_array);
1427

1428 1429 1430
  info->set_start_position(new_function_start);
  info->set_end_position(new_function_end);
  info->set_function_token_position(new_function_token_pos);
1431

1432 1433 1434 1435 1436 1437 1438 1439 1440 1441
  if (IsJSFunctionCode(info->code())) {
    // Patch relocation info section of the code.
    Handle<Code> patched_code = PatchPositionsInCode(Handle<Code>(info->code()),
                                                     position_change_array);
    if (*patched_code != info->code()) {
      // Replace all references to the code across the heap. In particular,
      // some stubs may refer to this code and this code may be being executed
      // on stack (it is safe to substitute the code object on stack, because
      // we only change the structure of rinfo and leave instructions
      // untouched).
1442
      ReplaceCodeObject(Handle<Code>(info->code()), patched_code);
1443
    }
1444
  }
1445
}
1446

1447

1448
static Handle<Script> CreateScriptCopy(Handle<Script> original) {
1449
  Isolate* isolate = original->GetIsolate();
1450

1451 1452
  Handle<String> original_source(String::cast(original->source()));
  Handle<Script> copy = isolate->factory()->NewScript(original_source);
1453

1454 1455 1456 1457 1458 1459 1460 1461 1462
  copy->set_name(original->name());
  copy->set_line_offset(original->line_offset());
  copy->set_column_offset(original->column_offset());
  copy->set_type(original->type());
  copy->set_context_data(original->context_data());
  copy->set_eval_from_shared(original->eval_from_shared());
  copy->set_eval_from_instructions_offset(
      original->eval_from_instructions_offset());

1463 1464 1465 1466
  // Copy all the flags, but clear compilation state.
  copy->set_flags(original->flags());
  copy->set_compilation_state(Script::COMPILATION_STATE_INITIAL);

1467 1468 1469 1470
  return copy;
}


1471 1472 1473
Handle<Object> LiveEdit::ChangeScriptSource(Handle<Script> original_script,
                                            Handle<String> new_source,
                                            Handle<Object> old_script_name) {
1474
  Isolate* isolate = original_script->GetIsolate();
1475 1476 1477 1478 1479
  Handle<Object> old_script_object;
  if (old_script_name->IsString()) {
    Handle<Script> old_script = CreateScriptCopy(original_script);
    old_script->set_name(String::cast(*old_script_name));
    old_script_object = old_script;
1480
    isolate->debug()->OnAfterCompile(old_script);
1481
  } else {
1482
    old_script_object = isolate->factory()->null_value();
1483 1484 1485 1486 1487
  }

  original_script->set_source(*new_source);

  // Drop line ends so that they will be recalculated.
1488
  original_script->set_line_ends(isolate->heap()->undefined_value());
1489

1490
  return old_script_object;
1491 1492 1493 1494 1495 1496 1497 1498 1499 1500
}



void LiveEdit::ReplaceRefToNestedFunction(
    Handle<JSValue> parent_function_wrapper,
    Handle<JSValue> orig_function_wrapper,
    Handle<JSValue> subst_function_wrapper) {

  Handle<SharedFunctionInfo> parent_shared =
1501
      UnwrapSharedFunctionInfoFromJSValue(parent_function_wrapper);
1502
  Handle<SharedFunctionInfo> orig_shared =
1503
      UnwrapSharedFunctionInfoFromJSValue(orig_function_wrapper);
1504
  Handle<SharedFunctionInfo> subst_shared =
1505
      UnwrapSharedFunctionInfoFromJSValue(subst_function_wrapper);
1506 1507 1508 1509 1510

  for (RelocIterator it(parent_shared->code()); !it.done(); it.next()) {
    if (it.rinfo()->rmode() == RelocInfo::EMBEDDED_OBJECT) {
      if (it.rinfo()->target_object() == *orig_shared) {
        it.rinfo()->set_target_object(*subst_shared);
1511
      }
1512 1513
    }
  }
1514 1515 1516
}


1517 1518 1519
// Check an activation against list of functions. If there is a function
// that matches, its status in result array is changed to status argument value.
static bool CheckActivation(Handle<JSArray> shared_info_array,
1520 1521
                            Handle<JSArray> result,
                            StackFrame* frame,
1522
                            LiveEdit::FunctionPatchabilityStatus status) {
1523 1524
  if (!frame->is_java_script()) return false;

1525
  Handle<JSFunction> function(JavaScriptFrame::cast(frame)->function());
1526

1527
  Isolate* isolate = shared_info_array->GetIsolate();
1528
  int len = GetArrayLength(shared_info_array);
1529
  for (int i = 0; i < len; i++) {
1530 1531
    HandleScope scope(isolate);
    Handle<Object> element =
1532
        Object::GetElement(isolate, shared_info_array, i).ToHandleChecked();
1533
    Handle<JSValue> jsvalue = Handle<JSValue>::cast(element);
1534 1535
    Handle<SharedFunctionInfo> shared =
        UnwrapSharedFunctionInfoFromJSValue(jsvalue);
1536

1537
    if (function->shared() == *shared || IsInlined(*function, *shared)) {
1538
      SetElementSloppy(result, i, Handle<Smi>(Smi::FromInt(status), isolate));
1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550
      return true;
    }
  }
  return false;
}


// Iterates over handler chain and removes all elements that are inside
// frames being dropped.
static bool FixTryCatchHandler(StackFrame* top_frame,
                               StackFrame* bottom_frame) {
  Address* pointer_address =
1551
      &Memory::Address_at(top_frame->isolate()->get_address_from_id(
1552
          Isolate::kHandlerAddress));
1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566

  while (*pointer_address < top_frame->sp()) {
    pointer_address = &Memory::Address_at(*pointer_address);
  }
  Address* above_frame_address = pointer_address;
  while (*pointer_address < bottom_frame->fp()) {
    pointer_address = &Memory::Address_at(*pointer_address);
  }
  bool change = *above_frame_address != *pointer_address;
  *above_frame_address = *pointer_address;
  return change;
}


1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581
// Initializes an artificial stack frame. The data it contains is used for:
//  a. successful work of frame dropper code which eventually gets control,
//  b. being compatible with regular stack structure for various stack
//     iterators.
// Returns address of stack allocated pointer to restarted function,
// the value that is called 'restarter_frame_function_pointer'. The value
// at this address (possibly updated by GC) may be used later when preparing
// 'step in' operation.
// Frame structure (conforms InternalFrame structure):
//   -- code
//   -- SMI maker
//   -- function (slot is called "context")
//   -- frame base
static Object** SetUpFrameDropperFrame(StackFrame* bottom_js_frame,
                                       Handle<Code> code) {
1582
  DCHECK(bottom_js_frame->is_java_script());
1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598

  Address fp = bottom_js_frame->fp();

  // Move function pointer into "context" slot.
  Memory::Object_at(fp + StandardFrameConstants::kContextOffset) =
      Memory::Object_at(fp + JavaScriptFrameConstants::kFunctionOffset);

  Memory::Object_at(fp + InternalFrameConstants::kCodeOffset) = *code;
  Memory::Object_at(fp + StandardFrameConstants::kMarkerOffset) =
      Smi::FromInt(StackFrame::INTERNAL);

  return reinterpret_cast<Object**>(&Memory::Object_at(
      fp + StandardFrameConstants::kContextOffset));
}


1599 1600 1601 1602 1603 1604
// Removes specified range of frames from stack. There may be 1 or more
// frames in range. Anyway the bottom frame is restarted rather than dropped,
// and therefore has to be a JavaScript frame.
// Returns error message or NULL.
static const char* DropFrames(Vector<StackFrame*> frames,
                              int top_frame_index,
1605
                              int bottom_js_frame_index,
1606
                              LiveEdit::FrameDropMode* mode,
1607
                              Object*** restarter_frame_function_pointer) {
1608
  if (!LiveEdit::kFrameDropperSupported) {
1609 1610 1611
    return "Stack manipulations are not supported in this architecture.";
  }

1612 1613 1614 1615
  StackFrame* pre_top_frame = frames[top_frame_index - 1];
  StackFrame* top_frame = frames[top_frame_index];
  StackFrame* bottom_js_frame = frames[bottom_js_frame_index];

1616
  DCHECK(bottom_js_frame->is_java_script());
1617 1618

  // Check the nature of the top frame.
1619
  Isolate* isolate = bottom_js_frame->isolate();
1620
  Code* pre_top_frame_code = pre_top_frame->LookupCode();
1621
  bool frame_has_padding = true;
1622
  if (pre_top_frame_code->is_inline_cache_stub() &&
1623
      pre_top_frame_code->is_debug_stub()) {
1624
    // OK, we can drop inline cache calls.
1625
    *mode = LiveEdit::FRAME_DROPPED_IN_IC_CALL;
1626
  } else if (pre_top_frame_code ==
1627
             isolate->builtins()->builtin(Builtins::kSlot_DebugBreak)) {
1628
    // OK, we can drop debug break slot.
1629
    *mode = LiveEdit::FRAME_DROPPED_IN_DEBUG_SLOT_CALL;
1630
  } else if (pre_top_frame_code ==
1631
             isolate->builtins()->builtin(Builtins::kFrameDropper_LiveEdit)) {
1632
    // OK, we can drop our own code.
1633 1634
    pre_top_frame = frames[top_frame_index - 2];
    top_frame = frames[top_frame_index - 1];
1635
    *mode = LiveEdit::CURRENTLY_SET_MODE;
1636
    frame_has_padding = false;
1637
  } else if (pre_top_frame_code ==
1638 1639
             isolate->builtins()->builtin(Builtins::kReturn_DebugBreak)) {
    *mode = LiveEdit::FRAME_DROPPED_IN_RETURN_CALL;
1640
  } else if (pre_top_frame_code->kind() == Code::STUB &&
1641
             CodeStub::GetMajorKey(pre_top_frame_code) == CodeStub::CEntry) {
1642 1643
    // Entry from our unit tests on 'debugger' statement.
    // It's fine, we support this case.
1644
    *mode = LiveEdit::FRAME_DROPPED_IN_DIRECT_CALL;
1645 1646 1647 1648
    // We don't have a padding from 'debugger' statement call.
    // Here the stub is CEntry, it's not debug-only and can't be padded.
    // If anyone would complain, a proxy padded stub could be added.
    frame_has_padding = false;
1649 1650 1651
  } else if (pre_top_frame->type() == StackFrame::ARGUMENTS_ADAPTOR) {
    // This must be adaptor that remain from the frame dropping that
    // is still on stack. A frame dropper frame must be above it.
1652
    DCHECK(frames[top_frame_index - 2]->LookupCode() ==
1653
           isolate->builtins()->builtin(Builtins::kFrameDropper_LiveEdit));
1654 1655
    pre_top_frame = frames[top_frame_index - 3];
    top_frame = frames[top_frame_index - 2];
1656
    *mode = LiveEdit::CURRENTLY_SET_MODE;
1657
    frame_has_padding = false;
1658 1659 1660 1661 1662
  } else {
    return "Unknown structure of stack above changing function";
  }

  Address unused_stack_top = top_frame->sp();
1663
  int new_frame_size = LiveEdit::kFrameDropperFrameSize * kPointerSize;
1664
  Address unused_stack_bottom = bottom_js_frame->fp()
1665
      - new_frame_size + kPointerSize;  // Bigger address end is exclusive.
1666

1667 1668 1669
  Address* top_frame_pc_address = top_frame->pc_address();

  // top_frame may be damaged below this point. Do not used it.
1670
  DCHECK(!(top_frame = NULL));
1671

1672
  if (unused_stack_top > unused_stack_bottom) {
1673
    if (frame_has_padding) {
1674 1675
      int shortage_bytes =
          static_cast<int>(unused_stack_top - unused_stack_bottom);
1676 1677

      Address padding_start = pre_top_frame->fp() -
1678
          LiveEdit::kFrameDropperFrameSize * kPointerSize;
1679 1680

      Address padding_pointer = padding_start;
1681
      Smi* padding_object = Smi::FromInt(LiveEdit::kFramePaddingValue);
1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695
      while (Memory::Object_at(padding_pointer) == padding_object) {
        padding_pointer -= kPointerSize;
      }
      int padding_counter =
          Smi::cast(Memory::Object_at(padding_pointer))->value();
      if (padding_counter * kPointerSize < shortage_bytes) {
        return "Not enough space for frame dropper frame "
            "(even with padding frame)";
      }
      Memory::Object_at(padding_pointer) =
          Smi::FromInt(padding_counter - shortage_bytes / kPointerSize);

      StackFrame* pre_pre_frame = frames[top_frame_index - 2];

1696 1697
      MemMove(padding_start + kPointerSize - shortage_bytes,
              padding_start + kPointerSize,
1698
              LiveEdit::kFrameDropperFrameSize * kPointerSize);
1699 1700 1701 1702 1703 1704 1705 1706 1707 1708

      pre_top_frame->UpdateFp(pre_top_frame->fp() - shortage_bytes);
      pre_pre_frame->SetCallerFp(pre_top_frame->fp());
      unused_stack_top -= shortage_bytes;

      STATIC_ASSERT(sizeof(Address) == kPointerSize);
      top_frame_pc_address -= shortage_bytes / kPointerSize;
    } else {
      return "Not enough space for frame dropper frame";
    }
1709 1710 1711 1712 1713 1714
  }

  // Committing now. After this point we should return only NULL value.

  FixTryCatchHandler(pre_top_frame, bottom_js_frame);
  // Make sure FixTryCatchHandler is idempotent.
1715
  DCHECK(!FixTryCatchHandler(pre_top_frame, bottom_js_frame));
1716

1717
  Handle<Code> code = isolate->builtins()->FrameDropper_LiveEdit();
1718
  *top_frame_pc_address = code->entry();
1719 1720
  pre_top_frame->SetCallerFp(bottom_js_frame->fp());

1721
  *restarter_frame_function_pointer =
1722
      SetUpFrameDropperFrame(bottom_js_frame, code);
1723

1724
  DCHECK((**restarter_frame_function_pointer)->IsJSFunction());
1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735

  for (Address a = unused_stack_top;
      a < unused_stack_bottom;
      a += kPointerSize) {
    Memory::Object_at(a) = Smi::FromInt(0);
  }

  return NULL;
}


1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747
// Describes a set of call frames that execute any of listed functions.
// Finding no such frames does not mean error.
class MultipleFunctionTarget {
 public:
  MultipleFunctionTarget(Handle<JSArray> shared_info_array,
      Handle<JSArray> result)
      : m_shared_info_array(shared_info_array),
        m_result(result) {}
  bool MatchActivation(StackFrame* frame,
      LiveEdit::FunctionPatchabilityStatus status) {
    return CheckActivation(m_shared_info_array, m_result, frame, status);
  }
1748
  const char* GetNotFoundMessage() const {
1749 1750 1751 1752 1753 1754 1755
    return NULL;
  }
 private:
  Handle<JSArray> m_shared_info_array;
  Handle<JSArray> m_result;
};

1756

1757 1758 1759
// Drops all call frame matched by target and all frames above them.
template<typename TARGET>
static const char* DropActivationsInActiveThreadImpl(
1760 1761 1762
    Isolate* isolate,
    TARGET& target,  // NOLINT
    bool do_drop) {
1763
  Debug* debug = isolate->debug();
1764 1765
  Zone zone(isolate);
  Vector<StackFrame*> frames = CreateStackMap(isolate, &zone);
1766 1767 1768 1769 1770 1771


  int top_frame_index = -1;
  int frame_index = 0;
  for (; frame_index < frames.length(); frame_index++) {
    StackFrame* frame = frames[frame_index];
1772
    if (frame->id() == debug->break_frame_id()) {
1773 1774 1775
      top_frame_index = frame_index;
      break;
    }
1776 1777
    if (target.MatchActivation(
            frame, LiveEdit::FUNCTION_BLOCKED_UNDER_NATIVE_CODE)) {
1778 1779 1780 1781 1782 1783 1784 1785
      // We are still above break_frame. It is not a target frame,
      // it is a problem.
      return "Debugger mark-up on stack is not found";
    }
  }

  if (top_frame_index == -1) {
    // We haven't found break frame, but no function is blocking us anyway.
1786
    return target.GetNotFoundMessage();
1787 1788 1789 1790
  }

  bool target_frame_found = false;
  int bottom_js_frame_index = top_frame_index;
1791 1792
  bool non_droppable_frame_found = false;
  LiveEdit::FunctionPatchabilityStatus non_droppable_reason;
1793 1794 1795

  for (; frame_index < frames.length(); frame_index++) {
    StackFrame* frame = frames[frame_index];
1796 1797 1798 1799 1800 1801 1802 1803 1804
    if (frame->is_exit()) {
      non_droppable_frame_found = true;
      non_droppable_reason = LiveEdit::FUNCTION_BLOCKED_UNDER_NATIVE_CODE;
      break;
    }
    if (frame->is_java_script() &&
        JavaScriptFrame::cast(frame)->function()->shared()->is_generator()) {
      non_droppable_frame_found = true;
      non_droppable_reason = LiveEdit::FUNCTION_BLOCKED_UNDER_GENERATOR;
1805 1806
      break;
    }
1807 1808
    if (target.MatchActivation(
            frame, LiveEdit::FUNCTION_BLOCKED_ON_ACTIVE_STACK)) {
1809 1810 1811 1812 1813
      target_frame_found = true;
      bottom_js_frame_index = frame_index;
    }
  }

1814 1815 1816 1817
  if (non_droppable_frame_found) {
    // There is a C or generator frame on stack.  We can't drop C frames, and we
    // can't restart generators.  Check that there are no target frames below
    // them.
1818 1819 1820
    for (; frame_index < frames.length(); frame_index++) {
      StackFrame* frame = frames[frame_index];
      if (frame->is_java_script()) {
1821 1822
        if (target.MatchActivation(frame, non_droppable_reason)) {
          // Fail.
1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835
          return NULL;
        }
      }
    }
  }

  if (!do_drop) {
    // We are in check-only mode.
    return NULL;
  }

  if (!target_frame_found) {
    // Nothing to drop.
1836
    return target.GetNotFoundMessage();
1837 1838
  }

1839
  LiveEdit::FrameDropMode drop_mode = LiveEdit::FRAMES_UNTOUCHED;
1840
  Object** restarter_frame_function_pointer = NULL;
1841
  const char* error_message = DropFrames(frames, top_frame_index,
1842 1843
                                         bottom_js_frame_index, &drop_mode,
                                         &restarter_frame_function_pointer);
1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856

  if (error_message != NULL) {
    return error_message;
  }

  // Adjust break_frame after some frames has been dropped.
  StackFrame::Id new_id = StackFrame::NO_ID;
  for (int i = bottom_js_frame_index + 1; i < frames.length(); i++) {
    if (frames[i]->type() == StackFrame::JAVA_SCRIPT) {
      new_id = frames[i]->id();
      break;
    }
  }
1857 1858
  debug->FramesHaveBeenDropped(
      new_id, drop_mode, restarter_frame_function_pointer);
1859 1860 1861
  return NULL;
}

1862

1863 1864 1865
// Fills result array with statuses of functions. Modifies the stack
// removing all listed function if possible and if do_drop is true.
static const char* DropActivationsInActiveThread(
1866
    Handle<JSArray> shared_info_array, Handle<JSArray> result, bool do_drop) {
1867 1868
  MultipleFunctionTarget target(shared_info_array, result);

1869 1870
  const char* message = DropActivationsInActiveThreadImpl(
      shared_info_array->GetIsolate(), target, do_drop);
1871 1872 1873 1874
  if (message) {
    return message;
  }

1875
  Isolate* isolate = shared_info_array->GetIsolate();
1876
  int array_len = GetArrayLength(shared_info_array);
1877 1878 1879

  // Replace "blocked on active" with "replaced on active" status.
  for (int i = 0; i < array_len; i++) {
1880
    Handle<Object> obj =
1881
        Object::GetElement(isolate, result, i).ToHandleChecked();
1882
    if (*obj == Smi::FromInt(LiveEdit::FUNCTION_BLOCKED_ON_ACTIVE_STACK)) {
1883
      Handle<Object> replaced(
1884
          Smi::FromInt(LiveEdit::FUNCTION_REPLACED_ON_ACTIVE_STACK), isolate);
1885
      SetElementSloppy(result, i, replaced);
1886 1887 1888 1889 1890 1891
    }
  }
  return NULL;
}


1892 1893 1894 1895 1896 1897
bool LiveEdit::FindActiveGenerators(Handle<FixedArray> shared_info_array,
                                    Handle<FixedArray> result,
                                    int len) {
  Isolate* isolate = shared_info_array->GetIsolate();
  bool found_suspended_activations = false;

1898
  DCHECK_LE(len, result->length());
1899 1900 1901

  FunctionPatchabilityStatus active = FUNCTION_BLOCKED_ACTIVE_GENERATOR;

1902
  Heap* heap = isolate->heap();
1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929
  HeapIterator iterator(heap);
  HeapObject* obj = NULL;
  while ((obj = iterator.next()) != NULL) {
    if (!obj->IsJSGeneratorObject()) continue;

    JSGeneratorObject* gen = JSGeneratorObject::cast(obj);
    if (gen->is_closed()) continue;

    HandleScope scope(isolate);

    for (int i = 0; i < len; i++) {
      Handle<JSValue> jsvalue =
          Handle<JSValue>::cast(FixedArray::get(shared_info_array, i));
      Handle<SharedFunctionInfo> shared =
          UnwrapSharedFunctionInfoFromJSValue(jsvalue);

      if (gen->function()->shared() == *shared) {
        result->set(i, Smi::FromInt(active));
        found_suspended_activations = true;
      }
    }
  }

  return found_suspended_activations;
}


1930 1931 1932 1933 1934 1935 1936
class InactiveThreadActivationsChecker : public ThreadVisitor {
 public:
  InactiveThreadActivationsChecker(Handle<JSArray> shared_info_array,
                                   Handle<JSArray> result)
      : shared_info_array_(shared_info_array), result_(result),
        has_blocked_functions_(false) {
  }
1937 1938
  void VisitThread(Isolate* isolate, ThreadLocalTop* top) {
    for (StackFrameIterator it(isolate, top); !it.done(); it.Advance()) {
1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955
      has_blocked_functions_ |= CheckActivation(
          shared_info_array_, result_, it.frame(),
          LiveEdit::FUNCTION_BLOCKED_ON_OTHER_STACK);
    }
  }
  bool HasBlockedFunctions() {
    return has_blocked_functions_;
  }

 private:
  Handle<JSArray> shared_info_array_;
  Handle<JSArray> result_;
  bool has_blocked_functions_;
};


Handle<JSArray> LiveEdit::CheckAndDropActivations(
1956
    Handle<JSArray> shared_info_array, bool do_drop) {
1957
  Isolate* isolate = shared_info_array->GetIsolate();
1958
  int len = GetArrayLength(shared_info_array);
1959

1960
  DCHECK(shared_info_array->HasFastElements());
1961 1962 1963
  Handle<FixedArray> shared_info_array_elements(
      FixedArray::cast(shared_info_array->elements()));

1964
  Handle<JSArray> result = isolate->factory()->NewJSArray(len);
1965 1966
  Handle<FixedArray> result_elements =
      JSObject::EnsureWritableFastElements(result);
1967 1968 1969

  // Fill the default values.
  for (int i = 0; i < len; i++) {
1970 1971
    FunctionPatchabilityStatus status = FUNCTION_AVAILABLE_FOR_PATCH;
    result_elements->set(i, Smi::FromInt(status));
1972 1973
  }

1974 1975 1976 1977 1978 1979 1980
  // Scan the heap for active generators -- those that are either currently
  // running (as we wouldn't want to restart them, because we don't know where
  // to restart them from) or suspended.  Fail if any one corresponds to the set
  // of functions being edited.
  if (FindActiveGenerators(shared_info_array_elements, result_elements, len)) {
    return result;
  }
1981

1982
  // Check inactive threads. Fail if some functions are blocked there.
1983 1984
  InactiveThreadActivationsChecker inactive_threads_checker(shared_info_array,
                                                            result);
1985
  isolate->thread_manager()->IterateArchivedThreads(
1986
      &inactive_threads_checker);
1987 1988 1989 1990 1991 1992
  if (inactive_threads_checker.HasBlockedFunctions()) {
    return result;
  }

  // Try to drop activations from the current stack.
  const char* error_message =
1993
      DropActivationsInActiveThread(shared_info_array, result, do_drop);
1994 1995
  if (error_message != NULL) {
    // Add error message as an array extra element.
1996 1997
    Handle<String> str =
        isolate->factory()->NewStringFromAsciiChecked(error_message);
1998
    SetElementSloppy(result, len, str);
1999 2000 2001 2002 2003
  }
  return result;
}


2004 2005 2006 2007
// Describes a single callframe a target. Not finding this frame
// means an error.
class SingleFrameTarget {
 public:
2008 2009 2010
  explicit SingleFrameTarget(JavaScriptFrame* frame)
      : m_frame(frame),
        m_saved_status(LiveEdit::FUNCTION_AVAILABLE_FOR_PATCH) {}
2011 2012 2013 2014 2015 2016 2017 2018 2019

  bool MatchActivation(StackFrame* frame,
      LiveEdit::FunctionPatchabilityStatus status) {
    if (frame->fp() == m_frame->fp()) {
      m_saved_status = status;
      return true;
    }
    return false;
  }
2020
  const char* GetNotFoundMessage() const {
2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033
    return "Failed to found requested frame";
  }
  LiveEdit::FunctionPatchabilityStatus saved_status() {
    return m_saved_status;
  }
 private:
  JavaScriptFrame* m_frame;
  LiveEdit::FunctionPatchabilityStatus m_saved_status;
};


// Finds a drops required frame and all frames above.
// Returns error message or NULL.
2034
const char* LiveEdit::RestartFrame(JavaScriptFrame* frame) {
2035 2036
  SingleFrameTarget target(frame);

2037 2038
  const char* result = DropActivationsInActiveThreadImpl(
      frame->isolate(), target, true);
2039 2040 2041 2042 2043 2044
  if (result != NULL) {
    return result;
  }
  if (target.saved_status() == LiveEdit::FUNCTION_BLOCKED_UNDER_NATIVE_CODE) {
    return "Function is blocked under native code";
  }
2045 2046 2047
  if (target.saved_status() == LiveEdit::FUNCTION_BLOCKED_UNDER_GENERATOR) {
    return "Function is blocked under a generator activation";
  }
2048
  return NULL;
2049 2050 2051
}


2052 2053 2054 2055 2056
LiveEditFunctionTracker::LiveEditFunctionTracker(Isolate* isolate,
                                                 FunctionLiteral* fun)
    : isolate_(isolate) {
  if (isolate_->active_function_info_listener() != NULL) {
    isolate_->active_function_info_listener()->FunctionStarted(fun);
2057 2058 2059 2060 2061
  }
}


LiveEditFunctionTracker::~LiveEditFunctionTracker() {
2062 2063
  if (isolate_->active_function_info_listener() != NULL) {
    isolate_->active_function_info_listener()->FunctionDone();
2064 2065 2066 2067
  }
}


2068
void LiveEditFunctionTracker::RecordFunctionInfo(
2069 2070
    Handle<SharedFunctionInfo> info, FunctionLiteral* lit,
    Zone* zone) {
2071
  if (isolate_->active_function_info_listener() != NULL) {
2072 2073
    isolate_->active_function_info_listener()->FunctionInfo(info, lit->scope(),
                                                            zone);
2074 2075 2076 2077
  }
}


2078
void LiveEditFunctionTracker::RecordRootFunctionInfo(Handle<Code> code) {
2079
  isolate_->active_function_info_listener()->FunctionCode(code);
2080 2081 2082
}


2083 2084
bool LiveEditFunctionTracker::IsActive(Isolate* isolate) {
  return isolate->active_function_info_listener() != NULL;
2085 2086
}

2087
} }  // namespace v8::internal