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