[presubmit] Enable readability/namespace linter checking.
[platform/upstream/v8.git] / src / debug / liveedit.h
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.
4
5 #ifndef V8_DEBUG_LIVEEDIT_H_
6 #define V8_DEBUG_LIVEEDIT_H_
7
8
9 // Live Edit feature implementation.
10 // User should be able to change script on already running VM. This feature
11 // matches hot swap features in other frameworks.
12 //
13 // The basic use-case is when user spots some mistake in function body
14 // from debugger and wishes to change the algorithm without restart.
15 //
16 // A single change always has a form of a simple replacement (in pseudo-code):
17 //   script.source[positions, positions+length] = new_string;
18 // Implementation first determines, which function's body includes this
19 // change area. Then both old and new versions of script are fully compiled
20 // in order to analyze, whether the function changed its outer scope
21 // expectations (or number of parameters). If it didn't, function's code is
22 // patched with a newly compiled code. If it did change, enclosing function
23 // gets patched. All inner functions are left untouched, whatever happened
24 // to them in a new script version. However, new version of code will
25 // instantiate newly compiled functions.
26
27
28 #include "src/allocation.h"
29 #include "src/compiler.h"
30
31 namespace v8 {
32 namespace internal {
33
34 // This class collects some specific information on structure of functions
35 // in a particular script. It gets called from compiler all the time, but
36 // actually records any data only when liveedit operation is in process;
37 // in any other time this class is very cheap.
38 //
39 // The primary interest of the Tracker is to record function scope structures
40 // in order to analyze whether function code maybe safely patched (with new
41 // code successfully reading existing data from function scopes). The Tracker
42 // also collects compiled function codes.
43 class LiveEditFunctionTracker {
44  public:
45   explicit LiveEditFunctionTracker(Isolate* isolate, FunctionLiteral* fun);
46   ~LiveEditFunctionTracker();
47   void RecordFunctionInfo(Handle<SharedFunctionInfo> info,
48                           FunctionLiteral* lit, Zone* zone);
49   void RecordRootFunctionInfo(Handle<Code> code);
50
51   static bool IsActive(Isolate* isolate);
52
53  private:
54   Isolate* isolate_;
55 };
56
57
58 class LiveEdit : AllStatic {
59  public:
60   // Describes how exactly a frame has been dropped from stack.
61   enum FrameDropMode {
62     // No frame has been dropped.
63     FRAMES_UNTOUCHED,
64     // The top JS frame had been calling IC stub. IC stub mustn't be called now.
65     FRAME_DROPPED_IN_IC_CALL,
66     // The top JS frame had been calling debug break slot stub. Patch the
67     // address this stub jumps to in the end.
68     FRAME_DROPPED_IN_DEBUG_SLOT_CALL,
69     // The top JS frame had been calling some C++ function. The return address
70     // gets patched automatically.
71     FRAME_DROPPED_IN_DIRECT_CALL,
72     FRAME_DROPPED_IN_RETURN_CALL,
73     CURRENTLY_SET_MODE
74   };
75
76   static void InitializeThreadLocal(Debug* debug);
77
78   static bool SetAfterBreakTarget(Debug* debug);
79
80   MUST_USE_RESULT static MaybeHandle<JSArray> GatherCompileInfo(
81       Handle<Script> script,
82       Handle<String> source);
83
84   static void ReplaceFunctionCode(Handle<JSArray> new_compile_info_array,
85                                   Handle<JSArray> shared_info_array);
86
87   static void FunctionSourceUpdated(Handle<JSArray> shared_info_array);
88
89   // Updates script field in FunctionSharedInfo.
90   static void SetFunctionScript(Handle<JSValue> function_wrapper,
91                                 Handle<Object> script_handle);
92
93   static void PatchFunctionPositions(Handle<JSArray> shared_info_array,
94                                      Handle<JSArray> position_change_array);
95
96   // For a script updates its source field. If old_script_name is provided
97   // (i.e. is a String), also creates a copy of the script with its original
98   // source and sends notification to debugger.
99   static Handle<Object> ChangeScriptSource(Handle<Script> original_script,
100                                            Handle<String> new_source,
101                                            Handle<Object> old_script_name);
102
103   // In a code of a parent function replaces original function as embedded
104   // object with a substitution one.
105   static void ReplaceRefToNestedFunction(Handle<JSValue> parent_function_shared,
106                                          Handle<JSValue> orig_function_shared,
107                                          Handle<JSValue> subst_function_shared);
108
109   // Find open generator activations, and set corresponding "result" elements to
110   // FUNCTION_BLOCKED_ACTIVE_GENERATOR.
111   static bool FindActiveGenerators(Handle<FixedArray> shared_info_array,
112                                    Handle<FixedArray> result, int len);
113
114   // Checks listed functions on stack and return array with corresponding
115   // FunctionPatchabilityStatus statuses; extra array element may
116   // contain general error message. Modifies the current stack and
117   // has restart the lowest found frames and drops all other frames above
118   // if possible and if do_drop is true.
119   static Handle<JSArray> CheckAndDropActivations(
120       Handle<JSArray> shared_info_array, bool do_drop);
121
122   // Restarts the call frame and completely drops all frames above it.
123   // Return error message or NULL.
124   static const char* RestartFrame(JavaScriptFrame* frame);
125
126   // A copy of this is in liveedit.js.
127   enum FunctionPatchabilityStatus {
128     FUNCTION_AVAILABLE_FOR_PATCH = 1,
129     FUNCTION_BLOCKED_ON_ACTIVE_STACK = 2,
130     FUNCTION_BLOCKED_ON_OTHER_STACK = 3,
131     FUNCTION_BLOCKED_UNDER_NATIVE_CODE = 4,
132     FUNCTION_REPLACED_ON_ACTIVE_STACK = 5,
133     FUNCTION_BLOCKED_UNDER_GENERATOR = 6,
134     FUNCTION_BLOCKED_ACTIVE_GENERATOR = 7
135   };
136
137   // Compares 2 strings line-by-line, then token-wise and returns diff in form
138   // of array of triplets (pos1, pos1_end, pos2_end) describing list
139   // of diff chunks.
140   static Handle<JSArray> CompareStrings(Handle<String> s1,
141                                         Handle<String> s2);
142
143   // Architecture-specific constant.
144   static const bool kFrameDropperSupported;
145
146   /**
147    * Defines layout of a stack frame that supports padding. This is a regular
148    * internal frame that has a flexible stack structure. LiveEdit can shift
149    * its lower part up the stack, taking up the 'padding' space when additional
150    * stack memory is required.
151    * Such frame is expected immediately above the topmost JavaScript frame.
152    *
153    * Stack Layout:
154    *   --- Top
155    *   LiveEdit routine frames
156    *   ---
157    *   C frames of debug handler
158    *   ---
159    *   ...
160    *   ---
161    *      An internal frame that has n padding words:
162    *      - any number of words as needed by code -- upper part of frame
163    *      - padding size: a Smi storing n -- current size of padding
164    *      - padding: n words filled with kPaddingValue in form of Smi
165    *      - 3 context/type words of a regular InternalFrame
166    *      - fp
167    *   ---
168    *      Topmost JavaScript frame
169    *   ---
170    *   ...
171    *   --- Bottom
172    */
173   // A size of frame base including fp. Padding words starts right above
174   // the base.
175   static const int kFrameDropperFrameSize = 4;
176   // A number of words that should be reserved on stack for the LiveEdit use.
177   // Stored on stack in form of Smi.
178   static const int kFramePaddingInitialSize = 1;
179   // A value that padding words are filled with (in form of Smi). Going
180   // bottom-top, the first word not having this value is a counter word.
181   static const int kFramePaddingValue = kFramePaddingInitialSize + 1;
182 };
183
184
185 // A general-purpose comparator between 2 arrays.
186 class Comparator {
187  public:
188   // Holds 2 arrays of some elements allowing to compare any pair of
189   // element from the first array and element from the second array.
190   class Input {
191    public:
192     virtual int GetLength1() = 0;
193     virtual int GetLength2() = 0;
194     virtual bool Equals(int index1, int index2) = 0;
195
196    protected:
197     virtual ~Input() {}
198   };
199
200   // Receives compare result as a series of chunks.
201   class Output {
202    public:
203     // Puts another chunk in result list. Note that technically speaking
204     // only 3 arguments actually needed with 4th being derivable.
205     virtual void AddChunk(int pos1, int pos2, int len1, int len2) = 0;
206
207    protected:
208     virtual ~Output() {}
209   };
210
211   // Finds the difference between 2 arrays of elements.
212   static void CalculateDifference(Input* input,
213                                   Output* result_writer);
214 };
215
216
217
218 // Simple helper class that creates more or less typed structures over
219 // JSArray object. This is an adhoc method of passing structures from C++
220 // to JavaScript.
221 template<typename S>
222 class JSArrayBasedStruct {
223  public:
224   static S Create(Isolate* isolate) {
225     Factory* factory = isolate->factory();
226     Handle<JSArray> array = factory->NewJSArray(S::kSize_);
227     return S(array);
228   }
229
230   static S cast(Object* object) {
231     JSArray* array = JSArray::cast(object);
232     Handle<JSArray> array_handle(array);
233     return S(array_handle);
234   }
235
236   explicit JSArrayBasedStruct(Handle<JSArray> array) : array_(array) {
237   }
238
239   Handle<JSArray> GetJSArray() {
240     return array_;
241   }
242
243   Isolate* isolate() const {
244     return array_->GetIsolate();
245   }
246
247  protected:
248   void SetField(int field_position, Handle<Object> value) {
249     Object::SetElement(isolate(), array_, field_position, value, SLOPPY)
250         .Assert();
251   }
252
253   void SetSmiValueField(int field_position, int value) {
254     SetField(field_position, Handle<Smi>(Smi::FromInt(value), isolate()));
255   }
256
257   Handle<Object> GetField(int field_position) {
258     return Object::GetElement(
259         isolate(), array_, field_position).ToHandleChecked();
260   }
261
262   int GetSmiValueField(int field_position) {
263     Handle<Object> res = GetField(field_position);
264     return Handle<Smi>::cast(res)->value();
265   }
266
267  private:
268   Handle<JSArray> array_;
269 };
270
271
272 // Represents some function compilation details. This structure will be used
273 // from JavaScript. It contains Code object, which is kept wrapped
274 // into a BlindReference for sanitizing reasons.
275 class FunctionInfoWrapper : public JSArrayBasedStruct<FunctionInfoWrapper> {
276  public:
277   explicit FunctionInfoWrapper(Handle<JSArray> array)
278       : JSArrayBasedStruct<FunctionInfoWrapper>(array) {
279   }
280
281   void SetInitialProperties(Handle<String> name, int start_position,
282                             int end_position, int param_num, int literal_count,
283                             int parent_index);
284
285   void SetFunctionCode(Handle<Code> function_code,
286                        Handle<HeapObject> code_scope_info);
287
288   void SetFunctionScopeInfo(Handle<Object> scope_info_array) {
289     this->SetField(kFunctionScopeInfoOffset_, scope_info_array);
290   }
291
292   void SetSharedFunctionInfo(Handle<SharedFunctionInfo> info);
293
294   int GetLiteralCount() {
295     return this->GetSmiValueField(kLiteralNumOffset_);
296   }
297
298   int GetParentIndex() {
299     return this->GetSmiValueField(kParentIndexOffset_);
300   }
301
302   Handle<Code> GetFunctionCode();
303
304   MaybeHandle<TypeFeedbackVector> GetFeedbackVector();
305
306   Handle<Object> GetCodeScopeInfo();
307
308   int GetStartPosition() {
309     return this->GetSmiValueField(kStartPositionOffset_);
310   }
311
312   int GetEndPosition() { return this->GetSmiValueField(kEndPositionOffset_); }
313
314  private:
315   static const int kFunctionNameOffset_ = 0;
316   static const int kStartPositionOffset_ = 1;
317   static const int kEndPositionOffset_ = 2;
318   static const int kParamNumOffset_ = 3;
319   static const int kCodeOffset_ = 4;
320   static const int kCodeScopeInfoOffset_ = 5;
321   static const int kFunctionScopeInfoOffset_ = 6;
322   static const int kParentIndexOffset_ = 7;
323   static const int kSharedFunctionInfoOffset_ = 8;
324   static const int kLiteralNumOffset_ = 9;
325   static const int kSize_ = 10;
326
327   friend class JSArrayBasedStruct<FunctionInfoWrapper>;
328 };
329
330
331 // Wraps SharedFunctionInfo along with some of its fields for passing it
332 // back to JavaScript. SharedFunctionInfo object itself is additionally
333 // wrapped into BlindReference for sanitizing reasons.
334 class SharedInfoWrapper : public JSArrayBasedStruct<SharedInfoWrapper> {
335  public:
336   static bool IsInstance(Handle<JSArray> array) {
337     if (array->length() != Smi::FromInt(kSize_)) return false;
338     Handle<Object> element(
339         Object::GetElement(array->GetIsolate(),
340                            array,
341                            kSharedInfoOffset_).ToHandleChecked());
342     if (!element->IsJSValue()) return false;
343     return Handle<JSValue>::cast(element)->value()->IsSharedFunctionInfo();
344   }
345
346   explicit SharedInfoWrapper(Handle<JSArray> array)
347       : JSArrayBasedStruct<SharedInfoWrapper>(array) {
348   }
349
350   void SetProperties(Handle<String> name,
351                      int start_position,
352                      int end_position,
353                      Handle<SharedFunctionInfo> info);
354
355   Handle<SharedFunctionInfo> GetInfo();
356
357  private:
358   static const int kFunctionNameOffset_ = 0;
359   static const int kStartPositionOffset_ = 1;
360   static const int kEndPositionOffset_ = 2;
361   static const int kSharedInfoOffset_ = 3;
362   static const int kSize_ = 4;
363
364   friend class JSArrayBasedStruct<SharedInfoWrapper>;
365 };
366
367 }  // namespace internal
368 }  // namespace v8
369
370 #endif /* V8_DEBUG_LIVEEDIT_H_ */