1 // 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.
10 #include "code-stubs.h"
11 #include "compilation-cache.h"
14 #include "deoptimizer.h"
15 #include "global-handles.h"
18 #include "scopeinfo.h"
25 void SetElementSloppy(Handle<JSObject> object,
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
31 JSObject::SetElement(object, index, value, NONE, SLOPPY).Assert();
35 // A simple implementation of dynamic programming algorithm. It solves
36 // the problem of finding the difference of 2 arrays. It uses a table of results
37 // of subproblems. Each cell contains a number together with 2-bit flag
38 // that helps building the chunk list.
41 explicit Differencer(Comparator::Input* input)
42 : input_(input), len1_(input->GetLength1()), len2_(input->GetLength2()) {
43 buffer_ = NewArray<int>(len1_ * len2_);
50 int array_size = len1_ * len2_;
51 for (int i = 0; i < array_size; i++) {
52 buffer_[i] = kEmptyCellValue;
56 // Makes sure that result for the full problem is calculated and stored
57 // in the table together with flags showing a path through subproblems.
59 CompareUpToTail(0, 0);
62 void SaveResult(Comparator::Output* chunk_writer) {
63 ResultWriter writer(chunk_writer);
70 Direction dir = get_direction(pos1, pos2);
90 writer.skip1(len1_ - pos1);
95 writer.skip2(len2_ - pos2);
104 Comparator::Input* input_;
115 MAX_DIRECTION_FLAG_VALUE = SKIP_ANY
118 // Computes result for a subtask and optionally caches it in the buffer table.
119 // All results values are shifted to make space for flags in the lower bits.
120 int CompareUpToTail(int pos1, int pos2) {
123 int cached_res = get_value4(pos1, pos2);
124 if (cached_res == kEmptyCellValue) {
127 if (input_->Equals(pos1, pos2)) {
128 res = CompareUpToTail(pos1 + 1, pos2 + 1);
131 int res1 = CompareUpToTail(pos1 + 1, pos2) +
132 (1 << kDirectionSizeBits);
133 int res2 = CompareUpToTail(pos1, pos2 + 1) +
134 (1 << kDirectionSizeBits);
138 } else if (res1 < res2) {
146 set_value4_and_dir(pos1, pos2, res, dir);
151 return (len1_ - pos1) << kDirectionSizeBits;
154 return (len2_ - pos2) << kDirectionSizeBits;
158 inline int& get_cell(int i1, int i2) {
159 return buffer_[i1 + i2 * len1_];
162 // Each cell keeps a value plus direction. Value is multiplied by 4.
163 void set_value4_and_dir(int i1, int i2, int value4, Direction dir) {
164 ASSERT((value4 & kDirectionMask) == 0);
165 get_cell(i1, i2) = value4 | dir;
168 int get_value4(int i1, int i2) {
169 return get_cell(i1, i2) & (kMaxUInt32 ^ kDirectionMask);
171 Direction get_direction(int i1, int i2) {
172 return static_cast<Direction>(get_cell(i1, i2) & kDirectionMask);
175 static const int kDirectionSizeBits = 2;
176 static const int kDirectionMask = (1 << kDirectionSizeBits) - 1;
177 static const int kEmptyCellValue = -1 << kDirectionSizeBits;
179 // This method only holds static assert statement (unfortunately you cannot
180 // place one in class scope).
181 void StaticAssertHolder() {
182 STATIC_ASSERT(MAX_DIRECTION_FLAG_VALUE < (1 << kDirectionSizeBits));
187 explicit ResultWriter(Comparator::Output* chunk_writer)
188 : chunk_writer_(chunk_writer), pos1_(0), pos2_(0),
189 pos1_begin_(-1), pos2_begin_(-1), has_open_chunk_(false) {
196 void skip1(int len1) {
200 void skip2(int len2) {
209 Comparator::Output* chunk_writer_;
214 bool has_open_chunk_;
217 if (!has_open_chunk_) {
220 has_open_chunk_ = true;
225 if (has_open_chunk_) {
226 chunk_writer_->AddChunk(pos1_begin_, pos2_begin_,
227 pos1_ - pos1_begin_, pos2_ - pos2_begin_);
228 has_open_chunk_ = false;
235 void Comparator::CalculateDifference(Comparator::Input* input,
236 Comparator::Output* result_writer) {
237 Differencer differencer(input);
238 differencer.Initialize();
239 differencer.FillTable();
240 differencer.SaveResult(result_writer);
244 static bool CompareSubstrings(Handle<String> s1, int pos1,
245 Handle<String> s2, int pos2, int len) {
246 for (int i = 0; i < len; i++) {
247 if (s1->Get(i + pos1) != s2->Get(i + pos2)) {
255 // Additional to Input interface. Lets switch Input range to subrange.
256 // More elegant way would be to wrap one Input as another Input object
257 // and translate positions there, but that would cost us additional virtual
258 // call per comparison.
259 class SubrangableInput : public Comparator::Input {
261 virtual void SetSubrange1(int offset, int len) = 0;
262 virtual void SetSubrange2(int offset, int len) = 0;
266 class SubrangableOutput : public Comparator::Output {
268 virtual void SetSubrange1(int offset, int len) = 0;
269 virtual void SetSubrange2(int offset, int len) = 0;
273 static int min(int a, int b) {
274 return a < b ? a : b;
278 // Finds common prefix and suffix in input. This parts shouldn't take space in
279 // linear programming table. Enable subranging in input and output.
280 static void NarrowDownInput(SubrangableInput* input,
281 SubrangableOutput* output) {
282 const int len1 = input->GetLength1();
283 const int len2 = input->GetLength2();
285 int common_prefix_len;
286 int common_suffix_len;
289 common_prefix_len = 0;
290 int prefix_limit = min(len1, len2);
291 while (common_prefix_len < prefix_limit &&
292 input->Equals(common_prefix_len, common_prefix_len)) {
296 common_suffix_len = 0;
297 int suffix_limit = min(len1 - common_prefix_len, len2 - common_prefix_len);
299 while (common_suffix_len < suffix_limit &&
300 input->Equals(len1 - common_suffix_len - 1,
301 len2 - common_suffix_len - 1)) {
306 if (common_prefix_len > 0 || common_suffix_len > 0) {
307 int new_len1 = len1 - common_suffix_len - common_prefix_len;
308 int new_len2 = len2 - common_suffix_len - common_prefix_len;
310 input->SetSubrange1(common_prefix_len, new_len1);
311 input->SetSubrange2(common_prefix_len, new_len2);
313 output->SetSubrange1(common_prefix_len, new_len1);
314 output->SetSubrange2(common_prefix_len, new_len2);
319 // A helper class that writes chunk numbers into JSArray.
320 // Each chunk is stored as 3 array elements: (pos1_begin, pos1_end, pos2_end).
321 class CompareOutputArrayWriter {
323 explicit CompareOutputArrayWriter(Isolate* isolate)
324 : array_(isolate->factory()->NewJSArray(10)), current_size_(0) {}
326 Handle<JSArray> GetResult() {
330 void WriteChunk(int char_pos1, int char_pos2, int char_len1, int char_len2) {
331 Isolate* isolate = array_->GetIsolate();
332 SetElementSloppy(array_,
334 Handle<Object>(Smi::FromInt(char_pos1), isolate));
335 SetElementSloppy(array_,
337 Handle<Object>(Smi::FromInt(char_pos1 + char_len1),
339 SetElementSloppy(array_,
341 Handle<Object>(Smi::FromInt(char_pos2 + char_len2),
347 Handle<JSArray> array_;
352 // Represents 2 strings as 2 arrays of tokens.
353 // TODO(LiveEdit): Currently it's actually an array of charactres.
354 // Make array of tokens instead.
355 class TokensCompareInput : public Comparator::Input {
357 TokensCompareInput(Handle<String> s1, int offset1, int len1,
358 Handle<String> s2, int offset2, int len2)
359 : s1_(s1), offset1_(offset1), len1_(len1),
360 s2_(s2), offset2_(offset2), len2_(len2) {
362 virtual int GetLength1() {
365 virtual int GetLength2() {
368 bool Equals(int index1, int index2) {
369 return s1_->Get(offset1_ + index1) == s2_->Get(offset2_ + index2);
382 // Stores compare result in JSArray. Converts substring positions
383 // to absolute positions.
384 class TokensCompareOutput : public Comparator::Output {
386 TokensCompareOutput(CompareOutputArrayWriter* array_writer,
387 int offset1, int offset2)
388 : array_writer_(array_writer), offset1_(offset1), offset2_(offset2) {
391 void AddChunk(int pos1, int pos2, int len1, int len2) {
392 array_writer_->WriteChunk(pos1 + offset1_, pos2 + offset2_, len1, len2);
396 CompareOutputArrayWriter* array_writer_;
402 // Wraps raw n-elements line_ends array as a list of n+1 lines. The last line
403 // never has terminating new line character.
404 class LineEndsWrapper {
406 explicit LineEndsWrapper(Handle<String> string)
407 : ends_array_(String::CalculateLineEnds(string, false)),
408 string_len_(string->length()) {
411 return ends_array_->length() + 1;
413 // Returns start for any line including start of the imaginary line after
415 int GetLineStart(int index) {
419 return GetLineEnd(index - 1);
422 int GetLineEnd(int index) {
423 if (index == ends_array_->length()) {
424 // End of the last line is always an end of the whole string.
425 // If the string ends with a new line character, the last line is an
426 // empty string after this character.
429 return GetPosAfterNewLine(index);
434 Handle<FixedArray> ends_array_;
437 int GetPosAfterNewLine(int index) {
438 return Smi::cast(ends_array_->get(index))->value() + 1;
443 // Represents 2 strings as 2 arrays of lines.
444 class LineArrayCompareInput : public SubrangableInput {
446 LineArrayCompareInput(Handle<String> s1, Handle<String> s2,
447 LineEndsWrapper line_ends1, LineEndsWrapper line_ends2)
448 : s1_(s1), s2_(s2), line_ends1_(line_ends1),
449 line_ends2_(line_ends2),
450 subrange_offset1_(0), subrange_offset2_(0),
451 subrange_len1_(line_ends1_.length()),
452 subrange_len2_(line_ends2_.length()) {
455 return subrange_len1_;
458 return subrange_len2_;
460 bool Equals(int index1, int index2) {
461 index1 += subrange_offset1_;
462 index2 += subrange_offset2_;
464 int line_start1 = line_ends1_.GetLineStart(index1);
465 int line_start2 = line_ends2_.GetLineStart(index2);
466 int line_end1 = line_ends1_.GetLineEnd(index1);
467 int line_end2 = line_ends2_.GetLineEnd(index2);
468 int len1 = line_end1 - line_start1;
469 int len2 = line_end2 - line_start2;
473 return CompareSubstrings(s1_, line_start1, s2_, line_start2,
476 void SetSubrange1(int offset, int len) {
477 subrange_offset1_ = offset;
478 subrange_len1_ = len;
480 void SetSubrange2(int offset, int len) {
481 subrange_offset2_ = offset;
482 subrange_len2_ = len;
488 LineEndsWrapper line_ends1_;
489 LineEndsWrapper line_ends2_;
490 int subrange_offset1_;
491 int subrange_offset2_;
497 // Stores compare result in JSArray. For each chunk tries to conduct
498 // a fine-grained nested diff token-wise.
499 class TokenizingLineArrayCompareOutput : public SubrangableOutput {
501 TokenizingLineArrayCompareOutput(LineEndsWrapper line_ends1,
502 LineEndsWrapper line_ends2,
503 Handle<String> s1, Handle<String> s2)
504 : array_writer_(s1->GetIsolate()),
505 line_ends1_(line_ends1), line_ends2_(line_ends2), s1_(s1), s2_(s2),
506 subrange_offset1_(0), subrange_offset2_(0) {
509 void AddChunk(int line_pos1, int line_pos2, int line_len1, int line_len2) {
510 line_pos1 += subrange_offset1_;
511 line_pos2 += subrange_offset2_;
513 int char_pos1 = line_ends1_.GetLineStart(line_pos1);
514 int char_pos2 = line_ends2_.GetLineStart(line_pos2);
515 int char_len1 = line_ends1_.GetLineStart(line_pos1 + line_len1) - char_pos1;
516 int char_len2 = line_ends2_.GetLineStart(line_pos2 + line_len2) - char_pos2;
518 if (char_len1 < CHUNK_LEN_LIMIT && char_len2 < CHUNK_LEN_LIMIT) {
519 // Chunk is small enough to conduct a nested token-level diff.
520 HandleScope subTaskScope(s1_->GetIsolate());
522 TokensCompareInput tokens_input(s1_, char_pos1, char_len1,
523 s2_, char_pos2, char_len2);
524 TokensCompareOutput tokens_output(&array_writer_, char_pos1,
527 Comparator::CalculateDifference(&tokens_input, &tokens_output);
529 array_writer_.WriteChunk(char_pos1, char_pos2, char_len1, char_len2);
532 void SetSubrange1(int offset, int len) {
533 subrange_offset1_ = offset;
535 void SetSubrange2(int offset, int len) {
536 subrange_offset2_ = offset;
539 Handle<JSArray> GetResult() {
540 return array_writer_.GetResult();
544 static const int CHUNK_LEN_LIMIT = 800;
546 CompareOutputArrayWriter array_writer_;
547 LineEndsWrapper line_ends1_;
548 LineEndsWrapper line_ends2_;
551 int subrange_offset1_;
552 int subrange_offset2_;
556 Handle<JSArray> LiveEdit::CompareStrings(Handle<String> s1,
558 s1 = String::Flatten(s1);
559 s2 = String::Flatten(s2);
561 LineEndsWrapper line_ends1(s1);
562 LineEndsWrapper line_ends2(s2);
564 LineArrayCompareInput input(s1, s2, line_ends1, line_ends2);
565 TokenizingLineArrayCompareOutput output(line_ends1, line_ends2, s1, s2);
567 NarrowDownInput(&input, &output);
569 Comparator::CalculateDifference(&input, &output);
571 return output.GetResult();
575 // Unwraps JSValue object, returning its field "value"
576 static Handle<Object> UnwrapJSValue(Handle<JSValue> jsValue) {
577 return Handle<Object>(jsValue->value(), jsValue->GetIsolate());
581 // Wraps any object into a OpaqueReference, that will hide the object
583 static Handle<JSValue> WrapInJSValue(Handle<HeapObject> object) {
584 Isolate* isolate = object->GetIsolate();
585 Handle<JSFunction> constructor = isolate->opaque_reference_function();
586 Handle<JSValue> result =
587 Handle<JSValue>::cast(isolate->factory()->NewJSObject(constructor));
588 result->set_value(*object);
593 static Handle<SharedFunctionInfo> UnwrapSharedFunctionInfoFromJSValue(
594 Handle<JSValue> jsValue) {
595 Object* shared = jsValue->value();
596 CHECK(shared->IsSharedFunctionInfo());
597 return Handle<SharedFunctionInfo>(SharedFunctionInfo::cast(shared));
601 static int GetArrayLength(Handle<JSArray> array) {
602 Object* length = array->length();
603 CHECK(length->IsSmi());
604 return Smi::cast(length)->value();
608 void FunctionInfoWrapper::SetInitialProperties(Handle<String> name,
615 HandleScope scope(isolate());
616 this->SetField(kFunctionNameOffset_, name);
617 this->SetSmiValueField(kStartPositionOffset_, start_position);
618 this->SetSmiValueField(kEndPositionOffset_, end_position);
619 this->SetSmiValueField(kParamNumOffset_, param_num);
620 this->SetSmiValueField(kLiteralNumOffset_, literal_count);
621 this->SetSmiValueField(kSlotNumOffset_, slot_count);
622 this->SetSmiValueField(kParentIndexOffset_, parent_index);
626 void FunctionInfoWrapper::SetFunctionCode(Handle<Code> function_code,
627 Handle<HeapObject> code_scope_info) {
628 Handle<JSValue> code_wrapper = WrapInJSValue(function_code);
629 this->SetField(kCodeOffset_, code_wrapper);
631 Handle<JSValue> scope_wrapper = WrapInJSValue(code_scope_info);
632 this->SetField(kCodeScopeInfoOffset_, scope_wrapper);
636 void FunctionInfoWrapper::SetSharedFunctionInfo(
637 Handle<SharedFunctionInfo> info) {
638 Handle<JSValue> info_holder = WrapInJSValue(info);
639 this->SetField(kSharedFunctionInfoOffset_, info_holder);
643 Handle<Code> FunctionInfoWrapper::GetFunctionCode() {
644 Handle<Object> element = this->GetField(kCodeOffset_);
645 Handle<JSValue> value_wrapper = Handle<JSValue>::cast(element);
646 Handle<Object> raw_result = UnwrapJSValue(value_wrapper);
647 CHECK(raw_result->IsCode());
648 return Handle<Code>::cast(raw_result);
652 Handle<FixedArray> FunctionInfoWrapper::GetFeedbackVector() {
653 Handle<Object> element = this->GetField(kSharedFunctionInfoOffset_);
654 Handle<FixedArray> result;
655 if (element->IsJSValue()) {
656 Handle<JSValue> value_wrapper = Handle<JSValue>::cast(element);
657 Handle<Object> raw_result = UnwrapJSValue(value_wrapper);
658 Handle<SharedFunctionInfo> shared =
659 Handle<SharedFunctionInfo>::cast(raw_result);
660 result = Handle<FixedArray>(shared->feedback_vector(), isolate());
661 CHECK_EQ(result->length(), GetSlotCount());
663 // Scripts may never have a SharedFunctionInfo created, so
664 // create a type feedback vector here.
665 int slot_count = GetSlotCount();
666 result = isolate()->factory()->NewTypeFeedbackVector(slot_count);
672 Handle<Object> FunctionInfoWrapper::GetCodeScopeInfo() {
673 Handle<Object> element = this->GetField(kCodeScopeInfoOffset_);
674 return UnwrapJSValue(Handle<JSValue>::cast(element));
678 void SharedInfoWrapper::SetProperties(Handle<String> name,
681 Handle<SharedFunctionInfo> info) {
682 HandleScope scope(isolate());
683 this->SetField(kFunctionNameOffset_, name);
684 Handle<JSValue> info_holder = WrapInJSValue(info);
685 this->SetField(kSharedInfoOffset_, info_holder);
686 this->SetSmiValueField(kStartPositionOffset_, start_position);
687 this->SetSmiValueField(kEndPositionOffset_, end_position);
691 Handle<SharedFunctionInfo> SharedInfoWrapper::GetInfo() {
692 Handle<Object> element = this->GetField(kSharedInfoOffset_);
693 Handle<JSValue> value_wrapper = Handle<JSValue>::cast(element);
694 return UnwrapSharedFunctionInfoFromJSValue(value_wrapper);
698 class FunctionInfoListener {
700 explicit FunctionInfoListener(Isolate* isolate) {
701 current_parent_index_ = -1;
703 result_ = isolate->factory()->NewJSArray(10);
706 void FunctionStarted(FunctionLiteral* fun) {
707 HandleScope scope(isolate());
708 FunctionInfoWrapper info = FunctionInfoWrapper::Create(isolate());
709 info.SetInitialProperties(fun->name(), fun->start_position(),
710 fun->end_position(), fun->parameter_count(),
711 fun->materialized_literal_count(),
713 current_parent_index_);
714 current_parent_index_ = len_;
715 SetElementSloppy(result_, len_, info.GetJSArray());
719 void FunctionDone() {
720 HandleScope scope(isolate());
721 FunctionInfoWrapper info =
722 FunctionInfoWrapper::cast(
724 isolate(), result_, current_parent_index_).ToHandleChecked());
725 current_parent_index_ = info.GetParentIndex();
728 // Saves only function code, because for a script function we
729 // may never create a SharedFunctionInfo object.
730 void FunctionCode(Handle<Code> function_code) {
731 FunctionInfoWrapper info =
732 FunctionInfoWrapper::cast(
734 isolate(), result_, current_parent_index_).ToHandleChecked());
735 info.SetFunctionCode(function_code,
736 Handle<HeapObject>(isolate()->heap()->null_value()));
739 // Saves full information about a function: its code, its scope info
740 // and a SharedFunctionInfo object.
741 void FunctionInfo(Handle<SharedFunctionInfo> shared, Scope* scope,
743 if (!shared->IsSharedFunctionInfo()) {
746 FunctionInfoWrapper info =
747 FunctionInfoWrapper::cast(
749 isolate(), result_, current_parent_index_).ToHandleChecked());
750 info.SetFunctionCode(Handle<Code>(shared->code()),
751 Handle<HeapObject>(shared->scope_info()));
752 info.SetSharedFunctionInfo(shared);
754 Handle<Object> scope_info_list = SerializeFunctionScope(scope, zone);
755 info.SetFunctionScopeInfo(scope_info_list);
758 Handle<JSArray> GetResult() { return result_; }
761 Isolate* isolate() const { return result_->GetIsolate(); }
763 Handle<Object> SerializeFunctionScope(Scope* scope, Zone* zone) {
764 Handle<JSArray> scope_info_list = isolate()->factory()->NewJSArray(10);
765 int scope_info_length = 0;
767 // Saves some description of scope. It stores name and indexes of
768 // variables in the whole scope chain. Null-named slots delimit
769 // scopes of this chain.
770 Scope* current_scope = scope;
771 while (current_scope != NULL) {
772 HandleScope handle_scope(isolate());
773 ZoneList<Variable*> stack_list(current_scope->StackLocalCount(), zone);
774 ZoneList<Variable*> context_list(
775 current_scope->ContextLocalCount(), zone);
776 current_scope->CollectStackAndContextLocals(&stack_list, &context_list);
777 context_list.Sort(&Variable::CompareIndex);
779 for (int i = 0; i < context_list.length(); i++) {
780 SetElementSloppy(scope_info_list,
782 context_list[i]->name());
787 Handle<Smi>(Smi::FromInt(context_list[i]->index()), isolate()));
790 SetElementSloppy(scope_info_list,
792 Handle<Object>(isolate()->heap()->null_value(),
796 current_scope = current_scope->outer_scope();
799 return scope_info_list;
802 Handle<JSArray> result_;
804 int current_parent_index_;
808 MaybeHandle<JSArray> LiveEdit::GatherCompileInfo(Handle<Script> script,
809 Handle<String> source) {
810 Isolate* isolate = script->GetIsolate();
812 FunctionInfoListener listener(isolate);
813 Handle<Object> original_source =
814 Handle<Object>(script->source(), isolate);
815 script->set_source(*source);
816 isolate->set_active_function_info_listener(&listener);
819 // Creating verbose TryCatch from public API is currently the only way to
820 // force code save location. We do not use this the object directly.
821 v8::TryCatch try_catch;
822 try_catch.SetVerbose(true);
824 // A logical 'try' section.
825 Compiler::CompileForLiveEdit(script);
828 // A logical 'catch' section.
829 Handle<JSObject> rethrow_exception;
830 if (isolate->has_pending_exception()) {
831 Handle<Object> exception(isolate->pending_exception(), isolate);
832 MessageLocation message_location = isolate->GetMessageLocation();
834 isolate->clear_pending_message();
835 isolate->clear_pending_exception();
837 // If possible, copy positions from message object to exception object.
838 if (exception->IsJSObject() && !message_location.script().is_null()) {
839 rethrow_exception = Handle<JSObject>::cast(exception);
841 Factory* factory = isolate->factory();
842 Handle<String> start_pos_key = factory->InternalizeOneByteString(
843 STATIC_ASCII_VECTOR("startPosition"));
844 Handle<String> end_pos_key = factory->InternalizeOneByteString(
845 STATIC_ASCII_VECTOR("endPosition"));
846 Handle<String> script_obj_key = factory->InternalizeOneByteString(
847 STATIC_ASCII_VECTOR("scriptObject"));
848 Handle<Smi> start_pos(
849 Smi::FromInt(message_location.start_pos()), isolate);
850 Handle<Smi> end_pos(Smi::FromInt(message_location.end_pos()), isolate);
851 Handle<JSObject> script_obj =
852 Script::GetWrapper(message_location.script());
853 JSReceiver::SetProperty(
854 rethrow_exception, start_pos_key, start_pos, NONE, SLOPPY).Assert();
855 JSReceiver::SetProperty(
856 rethrow_exception, end_pos_key, end_pos, NONE, SLOPPY).Assert();
857 JSReceiver::SetProperty(
858 rethrow_exception, script_obj_key, script_obj, NONE, SLOPPY).Assert();
862 // A logical 'finally' section.
863 isolate->set_active_function_info_listener(NULL);
864 script->set_source(*original_source);
866 if (rethrow_exception.is_null()) {
867 return listener.GetResult();
869 return isolate->Throw<JSArray>(rethrow_exception);
874 void LiveEdit::WrapSharedFunctionInfos(Handle<JSArray> array) {
875 Isolate* isolate = array->GetIsolate();
876 HandleScope scope(isolate);
877 int len = GetArrayLength(array);
878 for (int i = 0; i < len; i++) {
879 Handle<SharedFunctionInfo> info(
880 SharedFunctionInfo::cast(
881 *Object::GetElement(isolate, array, i).ToHandleChecked()));
882 SharedInfoWrapper info_wrapper = SharedInfoWrapper::Create(isolate);
883 Handle<String> name_handle(String::cast(info->name()));
884 info_wrapper.SetProperties(name_handle, info->start_position(),
885 info->end_position(), info);
886 SetElementSloppy(array, i, info_wrapper.GetJSArray());
891 // Visitor that finds all references to a particular code object,
892 // including "CODE_TARGET" references in other code objects and replaces
894 class ReplacingVisitor : public ObjectVisitor {
896 explicit ReplacingVisitor(Code* original, Code* substitution)
897 : original_(original), substitution_(substitution) {
900 virtual void VisitPointers(Object** start, Object** end) {
901 for (Object** p = start; p < end; p++) {
902 if (*p == original_) {
908 virtual void VisitCodeEntry(Address entry) {
909 if (Code::GetObjectFromEntryAddress(entry) == original_) {
910 Address substitution_entry = substitution_->instruction_start();
911 Memory::Address_at(entry) = substitution_entry;
915 virtual void VisitCodeTarget(RelocInfo* rinfo) {
916 if (RelocInfo::IsCodeTarget(rinfo->rmode()) &&
917 Code::GetCodeFromTargetAddress(rinfo->target_address()) == original_) {
918 Address substitution_entry = substitution_->instruction_start();
919 rinfo->set_target_address(substitution_entry);
923 virtual void VisitDebugTarget(RelocInfo* rinfo) {
924 VisitCodeTarget(rinfo);
933 // Finds all references to original and replaces them with substitution.
934 static void ReplaceCodeObject(Handle<Code> original,
935 Handle<Code> substitution) {
936 // Perform a full GC in order to ensure that we are not in the middle of an
937 // incremental marking phase when we are replacing the code object.
938 // Since we are not in an incremental marking phase we can write pointers
939 // to code objects (that are never in new space) without worrying about
941 Heap* heap = original->GetHeap();
942 heap->CollectAllGarbage(Heap::kMakeHeapIterableMask,
943 "liveedit.cc ReplaceCodeObject");
945 ASSERT(!heap->InNewSpace(*substitution));
947 DisallowHeapAllocation no_allocation;
949 ReplacingVisitor visitor(*original, *substitution);
951 // Iterate over all roots. Stack frames may have pointer into original code,
952 // so temporary replace the pointers with offset numbers
953 // in prologue/epilogue.
954 heap->IterateRoots(&visitor, VISIT_ALL);
956 // Now iterate over all pointers of all objects, including code_target
957 // implicit pointers.
958 HeapIterator iterator(heap);
959 for (HeapObject* obj = iterator.next(); obj != NULL; obj = iterator.next()) {
960 obj->Iterate(&visitor);
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
972 static void PatchLiterals(FunctionInfoWrapper* compile_info_wrapper,
973 Handle<SharedFunctionInfo> shared_info,
975 int new_literal_count = compile_info_wrapper->GetLiteralCount();
976 if (new_literal_count > 0) {
977 new_literal_count += JSFunction::kLiteralsPrefixSize;
979 int old_literal_count = shared_info->num_literals();
981 if (old_literal_count == new_literal_count) {
982 // If literal count didn't change, simply go over all functions
983 // and clear literal arrays.
984 ClearValuesVisitor visitor;
985 IterateJSFunctions(*shared_info, &visitor);
987 // When literal count changes, we have to create new array instances.
988 // Since we cannot create instances when iterating heap, we should first
989 // collect all functions and fix their literal arrays.
990 Handle<FixedArray> function_instances =
991 CollectJSFunctions(shared_info, isolate);
992 for (int i = 0; i < function_instances->length(); i++) {
993 Handle<JSFunction> fun(JSFunction::cast(function_instances->get(i)));
994 Handle<FixedArray> old_literals(fun->literals());
995 Handle<FixedArray> new_literals =
996 isolate->factory()->NewFixedArray(new_literal_count);
997 if (new_literal_count > 0) {
998 Handle<Context> native_context;
999 if (old_literals->length() >
1000 JSFunction::kLiteralNativeContextIndex) {
1001 native_context = Handle<Context>(
1002 JSFunction::NativeContextFromLiterals(fun->literals()));
1004 native_context = Handle<Context>(fun->context()->native_context());
1006 new_literals->set(JSFunction::kLiteralNativeContextIndex,
1009 fun->set_literals(*new_literals);
1012 shared_info->set_num_literals(new_literal_count);
1017 // Iterates all function instances in the HEAP that refers to the
1018 // provided shared_info.
1019 template<typename Visitor>
1020 static void IterateJSFunctions(SharedFunctionInfo* shared_info,
1022 DisallowHeapAllocation no_allocation;
1024 HeapIterator iterator(shared_info->GetHeap());
1025 for (HeapObject* obj = iterator.next(); obj != NULL;
1026 obj = iterator.next()) {
1027 if (obj->IsJSFunction()) {
1028 JSFunction* function = JSFunction::cast(obj);
1029 if (function->shared() == shared_info) {
1030 visitor->visit(function);
1036 // Finds all instances of JSFunction that refers to the provided shared_info
1037 // and returns array with them.
1038 static Handle<FixedArray> CollectJSFunctions(
1039 Handle<SharedFunctionInfo> shared_info, Isolate* isolate) {
1040 CountVisitor count_visitor;
1041 count_visitor.count = 0;
1042 IterateJSFunctions(*shared_info, &count_visitor);
1043 int size = count_visitor.count;
1045 Handle<FixedArray> result = isolate->factory()->NewFixedArray(size);
1047 CollectVisitor collect_visitor(result);
1048 IterateJSFunctions(*shared_info, &collect_visitor);
1053 class ClearValuesVisitor {
1055 void visit(JSFunction* fun) {
1056 FixedArray* literals = fun->literals();
1057 int len = literals->length();
1058 for (int j = JSFunction::kLiteralsPrefixSize; j < len; j++) {
1059 literals->set_undefined(j);
1064 class CountVisitor {
1066 void visit(JSFunction* fun) {
1072 class CollectVisitor {
1074 explicit CollectVisitor(Handle<FixedArray> output)
1075 : m_output(output), m_pos(0) {}
1077 void visit(JSFunction* fun) {
1078 m_output->set(m_pos, fun);
1082 Handle<FixedArray> m_output;
1088 // Check whether the code is natural function code (not a lazy-compile stub
1090 static bool IsJSFunctionCode(Code* code) {
1091 return code->kind() == Code::FUNCTION;
1095 // Returns true if an instance of candidate were inlined into function's code.
1096 static bool IsInlined(JSFunction* function, SharedFunctionInfo* candidate) {
1097 DisallowHeapAllocation no_gc;
1099 if (function->code()->kind() != Code::OPTIMIZED_FUNCTION) return false;
1101 DeoptimizationInputData* data =
1102 DeoptimizationInputData::cast(function->code()->deoptimization_data());
1104 if (data == function->GetIsolate()->heap()->empty_fixed_array()) {
1108 FixedArray* literals = data->LiteralArray();
1110 int inlined_count = data->InlinedFunctionCount()->value();
1111 for (int i = 0; i < inlined_count; ++i) {
1112 JSFunction* inlined = JSFunction::cast(literals->get(i));
1113 if (inlined->shared() == candidate) return true;
1120 // Marks code that shares the same shared function info or has inlined
1121 // code that shares the same function info.
1122 class DependentFunctionMarker: public OptimizedFunctionVisitor {
1124 SharedFunctionInfo* shared_info_;
1127 explicit DependentFunctionMarker(SharedFunctionInfo* shared_info)
1128 : shared_info_(shared_info), found_(false) { }
1130 virtual void EnterContext(Context* context) { } // Don't care.
1131 virtual void LeaveContext(Context* context) { } // Don't care.
1132 virtual void VisitFunction(JSFunction* function) {
1133 // It should be guaranteed by the iterator that everything is optimized.
1134 ASSERT(function->code()->kind() == Code::OPTIMIZED_FUNCTION);
1135 if (shared_info_ == function->shared() ||
1136 IsInlined(function, shared_info_)) {
1137 // Mark the code for deoptimization.
1138 function->code()->set_marked_for_deoptimization(true);
1145 static void DeoptimizeDependentFunctions(SharedFunctionInfo* function_info) {
1146 DisallowHeapAllocation no_allocation;
1147 DependentFunctionMarker marker(function_info);
1148 // TODO(titzer): need to traverse all optimized code to find OSR code here.
1149 Deoptimizer::VisitAllOptimizedFunctions(function_info->GetIsolate(), &marker);
1151 if (marker.found_) {
1152 // Only go through with the deoptimization if something was found.
1153 Deoptimizer::DeoptimizeMarkedCode(function_info->GetIsolate());
1158 void LiveEdit::ReplaceFunctionCode(
1159 Handle<JSArray> new_compile_info_array,
1160 Handle<JSArray> shared_info_array) {
1161 Isolate* isolate = new_compile_info_array->GetIsolate();
1163 FunctionInfoWrapper compile_info_wrapper(new_compile_info_array);
1164 SharedInfoWrapper shared_info_wrapper(shared_info_array);
1166 Handle<SharedFunctionInfo> shared_info = shared_info_wrapper.GetInfo();
1168 isolate->heap()->EnsureHeapIsIterable();
1170 if (IsJSFunctionCode(shared_info->code())) {
1171 Handle<Code> code = compile_info_wrapper.GetFunctionCode();
1172 ReplaceCodeObject(Handle<Code>(shared_info->code()), code);
1173 Handle<Object> code_scope_info = compile_info_wrapper.GetCodeScopeInfo();
1174 if (code_scope_info->IsFixedArray()) {
1175 shared_info->set_scope_info(ScopeInfo::cast(*code_scope_info));
1177 shared_info->DisableOptimization(kLiveEdit);
1178 // Update the type feedback vector
1179 Handle<FixedArray> feedback_vector =
1180 compile_info_wrapper.GetFeedbackVector();
1181 shared_info->set_feedback_vector(*feedback_vector);
1184 if (shared_info->debug_info()->IsDebugInfo()) {
1185 Handle<DebugInfo> debug_info(DebugInfo::cast(shared_info->debug_info()));
1186 Handle<Code> new_original_code =
1187 isolate->factory()->CopyCode(compile_info_wrapper.GetFunctionCode());
1188 debug_info->set_original_code(*new_original_code);
1191 int start_position = compile_info_wrapper.GetStartPosition();
1192 int end_position = compile_info_wrapper.GetEndPosition();
1193 shared_info->set_start_position(start_position);
1194 shared_info->set_end_position(end_position);
1196 LiteralFixer::PatchLiterals(&compile_info_wrapper, shared_info, isolate);
1198 shared_info->set_construct_stub(
1199 isolate->builtins()->builtin(Builtins::kJSConstructStubGeneric));
1201 DeoptimizeDependentFunctions(*shared_info);
1202 isolate->compilation_cache()->Remove(shared_info);
1206 void LiveEdit::FunctionSourceUpdated(Handle<JSArray> shared_info_array) {
1207 SharedInfoWrapper shared_info_wrapper(shared_info_array);
1208 Handle<SharedFunctionInfo> shared_info = shared_info_wrapper.GetInfo();
1210 DeoptimizeDependentFunctions(*shared_info);
1211 shared_info_array->GetIsolate()->compilation_cache()->Remove(shared_info);
1215 void LiveEdit::SetFunctionScript(Handle<JSValue> function_wrapper,
1216 Handle<Object> script_handle) {
1217 Handle<SharedFunctionInfo> shared_info =
1218 UnwrapSharedFunctionInfoFromJSValue(function_wrapper);
1219 CHECK(script_handle->IsScript() || script_handle->IsUndefined());
1220 shared_info->set_script(*script_handle);
1222 function_wrapper->GetIsolate()->compilation_cache()->Remove(shared_info);
1226 // For a script text change (defined as position_change_array), translates
1227 // position in unchanged text to position in changed text.
1228 // Text change is a set of non-overlapping regions in text, that have changed
1229 // their contents and length. It is specified as array of groups of 3 numbers:
1230 // (change_begin, change_end, change_end_new_position).
1231 // Each group describes a change in text; groups are sorted by change_begin.
1232 // Only position in text beyond any changes may be successfully translated.
1233 // If a positions is inside some region that changed, result is currently
1235 static int TranslatePosition(int original_position,
1236 Handle<JSArray> position_change_array) {
1237 int position_diff = 0;
1238 int array_len = GetArrayLength(position_change_array);
1239 Isolate* isolate = position_change_array->GetIsolate();
1240 // TODO(635): binary search may be used here
1241 for (int i = 0; i < array_len; i += 3) {
1242 HandleScope scope(isolate);
1243 Handle<Object> element = Object::GetElement(
1244 isolate, position_change_array, i).ToHandleChecked();
1245 CHECK(element->IsSmi());
1246 int chunk_start = Handle<Smi>::cast(element)->value();
1247 if (original_position < chunk_start) {
1250 element = Object::GetElement(
1251 isolate, position_change_array, i + 1).ToHandleChecked();
1252 CHECK(element->IsSmi());
1253 int chunk_end = Handle<Smi>::cast(element)->value();
1254 // Position mustn't be inside a chunk.
1255 ASSERT(original_position >= chunk_end);
1256 element = Object::GetElement(
1257 isolate, position_change_array, i + 2).ToHandleChecked();
1258 CHECK(element->IsSmi());
1259 int chunk_changed_end = Handle<Smi>::cast(element)->value();
1260 position_diff = chunk_changed_end - chunk_end;
1263 return original_position + position_diff;
1267 // Auto-growing buffer for writing relocation info code section. This buffer
1268 // is a simplified version of buffer from Assembler. Unlike Assembler, this
1269 // class is platform-independent and it works without dealing with instructions.
1270 // As specified by RelocInfo format, the buffer is filled in reversed order:
1271 // from upper to lower addresses.
1272 // It uses NewArray/DeleteArray for memory management.
1273 class RelocInfoBuffer {
1275 RelocInfoBuffer(int buffer_initial_capicity, byte* pc) {
1276 buffer_size_ = buffer_initial_capicity + kBufferGap;
1277 buffer_ = NewArray<byte>(buffer_size_);
1279 reloc_info_writer_.Reposition(buffer_ + buffer_size_, pc);
1281 ~RelocInfoBuffer() {
1282 DeleteArray(buffer_);
1285 // As specified by RelocInfo format, the buffer is filled in reversed order:
1286 // from upper to lower addresses.
1287 void Write(const RelocInfo* rinfo) {
1288 if (buffer_ + kBufferGap >= reloc_info_writer_.pos()) {
1291 reloc_info_writer_.Write(rinfo);
1294 Vector<byte> GetResult() {
1295 // Return the bytes from pos up to end of buffer.
1297 static_cast<int>((buffer_ + buffer_size_) - reloc_info_writer_.pos());
1298 return Vector<byte>(reloc_info_writer_.pos(), result_size);
1303 // Compute new buffer size.
1304 int new_buffer_size;
1305 if (buffer_size_ < 2 * KB) {
1306 new_buffer_size = 4 * KB;
1308 new_buffer_size = 2 * buffer_size_;
1310 // Some internal data structures overflow for very large buffers,
1311 // they must ensure that kMaximalBufferSize is not too large.
1312 if (new_buffer_size > kMaximalBufferSize) {
1313 V8::FatalProcessOutOfMemory("RelocInfoBuffer::GrowBuffer");
1316 // Set up new buffer.
1317 byte* new_buffer = NewArray<byte>(new_buffer_size);
1320 int curently_used_size =
1321 static_cast<int>(buffer_ + buffer_size_ - reloc_info_writer_.pos());
1322 OS::MemMove(new_buffer + new_buffer_size - curently_used_size,
1323 reloc_info_writer_.pos(), curently_used_size);
1325 reloc_info_writer_.Reposition(
1326 new_buffer + new_buffer_size - curently_used_size,
1327 reloc_info_writer_.last_pc());
1329 DeleteArray(buffer_);
1330 buffer_ = new_buffer;
1331 buffer_size_ = new_buffer_size;
1334 RelocInfoWriter reloc_info_writer_;
1338 static const int kBufferGap = RelocInfoWriter::kMaxSize;
1339 static const int kMaximalBufferSize = 512*MB;
1343 // Patch positions in code (changes relocation info section) and possibly
1344 // returns new instance of code.
1345 static Handle<Code> PatchPositionsInCode(
1347 Handle<JSArray> position_change_array) {
1348 Isolate* isolate = code->GetIsolate();
1350 RelocInfoBuffer buffer_writer(code->relocation_size(),
1351 code->instruction_start());
1354 for (RelocIterator it(*code); !it.done(); it.next()) {
1355 RelocInfo* rinfo = it.rinfo();
1356 if (RelocInfo::IsPosition(rinfo->rmode())) {
1357 int position = static_cast<int>(rinfo->data());
1358 int new_position = TranslatePosition(position,
1359 position_change_array);
1360 if (position != new_position) {
1361 RelocInfo info_copy(rinfo->pc(), rinfo->rmode(), new_position, NULL);
1362 buffer_writer.Write(&info_copy);
1366 if (RelocInfo::IsRealRelocMode(rinfo->rmode())) {
1367 buffer_writer.Write(it.rinfo());
1372 Vector<byte> buffer = buffer_writer.GetResult();
1374 if (buffer.length() == code->relocation_size()) {
1375 // Simply patch relocation area of code.
1376 OS::MemCopy(code->relocation_start(), buffer.start(), buffer.length());
1379 // Relocation info section now has different size. We cannot simply
1380 // rewrite it inside code object. Instead we have to create a new
1382 Handle<Code> result(isolate->factory()->CopyCode(code, buffer));
1388 void LiveEdit::PatchFunctionPositions(Handle<JSArray> shared_info_array,
1389 Handle<JSArray> position_change_array) {
1390 SharedInfoWrapper shared_info_wrapper(shared_info_array);
1391 Handle<SharedFunctionInfo> info = shared_info_wrapper.GetInfo();
1393 int old_function_start = info->start_position();
1394 int new_function_start = TranslatePosition(old_function_start,
1395 position_change_array);
1396 int new_function_end = TranslatePosition(info->end_position(),
1397 position_change_array);
1398 int new_function_token_pos =
1399 TranslatePosition(info->function_token_position(), position_change_array);
1401 info->set_start_position(new_function_start);
1402 info->set_end_position(new_function_end);
1403 info->set_function_token_position(new_function_token_pos);
1405 info->GetIsolate()->heap()->EnsureHeapIsIterable();
1407 if (IsJSFunctionCode(info->code())) {
1408 // Patch relocation info section of the code.
1409 Handle<Code> patched_code = PatchPositionsInCode(Handle<Code>(info->code()),
1410 position_change_array);
1411 if (*patched_code != info->code()) {
1412 // Replace all references to the code across the heap. In particular,
1413 // some stubs may refer to this code and this code may be being executed
1414 // on stack (it is safe to substitute the code object on stack, because
1415 // we only change the structure of rinfo and leave instructions
1417 ReplaceCodeObject(Handle<Code>(info->code()), patched_code);
1423 static Handle<Script> CreateScriptCopy(Handle<Script> original) {
1424 Isolate* isolate = original->GetIsolate();
1426 Handle<String> original_source(String::cast(original->source()));
1427 Handle<Script> copy = isolate->factory()->NewScript(original_source);
1429 copy->set_name(original->name());
1430 copy->set_line_offset(original->line_offset());
1431 copy->set_column_offset(original->column_offset());
1432 copy->set_type(original->type());
1433 copy->set_context_data(original->context_data());
1434 copy->set_eval_from_shared(original->eval_from_shared());
1435 copy->set_eval_from_instructions_offset(
1436 original->eval_from_instructions_offset());
1438 // Copy all the flags, but clear compilation state.
1439 copy->set_flags(original->flags());
1440 copy->set_compilation_state(Script::COMPILATION_STATE_INITIAL);
1446 Handle<Object> LiveEdit::ChangeScriptSource(Handle<Script> original_script,
1447 Handle<String> new_source,
1448 Handle<Object> old_script_name) {
1449 Isolate* isolate = original_script->GetIsolate();
1450 Handle<Object> old_script_object;
1451 if (old_script_name->IsString()) {
1452 Handle<Script> old_script = CreateScriptCopy(original_script);
1453 old_script->set_name(String::cast(*old_script_name));
1454 old_script_object = old_script;
1455 isolate->debugger()->OnAfterCompile(
1456 old_script, Debugger::SEND_WHEN_DEBUGGING);
1458 old_script_object = isolate->factory()->null_value();
1461 original_script->set_source(*new_source);
1463 // Drop line ends so that they will be recalculated.
1464 original_script->set_line_ends(isolate->heap()->undefined_value());
1466 return old_script_object;
1471 void LiveEdit::ReplaceRefToNestedFunction(
1472 Handle<JSValue> parent_function_wrapper,
1473 Handle<JSValue> orig_function_wrapper,
1474 Handle<JSValue> subst_function_wrapper) {
1476 Handle<SharedFunctionInfo> parent_shared =
1477 UnwrapSharedFunctionInfoFromJSValue(parent_function_wrapper);
1478 Handle<SharedFunctionInfo> orig_shared =
1479 UnwrapSharedFunctionInfoFromJSValue(orig_function_wrapper);
1480 Handle<SharedFunctionInfo> subst_shared =
1481 UnwrapSharedFunctionInfoFromJSValue(subst_function_wrapper);
1483 for (RelocIterator it(parent_shared->code()); !it.done(); it.next()) {
1484 if (it.rinfo()->rmode() == RelocInfo::EMBEDDED_OBJECT) {
1485 if (it.rinfo()->target_object() == *orig_shared) {
1486 it.rinfo()->set_target_object(*subst_shared);
1493 // Check an activation against list of functions. If there is a function
1494 // that matches, its status in result array is changed to status argument value.
1495 static bool CheckActivation(Handle<JSArray> shared_info_array,
1496 Handle<JSArray> result,
1498 LiveEdit::FunctionPatchabilityStatus status) {
1499 if (!frame->is_java_script()) return false;
1501 Handle<JSFunction> function(JavaScriptFrame::cast(frame)->function());
1503 Isolate* isolate = shared_info_array->GetIsolate();
1504 int len = GetArrayLength(shared_info_array);
1505 for (int i = 0; i < len; i++) {
1506 HandleScope scope(isolate);
1507 Handle<Object> element =
1508 Object::GetElement(isolate, shared_info_array, i).ToHandleChecked();
1509 Handle<JSValue> jsvalue = Handle<JSValue>::cast(element);
1510 Handle<SharedFunctionInfo> shared =
1511 UnwrapSharedFunctionInfoFromJSValue(jsvalue);
1513 if (function->shared() == *shared || IsInlined(*function, *shared)) {
1514 SetElementSloppy(result, i, Handle<Smi>(Smi::FromInt(status), isolate));
1522 // Iterates over handler chain and removes all elements that are inside
1523 // frames being dropped.
1524 static bool FixTryCatchHandler(StackFrame* top_frame,
1525 StackFrame* bottom_frame) {
1526 Address* pointer_address =
1527 &Memory::Address_at(top_frame->isolate()->get_address_from_id(
1528 Isolate::kHandlerAddress));
1530 while (*pointer_address < top_frame->sp()) {
1531 pointer_address = &Memory::Address_at(*pointer_address);
1533 Address* above_frame_address = pointer_address;
1534 while (*pointer_address < bottom_frame->fp()) {
1535 pointer_address = &Memory::Address_at(*pointer_address);
1537 bool change = *above_frame_address != *pointer_address;
1538 *above_frame_address = *pointer_address;
1543 // Removes specified range of frames from stack. There may be 1 or more
1544 // frames in range. Anyway the bottom frame is restarted rather than dropped,
1545 // and therefore has to be a JavaScript frame.
1546 // Returns error message or NULL.
1547 static const char* DropFrames(Vector<StackFrame*> frames,
1548 int top_frame_index,
1549 int bottom_js_frame_index,
1550 Debug::FrameDropMode* mode,
1551 Object*** restarter_frame_function_pointer) {
1552 if (!Debug::kFrameDropperSupported) {
1553 return "Stack manipulations are not supported in this architecture.";
1556 StackFrame* pre_top_frame = frames[top_frame_index - 1];
1557 StackFrame* top_frame = frames[top_frame_index];
1558 StackFrame* bottom_js_frame = frames[bottom_js_frame_index];
1560 ASSERT(bottom_js_frame->is_java_script());
1562 // Check the nature of the top frame.
1563 Isolate* isolate = bottom_js_frame->isolate();
1564 Code* pre_top_frame_code = pre_top_frame->LookupCode();
1565 bool frame_has_padding;
1566 if (pre_top_frame_code->is_inline_cache_stub() &&
1567 pre_top_frame_code->is_debug_stub()) {
1568 // OK, we can drop inline cache calls.
1569 *mode = Debug::FRAME_DROPPED_IN_IC_CALL;
1570 frame_has_padding = Debug::FramePaddingLayout::kIsSupported;
1571 } else if (pre_top_frame_code ==
1572 isolate->builtins()->builtin(Builtins::kSlot_DebugBreak)) {
1573 // OK, we can drop debug break slot.
1574 *mode = Debug::FRAME_DROPPED_IN_DEBUG_SLOT_CALL;
1575 frame_has_padding = Debug::FramePaddingLayout::kIsSupported;
1576 } else if (pre_top_frame_code ==
1577 isolate->builtins()->builtin(
1578 Builtins::kFrameDropper_LiveEdit)) {
1579 // OK, we can drop our own code.
1580 pre_top_frame = frames[top_frame_index - 2];
1581 top_frame = frames[top_frame_index - 1];
1582 *mode = Debug::CURRENTLY_SET_MODE;
1583 frame_has_padding = false;
1584 } else if (pre_top_frame_code ==
1585 isolate->builtins()->builtin(Builtins::kReturn_DebugBreak)) {
1586 *mode = Debug::FRAME_DROPPED_IN_RETURN_CALL;
1587 frame_has_padding = Debug::FramePaddingLayout::kIsSupported;
1588 } else if (pre_top_frame_code->kind() == Code::STUB &&
1589 pre_top_frame_code->major_key() == CodeStub::CEntry) {
1590 // Entry from our unit tests on 'debugger' statement.
1591 // It's fine, we support this case.
1592 *mode = Debug::FRAME_DROPPED_IN_DIRECT_CALL;
1593 // We don't have a padding from 'debugger' statement call.
1594 // Here the stub is CEntry, it's not debug-only and can't be padded.
1595 // If anyone would complain, a proxy padded stub could be added.
1596 frame_has_padding = false;
1597 } else if (pre_top_frame->type() == StackFrame::ARGUMENTS_ADAPTOR) {
1598 // This must be adaptor that remain from the frame dropping that
1599 // is still on stack. A frame dropper frame must be above it.
1600 ASSERT(frames[top_frame_index - 2]->LookupCode() ==
1601 isolate->builtins()->builtin(Builtins::kFrameDropper_LiveEdit));
1602 pre_top_frame = frames[top_frame_index - 3];
1603 top_frame = frames[top_frame_index - 2];
1604 *mode = Debug::CURRENTLY_SET_MODE;
1605 frame_has_padding = false;
1607 return "Unknown structure of stack above changing function";
1610 Address unused_stack_top = top_frame->sp();
1611 Address unused_stack_bottom = bottom_js_frame->fp()
1612 - Debug::kFrameDropperFrameSize * kPointerSize // Size of the new frame.
1613 + kPointerSize; // Bigger address end is exclusive.
1615 Address* top_frame_pc_address = top_frame->pc_address();
1617 // top_frame may be damaged below this point. Do not used it.
1618 ASSERT(!(top_frame = NULL));
1620 if (unused_stack_top > unused_stack_bottom) {
1621 if (frame_has_padding) {
1622 int shortage_bytes =
1623 static_cast<int>(unused_stack_top - unused_stack_bottom);
1625 Address padding_start = pre_top_frame->fp() -
1626 Debug::FramePaddingLayout::kFrameBaseSize * kPointerSize;
1628 Address padding_pointer = padding_start;
1629 Smi* padding_object =
1630 Smi::FromInt(Debug::FramePaddingLayout::kPaddingValue);
1631 while (Memory::Object_at(padding_pointer) == padding_object) {
1632 padding_pointer -= kPointerSize;
1634 int padding_counter =
1635 Smi::cast(Memory::Object_at(padding_pointer))->value();
1636 if (padding_counter * kPointerSize < shortage_bytes) {
1637 return "Not enough space for frame dropper frame "
1638 "(even with padding frame)";
1640 Memory::Object_at(padding_pointer) =
1641 Smi::FromInt(padding_counter - shortage_bytes / kPointerSize);
1643 StackFrame* pre_pre_frame = frames[top_frame_index - 2];
1645 OS::MemMove(padding_start + kPointerSize - shortage_bytes,
1646 padding_start + kPointerSize,
1647 Debug::FramePaddingLayout::kFrameBaseSize * kPointerSize);
1649 pre_top_frame->UpdateFp(pre_top_frame->fp() - shortage_bytes);
1650 pre_pre_frame->SetCallerFp(pre_top_frame->fp());
1651 unused_stack_top -= shortage_bytes;
1653 STATIC_ASSERT(sizeof(Address) == kPointerSize);
1654 top_frame_pc_address -= shortage_bytes / kPointerSize;
1656 return "Not enough space for frame dropper frame";
1660 // Committing now. After this point we should return only NULL value.
1662 FixTryCatchHandler(pre_top_frame, bottom_js_frame);
1663 // Make sure FixTryCatchHandler is idempotent.
1664 ASSERT(!FixTryCatchHandler(pre_top_frame, bottom_js_frame));
1666 Handle<Code> code = isolate->builtins()->FrameDropper_LiveEdit();
1667 *top_frame_pc_address = code->entry();
1668 pre_top_frame->SetCallerFp(bottom_js_frame->fp());
1670 *restarter_frame_function_pointer =
1671 Debug::SetUpFrameDropperFrame(bottom_js_frame, code);
1673 ASSERT((**restarter_frame_function_pointer)->IsJSFunction());
1675 for (Address a = unused_stack_top;
1676 a < unused_stack_bottom;
1677 a += kPointerSize) {
1678 Memory::Object_at(a) = Smi::FromInt(0);
1685 static bool IsDropableFrame(StackFrame* frame) {
1686 return !frame->is_exit();
1690 // Describes a set of call frames that execute any of listed functions.
1691 // Finding no such frames does not mean error.
1692 class MultipleFunctionTarget {
1694 MultipleFunctionTarget(Handle<JSArray> shared_info_array,
1695 Handle<JSArray> result)
1696 : m_shared_info_array(shared_info_array),
1698 bool MatchActivation(StackFrame* frame,
1699 LiveEdit::FunctionPatchabilityStatus status) {
1700 return CheckActivation(m_shared_info_array, m_result, frame, status);
1702 const char* GetNotFoundMessage() {
1706 Handle<JSArray> m_shared_info_array;
1707 Handle<JSArray> m_result;
1711 // Drops all call frame matched by target and all frames above them.
1712 template<typename TARGET>
1713 static const char* DropActivationsInActiveThreadImpl(
1714 Isolate* isolate, TARGET& target, bool do_drop) {
1715 Debug* debug = isolate->debug();
1717 Vector<StackFrame*> frames = CreateStackMap(isolate, &zone);
1720 int top_frame_index = -1;
1721 int frame_index = 0;
1722 for (; frame_index < frames.length(); frame_index++) {
1723 StackFrame* frame = frames[frame_index];
1724 if (frame->id() == debug->break_frame_id()) {
1725 top_frame_index = frame_index;
1728 if (target.MatchActivation(
1729 frame, LiveEdit::FUNCTION_BLOCKED_UNDER_NATIVE_CODE)) {
1730 // We are still above break_frame. It is not a target frame,
1732 return "Debugger mark-up on stack is not found";
1736 if (top_frame_index == -1) {
1737 // We haven't found break frame, but no function is blocking us anyway.
1738 return target.GetNotFoundMessage();
1741 bool target_frame_found = false;
1742 int bottom_js_frame_index = top_frame_index;
1743 bool c_code_found = false;
1745 for (; frame_index < frames.length(); frame_index++) {
1746 StackFrame* frame = frames[frame_index];
1747 if (!IsDropableFrame(frame)) {
1748 c_code_found = true;
1751 if (target.MatchActivation(
1752 frame, LiveEdit::FUNCTION_BLOCKED_ON_ACTIVE_STACK)) {
1753 target_frame_found = true;
1754 bottom_js_frame_index = frame_index;
1759 // There is a C frames on stack. Check that there are no target frames
1761 for (; frame_index < frames.length(); frame_index++) {
1762 StackFrame* frame = frames[frame_index];
1763 if (frame->is_java_script()) {
1764 if (target.MatchActivation(
1765 frame, LiveEdit::FUNCTION_BLOCKED_UNDER_NATIVE_CODE)) {
1766 // Cannot drop frame under C frames.
1774 // We are in check-only mode.
1778 if (!target_frame_found) {
1780 return target.GetNotFoundMessage();
1783 Debug::FrameDropMode drop_mode = Debug::FRAMES_UNTOUCHED;
1784 Object** restarter_frame_function_pointer = NULL;
1785 const char* error_message = DropFrames(frames, top_frame_index,
1786 bottom_js_frame_index, &drop_mode,
1787 &restarter_frame_function_pointer);
1789 if (error_message != NULL) {
1790 return error_message;
1793 // Adjust break_frame after some frames has been dropped.
1794 StackFrame::Id new_id = StackFrame::NO_ID;
1795 for (int i = bottom_js_frame_index + 1; i < frames.length(); i++) {
1796 if (frames[i]->type() == StackFrame::JAVA_SCRIPT) {
1797 new_id = frames[i]->id();
1801 debug->FramesHaveBeenDropped(new_id, drop_mode,
1802 restarter_frame_function_pointer);
1807 // Fills result array with statuses of functions. Modifies the stack
1808 // removing all listed function if possible and if do_drop is true.
1809 static const char* DropActivationsInActiveThread(
1810 Handle<JSArray> shared_info_array, Handle<JSArray> result, bool do_drop) {
1811 MultipleFunctionTarget target(shared_info_array, result);
1813 const char* message = DropActivationsInActiveThreadImpl(
1814 shared_info_array->GetIsolate(), target, do_drop);
1819 Isolate* isolate = shared_info_array->GetIsolate();
1820 int array_len = GetArrayLength(shared_info_array);
1822 // Replace "blocked on active" with "replaced on active" status.
1823 for (int i = 0; i < array_len; i++) {
1824 Handle<Object> obj =
1825 Object::GetElement(isolate, result, i).ToHandleChecked();
1826 if (*obj == Smi::FromInt(LiveEdit::FUNCTION_BLOCKED_ON_ACTIVE_STACK)) {
1827 Handle<Object> replaced(
1828 Smi::FromInt(LiveEdit::FUNCTION_REPLACED_ON_ACTIVE_STACK), isolate);
1829 SetElementSloppy(result, i, replaced);
1836 class InactiveThreadActivationsChecker : public ThreadVisitor {
1838 InactiveThreadActivationsChecker(Handle<JSArray> shared_info_array,
1839 Handle<JSArray> result)
1840 : shared_info_array_(shared_info_array), result_(result),
1841 has_blocked_functions_(false) {
1843 void VisitThread(Isolate* isolate, ThreadLocalTop* top) {
1844 for (StackFrameIterator it(isolate, top); !it.done(); it.Advance()) {
1845 has_blocked_functions_ |= CheckActivation(
1846 shared_info_array_, result_, it.frame(),
1847 LiveEdit::FUNCTION_BLOCKED_ON_OTHER_STACK);
1850 bool HasBlockedFunctions() {
1851 return has_blocked_functions_;
1855 Handle<JSArray> shared_info_array_;
1856 Handle<JSArray> result_;
1857 bool has_blocked_functions_;
1861 Handle<JSArray> LiveEdit::CheckAndDropActivations(
1862 Handle<JSArray> shared_info_array, bool do_drop) {
1863 Isolate* isolate = shared_info_array->GetIsolate();
1864 int len = GetArrayLength(shared_info_array);
1866 Handle<JSArray> result = isolate->factory()->NewJSArray(len);
1868 // Fill the default values.
1869 for (int i = 0; i < len; i++) {
1873 Handle<Smi>(Smi::FromInt(FUNCTION_AVAILABLE_FOR_PATCH), isolate));
1877 // First check inactive threads. Fail if some functions are blocked there.
1878 InactiveThreadActivationsChecker inactive_threads_checker(shared_info_array,
1880 isolate->thread_manager()->IterateArchivedThreads(
1881 &inactive_threads_checker);
1882 if (inactive_threads_checker.HasBlockedFunctions()) {
1886 // Try to drop activations from the current stack.
1887 const char* error_message =
1888 DropActivationsInActiveThread(shared_info_array, result, do_drop);
1889 if (error_message != NULL) {
1890 // Add error message as an array extra element.
1891 Handle<String> str =
1892 isolate->factory()->NewStringFromAsciiChecked(error_message);
1893 SetElementSloppy(result, len, str);
1899 // Describes a single callframe a target. Not finding this frame
1901 class SingleFrameTarget {
1903 explicit SingleFrameTarget(JavaScriptFrame* frame)
1905 m_saved_status(LiveEdit::FUNCTION_AVAILABLE_FOR_PATCH) {}
1907 bool MatchActivation(StackFrame* frame,
1908 LiveEdit::FunctionPatchabilityStatus status) {
1909 if (frame->fp() == m_frame->fp()) {
1910 m_saved_status = status;
1915 const char* GetNotFoundMessage() {
1916 return "Failed to found requested frame";
1918 LiveEdit::FunctionPatchabilityStatus saved_status() {
1919 return m_saved_status;
1922 JavaScriptFrame* m_frame;
1923 LiveEdit::FunctionPatchabilityStatus m_saved_status;
1927 // Finds a drops required frame and all frames above.
1928 // Returns error message or NULL.
1929 const char* LiveEdit::RestartFrame(JavaScriptFrame* frame) {
1930 SingleFrameTarget target(frame);
1932 const char* result = DropActivationsInActiveThreadImpl(
1933 frame->isolate(), target, true);
1934 if (result != NULL) {
1937 if (target.saved_status() == LiveEdit::FUNCTION_BLOCKED_UNDER_NATIVE_CODE) {
1938 return "Function is blocked under native code";
1944 LiveEditFunctionTracker::LiveEditFunctionTracker(Isolate* isolate,
1945 FunctionLiteral* fun)
1946 : isolate_(isolate) {
1947 if (isolate_->active_function_info_listener() != NULL) {
1948 isolate_->active_function_info_listener()->FunctionStarted(fun);
1953 LiveEditFunctionTracker::~LiveEditFunctionTracker() {
1954 if (isolate_->active_function_info_listener() != NULL) {
1955 isolate_->active_function_info_listener()->FunctionDone();
1960 void LiveEditFunctionTracker::RecordFunctionInfo(
1961 Handle<SharedFunctionInfo> info, FunctionLiteral* lit,
1963 if (isolate_->active_function_info_listener() != NULL) {
1964 isolate_->active_function_info_listener()->FunctionInfo(info, lit->scope(),
1970 void LiveEditFunctionTracker::RecordRootFunctionInfo(Handle<Code> code) {
1971 isolate_->active_function_info_listener()->FunctionCode(code);
1975 bool LiveEditFunctionTracker::IsActive(Isolate* isolate) {
1976 return isolate->active_function_info_listener() != NULL;
1979 } } // namespace v8::internal