blob: 50d60a1d9bbeec81590e5b29d8a91fdb097a5a8b [file] [log] [blame]
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001// Copyright 2012 the V8 project authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "src/debug/liveedit.h"
6
7#include "src/ast/scopeinfo.h"
8#include "src/ast/scopes.h"
9#include "src/code-stubs.h"
10#include "src/compilation-cache.h"
11#include "src/compiler.h"
12#include "src/debug/debug.h"
13#include "src/deoptimizer.h"
14#include "src/frames-inl.h"
15#include "src/global-handles.h"
Ben Murdochc5610432016-08-08 18:44:38 +010016#include "src/interpreter/source-position-table.h"
Ben Murdoch4a90d5f2016-03-22 12:00:34 +000017#include "src/isolate-inl.h"
18#include "src/messages.h"
19#include "src/parsing/parser.h"
20#include "src/v8.h"
21#include "src/v8memory.h"
22
23namespace v8 {
24namespace internal {
25
26void SetElementSloppy(Handle<JSObject> object,
27 uint32_t index,
28 Handle<Object> value) {
29 // Ignore return value from SetElement. It can only be a failure if there
30 // are element setters causing exceptions and the debugger context has none
31 // of these.
32 Object::SetElement(object->GetIsolate(), object, index, value, SLOPPY)
33 .Assert();
34}
35
36
37// A simple implementation of dynamic programming algorithm. It solves
38// the problem of finding the difference of 2 arrays. It uses a table of results
39// of subproblems. Each cell contains a number together with 2-bit flag
40// that helps building the chunk list.
41class Differencer {
42 public:
43 explicit Differencer(Comparator::Input* input)
44 : input_(input), len1_(input->GetLength1()), len2_(input->GetLength2()) {
45 buffer_ = NewArray<int>(len1_ * len2_);
46 }
47 ~Differencer() {
48 DeleteArray(buffer_);
49 }
50
51 void Initialize() {
52 int array_size = len1_ * len2_;
53 for (int i = 0; i < array_size; i++) {
54 buffer_[i] = kEmptyCellValue;
55 }
56 }
57
58 // Makes sure that result for the full problem is calculated and stored
59 // in the table together with flags showing a path through subproblems.
60 void FillTable() {
61 CompareUpToTail(0, 0);
62 }
63
64 void SaveResult(Comparator::Output* chunk_writer) {
65 ResultWriter writer(chunk_writer);
66
67 int pos1 = 0;
68 int pos2 = 0;
69 while (true) {
70 if (pos1 < len1_) {
71 if (pos2 < len2_) {
72 Direction dir = get_direction(pos1, pos2);
73 switch (dir) {
74 case EQ:
75 writer.eq();
76 pos1++;
77 pos2++;
78 break;
79 case SKIP1:
80 writer.skip1(1);
81 pos1++;
82 break;
83 case SKIP2:
84 case SKIP_ANY:
85 writer.skip2(1);
86 pos2++;
87 break;
88 default:
89 UNREACHABLE();
90 }
91 } else {
92 writer.skip1(len1_ - pos1);
93 break;
94 }
95 } else {
96 if (len2_ != pos2) {
97 writer.skip2(len2_ - pos2);
98 }
99 break;
100 }
101 }
102 writer.close();
103 }
104
105 private:
106 Comparator::Input* input_;
107 int* buffer_;
108 int len1_;
109 int len2_;
110
111 enum Direction {
112 EQ = 0,
113 SKIP1,
114 SKIP2,
115 SKIP_ANY,
116
117 MAX_DIRECTION_FLAG_VALUE = SKIP_ANY
118 };
119
120 // Computes result for a subtask and optionally caches it in the buffer table.
121 // All results values are shifted to make space for flags in the lower bits.
122 int CompareUpToTail(int pos1, int pos2) {
123 if (pos1 < len1_) {
124 if (pos2 < len2_) {
125 int cached_res = get_value4(pos1, pos2);
126 if (cached_res == kEmptyCellValue) {
127 Direction dir;
128 int res;
129 if (input_->Equals(pos1, pos2)) {
130 res = CompareUpToTail(pos1 + 1, pos2 + 1);
131 dir = EQ;
132 } else {
133 int res1 = CompareUpToTail(pos1 + 1, pos2) +
134 (1 << kDirectionSizeBits);
135 int res2 = CompareUpToTail(pos1, pos2 + 1) +
136 (1 << kDirectionSizeBits);
137 if (res1 == res2) {
138 res = res1;
139 dir = SKIP_ANY;
140 } else if (res1 < res2) {
141 res = res1;
142 dir = SKIP1;
143 } else {
144 res = res2;
145 dir = SKIP2;
146 }
147 }
148 set_value4_and_dir(pos1, pos2, res, dir);
149 cached_res = res;
150 }
151 return cached_res;
152 } else {
153 return (len1_ - pos1) << kDirectionSizeBits;
154 }
155 } else {
156 return (len2_ - pos2) << kDirectionSizeBits;
157 }
158 }
159
160 inline int& get_cell(int i1, int i2) {
161 return buffer_[i1 + i2 * len1_];
162 }
163
164 // Each cell keeps a value plus direction. Value is multiplied by 4.
165 void set_value4_and_dir(int i1, int i2, int value4, Direction dir) {
166 DCHECK((value4 & kDirectionMask) == 0);
167 get_cell(i1, i2) = value4 | dir;
168 }
169
170 int get_value4(int i1, int i2) {
171 return get_cell(i1, i2) & (kMaxUInt32 ^ kDirectionMask);
172 }
173 Direction get_direction(int i1, int i2) {
174 return static_cast<Direction>(get_cell(i1, i2) & kDirectionMask);
175 }
176
177 static const int kDirectionSizeBits = 2;
178 static const int kDirectionMask = (1 << kDirectionSizeBits) - 1;
179 static const int kEmptyCellValue = ~0u << kDirectionSizeBits;
180
181 // This method only holds static assert statement (unfortunately you cannot
182 // place one in class scope).
183 void StaticAssertHolder() {
184 STATIC_ASSERT(MAX_DIRECTION_FLAG_VALUE < (1 << kDirectionSizeBits));
185 }
186
187 class ResultWriter {
188 public:
189 explicit ResultWriter(Comparator::Output* chunk_writer)
190 : chunk_writer_(chunk_writer), pos1_(0), pos2_(0),
191 pos1_begin_(-1), pos2_begin_(-1), has_open_chunk_(false) {
192 }
193 void eq() {
194 FlushChunk();
195 pos1_++;
196 pos2_++;
197 }
198 void skip1(int len1) {
199 StartChunk();
200 pos1_ += len1;
201 }
202 void skip2(int len2) {
203 StartChunk();
204 pos2_ += len2;
205 }
206 void close() {
207 FlushChunk();
208 }
209
210 private:
211 Comparator::Output* chunk_writer_;
212 int pos1_;
213 int pos2_;
214 int pos1_begin_;
215 int pos2_begin_;
216 bool has_open_chunk_;
217
218 void StartChunk() {
219 if (!has_open_chunk_) {
220 pos1_begin_ = pos1_;
221 pos2_begin_ = pos2_;
222 has_open_chunk_ = true;
223 }
224 }
225
226 void FlushChunk() {
227 if (has_open_chunk_) {
228 chunk_writer_->AddChunk(pos1_begin_, pos2_begin_,
229 pos1_ - pos1_begin_, pos2_ - pos2_begin_);
230 has_open_chunk_ = false;
231 }
232 }
233 };
234};
235
236
237void Comparator::CalculateDifference(Comparator::Input* input,
238 Comparator::Output* result_writer) {
239 Differencer differencer(input);
240 differencer.Initialize();
241 differencer.FillTable();
242 differencer.SaveResult(result_writer);
243}
244
245
246static bool CompareSubstrings(Handle<String> s1, int pos1,
247 Handle<String> s2, int pos2, int len) {
248 for (int i = 0; i < len; i++) {
249 if (s1->Get(i + pos1) != s2->Get(i + pos2)) {
250 return false;
251 }
252 }
253 return true;
254}
255
256
257// Additional to Input interface. Lets switch Input range to subrange.
258// More elegant way would be to wrap one Input as another Input object
259// and translate positions there, but that would cost us additional virtual
260// call per comparison.
261class SubrangableInput : public Comparator::Input {
262 public:
263 virtual void SetSubrange1(int offset, int len) = 0;
264 virtual void SetSubrange2(int offset, int len) = 0;
265};
266
267
268class SubrangableOutput : public Comparator::Output {
269 public:
270 virtual void SetSubrange1(int offset, int len) = 0;
271 virtual void SetSubrange2(int offset, int len) = 0;
272};
273
274
275static int min(int a, int b) {
276 return a < b ? a : b;
277}
278
279
280// Finds common prefix and suffix in input. This parts shouldn't take space in
281// linear programming table. Enable subranging in input and output.
282static void NarrowDownInput(SubrangableInput* input,
283 SubrangableOutput* output) {
284 const int len1 = input->GetLength1();
285 const int len2 = input->GetLength2();
286
287 int common_prefix_len;
288 int common_suffix_len;
289
290 {
291 common_prefix_len = 0;
292 int prefix_limit = min(len1, len2);
293 while (common_prefix_len < prefix_limit &&
294 input->Equals(common_prefix_len, common_prefix_len)) {
295 common_prefix_len++;
296 }
297
298 common_suffix_len = 0;
299 int suffix_limit = min(len1 - common_prefix_len, len2 - common_prefix_len);
300
301 while (common_suffix_len < suffix_limit &&
302 input->Equals(len1 - common_suffix_len - 1,
303 len2 - common_suffix_len - 1)) {
304 common_suffix_len++;
305 }
306 }
307
308 if (common_prefix_len > 0 || common_suffix_len > 0) {
309 int new_len1 = len1 - common_suffix_len - common_prefix_len;
310 int new_len2 = len2 - common_suffix_len - common_prefix_len;
311
312 input->SetSubrange1(common_prefix_len, new_len1);
313 input->SetSubrange2(common_prefix_len, new_len2);
314
315 output->SetSubrange1(common_prefix_len, new_len1);
316 output->SetSubrange2(common_prefix_len, new_len2);
317 }
318}
319
320
321// A helper class that writes chunk numbers into JSArray.
322// Each chunk is stored as 3 array elements: (pos1_begin, pos1_end, pos2_end).
323class CompareOutputArrayWriter {
324 public:
325 explicit CompareOutputArrayWriter(Isolate* isolate)
326 : array_(isolate->factory()->NewJSArray(10)), current_size_(0) {}
327
328 Handle<JSArray> GetResult() {
329 return array_;
330 }
331
332 void WriteChunk(int char_pos1, int char_pos2, int char_len1, int char_len2) {
333 Isolate* isolate = array_->GetIsolate();
334 SetElementSloppy(array_,
335 current_size_,
336 Handle<Object>(Smi::FromInt(char_pos1), isolate));
337 SetElementSloppy(array_,
338 current_size_ + 1,
339 Handle<Object>(Smi::FromInt(char_pos1 + char_len1),
340 isolate));
341 SetElementSloppy(array_,
342 current_size_ + 2,
343 Handle<Object>(Smi::FromInt(char_pos2 + char_len2),
344 isolate));
345 current_size_ += 3;
346 }
347
348 private:
349 Handle<JSArray> array_;
350 int current_size_;
351};
352
353
354// Represents 2 strings as 2 arrays of tokens.
355// TODO(LiveEdit): Currently it's actually an array of charactres.
356// Make array of tokens instead.
357class TokensCompareInput : public Comparator::Input {
358 public:
359 TokensCompareInput(Handle<String> s1, int offset1, int len1,
360 Handle<String> s2, int offset2, int len2)
361 : s1_(s1), offset1_(offset1), len1_(len1),
362 s2_(s2), offset2_(offset2), len2_(len2) {
363 }
364 virtual int GetLength1() {
365 return len1_;
366 }
367 virtual int GetLength2() {
368 return len2_;
369 }
370 bool Equals(int index1, int index2) {
371 return s1_->Get(offset1_ + index1) == s2_->Get(offset2_ + index2);
372 }
373
374 private:
375 Handle<String> s1_;
376 int offset1_;
377 int len1_;
378 Handle<String> s2_;
379 int offset2_;
380 int len2_;
381};
382
383
384// Stores compare result in JSArray. Converts substring positions
385// to absolute positions.
386class TokensCompareOutput : public Comparator::Output {
387 public:
388 TokensCompareOutput(CompareOutputArrayWriter* array_writer,
389 int offset1, int offset2)
390 : array_writer_(array_writer), offset1_(offset1), offset2_(offset2) {
391 }
392
393 void AddChunk(int pos1, int pos2, int len1, int len2) {
394 array_writer_->WriteChunk(pos1 + offset1_, pos2 + offset2_, len1, len2);
395 }
396
397 private:
398 CompareOutputArrayWriter* array_writer_;
399 int offset1_;
400 int offset2_;
401};
402
403
404// Wraps raw n-elements line_ends array as a list of n+1 lines. The last line
405// never has terminating new line character.
406class LineEndsWrapper {
407 public:
408 explicit LineEndsWrapper(Handle<String> string)
409 : ends_array_(String::CalculateLineEnds(string, false)),
410 string_len_(string->length()) {
411 }
412 int length() {
413 return ends_array_->length() + 1;
414 }
415 // Returns start for any line including start of the imaginary line after
416 // the last line.
417 int GetLineStart(int index) {
418 if (index == 0) {
419 return 0;
420 } else {
421 return GetLineEnd(index - 1);
422 }
423 }
424 int GetLineEnd(int index) {
425 if (index == ends_array_->length()) {
426 // End of the last line is always an end of the whole string.
427 // If the string ends with a new line character, the last line is an
428 // empty string after this character.
429 return string_len_;
430 } else {
431 return GetPosAfterNewLine(index);
432 }
433 }
434
435 private:
436 Handle<FixedArray> ends_array_;
437 int string_len_;
438
439 int GetPosAfterNewLine(int index) {
440 return Smi::cast(ends_array_->get(index))->value() + 1;
441 }
442};
443
444
445// Represents 2 strings as 2 arrays of lines.
446class LineArrayCompareInput : public SubrangableInput {
447 public:
448 LineArrayCompareInput(Handle<String> s1, Handle<String> s2,
449 LineEndsWrapper line_ends1, LineEndsWrapper line_ends2)
450 : s1_(s1), s2_(s2), line_ends1_(line_ends1),
451 line_ends2_(line_ends2),
452 subrange_offset1_(0), subrange_offset2_(0),
453 subrange_len1_(line_ends1_.length()),
454 subrange_len2_(line_ends2_.length()) {
455 }
456 int GetLength1() {
457 return subrange_len1_;
458 }
459 int GetLength2() {
460 return subrange_len2_;
461 }
462 bool Equals(int index1, int index2) {
463 index1 += subrange_offset1_;
464 index2 += subrange_offset2_;
465
466 int line_start1 = line_ends1_.GetLineStart(index1);
467 int line_start2 = line_ends2_.GetLineStart(index2);
468 int line_end1 = line_ends1_.GetLineEnd(index1);
469 int line_end2 = line_ends2_.GetLineEnd(index2);
470 int len1 = line_end1 - line_start1;
471 int len2 = line_end2 - line_start2;
472 if (len1 != len2) {
473 return false;
474 }
475 return CompareSubstrings(s1_, line_start1, s2_, line_start2,
476 len1);
477 }
478 void SetSubrange1(int offset, int len) {
479 subrange_offset1_ = offset;
480 subrange_len1_ = len;
481 }
482 void SetSubrange2(int offset, int len) {
483 subrange_offset2_ = offset;
484 subrange_len2_ = len;
485 }
486
487 private:
488 Handle<String> s1_;
489 Handle<String> s2_;
490 LineEndsWrapper line_ends1_;
491 LineEndsWrapper line_ends2_;
492 int subrange_offset1_;
493 int subrange_offset2_;
494 int subrange_len1_;
495 int subrange_len2_;
496};
497
498
499// Stores compare result in JSArray. For each chunk tries to conduct
500// a fine-grained nested diff token-wise.
501class TokenizingLineArrayCompareOutput : public SubrangableOutput {
502 public:
503 TokenizingLineArrayCompareOutput(LineEndsWrapper line_ends1,
504 LineEndsWrapper line_ends2,
505 Handle<String> s1, Handle<String> s2)
506 : array_writer_(s1->GetIsolate()),
507 line_ends1_(line_ends1), line_ends2_(line_ends2), s1_(s1), s2_(s2),
508 subrange_offset1_(0), subrange_offset2_(0) {
509 }
510
511 void AddChunk(int line_pos1, int line_pos2, int line_len1, int line_len2) {
512 line_pos1 += subrange_offset1_;
513 line_pos2 += subrange_offset2_;
514
515 int char_pos1 = line_ends1_.GetLineStart(line_pos1);
516 int char_pos2 = line_ends2_.GetLineStart(line_pos2);
517 int char_len1 = line_ends1_.GetLineStart(line_pos1 + line_len1) - char_pos1;
518 int char_len2 = line_ends2_.GetLineStart(line_pos2 + line_len2) - char_pos2;
519
520 if (char_len1 < CHUNK_LEN_LIMIT && char_len2 < CHUNK_LEN_LIMIT) {
521 // Chunk is small enough to conduct a nested token-level diff.
522 HandleScope subTaskScope(s1_->GetIsolate());
523
524 TokensCompareInput tokens_input(s1_, char_pos1, char_len1,
525 s2_, char_pos2, char_len2);
526 TokensCompareOutput tokens_output(&array_writer_, char_pos1,
527 char_pos2);
528
529 Comparator::CalculateDifference(&tokens_input, &tokens_output);
530 } else {
531 array_writer_.WriteChunk(char_pos1, char_pos2, char_len1, char_len2);
532 }
533 }
534 void SetSubrange1(int offset, int len) {
535 subrange_offset1_ = offset;
536 }
537 void SetSubrange2(int offset, int len) {
538 subrange_offset2_ = offset;
539 }
540
541 Handle<JSArray> GetResult() {
542 return array_writer_.GetResult();
543 }
544
545 private:
546 static const int CHUNK_LEN_LIMIT = 800;
547
548 CompareOutputArrayWriter array_writer_;
549 LineEndsWrapper line_ends1_;
550 LineEndsWrapper line_ends2_;
551 Handle<String> s1_;
552 Handle<String> s2_;
553 int subrange_offset1_;
554 int subrange_offset2_;
555};
556
557
558Handle<JSArray> LiveEdit::CompareStrings(Handle<String> s1,
559 Handle<String> s2) {
560 s1 = String::Flatten(s1);
561 s2 = String::Flatten(s2);
562
563 LineEndsWrapper line_ends1(s1);
564 LineEndsWrapper line_ends2(s2);
565
566 LineArrayCompareInput input(s1, s2, line_ends1, line_ends2);
567 TokenizingLineArrayCompareOutput output(line_ends1, line_ends2, s1, s2);
568
569 NarrowDownInput(&input, &output);
570
571 Comparator::CalculateDifference(&input, &output);
572
573 return output.GetResult();
574}
575
576
577// Unwraps JSValue object, returning its field "value"
578static Handle<Object> UnwrapJSValue(Handle<JSValue> jsValue) {
579 return Handle<Object>(jsValue->value(), jsValue->GetIsolate());
580}
581
582
583// Wraps any object into a OpaqueReference, that will hide the object
584// from JavaScript.
585static Handle<JSValue> WrapInJSValue(Handle<HeapObject> object) {
586 Isolate* isolate = object->GetIsolate();
587 Handle<JSFunction> constructor = isolate->opaque_reference_function();
588 Handle<JSValue> result =
589 Handle<JSValue>::cast(isolate->factory()->NewJSObject(constructor));
590 result->set_value(*object);
591 return result;
592}
593
594
595static Handle<SharedFunctionInfo> UnwrapSharedFunctionInfoFromJSValue(
596 Handle<JSValue> jsValue) {
597 Object* shared = jsValue->value();
598 CHECK(shared->IsSharedFunctionInfo());
599 return Handle<SharedFunctionInfo>(SharedFunctionInfo::cast(shared));
600}
601
602
603static int GetArrayLength(Handle<JSArray> array) {
604 Object* length = array->length();
605 CHECK(length->IsSmi());
606 return Smi::cast(length)->value();
607}
608
609
610void FunctionInfoWrapper::SetInitialProperties(Handle<String> name,
611 int start_position,
612 int end_position, int param_num,
613 int literal_count,
614 int parent_index) {
615 HandleScope scope(isolate());
616 this->SetField(kFunctionNameOffset_, name);
617 this->SetSmiValueField(kStartPositionOffset_, start_position);
618 this->SetSmiValueField(kEndPositionOffset_, end_position);
619 this->SetSmiValueField(kParamNumOffset_, param_num);
620 this->SetSmiValueField(kLiteralNumOffset_, literal_count);
621 this->SetSmiValueField(kParentIndexOffset_, parent_index);
622}
623
624
625void FunctionInfoWrapper::SetFunctionCode(Handle<Code> function_code,
626 Handle<HeapObject> code_scope_info) {
Ben Murdochc5610432016-08-08 18:44:38 +0100627 // CompileForLiveEdit must deliver full-codegen code.
628 DCHECK(function_code->kind() == Code::FUNCTION);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000629 Handle<JSValue> code_wrapper = WrapInJSValue(function_code);
630 this->SetField(kCodeOffset_, code_wrapper);
631
632 Handle<JSValue> scope_wrapper = WrapInJSValue(code_scope_info);
633 this->SetField(kCodeScopeInfoOffset_, scope_wrapper);
634}
635
636
637void FunctionInfoWrapper::SetSharedFunctionInfo(
638 Handle<SharedFunctionInfo> info) {
639 Handle<JSValue> info_holder = WrapInJSValue(info);
640 this->SetField(kSharedFunctionInfoOffset_, info_holder);
641}
642
643
644Handle<Code> FunctionInfoWrapper::GetFunctionCode() {
645 Handle<Object> element = this->GetField(kCodeOffset_);
646 Handle<JSValue> value_wrapper = Handle<JSValue>::cast(element);
647 Handle<Object> raw_result = UnwrapJSValue(value_wrapper);
648 CHECK(raw_result->IsCode());
649 return Handle<Code>::cast(raw_result);
650}
651
652
653MaybeHandle<TypeFeedbackVector> FunctionInfoWrapper::GetFeedbackVector() {
654 Handle<Object> element = this->GetField(kSharedFunctionInfoOffset_);
655 if (element->IsJSValue()) {
656 Handle<JSValue> value_wrapper = Handle<JSValue>::cast(element);
657 Handle<Object> raw_result = UnwrapJSValue(value_wrapper);
658 Handle<SharedFunctionInfo> shared =
659 Handle<SharedFunctionInfo>::cast(raw_result);
660 return Handle<TypeFeedbackVector>(shared->feedback_vector(), isolate());
661 } else {
662 // Scripts may never have a SharedFunctionInfo created.
663 return MaybeHandle<TypeFeedbackVector>();
664 }
665}
666
667
668Handle<Object> FunctionInfoWrapper::GetCodeScopeInfo() {
669 Handle<Object> element = this->GetField(kCodeScopeInfoOffset_);
670 return UnwrapJSValue(Handle<JSValue>::cast(element));
671}
672
673
674void SharedInfoWrapper::SetProperties(Handle<String> name,
675 int start_position,
676 int end_position,
677 Handle<SharedFunctionInfo> info) {
678 HandleScope scope(isolate());
679 this->SetField(kFunctionNameOffset_, name);
680 Handle<JSValue> info_holder = WrapInJSValue(info);
681 this->SetField(kSharedInfoOffset_, info_holder);
682 this->SetSmiValueField(kStartPositionOffset_, start_position);
683 this->SetSmiValueField(kEndPositionOffset_, end_position);
684}
685
686
687Handle<SharedFunctionInfo> SharedInfoWrapper::GetInfo() {
688 Handle<Object> element = this->GetField(kSharedInfoOffset_);
689 Handle<JSValue> value_wrapper = Handle<JSValue>::cast(element);
690 return UnwrapSharedFunctionInfoFromJSValue(value_wrapper);
691}
692
693
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000694void LiveEdit::InitializeThreadLocal(Debug* debug) {
695 debug->thread_local_.frame_drop_mode_ = LiveEdit::FRAMES_UNTOUCHED;
696}
697
698
699bool LiveEdit::SetAfterBreakTarget(Debug* debug) {
700 Code* code = NULL;
701 Isolate* isolate = debug->isolate_;
702 switch (debug->thread_local_.frame_drop_mode_) {
703 case FRAMES_UNTOUCHED:
704 return false;
705 case FRAME_DROPPED_IN_DEBUG_SLOT_CALL:
706 // Debug break slot stub does not return normally, instead it manually
707 // cleans the stack and jumps. We should patch the jump address.
708 code = isolate->builtins()->builtin(Builtins::kFrameDropper_LiveEdit);
709 break;
710 case FRAME_DROPPED_IN_DIRECT_CALL:
711 // Nothing to do, after_break_target is not used here.
712 return true;
713 case FRAME_DROPPED_IN_RETURN_CALL:
714 code = isolate->builtins()->builtin(Builtins::kFrameDropper_LiveEdit);
715 break;
716 case CURRENTLY_SET_MODE:
717 UNREACHABLE();
718 break;
719 }
720 debug->after_break_target_ = code->entry();
721 return true;
722}
723
724
725MaybeHandle<JSArray> LiveEdit::GatherCompileInfo(Handle<Script> script,
726 Handle<String> source) {
727 Isolate* isolate = script->GetIsolate();
728
Ben Murdochc5610432016-08-08 18:44:38 +0100729 MaybeHandle<JSArray> infos;
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000730 Handle<Object> original_source =
731 Handle<Object>(script->source(), isolate);
732 script->set_source(*source);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000733
734 {
735 // Creating verbose TryCatch from public API is currently the only way to
736 // force code save location. We do not use this the object directly.
737 v8::TryCatch try_catch(reinterpret_cast<v8::Isolate*>(isolate));
738 try_catch.SetVerbose(true);
739
740 // A logical 'try' section.
Ben Murdochc5610432016-08-08 18:44:38 +0100741 infos = Compiler::CompileForLiveEdit(script);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000742 }
743
744 // A logical 'catch' section.
745 Handle<JSObject> rethrow_exception;
746 if (isolate->has_pending_exception()) {
747 Handle<Object> exception(isolate->pending_exception(), isolate);
748 MessageLocation message_location = isolate->GetMessageLocation();
749
750 isolate->clear_pending_message();
751 isolate->clear_pending_exception();
752
753 // If possible, copy positions from message object to exception object.
754 if (exception->IsJSObject() && !message_location.script().is_null()) {
755 rethrow_exception = Handle<JSObject>::cast(exception);
756
757 Factory* factory = isolate->factory();
758 Handle<String> start_pos_key = factory->InternalizeOneByteString(
759 STATIC_CHAR_VECTOR("startPosition"));
760 Handle<String> end_pos_key =
761 factory->InternalizeOneByteString(STATIC_CHAR_VECTOR("endPosition"));
762 Handle<String> script_obj_key =
763 factory->InternalizeOneByteString(STATIC_CHAR_VECTOR("scriptObject"));
764 Handle<Smi> start_pos(
765 Smi::FromInt(message_location.start_pos()), isolate);
766 Handle<Smi> end_pos(Smi::FromInt(message_location.end_pos()), isolate);
767 Handle<JSObject> script_obj =
768 Script::GetWrapper(message_location.script());
769 Object::SetProperty(rethrow_exception, start_pos_key, start_pos, SLOPPY)
770 .Assert();
771 Object::SetProperty(rethrow_exception, end_pos_key, end_pos, SLOPPY)
772 .Assert();
773 Object::SetProperty(rethrow_exception, script_obj_key, script_obj, SLOPPY)
774 .Assert();
775 }
776 }
777
778 // A logical 'finally' section.
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000779 script->set_source(*original_source);
780
781 if (rethrow_exception.is_null()) {
Ben Murdochc5610432016-08-08 18:44:38 +0100782 return infos.ToHandleChecked();
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000783 } else {
784 return isolate->Throw<JSArray>(rethrow_exception);
785 }
786}
787
788
789// Visitor that finds all references to a particular code object,
790// including "CODE_TARGET" references in other code objects and replaces
791// them on the fly.
792class ReplacingVisitor : public ObjectVisitor {
793 public:
794 explicit ReplacingVisitor(Code* original, Code* substitution)
795 : original_(original), substitution_(substitution) {
796 }
797
798 void VisitPointers(Object** start, Object** end) override {
799 for (Object** p = start; p < end; p++) {
800 if (*p == original_) {
801 *p = substitution_;
802 }
803 }
804 }
805
806 void VisitCodeEntry(Address entry) override {
807 if (Code::GetObjectFromEntryAddress(entry) == original_) {
808 Address substitution_entry = substitution_->instruction_start();
809 Memory::Address_at(entry) = substitution_entry;
810 }
811 }
812
813 void VisitCodeTarget(RelocInfo* rinfo) override {
814 if (RelocInfo::IsCodeTarget(rinfo->rmode()) &&
815 Code::GetCodeFromTargetAddress(rinfo->target_address()) == original_) {
816 Address substitution_entry = substitution_->instruction_start();
817 rinfo->set_target_address(substitution_entry);
818 }
819 }
820
821 void VisitDebugTarget(RelocInfo* rinfo) override { VisitCodeTarget(rinfo); }
822
823 private:
824 Code* original_;
825 Code* substitution_;
826};
827
828
829// Finds all references to original and replaces them with substitution.
830static void ReplaceCodeObject(Handle<Code> original,
831 Handle<Code> substitution) {
832 // Perform a full GC in order to ensure that we are not in the middle of an
833 // incremental marking phase when we are replacing the code object.
834 // Since we are not in an incremental marking phase we can write pointers
835 // to code objects (that are never in new space) without worrying about
836 // write barriers.
837 Heap* heap = original->GetHeap();
838 HeapIterator iterator(heap);
839
840 DCHECK(!heap->InNewSpace(*substitution));
841
842 ReplacingVisitor visitor(*original, *substitution);
843
844 // Iterate over all roots. Stack frames may have pointer into original code,
845 // so temporary replace the pointers with offset numbers
846 // in prologue/epilogue.
847 heap->IterateRoots(&visitor, VISIT_ALL);
848
849 // Now iterate over all pointers of all objects, including code_target
850 // implicit pointers.
851 for (HeapObject* obj = iterator.next(); obj != NULL; obj = iterator.next()) {
852 obj->Iterate(&visitor);
853 }
854}
855
856
857// Patch function literals.
858// Name 'literals' is a misnomer. Rather it's a cache for complex object
859// boilerplates and for a native context. We must clean cached values.
860// Additionally we may need to allocate a new array if number of literals
861// changed.
862class LiteralFixer {
863 public:
864 static void PatchLiterals(FunctionInfoWrapper* compile_info_wrapper,
865 Handle<SharedFunctionInfo> shared_info,
866 Isolate* isolate) {
867 int new_literal_count = compile_info_wrapper->GetLiteralCount();
868 int old_literal_count = shared_info->num_literals();
869
870 if (old_literal_count == new_literal_count) {
871 // If literal count didn't change, simply go over all functions
872 // and clear literal arrays.
873 ClearValuesVisitor visitor;
874 IterateJSFunctions(shared_info, &visitor);
875 } else {
876 // When literal count changes, we have to create new array instances.
877 // Since we cannot create instances when iterating heap, we should first
878 // collect all functions and fix their literal arrays.
879 Handle<FixedArray> function_instances =
880 CollectJSFunctions(shared_info, isolate);
881 Handle<TypeFeedbackVector> vector(shared_info->feedback_vector());
882
883 for (int i = 0; i < function_instances->length(); i++) {
884 Handle<JSFunction> fun(JSFunction::cast(function_instances->get(i)));
885 Handle<LiteralsArray> new_literals =
886 LiteralsArray::New(isolate, vector, new_literal_count, TENURED);
887 fun->set_literals(*new_literals);
888 }
889
890 shared_info->set_num_literals(new_literal_count);
891 }
892 }
893
894 private:
895 // Iterates all function instances in the HEAP that refers to the
896 // provided shared_info.
897 template<typename Visitor>
898 static void IterateJSFunctions(Handle<SharedFunctionInfo> shared_info,
899 Visitor* visitor) {
900 HeapIterator iterator(shared_info->GetHeap());
901 for (HeapObject* obj = iterator.next(); obj != NULL;
902 obj = iterator.next()) {
903 if (obj->IsJSFunction()) {
904 JSFunction* function = JSFunction::cast(obj);
905 if (function->shared() == *shared_info) {
906 visitor->visit(function);
907 }
908 }
909 }
910 }
911
912 // Finds all instances of JSFunction that refers to the provided shared_info
913 // and returns array with them.
914 static Handle<FixedArray> CollectJSFunctions(
915 Handle<SharedFunctionInfo> shared_info, Isolate* isolate) {
916 CountVisitor count_visitor;
917 count_visitor.count = 0;
918 IterateJSFunctions(shared_info, &count_visitor);
919 int size = count_visitor.count;
920
921 Handle<FixedArray> result = isolate->factory()->NewFixedArray(size);
922 if (size > 0) {
923 CollectVisitor collect_visitor(result);
924 IterateJSFunctions(shared_info, &collect_visitor);
925 }
926 return result;
927 }
928
929 class ClearValuesVisitor {
930 public:
931 void visit(JSFunction* fun) {
932 FixedArray* literals = fun->literals();
933 int len = literals->length();
934 for (int j = 0; j < len; j++) {
935 literals->set_undefined(j);
936 }
937 }
938 };
939
940 class CountVisitor {
941 public:
942 void visit(JSFunction* fun) {
943 count++;
944 }
945 int count;
946 };
947
948 class CollectVisitor {
949 public:
950 explicit CollectVisitor(Handle<FixedArray> output)
951 : m_output(output), m_pos(0) {}
952
953 void visit(JSFunction* fun) {
954 m_output->set(m_pos, fun);
955 m_pos++;
956 }
957 private:
958 Handle<FixedArray> m_output;
959 int m_pos;
960 };
961};
962
963
964// Marks code that shares the same shared function info or has inlined
965// code that shares the same function info.
966class DependentFunctionMarker: public OptimizedFunctionVisitor {
967 public:
968 SharedFunctionInfo* shared_info_;
969 bool found_;
970
971 explicit DependentFunctionMarker(SharedFunctionInfo* shared_info)
972 : shared_info_(shared_info), found_(false) { }
973
974 virtual void EnterContext(Context* context) { } // Don't care.
975 virtual void LeaveContext(Context* context) { } // Don't care.
976 virtual void VisitFunction(JSFunction* function) {
977 // It should be guaranteed by the iterator that everything is optimized.
978 DCHECK(function->code()->kind() == Code::OPTIMIZED_FUNCTION);
979 if (function->Inlines(shared_info_)) {
980 // Mark the code for deoptimization.
981 function->code()->set_marked_for_deoptimization(true);
982 found_ = true;
983 }
984 }
985};
986
987
988static void DeoptimizeDependentFunctions(SharedFunctionInfo* function_info) {
989 DisallowHeapAllocation no_allocation;
990 DependentFunctionMarker marker(function_info);
991 // TODO(titzer): need to traverse all optimized code to find OSR code here.
992 Deoptimizer::VisitAllOptimizedFunctions(function_info->GetIsolate(), &marker);
993
994 if (marker.found_) {
995 // Only go through with the deoptimization if something was found.
996 Deoptimizer::DeoptimizeMarkedCode(function_info->GetIsolate());
997 }
998}
999
1000
1001void LiveEdit::ReplaceFunctionCode(
1002 Handle<JSArray> new_compile_info_array,
1003 Handle<JSArray> shared_info_array) {
1004 Isolate* isolate = new_compile_info_array->GetIsolate();
1005
1006 FunctionInfoWrapper compile_info_wrapper(new_compile_info_array);
1007 SharedInfoWrapper shared_info_wrapper(shared_info_array);
1008
1009 Handle<SharedFunctionInfo> shared_info = shared_info_wrapper.GetInfo();
1010
Ben Murdochc5610432016-08-08 18:44:38 +01001011 if (shared_info->is_compiled()) {
1012 Handle<Code> new_code = compile_info_wrapper.GetFunctionCode();
1013 Handle<Code> old_code(shared_info->code());
1014 if (shared_info->HasBytecodeArray()) {
1015 // The old code is interpreted. If we clear the bytecode array, the
1016 // interpreter entry trampoline will self-heal and go to compiled code.
1017 shared_info->ClearBytecodeArray();
1018 shared_info->ReplaceCode(*new_code);
1019 } else {
1020 DCHECK(old_code->kind() == Code::FUNCTION);
1021 ReplaceCodeObject(old_code, new_code);
1022 }
1023 if (shared_info->HasDebugInfo()) {
1024 // Existing break points will be re-applied. Reset the debug info here.
1025 isolate->debug()->RemoveDebugInfoAndClearFromShared(
1026 handle(shared_info->GetDebugInfo()));
1027 }
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001028 Handle<Object> code_scope_info = compile_info_wrapper.GetCodeScopeInfo();
1029 if (code_scope_info->IsFixedArray()) {
1030 shared_info->set_scope_info(ScopeInfo::cast(*code_scope_info));
1031 }
1032 shared_info->DisableOptimization(kLiveEdit);
1033 // Update the type feedback vector, if needed.
1034 MaybeHandle<TypeFeedbackVector> feedback_vector =
1035 compile_info_wrapper.GetFeedbackVector();
1036 if (!feedback_vector.is_null()) {
1037 shared_info->set_feedback_vector(*feedback_vector.ToHandleChecked());
1038 }
1039 }
1040
1041 int start_position = compile_info_wrapper.GetStartPosition();
1042 int end_position = compile_info_wrapper.GetEndPosition();
1043 shared_info->set_start_position(start_position);
1044 shared_info->set_end_position(end_position);
1045
1046 LiteralFixer::PatchLiterals(&compile_info_wrapper, shared_info, isolate);
1047
1048 DeoptimizeDependentFunctions(*shared_info);
1049 isolate->compilation_cache()->Remove(shared_info);
1050}
1051
1052
1053void LiveEdit::FunctionSourceUpdated(Handle<JSArray> shared_info_array) {
1054 SharedInfoWrapper shared_info_wrapper(shared_info_array);
1055 Handle<SharedFunctionInfo> shared_info = shared_info_wrapper.GetInfo();
1056
1057 DeoptimizeDependentFunctions(*shared_info);
1058 shared_info_array->GetIsolate()->compilation_cache()->Remove(shared_info);
1059}
1060
1061
1062void LiveEdit::SetFunctionScript(Handle<JSValue> function_wrapper,
1063 Handle<Object> script_handle) {
1064 Handle<SharedFunctionInfo> shared_info =
1065 UnwrapSharedFunctionInfoFromJSValue(function_wrapper);
1066 CHECK(script_handle->IsScript() || script_handle->IsUndefined());
1067 SharedFunctionInfo::SetScript(shared_info, script_handle);
1068 shared_info->DisableOptimization(kLiveEdit);
1069
1070 function_wrapper->GetIsolate()->compilation_cache()->Remove(shared_info);
1071}
1072
1073
1074// For a script text change (defined as position_change_array), translates
1075// position in unchanged text to position in changed text.
1076// Text change is a set of non-overlapping regions in text, that have changed
1077// their contents and length. It is specified as array of groups of 3 numbers:
1078// (change_begin, change_end, change_end_new_position).
1079// Each group describes a change in text; groups are sorted by change_begin.
1080// Only position in text beyond any changes may be successfully translated.
1081// If a positions is inside some region that changed, result is currently
1082// undefined.
1083static int TranslatePosition(int original_position,
1084 Handle<JSArray> position_change_array) {
1085 int position_diff = 0;
1086 int array_len = GetArrayLength(position_change_array);
1087 Isolate* isolate = position_change_array->GetIsolate();
1088 // TODO(635): binary search may be used here
1089 for (int i = 0; i < array_len; i += 3) {
1090 HandleScope scope(isolate);
Ben Murdochda12d292016-06-02 14:46:10 +01001091 Handle<Object> element =
1092 JSReceiver::GetElement(isolate, position_change_array, i)
1093 .ToHandleChecked();
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001094 CHECK(element->IsSmi());
1095 int chunk_start = Handle<Smi>::cast(element)->value();
1096 if (original_position < chunk_start) {
1097 break;
1098 }
Ben Murdochda12d292016-06-02 14:46:10 +01001099 element = JSReceiver::GetElement(isolate, position_change_array, i + 1)
1100 .ToHandleChecked();
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001101 CHECK(element->IsSmi());
1102 int chunk_end = Handle<Smi>::cast(element)->value();
1103 // Position mustn't be inside a chunk.
1104 DCHECK(original_position >= chunk_end);
Ben Murdochda12d292016-06-02 14:46:10 +01001105 element = JSReceiver::GetElement(isolate, position_change_array, i + 2)
1106 .ToHandleChecked();
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001107 CHECK(element->IsSmi());
1108 int chunk_changed_end = Handle<Smi>::cast(element)->value();
1109 position_diff = chunk_changed_end - chunk_end;
1110 }
1111
1112 return original_position + position_diff;
1113}
1114
1115
1116// Auto-growing buffer for writing relocation info code section. This buffer
1117// is a simplified version of buffer from Assembler. Unlike Assembler, this
1118// class is platform-independent and it works without dealing with instructions.
1119// As specified by RelocInfo format, the buffer is filled in reversed order:
1120// from upper to lower addresses.
1121// It uses NewArray/DeleteArray for memory management.
1122class RelocInfoBuffer {
1123 public:
1124 RelocInfoBuffer(int buffer_initial_capicity, byte* pc) {
1125 buffer_size_ = buffer_initial_capicity + kBufferGap;
1126 buffer_ = NewArray<byte>(buffer_size_);
1127
1128 reloc_info_writer_.Reposition(buffer_ + buffer_size_, pc);
1129 }
1130 ~RelocInfoBuffer() {
1131 DeleteArray(buffer_);
1132 }
1133
1134 // As specified by RelocInfo format, the buffer is filled in reversed order:
1135 // from upper to lower addresses.
1136 void Write(const RelocInfo* rinfo) {
1137 if (buffer_ + kBufferGap >= reloc_info_writer_.pos()) {
1138 Grow();
1139 }
1140 reloc_info_writer_.Write(rinfo);
1141 }
1142
1143 Vector<byte> GetResult() {
1144 // Return the bytes from pos up to end of buffer.
1145 int result_size =
1146 static_cast<int>((buffer_ + buffer_size_) - reloc_info_writer_.pos());
1147 return Vector<byte>(reloc_info_writer_.pos(), result_size);
1148 }
1149
1150 private:
1151 void Grow() {
1152 // Compute new buffer size.
1153 int new_buffer_size;
1154 if (buffer_size_ < 2 * KB) {
1155 new_buffer_size = 4 * KB;
1156 } else {
1157 new_buffer_size = 2 * buffer_size_;
1158 }
1159 // Some internal data structures overflow for very large buffers,
1160 // they must ensure that kMaximalBufferSize is not too large.
1161 if (new_buffer_size > kMaximalBufferSize) {
1162 V8::FatalProcessOutOfMemory("RelocInfoBuffer::GrowBuffer");
1163 }
1164
1165 // Set up new buffer.
1166 byte* new_buffer = NewArray<byte>(new_buffer_size);
1167
1168 // Copy the data.
1169 int curently_used_size =
1170 static_cast<int>(buffer_ + buffer_size_ - reloc_info_writer_.pos());
1171 MemMove(new_buffer + new_buffer_size - curently_used_size,
1172 reloc_info_writer_.pos(), curently_used_size);
1173
1174 reloc_info_writer_.Reposition(
1175 new_buffer + new_buffer_size - curently_used_size,
1176 reloc_info_writer_.last_pc());
1177
1178 DeleteArray(buffer_);
1179 buffer_ = new_buffer;
1180 buffer_size_ = new_buffer_size;
1181 }
1182
1183 RelocInfoWriter reloc_info_writer_;
1184 byte* buffer_;
1185 int buffer_size_;
1186
1187 static const int kBufferGap = RelocInfoWriter::kMaxSize;
1188 static const int kMaximalBufferSize = 512*MB;
1189};
1190
Ben Murdochc5610432016-08-08 18:44:38 +01001191namespace {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001192// Patch positions in code (changes relocation info section) and possibly
1193// returns new instance of code.
Ben Murdochc5610432016-08-08 18:44:38 +01001194Handle<Code> PatchPositionsInCode(Handle<Code> code,
1195 Handle<JSArray> position_change_array) {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001196 Isolate* isolate = code->GetIsolate();
1197
1198 RelocInfoBuffer buffer_writer(code->relocation_size(),
1199 code->instruction_start());
1200
1201 {
1202 for (RelocIterator it(*code); !it.done(); it.next()) {
1203 RelocInfo* rinfo = it.rinfo();
1204 if (RelocInfo::IsPosition(rinfo->rmode())) {
1205 int position = static_cast<int>(rinfo->data());
1206 int new_position = TranslatePosition(position,
1207 position_change_array);
1208 if (position != new_position) {
1209 RelocInfo info_copy(rinfo->isolate(), rinfo->pc(), rinfo->rmode(),
1210 new_position, NULL);
1211 buffer_writer.Write(&info_copy);
1212 continue;
1213 }
1214 }
1215 if (RelocInfo::IsRealRelocMode(rinfo->rmode())) {
1216 buffer_writer.Write(it.rinfo());
1217 }
1218 }
1219 }
1220
1221 Vector<byte> buffer = buffer_writer.GetResult();
1222
1223 if (buffer.length() == code->relocation_size()) {
1224 // Simply patch relocation area of code.
1225 MemCopy(code->relocation_start(), buffer.start(), buffer.length());
1226 return code;
1227 } else {
1228 // Relocation info section now has different size. We cannot simply
1229 // rewrite it inside code object. Instead we have to create a new
1230 // code object.
1231 Handle<Code> result(isolate->factory()->CopyCode(code, buffer));
1232 return result;
1233 }
1234}
1235
Ben Murdochc5610432016-08-08 18:44:38 +01001236void PatchPositionsInBytecodeArray(Handle<BytecodeArray> bytecode,
1237 Handle<JSArray> position_change_array) {
1238 Isolate* isolate = bytecode->GetIsolate();
1239 Zone zone(isolate->allocator());
1240 interpreter::SourcePositionTableBuilder builder(isolate, &zone);
1241
1242 for (interpreter::SourcePositionTableIterator iterator(
1243 bytecode->source_position_table());
1244 !iterator.done(); iterator.Advance()) {
1245 int position = iterator.source_position();
1246 int new_position = TranslatePosition(position, position_change_array);
1247 builder.AddPosition(iterator.bytecode_offset(), new_position,
1248 iterator.is_statement());
1249 }
1250
1251 bytecode->set_source_position_table(*builder.ToSourcePositionTable());
1252}
1253} // namespace
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001254
1255void LiveEdit::PatchFunctionPositions(Handle<JSArray> shared_info_array,
1256 Handle<JSArray> position_change_array) {
1257 SharedInfoWrapper shared_info_wrapper(shared_info_array);
1258 Handle<SharedFunctionInfo> info = shared_info_wrapper.GetInfo();
1259
1260 int old_function_start = info->start_position();
1261 int new_function_start = TranslatePosition(old_function_start,
1262 position_change_array);
1263 int new_function_end = TranslatePosition(info->end_position(),
1264 position_change_array);
1265 int new_function_token_pos =
1266 TranslatePosition(info->function_token_position(), position_change_array);
1267
1268 info->set_start_position(new_function_start);
1269 info->set_end_position(new_function_end);
1270 info->set_function_token_position(new_function_token_pos);
1271
1272 if (info->code()->kind() == Code::FUNCTION) {
1273 // Patch relocation info section of the code.
1274 Handle<Code> patched_code = PatchPositionsInCode(Handle<Code>(info->code()),
1275 position_change_array);
1276 if (*patched_code != info->code()) {
1277 // Replace all references to the code across the heap. In particular,
1278 // some stubs may refer to this code and this code may be being executed
1279 // on stack (it is safe to substitute the code object on stack, because
1280 // we only change the structure of rinfo and leave instructions
1281 // untouched).
1282 ReplaceCodeObject(Handle<Code>(info->code()), patched_code);
1283 }
Ben Murdochc5610432016-08-08 18:44:38 +01001284 } else if (info->HasBytecodeArray()) {
1285 PatchPositionsInBytecodeArray(Handle<BytecodeArray>(info->bytecode_array()),
1286 position_change_array);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001287 }
1288}
1289
1290
1291static Handle<Script> CreateScriptCopy(Handle<Script> original) {
1292 Isolate* isolate = original->GetIsolate();
1293
1294 Handle<String> original_source(String::cast(original->source()));
1295 Handle<Script> copy = isolate->factory()->NewScript(original_source);
1296
1297 copy->set_name(original->name());
1298 copy->set_line_offset(original->line_offset());
1299 copy->set_column_offset(original->column_offset());
1300 copy->set_type(original->type());
1301 copy->set_context_data(original->context_data());
1302 copy->set_eval_from_shared(original->eval_from_shared());
Ben Murdochc5610432016-08-08 18:44:38 +01001303 copy->set_eval_from_position(original->eval_from_position());
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001304
1305 // Copy all the flags, but clear compilation state.
1306 copy->set_flags(original->flags());
1307 copy->set_compilation_state(Script::COMPILATION_STATE_INITIAL);
1308
1309 return copy;
1310}
1311
1312
1313Handle<Object> LiveEdit::ChangeScriptSource(Handle<Script> original_script,
1314 Handle<String> new_source,
1315 Handle<Object> old_script_name) {
1316 Isolate* isolate = original_script->GetIsolate();
1317 Handle<Object> old_script_object;
1318 if (old_script_name->IsString()) {
1319 Handle<Script> old_script = CreateScriptCopy(original_script);
1320 old_script->set_name(String::cast(*old_script_name));
1321 old_script_object = old_script;
1322 isolate->debug()->OnAfterCompile(old_script);
1323 } else {
1324 old_script_object = isolate->factory()->null_value();
1325 }
1326
1327 original_script->set_source(*new_source);
1328
1329 // Drop line ends so that they will be recalculated.
1330 original_script->set_line_ends(isolate->heap()->undefined_value());
1331
1332 return old_script_object;
1333}
1334
1335
1336
1337void LiveEdit::ReplaceRefToNestedFunction(
1338 Handle<JSValue> parent_function_wrapper,
1339 Handle<JSValue> orig_function_wrapper,
1340 Handle<JSValue> subst_function_wrapper) {
1341
1342 Handle<SharedFunctionInfo> parent_shared =
1343 UnwrapSharedFunctionInfoFromJSValue(parent_function_wrapper);
1344 Handle<SharedFunctionInfo> orig_shared =
1345 UnwrapSharedFunctionInfoFromJSValue(orig_function_wrapper);
1346 Handle<SharedFunctionInfo> subst_shared =
1347 UnwrapSharedFunctionInfoFromJSValue(subst_function_wrapper);
1348
1349 for (RelocIterator it(parent_shared->code()); !it.done(); it.next()) {
1350 if (it.rinfo()->rmode() == RelocInfo::EMBEDDED_OBJECT) {
1351 if (it.rinfo()->target_object() == *orig_shared) {
1352 it.rinfo()->set_target_object(*subst_shared);
1353 }
1354 }
1355 }
1356}
1357
1358
1359// Check an activation against list of functions. If there is a function
1360// that matches, its status in result array is changed to status argument value.
1361static bool CheckActivation(Handle<JSArray> shared_info_array,
1362 Handle<JSArray> result,
1363 StackFrame* frame,
1364 LiveEdit::FunctionPatchabilityStatus status) {
1365 if (!frame->is_java_script()) return false;
1366
1367 Handle<JSFunction> function(JavaScriptFrame::cast(frame)->function());
1368
1369 Isolate* isolate = shared_info_array->GetIsolate();
1370 int len = GetArrayLength(shared_info_array);
1371 for (int i = 0; i < len; i++) {
1372 HandleScope scope(isolate);
1373 Handle<Object> element =
Ben Murdochda12d292016-06-02 14:46:10 +01001374 JSReceiver::GetElement(isolate, shared_info_array, i).ToHandleChecked();
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001375 Handle<JSValue> jsvalue = Handle<JSValue>::cast(element);
1376 Handle<SharedFunctionInfo> shared =
1377 UnwrapSharedFunctionInfoFromJSValue(jsvalue);
1378
1379 if (function->Inlines(*shared)) {
1380 SetElementSloppy(result, i, Handle<Smi>(Smi::FromInt(status), isolate));
1381 return true;
1382 }
1383 }
1384 return false;
1385}
1386
1387
1388// Iterates over handler chain and removes all elements that are inside
1389// frames being dropped.
1390static bool FixTryCatchHandler(StackFrame* top_frame,
1391 StackFrame* bottom_frame) {
1392 Address* pointer_address =
1393 &Memory::Address_at(top_frame->isolate()->get_address_from_id(
1394 Isolate::kHandlerAddress));
1395
1396 while (*pointer_address < top_frame->sp()) {
1397 pointer_address = &Memory::Address_at(*pointer_address);
1398 }
1399 Address* above_frame_address = pointer_address;
1400 while (*pointer_address < bottom_frame->fp()) {
1401 pointer_address = &Memory::Address_at(*pointer_address);
1402 }
1403 bool change = *above_frame_address != *pointer_address;
1404 *above_frame_address = *pointer_address;
1405 return change;
1406}
1407
1408
1409// Initializes an artificial stack frame. The data it contains is used for:
1410// a. successful work of frame dropper code which eventually gets control,
Ben Murdochda12d292016-06-02 14:46:10 +01001411// b. being compatible with a typed frame structure for various stack
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001412// iterators.
Ben Murdochda12d292016-06-02 14:46:10 +01001413// Frame structure (conforms to InternalFrame structure):
1414// -- function
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001415// -- code
Ben Murdochda12d292016-06-02 14:46:10 +01001416// -- SMI marker
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001417// -- frame base
1418static void SetUpFrameDropperFrame(StackFrame* bottom_js_frame,
1419 Handle<Code> code) {
1420 DCHECK(bottom_js_frame->is_java_script());
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001421 Address fp = bottom_js_frame->fp();
Ben Murdochda12d292016-06-02 14:46:10 +01001422 Memory::Object_at(fp + FrameDropperFrameConstants::kFunctionOffset) =
1423 Memory::Object_at(fp + StandardFrameConstants::kFunctionOffset);
1424 Memory::Object_at(fp + FrameDropperFrameConstants::kFrameTypeOffset) =
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001425 Smi::FromInt(StackFrame::INTERNAL);
Ben Murdochda12d292016-06-02 14:46:10 +01001426 Memory::Object_at(fp + FrameDropperFrameConstants::kCodeOffset) = *code;
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001427}
1428
1429
1430// Removes specified range of frames from stack. There may be 1 or more
1431// frames in range. Anyway the bottom frame is restarted rather than dropped,
1432// and therefore has to be a JavaScript frame.
1433// Returns error message or NULL.
1434static const char* DropFrames(Vector<StackFrame*> frames, int top_frame_index,
1435 int bottom_js_frame_index,
1436 LiveEdit::FrameDropMode* mode) {
1437 if (!LiveEdit::kFrameDropperSupported) {
1438 return "Stack manipulations are not supported in this architecture.";
1439 }
1440
1441 StackFrame* pre_top_frame = frames[top_frame_index - 1];
1442 StackFrame* top_frame = frames[top_frame_index];
1443 StackFrame* bottom_js_frame = frames[bottom_js_frame_index];
1444
1445 DCHECK(bottom_js_frame->is_java_script());
1446
1447 // Check the nature of the top frame.
1448 Isolate* isolate = bottom_js_frame->isolate();
1449 Code* pre_top_frame_code = pre_top_frame->LookupCode();
1450 bool frame_has_padding = true;
1451 if (pre_top_frame_code ==
1452 isolate->builtins()->builtin(Builtins::kSlot_DebugBreak)) {
1453 // OK, we can drop debug break slot.
1454 *mode = LiveEdit::FRAME_DROPPED_IN_DEBUG_SLOT_CALL;
1455 } else if (pre_top_frame_code ==
1456 isolate->builtins()->builtin(Builtins::kFrameDropper_LiveEdit)) {
1457 // OK, we can drop our own code.
1458 pre_top_frame = frames[top_frame_index - 2];
1459 top_frame = frames[top_frame_index - 1];
1460 *mode = LiveEdit::CURRENTLY_SET_MODE;
1461 frame_has_padding = false;
1462 } else if (pre_top_frame_code ==
1463 isolate->builtins()->builtin(Builtins::kReturn_DebugBreak)) {
1464 *mode = LiveEdit::FRAME_DROPPED_IN_RETURN_CALL;
1465 } else if (pre_top_frame_code->kind() == Code::STUB &&
1466 CodeStub::GetMajorKey(pre_top_frame_code) == CodeStub::CEntry) {
1467 // Entry from our unit tests on 'debugger' statement.
1468 // It's fine, we support this case.
1469 *mode = LiveEdit::FRAME_DROPPED_IN_DIRECT_CALL;
1470 // We don't have a padding from 'debugger' statement call.
1471 // Here the stub is CEntry, it's not debug-only and can't be padded.
1472 // If anyone would complain, a proxy padded stub could be added.
1473 frame_has_padding = false;
1474 } else if (pre_top_frame->type() == StackFrame::ARGUMENTS_ADAPTOR) {
1475 // This must be adaptor that remain from the frame dropping that
1476 // is still on stack. A frame dropper frame must be above it.
1477 DCHECK(frames[top_frame_index - 2]->LookupCode() ==
1478 isolate->builtins()->builtin(Builtins::kFrameDropper_LiveEdit));
1479 pre_top_frame = frames[top_frame_index - 3];
1480 top_frame = frames[top_frame_index - 2];
1481 *mode = LiveEdit::CURRENTLY_SET_MODE;
1482 frame_has_padding = false;
Ben Murdochc5610432016-08-08 18:44:38 +01001483 } else if (pre_top_frame_code->kind() == Code::BYTECODE_HANDLER) {
1484 // Interpreted bytecode takes up two stack frames, one for the bytecode
1485 // handler and one for the interpreter entry trampoline. Therefore we shift
1486 // up by one frame.
1487 *mode = LiveEdit::FRAME_DROPPED_IN_DIRECT_CALL;
1488 pre_top_frame = frames[top_frame_index - 2];
1489 top_frame = frames[top_frame_index - 1];
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001490 } else {
1491 return "Unknown structure of stack above changing function";
1492 }
1493
1494 Address unused_stack_top = top_frame->sp();
Ben Murdochda12d292016-06-02 14:46:10 +01001495 Address unused_stack_bottom =
1496 bottom_js_frame->fp() - FrameDropperFrameConstants::kFixedFrameSize +
1497 2 * kPointerSize; // Bigger address end is exclusive.
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001498
1499 Address* top_frame_pc_address = top_frame->pc_address();
1500
1501 // top_frame may be damaged below this point. Do not used it.
1502 DCHECK(!(top_frame = NULL));
1503
1504 if (unused_stack_top > unused_stack_bottom) {
1505 if (frame_has_padding) {
1506 int shortage_bytes =
1507 static_cast<int>(unused_stack_top - unused_stack_bottom);
1508
Ben Murdochda12d292016-06-02 14:46:10 +01001509 Address padding_start =
1510 pre_top_frame->fp() -
1511 (FrameDropperFrameConstants::kFixedFrameSize - kPointerSize);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001512
1513 Address padding_pointer = padding_start;
1514 Smi* padding_object = Smi::FromInt(LiveEdit::kFramePaddingValue);
1515 while (Memory::Object_at(padding_pointer) == padding_object) {
1516 padding_pointer -= kPointerSize;
1517 }
1518 int padding_counter =
1519 Smi::cast(Memory::Object_at(padding_pointer))->value();
1520 if (padding_counter * kPointerSize < shortage_bytes) {
1521 return "Not enough space for frame dropper frame "
1522 "(even with padding frame)";
1523 }
1524 Memory::Object_at(padding_pointer) =
1525 Smi::FromInt(padding_counter - shortage_bytes / kPointerSize);
1526
1527 StackFrame* pre_pre_frame = frames[top_frame_index - 2];
1528
1529 MemMove(padding_start + kPointerSize - shortage_bytes,
1530 padding_start + kPointerSize,
Ben Murdochda12d292016-06-02 14:46:10 +01001531 FrameDropperFrameConstants::kFixedFrameSize - kPointerSize);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001532
1533 pre_top_frame->UpdateFp(pre_top_frame->fp() - shortage_bytes);
1534 pre_pre_frame->SetCallerFp(pre_top_frame->fp());
1535 unused_stack_top -= shortage_bytes;
1536
1537 STATIC_ASSERT(sizeof(Address) == kPointerSize);
1538 top_frame_pc_address -= shortage_bytes / kPointerSize;
1539 } else {
1540 return "Not enough space for frame dropper frame";
1541 }
1542 }
1543
1544 // Committing now. After this point we should return only NULL value.
1545
1546 FixTryCatchHandler(pre_top_frame, bottom_js_frame);
1547 // Make sure FixTryCatchHandler is idempotent.
1548 DCHECK(!FixTryCatchHandler(pre_top_frame, bottom_js_frame));
1549
1550 Handle<Code> code = isolate->builtins()->FrameDropper_LiveEdit();
1551 *top_frame_pc_address = code->entry();
1552 pre_top_frame->SetCallerFp(bottom_js_frame->fp());
1553
1554 SetUpFrameDropperFrame(bottom_js_frame, code);
1555
1556 for (Address a = unused_stack_top;
1557 a < unused_stack_bottom;
1558 a += kPointerSize) {
1559 Memory::Object_at(a) = Smi::FromInt(0);
1560 }
1561
1562 return NULL;
1563}
1564
1565
1566// Describes a set of call frames that execute any of listed functions.
1567// Finding no such frames does not mean error.
1568class MultipleFunctionTarget {
1569 public:
1570 MultipleFunctionTarget(Handle<JSArray> old_shared_array,
1571 Handle<JSArray> new_shared_array,
1572 Handle<JSArray> result)
1573 : old_shared_array_(old_shared_array),
1574 new_shared_array_(new_shared_array),
1575 result_(result) {}
1576 bool MatchActivation(StackFrame* frame,
1577 LiveEdit::FunctionPatchabilityStatus status) {
1578 return CheckActivation(old_shared_array_, result_, frame, status);
1579 }
1580 const char* GetNotFoundMessage() const {
1581 return NULL;
1582 }
1583 bool FrameUsesNewTarget(StackFrame* frame) {
1584 if (!frame->is_java_script()) return false;
1585 JavaScriptFrame* jsframe = JavaScriptFrame::cast(frame);
1586 Handle<SharedFunctionInfo> old_shared(jsframe->function()->shared());
1587 Isolate* isolate = old_shared->GetIsolate();
1588 int len = GetArrayLength(old_shared_array_);
1589 // Find corresponding new shared function info and return whether it
1590 // references new.target.
1591 for (int i = 0; i < len; i++) {
1592 HandleScope scope(isolate);
1593 Handle<Object> old_element =
Ben Murdochda12d292016-06-02 14:46:10 +01001594 JSReceiver::GetElement(isolate, old_shared_array_, i)
1595 .ToHandleChecked();
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001596 if (!old_shared.is_identical_to(UnwrapSharedFunctionInfoFromJSValue(
1597 Handle<JSValue>::cast(old_element)))) {
1598 continue;
1599 }
1600
1601 Handle<Object> new_element =
Ben Murdochda12d292016-06-02 14:46:10 +01001602 JSReceiver::GetElement(isolate, new_shared_array_, i)
1603 .ToHandleChecked();
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001604 if (new_element->IsUndefined()) return false;
1605 Handle<SharedFunctionInfo> new_shared =
1606 UnwrapSharedFunctionInfoFromJSValue(
1607 Handle<JSValue>::cast(new_element));
1608 if (new_shared->scope_info()->HasNewTarget()) {
1609 SetElementSloppy(
1610 result_, i,
1611 Handle<Smi>(
1612 Smi::FromInt(
1613 LiveEdit::FUNCTION_BLOCKED_NO_NEW_TARGET_ON_RESTART),
1614 isolate));
1615 return true;
1616 }
1617 return false;
1618 }
1619 return false;
1620 }
1621
1622 private:
1623 Handle<JSArray> old_shared_array_;
1624 Handle<JSArray> new_shared_array_;
1625 Handle<JSArray> result_;
1626};
1627
1628
1629// Drops all call frame matched by target and all frames above them.
1630template <typename TARGET>
1631static const char* DropActivationsInActiveThreadImpl(Isolate* isolate,
1632 TARGET& target, // NOLINT
1633 bool do_drop) {
1634 Debug* debug = isolate->debug();
Ben Murdochda12d292016-06-02 14:46:10 +01001635 Zone zone(isolate->allocator());
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001636 Vector<StackFrame*> frames = CreateStackMap(isolate, &zone);
1637
1638
1639 int top_frame_index = -1;
1640 int frame_index = 0;
1641 for (; frame_index < frames.length(); frame_index++) {
1642 StackFrame* frame = frames[frame_index];
1643 if (frame->id() == debug->break_frame_id()) {
1644 top_frame_index = frame_index;
1645 break;
1646 }
1647 if (target.MatchActivation(
1648 frame, LiveEdit::FUNCTION_BLOCKED_UNDER_NATIVE_CODE)) {
1649 // We are still above break_frame. It is not a target frame,
1650 // it is a problem.
1651 return "Debugger mark-up on stack is not found";
1652 }
1653 }
1654
1655 if (top_frame_index == -1) {
1656 // We haven't found break frame, but no function is blocking us anyway.
1657 return target.GetNotFoundMessage();
1658 }
1659
1660 bool target_frame_found = false;
1661 int bottom_js_frame_index = top_frame_index;
1662 bool non_droppable_frame_found = false;
1663 LiveEdit::FunctionPatchabilityStatus non_droppable_reason;
1664
1665 for (; frame_index < frames.length(); frame_index++) {
1666 StackFrame* frame = frames[frame_index];
1667 if (frame->is_exit()) {
1668 non_droppable_frame_found = true;
1669 non_droppable_reason = LiveEdit::FUNCTION_BLOCKED_UNDER_NATIVE_CODE;
1670 break;
1671 }
1672 if (frame->is_java_script()) {
1673 SharedFunctionInfo* shared =
1674 JavaScriptFrame::cast(frame)->function()->shared();
1675 if (shared->is_generator()) {
1676 non_droppable_frame_found = true;
1677 non_droppable_reason = LiveEdit::FUNCTION_BLOCKED_UNDER_GENERATOR;
1678 break;
1679 }
1680 }
1681 if (target.MatchActivation(
1682 frame, LiveEdit::FUNCTION_BLOCKED_ON_ACTIVE_STACK)) {
1683 target_frame_found = true;
1684 bottom_js_frame_index = frame_index;
1685 }
1686 }
1687
1688 if (non_droppable_frame_found) {
1689 // There is a C or generator frame on stack. We can't drop C frames, and we
1690 // can't restart generators. Check that there are no target frames below
1691 // them.
1692 for (; frame_index < frames.length(); frame_index++) {
1693 StackFrame* frame = frames[frame_index];
1694 if (frame->is_java_script()) {
1695 if (target.MatchActivation(frame, non_droppable_reason)) {
1696 // Fail.
1697 return NULL;
1698 }
1699 }
1700 }
1701 }
1702
1703 // We cannot restart a frame that uses new.target.
1704 if (target.FrameUsesNewTarget(frames[bottom_js_frame_index])) return NULL;
1705
1706 if (!do_drop) {
1707 // We are in check-only mode.
1708 return NULL;
1709 }
1710
1711 if (!target_frame_found) {
1712 // Nothing to drop.
1713 return target.GetNotFoundMessage();
1714 }
1715
1716 LiveEdit::FrameDropMode drop_mode = LiveEdit::FRAMES_UNTOUCHED;
1717 const char* error_message =
1718 DropFrames(frames, top_frame_index, bottom_js_frame_index, &drop_mode);
1719
1720 if (error_message != NULL) {
1721 return error_message;
1722 }
1723
1724 // Adjust break_frame after some frames has been dropped.
1725 StackFrame::Id new_id = StackFrame::NO_ID;
1726 for (int i = bottom_js_frame_index + 1; i < frames.length(); i++) {
Ben Murdochc5610432016-08-08 18:44:38 +01001727 if (frames[i]->type() == StackFrame::JAVA_SCRIPT ||
1728 frames[i]->type() == StackFrame::INTERPRETED) {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001729 new_id = frames[i]->id();
1730 break;
1731 }
1732 }
1733 debug->FramesHaveBeenDropped(new_id, drop_mode);
1734 return NULL;
1735}
1736
1737
1738// Fills result array with statuses of functions. Modifies the stack
1739// removing all listed function if possible and if do_drop is true.
1740static const char* DropActivationsInActiveThread(
1741 Handle<JSArray> old_shared_array, Handle<JSArray> new_shared_array,
1742 Handle<JSArray> result, bool do_drop) {
1743 MultipleFunctionTarget target(old_shared_array, new_shared_array, result);
1744 Isolate* isolate = old_shared_array->GetIsolate();
1745
1746 const char* message =
1747 DropActivationsInActiveThreadImpl(isolate, target, do_drop);
1748 if (message) {
1749 return message;
1750 }
1751
1752 int array_len = GetArrayLength(old_shared_array);
1753
1754 // Replace "blocked on active" with "replaced on active" status.
1755 for (int i = 0; i < array_len; i++) {
1756 Handle<Object> obj =
Ben Murdochda12d292016-06-02 14:46:10 +01001757 JSReceiver::GetElement(isolate, result, i).ToHandleChecked();
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001758 if (*obj == Smi::FromInt(LiveEdit::FUNCTION_BLOCKED_ON_ACTIVE_STACK)) {
1759 Handle<Object> replaced(
1760 Smi::FromInt(LiveEdit::FUNCTION_REPLACED_ON_ACTIVE_STACK), isolate);
1761 SetElementSloppy(result, i, replaced);
1762 }
1763 }
1764 return NULL;
1765}
1766
1767
1768bool LiveEdit::FindActiveGenerators(Handle<FixedArray> shared_info_array,
1769 Handle<FixedArray> result,
1770 int len) {
1771 Isolate* isolate = shared_info_array->GetIsolate();
1772 bool found_suspended_activations = false;
1773
1774 DCHECK_LE(len, result->length());
1775
1776 FunctionPatchabilityStatus active = FUNCTION_BLOCKED_ACTIVE_GENERATOR;
1777
1778 Heap* heap = isolate->heap();
1779 HeapIterator iterator(heap);
1780 HeapObject* obj = NULL;
1781 while ((obj = iterator.next()) != NULL) {
1782 if (!obj->IsJSGeneratorObject()) continue;
1783
1784 JSGeneratorObject* gen = JSGeneratorObject::cast(obj);
1785 if (gen->is_closed()) continue;
1786
1787 HandleScope scope(isolate);
1788
1789 for (int i = 0; i < len; i++) {
Ben Murdoch097c5b22016-05-18 11:27:45 +01001790 Handle<JSValue> jsvalue = Handle<JSValue>::cast(
1791 FixedArray::get(*shared_info_array, i, isolate));
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001792 Handle<SharedFunctionInfo> shared =
1793 UnwrapSharedFunctionInfoFromJSValue(jsvalue);
1794
1795 if (gen->function()->shared() == *shared) {
1796 result->set(i, Smi::FromInt(active));
1797 found_suspended_activations = true;
1798 }
1799 }
1800 }
1801
1802 return found_suspended_activations;
1803}
1804
1805
1806class InactiveThreadActivationsChecker : public ThreadVisitor {
1807 public:
1808 InactiveThreadActivationsChecker(Handle<JSArray> old_shared_array,
1809 Handle<JSArray> result)
1810 : old_shared_array_(old_shared_array),
1811 result_(result),
1812 has_blocked_functions_(false) {}
1813 void VisitThread(Isolate* isolate, ThreadLocalTop* top) {
1814 for (StackFrameIterator it(isolate, top); !it.done(); it.Advance()) {
1815 has_blocked_functions_ |=
1816 CheckActivation(old_shared_array_, result_, it.frame(),
1817 LiveEdit::FUNCTION_BLOCKED_ON_OTHER_STACK);
1818 }
1819 }
1820 bool HasBlockedFunctions() {
1821 return has_blocked_functions_;
1822 }
1823
1824 private:
1825 Handle<JSArray> old_shared_array_;
1826 Handle<JSArray> result_;
1827 bool has_blocked_functions_;
1828};
1829
1830
1831Handle<JSArray> LiveEdit::CheckAndDropActivations(
1832 Handle<JSArray> old_shared_array, Handle<JSArray> new_shared_array,
1833 bool do_drop) {
1834 Isolate* isolate = old_shared_array->GetIsolate();
1835 int len = GetArrayLength(old_shared_array);
1836
1837 DCHECK(old_shared_array->HasFastElements());
1838 Handle<FixedArray> old_shared_array_elements(
1839 FixedArray::cast(old_shared_array->elements()));
1840
1841 Handle<JSArray> result = isolate->factory()->NewJSArray(len);
Ben Murdochda12d292016-06-02 14:46:10 +01001842 JSObject::EnsureWritableFastElements(result);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001843 Handle<FixedArray> result_elements =
Ben Murdochda12d292016-06-02 14:46:10 +01001844 handle(FixedArray::cast(result->elements()), isolate);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001845
1846 // Fill the default values.
1847 for (int i = 0; i < len; i++) {
1848 FunctionPatchabilityStatus status = FUNCTION_AVAILABLE_FOR_PATCH;
1849 result_elements->set(i, Smi::FromInt(status));
1850 }
1851
1852 // Scan the heap for active generators -- those that are either currently
1853 // running (as we wouldn't want to restart them, because we don't know where
1854 // to restart them from) or suspended. Fail if any one corresponds to the set
1855 // of functions being edited.
1856 if (FindActiveGenerators(old_shared_array_elements, result_elements, len)) {
1857 return result;
1858 }
1859
1860 // Check inactive threads. Fail if some functions are blocked there.
1861 InactiveThreadActivationsChecker inactive_threads_checker(old_shared_array,
1862 result);
1863 isolate->thread_manager()->IterateArchivedThreads(
1864 &inactive_threads_checker);
1865 if (inactive_threads_checker.HasBlockedFunctions()) {
1866 return result;
1867 }
1868
1869 // Try to drop activations from the current stack.
1870 const char* error_message = DropActivationsInActiveThread(
1871 old_shared_array, new_shared_array, result, do_drop);
1872 if (error_message != NULL) {
1873 // Add error message as an array extra element.
1874 Handle<String> str =
1875 isolate->factory()->NewStringFromAsciiChecked(error_message);
1876 SetElementSloppy(result, len, str);
1877 }
1878 return result;
1879}
1880
1881
1882// Describes a single callframe a target. Not finding this frame
1883// means an error.
1884class SingleFrameTarget {
1885 public:
1886 explicit SingleFrameTarget(JavaScriptFrame* frame)
1887 : m_frame(frame),
1888 m_saved_status(LiveEdit::FUNCTION_AVAILABLE_FOR_PATCH) {}
1889
1890 bool MatchActivation(StackFrame* frame,
1891 LiveEdit::FunctionPatchabilityStatus status) {
1892 if (frame->fp() == m_frame->fp()) {
1893 m_saved_status = status;
1894 return true;
1895 }
1896 return false;
1897 }
1898 const char* GetNotFoundMessage() const {
1899 return "Failed to found requested frame";
1900 }
1901 LiveEdit::FunctionPatchabilityStatus saved_status() {
1902 return m_saved_status;
1903 }
1904 void set_status(LiveEdit::FunctionPatchabilityStatus status) {
1905 m_saved_status = status;
1906 }
1907
1908 bool FrameUsesNewTarget(StackFrame* frame) {
1909 if (!frame->is_java_script()) return false;
1910 JavaScriptFrame* jsframe = JavaScriptFrame::cast(frame);
1911 Handle<SharedFunctionInfo> shared(jsframe->function()->shared());
1912 return shared->scope_info()->HasNewTarget();
1913 }
1914
1915 private:
1916 JavaScriptFrame* m_frame;
1917 LiveEdit::FunctionPatchabilityStatus m_saved_status;
1918};
1919
1920
1921// Finds a drops required frame and all frames above.
1922// Returns error message or NULL.
1923const char* LiveEdit::RestartFrame(JavaScriptFrame* frame) {
1924 SingleFrameTarget target(frame);
1925
1926 const char* result =
1927 DropActivationsInActiveThreadImpl(frame->isolate(), target, true);
1928 if (result != NULL) {
1929 return result;
1930 }
1931 if (target.saved_status() == LiveEdit::FUNCTION_BLOCKED_UNDER_NATIVE_CODE) {
1932 return "Function is blocked under native code";
1933 }
1934 if (target.saved_status() == LiveEdit::FUNCTION_BLOCKED_UNDER_GENERATOR) {
1935 return "Function is blocked under a generator activation";
1936 }
1937 return NULL;
1938}
1939
Ben Murdochc5610432016-08-08 18:44:38 +01001940Handle<JSArray> LiveEditFunctionTracker::Collect(FunctionLiteral* node,
1941 Handle<Script> script,
1942 Zone* zone, Isolate* isolate) {
1943 LiveEditFunctionTracker visitor(script, zone, isolate);
1944 visitor.VisitFunctionLiteral(node);
1945 return visitor.result_;
1946}
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001947
Ben Murdochc5610432016-08-08 18:44:38 +01001948LiveEditFunctionTracker::LiveEditFunctionTracker(Handle<Script> script,
1949 Zone* zone, Isolate* isolate)
1950 : AstTraversalVisitor(isolate) {
1951 current_parent_index_ = -1;
1952 isolate_ = isolate;
1953 len_ = 0;
1954 result_ = isolate->factory()->NewJSArray(10);
1955 script_ = script;
1956 zone_ = zone;
1957}
1958
1959void LiveEditFunctionTracker::VisitFunctionLiteral(FunctionLiteral* node) {
1960 Scope* scope = node->scope();
1961
1962 // FunctionStarted is called in pre-order.
1963 FunctionStarted(node);
1964
1965 VisitDeclarations(scope->declarations());
1966 VisitStatements(node->body());
1967
1968 // FunctionDone are called in post-order.
1969 // TODO(jgruber): If required, replace the (linear cost)
1970 // FindSharedFunctionInfo call with a more efficient implementation.
1971 Handle<SharedFunctionInfo> info =
1972 script_->FindSharedFunctionInfo(node).ToHandleChecked();
1973 FunctionDone(info, scope);
1974}
1975
1976void LiveEditFunctionTracker::FunctionStarted(FunctionLiteral* fun) {
1977 HandleScope handle_scope(isolate_);
1978 FunctionInfoWrapper info = FunctionInfoWrapper::Create(isolate_);
1979 info.SetInitialProperties(fun->name(), fun->start_position(),
1980 fun->end_position(), fun->parameter_count(),
1981 fun->materialized_literal_count(),
1982 current_parent_index_);
1983 current_parent_index_ = len_;
1984 SetElementSloppy(result_, len_, info.GetJSArray());
1985 len_++;
1986}
1987
1988// Saves full information about a function: its code, its scope info
1989// and a SharedFunctionInfo object.
1990void LiveEditFunctionTracker::FunctionDone(Handle<SharedFunctionInfo> shared,
1991 Scope* scope) {
1992 HandleScope handle_scope(isolate_);
1993 FunctionInfoWrapper info = FunctionInfoWrapper::cast(
1994 *JSReceiver::GetElement(isolate_, result_, current_parent_index_)
1995 .ToHandleChecked());
1996 info.SetFunctionCode(Handle<Code>(shared->code()),
1997 Handle<HeapObject>(shared->scope_info()));
1998 info.SetSharedFunctionInfo(shared);
1999
2000 Handle<Object> scope_info_list = SerializeFunctionScope(scope);
2001 info.SetFunctionScopeInfo(scope_info_list);
2002
2003 current_parent_index_ = info.GetParentIndex();
2004}
2005
2006Handle<Object> LiveEditFunctionTracker::SerializeFunctionScope(Scope* scope) {
2007 Handle<JSArray> scope_info_list = isolate_->factory()->NewJSArray(10);
2008 int scope_info_length = 0;
2009
2010 // Saves some description of scope. It stores name and indexes of
2011 // variables in the whole scope chain. Null-named slots delimit
2012 // scopes of this chain.
2013 Scope* current_scope = scope;
2014 while (current_scope != NULL) {
2015 HandleScope handle_scope(isolate_);
2016 ZoneList<Variable*> stack_list(current_scope->StackLocalCount(), zone_);
2017 ZoneList<Variable*> context_list(current_scope->ContextLocalCount(), zone_);
2018 ZoneList<Variable*> globals_list(current_scope->ContextGlobalCount(),
2019 zone_);
2020 current_scope->CollectStackAndContextLocals(&stack_list, &context_list,
2021 &globals_list);
2022 context_list.Sort(&Variable::CompareIndex);
2023
2024 for (int i = 0; i < context_list.length(); i++) {
2025 SetElementSloppy(scope_info_list, scope_info_length,
2026 context_list[i]->name());
2027 scope_info_length++;
2028 SetElementSloppy(
2029 scope_info_list, scope_info_length,
2030 Handle<Smi>(Smi::FromInt(context_list[i]->index()), isolate_));
2031 scope_info_length++;
2032 }
2033 SetElementSloppy(scope_info_list, scope_info_length,
2034 Handle<Object>(isolate_->heap()->null_value(), isolate_));
2035 scope_info_length++;
2036
2037 current_scope = current_scope->outer_scope();
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002038 }
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002039
Ben Murdochc5610432016-08-08 18:44:38 +01002040 return scope_info_list;
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002041}
2042
2043} // namespace internal
2044} // namespace v8