forked from v8/v8
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathliveedit.cc
More file actions
2012 lines (1696 loc) · 66.5 KB
/
liveedit.cc
File metadata and controls
2012 lines (1696 loc) · 66.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2012 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/debug/liveedit.h"
#include "src/code-stubs.h"
#include "src/compilation-cache.h"
#include "src/compiler.h"
#include "src/debug/debug.h"
#include "src/deoptimizer.h"
#include "src/frames-inl.h"
#include "src/global-handles.h"
#include "src/isolate-inl.h"
#include "src/messages.h"
#include "src/parser.h"
#include "src/scopeinfo.h"
#include "src/scopes.h"
#include "src/v8.h"
#include "src/v8memory.h"
namespace v8 {
namespace internal {
void SetElementSloppy(Handle<JSObject> object,
uint32_t index,
Handle<Object> value) {
// Ignore return value from SetElement. It can only be a failure if there
// are element setters causing exceptions and the debugger context has none
// of these.
Object::SetElement(object->GetIsolate(), object, index, value, SLOPPY)
.Assert();
}
// A simple implementation of dynamic programming algorithm. It solves
// the problem of finding the difference of 2 arrays. It uses a table of results
// of subproblems. Each cell contains a number together with 2-bit flag
// that helps building the chunk list.
class Differencer {
public:
explicit Differencer(Comparator::Input* input)
: input_(input), len1_(input->GetLength1()), len2_(input->GetLength2()) {
buffer_ = NewArray<int>(len1_ * len2_);
}
~Differencer() {
DeleteArray(buffer_);
}
void Initialize() {
int array_size = len1_ * len2_;
for (int i = 0; i < array_size; i++) {
buffer_[i] = kEmptyCellValue;
}
}
// Makes sure that result for the full problem is calculated and stored
// in the table together with flags showing a path through subproblems.
void FillTable() {
CompareUpToTail(0, 0);
}
void SaveResult(Comparator::Output* chunk_writer) {
ResultWriter writer(chunk_writer);
int pos1 = 0;
int pos2 = 0;
while (true) {
if (pos1 < len1_) {
if (pos2 < len2_) {
Direction dir = get_direction(pos1, pos2);
switch (dir) {
case EQ:
writer.eq();
pos1++;
pos2++;
break;
case SKIP1:
writer.skip1(1);
pos1++;
break;
case SKIP2:
case SKIP_ANY:
writer.skip2(1);
pos2++;
break;
default:
UNREACHABLE();
}
} else {
writer.skip1(len1_ - pos1);
break;
}
} else {
if (len2_ != pos2) {
writer.skip2(len2_ - pos2);
}
break;
}
}
writer.close();
}
private:
Comparator::Input* input_;
int* buffer_;
int len1_;
int len2_;
enum Direction {
EQ = 0,
SKIP1,
SKIP2,
SKIP_ANY,
MAX_DIRECTION_FLAG_VALUE = SKIP_ANY
};
// Computes result for a subtask and optionally caches it in the buffer table.
// All results values are shifted to make space for flags in the lower bits.
int CompareUpToTail(int pos1, int pos2) {
if (pos1 < len1_) {
if (pos2 < len2_) {
int cached_res = get_value4(pos1, pos2);
if (cached_res == kEmptyCellValue) {
Direction dir;
int res;
if (input_->Equals(pos1, pos2)) {
res = CompareUpToTail(pos1 + 1, pos2 + 1);
dir = EQ;
} else {
int res1 = CompareUpToTail(pos1 + 1, pos2) +
(1 << kDirectionSizeBits);
int res2 = CompareUpToTail(pos1, pos2 + 1) +
(1 << kDirectionSizeBits);
if (res1 == res2) {
res = res1;
dir = SKIP_ANY;
} else if (res1 < res2) {
res = res1;
dir = SKIP1;
} else {
res = res2;
dir = SKIP2;
}
}
set_value4_and_dir(pos1, pos2, res, dir);
cached_res = res;
}
return cached_res;
} else {
return (len1_ - pos1) << kDirectionSizeBits;
}
} else {
return (len2_ - pos2) << kDirectionSizeBits;
}
}
inline int& get_cell(int i1, int i2) {
return buffer_[i1 + i2 * len1_];
}
// Each cell keeps a value plus direction. Value is multiplied by 4.
void set_value4_and_dir(int i1, int i2, int value4, Direction dir) {
DCHECK((value4 & kDirectionMask) == 0);
get_cell(i1, i2) = value4 | dir;
}
int get_value4(int i1, int i2) {
return get_cell(i1, i2) & (kMaxUInt32 ^ kDirectionMask);
}
Direction get_direction(int i1, int i2) {
return static_cast<Direction>(get_cell(i1, i2) & kDirectionMask);
}
static const int kDirectionSizeBits = 2;
static const int kDirectionMask = (1 << kDirectionSizeBits) - 1;
static const int kEmptyCellValue = ~0u << kDirectionSizeBits;
// This method only holds static assert statement (unfortunately you cannot
// place one in class scope).
void StaticAssertHolder() {
STATIC_ASSERT(MAX_DIRECTION_FLAG_VALUE < (1 << kDirectionSizeBits));
}
class ResultWriter {
public:
explicit ResultWriter(Comparator::Output* chunk_writer)
: chunk_writer_(chunk_writer), pos1_(0), pos2_(0),
pos1_begin_(-1), pos2_begin_(-1), has_open_chunk_(false) {
}
void eq() {
FlushChunk();
pos1_++;
pos2_++;
}
void skip1(int len1) {
StartChunk();
pos1_ += len1;
}
void skip2(int len2) {
StartChunk();
pos2_ += len2;
}
void close() {
FlushChunk();
}
private:
Comparator::Output* chunk_writer_;
int pos1_;
int pos2_;
int pos1_begin_;
int pos2_begin_;
bool has_open_chunk_;
void StartChunk() {
if (!has_open_chunk_) {
pos1_begin_ = pos1_;
pos2_begin_ = pos2_;
has_open_chunk_ = true;
}
}
void FlushChunk() {
if (has_open_chunk_) {
chunk_writer_->AddChunk(pos1_begin_, pos2_begin_,
pos1_ - pos1_begin_, pos2_ - pos2_begin_);
has_open_chunk_ = false;
}
}
};
};
void Comparator::CalculateDifference(Comparator::Input* input,
Comparator::Output* result_writer) {
Differencer differencer(input);
differencer.Initialize();
differencer.FillTable();
differencer.SaveResult(result_writer);
}
static bool CompareSubstrings(Handle<String> s1, int pos1,
Handle<String> s2, int pos2, int len) {
for (int i = 0; i < len; i++) {
if (s1->Get(i + pos1) != s2->Get(i + pos2)) {
return false;
}
}
return true;
}
// Additional to Input interface. Lets switch Input range to subrange.
// More elegant way would be to wrap one Input as another Input object
// and translate positions there, but that would cost us additional virtual
// call per comparison.
class SubrangableInput : public Comparator::Input {
public:
virtual void SetSubrange1(int offset, int len) = 0;
virtual void SetSubrange2(int offset, int len) = 0;
};
class SubrangableOutput : public Comparator::Output {
public:
virtual void SetSubrange1(int offset, int len) = 0;
virtual void SetSubrange2(int offset, int len) = 0;
};
static int min(int a, int b) {
return a < b ? a : b;
}
// Finds common prefix and suffix in input. This parts shouldn't take space in
// linear programming table. Enable subranging in input and output.
static void NarrowDownInput(SubrangableInput* input,
SubrangableOutput* output) {
const int len1 = input->GetLength1();
const int len2 = input->GetLength2();
int common_prefix_len;
int common_suffix_len;
{
common_prefix_len = 0;
int prefix_limit = min(len1, len2);
while (common_prefix_len < prefix_limit &&
input->Equals(common_prefix_len, common_prefix_len)) {
common_prefix_len++;
}
common_suffix_len = 0;
int suffix_limit = min(len1 - common_prefix_len, len2 - common_prefix_len);
while (common_suffix_len < suffix_limit &&
input->Equals(len1 - common_suffix_len - 1,
len2 - common_suffix_len - 1)) {
common_suffix_len++;
}
}
if (common_prefix_len > 0 || common_suffix_len > 0) {
int new_len1 = len1 - common_suffix_len - common_prefix_len;
int new_len2 = len2 - common_suffix_len - common_prefix_len;
input->SetSubrange1(common_prefix_len, new_len1);
input->SetSubrange2(common_prefix_len, new_len2);
output->SetSubrange1(common_prefix_len, new_len1);
output->SetSubrange2(common_prefix_len, new_len2);
}
}
// A helper class that writes chunk numbers into JSArray.
// Each chunk is stored as 3 array elements: (pos1_begin, pos1_end, pos2_end).
class CompareOutputArrayWriter {
public:
explicit CompareOutputArrayWriter(Isolate* isolate)
: array_(isolate->factory()->NewJSArray(10)), current_size_(0) {}
Handle<JSArray> GetResult() {
return array_;
}
void WriteChunk(int char_pos1, int char_pos2, int char_len1, int char_len2) {
Isolate* isolate = array_->GetIsolate();
SetElementSloppy(array_,
current_size_,
Handle<Object>(Smi::FromInt(char_pos1), isolate));
SetElementSloppy(array_,
current_size_ + 1,
Handle<Object>(Smi::FromInt(char_pos1 + char_len1),
isolate));
SetElementSloppy(array_,
current_size_ + 2,
Handle<Object>(Smi::FromInt(char_pos2 + char_len2),
isolate));
current_size_ += 3;
}
private:
Handle<JSArray> array_;
int current_size_;
};
// Represents 2 strings as 2 arrays of tokens.
// TODO(LiveEdit): Currently it's actually an array of charactres.
// Make array of tokens instead.
class TokensCompareInput : public Comparator::Input {
public:
TokensCompareInput(Handle<String> s1, int offset1, int len1,
Handle<String> s2, int offset2, int len2)
: s1_(s1), offset1_(offset1), len1_(len1),
s2_(s2), offset2_(offset2), len2_(len2) {
}
virtual int GetLength1() {
return len1_;
}
virtual int GetLength2() {
return len2_;
}
bool Equals(int index1, int index2) {
return s1_->Get(offset1_ + index1) == s2_->Get(offset2_ + index2);
}
private:
Handle<String> s1_;
int offset1_;
int len1_;
Handle<String> s2_;
int offset2_;
int len2_;
};
// Stores compare result in JSArray. Converts substring positions
// to absolute positions.
class TokensCompareOutput : public Comparator::Output {
public:
TokensCompareOutput(CompareOutputArrayWriter* array_writer,
int offset1, int offset2)
: array_writer_(array_writer), offset1_(offset1), offset2_(offset2) {
}
void AddChunk(int pos1, int pos2, int len1, int len2) {
array_writer_->WriteChunk(pos1 + offset1_, pos2 + offset2_, len1, len2);
}
private:
CompareOutputArrayWriter* array_writer_;
int offset1_;
int offset2_;
};
// Wraps raw n-elements line_ends array as a list of n+1 lines. The last line
// never has terminating new line character.
class LineEndsWrapper {
public:
explicit LineEndsWrapper(Handle<String> string)
: ends_array_(String::CalculateLineEnds(string, false)),
string_len_(string->length()) {
}
int length() {
return ends_array_->length() + 1;
}
// Returns start for any line including start of the imaginary line after
// the last line.
int GetLineStart(int index) {
if (index == 0) {
return 0;
} else {
return GetLineEnd(index - 1);
}
}
int GetLineEnd(int index) {
if (index == ends_array_->length()) {
// End of the last line is always an end of the whole string.
// If the string ends with a new line character, the last line is an
// empty string after this character.
return string_len_;
} else {
return GetPosAfterNewLine(index);
}
}
private:
Handle<FixedArray> ends_array_;
int string_len_;
int GetPosAfterNewLine(int index) {
return Smi::cast(ends_array_->get(index))->value() + 1;
}
};
// Represents 2 strings as 2 arrays of lines.
class LineArrayCompareInput : public SubrangableInput {
public:
LineArrayCompareInput(Handle<String> s1, Handle<String> s2,
LineEndsWrapper line_ends1, LineEndsWrapper line_ends2)
: s1_(s1), s2_(s2), line_ends1_(line_ends1),
line_ends2_(line_ends2),
subrange_offset1_(0), subrange_offset2_(0),
subrange_len1_(line_ends1_.length()),
subrange_len2_(line_ends2_.length()) {
}
int GetLength1() {
return subrange_len1_;
}
int GetLength2() {
return subrange_len2_;
}
bool Equals(int index1, int index2) {
index1 += subrange_offset1_;
index2 += subrange_offset2_;
int line_start1 = line_ends1_.GetLineStart(index1);
int line_start2 = line_ends2_.GetLineStart(index2);
int line_end1 = line_ends1_.GetLineEnd(index1);
int line_end2 = line_ends2_.GetLineEnd(index2);
int len1 = line_end1 - line_start1;
int len2 = line_end2 - line_start2;
if (len1 != len2) {
return false;
}
return CompareSubstrings(s1_, line_start1, s2_, line_start2,
len1);
}
void SetSubrange1(int offset, int len) {
subrange_offset1_ = offset;
subrange_len1_ = len;
}
void SetSubrange2(int offset, int len) {
subrange_offset2_ = offset;
subrange_len2_ = len;
}
private:
Handle<String> s1_;
Handle<String> s2_;
LineEndsWrapper line_ends1_;
LineEndsWrapper line_ends2_;
int subrange_offset1_;
int subrange_offset2_;
int subrange_len1_;
int subrange_len2_;
};
// Stores compare result in JSArray. For each chunk tries to conduct
// a fine-grained nested diff token-wise.
class TokenizingLineArrayCompareOutput : public SubrangableOutput {
public:
TokenizingLineArrayCompareOutput(LineEndsWrapper line_ends1,
LineEndsWrapper line_ends2,
Handle<String> s1, Handle<String> s2)
: array_writer_(s1->GetIsolate()),
line_ends1_(line_ends1), line_ends2_(line_ends2), s1_(s1), s2_(s2),
subrange_offset1_(0), subrange_offset2_(0) {
}
void AddChunk(int line_pos1, int line_pos2, int line_len1, int line_len2) {
line_pos1 += subrange_offset1_;
line_pos2 += subrange_offset2_;
int char_pos1 = line_ends1_.GetLineStart(line_pos1);
int char_pos2 = line_ends2_.GetLineStart(line_pos2);
int char_len1 = line_ends1_.GetLineStart(line_pos1 + line_len1) - char_pos1;
int char_len2 = line_ends2_.GetLineStart(line_pos2 + line_len2) - char_pos2;
if (char_len1 < CHUNK_LEN_LIMIT && char_len2 < CHUNK_LEN_LIMIT) {
// Chunk is small enough to conduct a nested token-level diff.
HandleScope subTaskScope(s1_->GetIsolate());
TokensCompareInput tokens_input(s1_, char_pos1, char_len1,
s2_, char_pos2, char_len2);
TokensCompareOutput tokens_output(&array_writer_, char_pos1,
char_pos2);
Comparator::CalculateDifference(&tokens_input, &tokens_output);
} else {
array_writer_.WriteChunk(char_pos1, char_pos2, char_len1, char_len2);
}
}
void SetSubrange1(int offset, int len) {
subrange_offset1_ = offset;
}
void SetSubrange2(int offset, int len) {
subrange_offset2_ = offset;
}
Handle<JSArray> GetResult() {
return array_writer_.GetResult();
}
private:
static const int CHUNK_LEN_LIMIT = 800;
CompareOutputArrayWriter array_writer_;
LineEndsWrapper line_ends1_;
LineEndsWrapper line_ends2_;
Handle<String> s1_;
Handle<String> s2_;
int subrange_offset1_;
int subrange_offset2_;
};
Handle<JSArray> LiveEdit::CompareStrings(Handle<String> s1,
Handle<String> s2) {
s1 = String::Flatten(s1);
s2 = String::Flatten(s2);
LineEndsWrapper line_ends1(s1);
LineEndsWrapper line_ends2(s2);
LineArrayCompareInput input(s1, s2, line_ends1, line_ends2);
TokenizingLineArrayCompareOutput output(line_ends1, line_ends2, s1, s2);
NarrowDownInput(&input, &output);
Comparator::CalculateDifference(&input, &output);
return output.GetResult();
}
// Unwraps JSValue object, returning its field "value"
static Handle<Object> UnwrapJSValue(Handle<JSValue> jsValue) {
return Handle<Object>(jsValue->value(), jsValue->GetIsolate());
}
// Wraps any object into a OpaqueReference, that will hide the object
// from JavaScript.
static Handle<JSValue> WrapInJSValue(Handle<HeapObject> object) {
Isolate* isolate = object->GetIsolate();
Handle<JSFunction> constructor = isolate->opaque_reference_function();
Handle<JSValue> result =
Handle<JSValue>::cast(isolate->factory()->NewJSObject(constructor));
result->set_value(*object);
return result;
}
static Handle<SharedFunctionInfo> UnwrapSharedFunctionInfoFromJSValue(
Handle<JSValue> jsValue) {
Object* shared = jsValue->value();
CHECK(shared->IsSharedFunctionInfo());
return Handle<SharedFunctionInfo>(SharedFunctionInfo::cast(shared));
}
static int GetArrayLength(Handle<JSArray> array) {
Object* length = array->length();
CHECK(length->IsSmi());
return Smi::cast(length)->value();
}
void FunctionInfoWrapper::SetInitialProperties(Handle<String> name,
int start_position,
int end_position, int param_num,
int literal_count,
int parent_index) {
HandleScope scope(isolate());
this->SetField(kFunctionNameOffset_, name);
this->SetSmiValueField(kStartPositionOffset_, start_position);
this->SetSmiValueField(kEndPositionOffset_, end_position);
this->SetSmiValueField(kParamNumOffset_, param_num);
this->SetSmiValueField(kLiteralNumOffset_, literal_count);
this->SetSmiValueField(kParentIndexOffset_, parent_index);
}
void FunctionInfoWrapper::SetFunctionCode(Handle<Code> function_code,
Handle<HeapObject> code_scope_info) {
Handle<JSValue> code_wrapper = WrapInJSValue(function_code);
this->SetField(kCodeOffset_, code_wrapper);
Handle<JSValue> scope_wrapper = WrapInJSValue(code_scope_info);
this->SetField(kCodeScopeInfoOffset_, scope_wrapper);
}
void FunctionInfoWrapper::SetSharedFunctionInfo(
Handle<SharedFunctionInfo> info) {
Handle<JSValue> info_holder = WrapInJSValue(info);
this->SetField(kSharedFunctionInfoOffset_, info_holder);
}
Handle<Code> FunctionInfoWrapper::GetFunctionCode() {
Handle<Object> element = this->GetField(kCodeOffset_);
Handle<JSValue> value_wrapper = Handle<JSValue>::cast(element);
Handle<Object> raw_result = UnwrapJSValue(value_wrapper);
CHECK(raw_result->IsCode());
return Handle<Code>::cast(raw_result);
}
MaybeHandle<TypeFeedbackVector> FunctionInfoWrapper::GetFeedbackVector() {
Handle<Object> element = this->GetField(kSharedFunctionInfoOffset_);
if (element->IsJSValue()) {
Handle<JSValue> value_wrapper = Handle<JSValue>::cast(element);
Handle<Object> raw_result = UnwrapJSValue(value_wrapper);
Handle<SharedFunctionInfo> shared =
Handle<SharedFunctionInfo>::cast(raw_result);
return Handle<TypeFeedbackVector>(shared->feedback_vector(), isolate());
} else {
// Scripts may never have a SharedFunctionInfo created.
return MaybeHandle<TypeFeedbackVector>();
}
}
Handle<Object> FunctionInfoWrapper::GetCodeScopeInfo() {
Handle<Object> element = this->GetField(kCodeScopeInfoOffset_);
return UnwrapJSValue(Handle<JSValue>::cast(element));
}
void SharedInfoWrapper::SetProperties(Handle<String> name,
int start_position,
int end_position,
Handle<SharedFunctionInfo> info) {
HandleScope scope(isolate());
this->SetField(kFunctionNameOffset_, name);
Handle<JSValue> info_holder = WrapInJSValue(info);
this->SetField(kSharedInfoOffset_, info_holder);
this->SetSmiValueField(kStartPositionOffset_, start_position);
this->SetSmiValueField(kEndPositionOffset_, end_position);
}
Handle<SharedFunctionInfo> SharedInfoWrapper::GetInfo() {
Handle<Object> element = this->GetField(kSharedInfoOffset_);
Handle<JSValue> value_wrapper = Handle<JSValue>::cast(element);
return UnwrapSharedFunctionInfoFromJSValue(value_wrapper);
}
class FunctionInfoListener {
public:
explicit FunctionInfoListener(Isolate* isolate) {
current_parent_index_ = -1;
len_ = 0;
result_ = isolate->factory()->NewJSArray(10);
}
void FunctionStarted(FunctionLiteral* fun) {
HandleScope scope(isolate());
FunctionInfoWrapper info = FunctionInfoWrapper::Create(isolate());
info.SetInitialProperties(fun->name(), fun->start_position(),
fun->end_position(), fun->parameter_count(),
fun->materialized_literal_count(),
current_parent_index_);
current_parent_index_ = len_;
SetElementSloppy(result_, len_, info.GetJSArray());
len_++;
}
void FunctionDone() {
HandleScope scope(isolate());
FunctionInfoWrapper info =
FunctionInfoWrapper::cast(
*Object::GetElement(
isolate(), result_, current_parent_index_).ToHandleChecked());
current_parent_index_ = info.GetParentIndex();
}
// Saves only function code, because for a script function we
// may never create a SharedFunctionInfo object.
void FunctionCode(Handle<Code> function_code) {
FunctionInfoWrapper info =
FunctionInfoWrapper::cast(
*Object::GetElement(
isolate(), result_, current_parent_index_).ToHandleChecked());
info.SetFunctionCode(function_code,
Handle<HeapObject>(isolate()->heap()->null_value()));
}
// Saves full information about a function: its code, its scope info
// and a SharedFunctionInfo object.
void FunctionInfo(Handle<SharedFunctionInfo> shared, Scope* scope,
Zone* zone) {
if (!shared->IsSharedFunctionInfo()) {
return;
}
FunctionInfoWrapper info =
FunctionInfoWrapper::cast(
*Object::GetElement(
isolate(), result_, current_parent_index_).ToHandleChecked());
info.SetFunctionCode(Handle<Code>(shared->code()),
Handle<HeapObject>(shared->scope_info()));
info.SetSharedFunctionInfo(shared);
Handle<Object> scope_info_list = SerializeFunctionScope(scope, zone);
info.SetFunctionScopeInfo(scope_info_list);
}
Handle<JSArray> GetResult() { return result_; }
private:
Isolate* isolate() const { return result_->GetIsolate(); }
Handle<Object> SerializeFunctionScope(Scope* scope, Zone* zone) {
Handle<JSArray> scope_info_list = isolate()->factory()->NewJSArray(10);
int scope_info_length = 0;
// Saves some description of scope. It stores name and indexes of
// variables in the whole scope chain. Null-named slots delimit
// scopes of this chain.
Scope* current_scope = scope;
while (current_scope != NULL) {
HandleScope handle_scope(isolate());
ZoneList<Variable*> stack_list(current_scope->StackLocalCount(), zone);
ZoneList<Variable*> context_list(
current_scope->ContextLocalCount(), zone);
ZoneList<Variable*> globals_list(current_scope->ContextGlobalCount(),
zone);
current_scope->CollectStackAndContextLocals(&stack_list, &context_list,
&globals_list);
context_list.Sort(&Variable::CompareIndex);
for (int i = 0; i < context_list.length(); i++) {
SetElementSloppy(scope_info_list,
scope_info_length,
context_list[i]->name());
scope_info_length++;
SetElementSloppy(
scope_info_list,
scope_info_length,
Handle<Smi>(Smi::FromInt(context_list[i]->index()), isolate()));
scope_info_length++;
}
SetElementSloppy(scope_info_list,
scope_info_length,
Handle<Object>(isolate()->heap()->null_value(),
isolate()));
scope_info_length++;
current_scope = current_scope->outer_scope();
}
return scope_info_list;
}
Handle<JSArray> result_;
int len_;
int current_parent_index_;
};
void LiveEdit::InitializeThreadLocal(Debug* debug) {
debug->thread_local_.frame_drop_mode_ = LiveEdit::FRAMES_UNTOUCHED;
}
bool LiveEdit::SetAfterBreakTarget(Debug* debug) {
Code* code = NULL;
Isolate* isolate = debug->isolate_;
switch (debug->thread_local_.frame_drop_mode_) {
case FRAMES_UNTOUCHED:
return false;
case FRAME_DROPPED_IN_IC_CALL:
// We must have been calling IC stub. Do not go there anymore.
code = isolate->builtins()->builtin(Builtins::kPlainReturn_LiveEdit);
break;
case FRAME_DROPPED_IN_DEBUG_SLOT_CALL:
// Debug break slot stub does not return normally, instead it manually
// cleans the stack and jumps. We should patch the jump address.
code = isolate->builtins()->builtin(Builtins::kFrameDropper_LiveEdit);
break;
case FRAME_DROPPED_IN_DIRECT_CALL:
// Nothing to do, after_break_target is not used here.
return true;
case FRAME_DROPPED_IN_RETURN_CALL:
code = isolate->builtins()->builtin(Builtins::kFrameDropper_LiveEdit);
break;
case CURRENTLY_SET_MODE:
UNREACHABLE();
break;
}
debug->after_break_target_ = code->entry();
return true;
}
MaybeHandle<JSArray> LiveEdit::GatherCompileInfo(Handle<Script> script,
Handle<String> source) {
Isolate* isolate = script->GetIsolate();
FunctionInfoListener listener(isolate);
Handle<Object> original_source =
Handle<Object>(script->source(), isolate);
script->set_source(*source);
isolate->set_active_function_info_listener(&listener);
{
// Creating verbose TryCatch from public API is currently the only way to
// force code save location. We do not use this the object directly.
v8::TryCatch try_catch(reinterpret_cast<v8::Isolate*>(isolate));
try_catch.SetVerbose(true);
// A logical 'try' section.
Compiler::CompileForLiveEdit(script);
}
// A logical 'catch' section.
Handle<JSObject> rethrow_exception;
if (isolate->has_pending_exception()) {
Handle<Object> exception(isolate->pending_exception(), isolate);
MessageLocation message_location = isolate->GetMessageLocation();
isolate->clear_pending_message();
isolate->clear_pending_exception();
// If possible, copy positions from message object to exception object.
if (exception->IsJSObject() && !message_location.script().is_null()) {
rethrow_exception = Handle<JSObject>::cast(exception);
Factory* factory = isolate->factory();
Handle<String> start_pos_key = factory->InternalizeOneByteString(
STATIC_CHAR_VECTOR("startPosition"));
Handle<String> end_pos_key =
factory->InternalizeOneByteString(STATIC_CHAR_VECTOR("endPosition"));
Handle<String> script_obj_key =
factory->InternalizeOneByteString(STATIC_CHAR_VECTOR("scriptObject"));
Handle<Smi> start_pos(
Smi::FromInt(message_location.start_pos()), isolate);
Handle<Smi> end_pos(Smi::FromInt(message_location.end_pos()), isolate);
Handle<JSObject> script_obj =
Script::GetWrapper(message_location.script());
Object::SetProperty(rethrow_exception, start_pos_key, start_pos, SLOPPY)
.Assert();
Object::SetProperty(rethrow_exception, end_pos_key, end_pos, SLOPPY)
.Assert();
Object::SetProperty(rethrow_exception, script_obj_key, script_obj, SLOPPY)
.Assert();
}
}
// A logical 'finally' section.
isolate->set_active_function_info_listener(NULL);
script->set_source(*original_source);
if (rethrow_exception.is_null()) {
return listener.GetResult();
} else {
return isolate->Throw<JSArray>(rethrow_exception);
}
}
// Visitor that finds all references to a particular code object,
// including "CODE_TARGET" references in other code objects and replaces
// them on the fly.
class ReplacingVisitor : public ObjectVisitor {
public:
explicit ReplacingVisitor(Code* original, Code* substitution)
: original_(original), substitution_(substitution) {
}
virtual void VisitPointers(Object** start, Object** end) {
for (Object** p = start; p < end; p++) {
if (*p == original_) {
*p = substitution_;
}
}
}
virtual void VisitCodeEntry(Address entry) {
if (Code::GetObjectFromEntryAddress(entry) == original_) {
Address substitution_entry = substitution_->instruction_start();
Memory::Address_at(entry) = substitution_entry;
}
}
virtual void VisitCodeTarget(RelocInfo* rinfo) {
if (RelocInfo::IsCodeTarget(rinfo->rmode()) &&
Code::GetCodeFromTargetAddress(rinfo->target_address()) == original_) {
Address substitution_entry = substitution_->instruction_start();
rinfo->set_target_address(substitution_entry);
}
}
virtual void VisitDebugTarget(RelocInfo* rinfo) {
VisitCodeTarget(rinfo);
}
private:
Code* original_;
Code* substitution_;
};
// Finds all references to original and replaces them with substitution.
static void ReplaceCodeObject(Handle<Code> original,
Handle<Code> substitution) {
// Perform a full GC in order to ensure that we are not in the middle of an
// incremental marking phase when we are replacing the code object.
// Since we are not in an incremental marking phase we can write pointers
// to code objects (that are never in new space) without worrying about
// write barriers.
Heap* heap = original->GetHeap();
HeapIterator iterator(heap);
DCHECK(!heap->InNewSpace(*substitution));
ReplacingVisitor visitor(*original, *substitution);
// Iterate over all roots. Stack frames may have pointer into original code,
// so temporary replace the pointers with offset numbers
// in prologue/epilogue.
heap->IterateRoots(&visitor, VISIT_ALL);
// Now iterate over all pointers of all objects, including code_target
// implicit pointers.
for (HeapObject* obj = iterator.next(); obj != NULL; obj = iterator.next()) {
obj->Iterate(&visitor);
}
}
// Patch function literals.
// Name 'literals' is a misnomer. Rather it's a cache for complex object
// boilerplates and for a native context. We must clean cached values.
// Additionally we may need to allocate a new array if number of literals
// changed.
class LiteralFixer {
public:
static void PatchLiterals(FunctionInfoWrapper* compile_info_wrapper,
Handle<SharedFunctionInfo> shared_info,
Isolate* isolate) {
int new_literal_count = compile_info_wrapper->GetLiteralCount();
int old_literal_count = shared_info->num_literals();
if (old_literal_count == new_literal_count) {
// If literal count didn't change, simply go over all functions
// and clear literal arrays.
ClearValuesVisitor visitor;
IterateJSFunctions(shared_info, &visitor);
} else {
// When literal count changes, we have to create new array instances.
// Since we cannot create instances when iterating heap, we should first
// collect all functions and fix their literal arrays.
Handle<FixedArray> function_instances =
CollectJSFunctions(shared_info, isolate);
for (int i = 0; i < function_instances->length(); i++) {
Handle<JSFunction> fun(JSFunction::cast(function_instances->get(i)));
Handle<FixedArray> new_literals =