-
-
Notifications
You must be signed in to change notification settings - Fork 142
Expand file tree
/
Copy pathAndroidJsV8Inspector.java
More file actions
368 lines (301 loc) · 12.4 KB
/
AndroidJsV8Inspector.java
File metadata and controls
368 lines (301 loc) · 12.4 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
package com.tns;
import android.os.Handler;
import android.util.Log;
import android.util.Pair;
import android.webkit.MimeTypeMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicBoolean;
import dalvik.annotation.optimization.CriticalNative;
import dalvik.annotation.optimization.FastNative;
import fi.iki.elonen.NanoHTTPD;
import fi.iki.elonen.NanoWSD;
class AndroidJsV8Inspector {
private JsV8InspectorServer server;
private static String ApplicationDir;
private String packageName;
@CriticalNative
protected native final void init();
@FastNative
protected native final void connect(Object connection);
@CriticalNative
private native void scheduleBreak();
@CriticalNative
protected static native void disconnect();
@FastNative
protected native final void dispatchMessage(String message);
private Handler mainHandler;
private final Object debugBrkLock;
private Logger currentRuntimeLogger;
private static AtomicBoolean ReadyToProcessMessages = new AtomicBoolean(false);
private LinkedBlockingQueue<String> inspectorMessages = new LinkedBlockingQueue<String>();
private LinkedBlockingQueue<String> pendingInspectorMessages = new LinkedBlockingQueue<String>();
AndroidJsV8Inspector(String filesDir, String packageName) {
ApplicationDir = filesDir;
this.packageName = packageName;
this.debugBrkLock = new Object();
}
public void start() throws IOException {
if (this.server == null) {
Runtime currentRuntime = Runtime.getCurrentRuntime();
mainHandler = currentRuntime.getHandler();
currentRuntimeLogger = currentRuntime.getLogger();
this.server = new JsV8InspectorServer(this.packageName + "-inspectorServer", currentRuntimeLogger);
this.server.start(-1);
if (currentRuntimeLogger.isEnabled()) {
Log.d("V8Inspector", "start debugger ThreadId:" + Thread.currentThread().getId());
}
init();
}
}
@RuntimeCallable
private static void sendToDevToolsConsole(Object connection, String message, String level) {
try {
JSONObject consoleMessage = new JSONObject();
JSONObject params = new JSONObject();
params.put("type", level);
params.put("executionContextId", 0);
params.put("timestamp", 0.000000000000000);
JSONArray args = new JSONArray();
args.put(message);
params.put("args", args);
consoleMessage.put("method", "Runtime.consoleAPICalled");
consoleMessage.put("params", params);
String sendingText = consoleMessage.toString();
AndroidJsV8Inspector.send(connection, sendingText);
} catch (JSONException | IOException e) {
if (com.tns.Runtime.isDebuggable()) {
e.printStackTrace();
}
}
}
@RuntimeCallable
private static void send(Object connection, String payload) throws IOException {
JsV8InspectorWebSocket socketConnection = (JsV8InspectorWebSocket) connection;
if (socketConnection.isOpen()) {
socketConnection.send(payload);
}
}
@RuntimeCallable
private static String getInspectorMessage(Object connection) {
return ((JsV8InspectorWebSocket) connection).getInspectorMessage();
}
@RuntimeCallable
public static Pair<String, String>[] getPageResources() {
// necessary to align the data dir returned by context (emulator) and that used by the v8 inspector
if (ApplicationDir.startsWith("/data/user/0/")) {
ApplicationDir = ApplicationDir.replaceFirst("/data/user/0/", "/data/data/");
}
String dataDir = ApplicationDir;
File rootFilesDir = new File(dataDir, "app");
List<Pair<String, String>> resources = traverseResources(rootFilesDir);
@SuppressWarnings("unchecked")
Pair<String, String>[] result = resources.toArray((Pair<String, String>[]) Array.newInstance(resources.get(0).getClass(), resources.size()));
return result;
}
private static List<Pair<String, String>> traverseResources(File dir) {
List<Pair<String, String>> resources = new ArrayList<>();
Queue<File> directories = new LinkedList<>();
directories.add(dir);
while (!directories.isEmpty()) {
File currentDir = directories.poll();
File[] files = currentDir.listFiles();
for (File file : files) {
if (file.isDirectory()) {
directories.add(file);
} else {
resources.add(new Pair<>("file://" + file.getAbsolutePath(), getMimeType(file.getAbsolutePath())));
}
}
}
return resources;
}
private static String getMimeType(String url) {
String type = null;
String extension = MimeTypeMap.getFileExtensionFromUrl(url);
if (!extension.isEmpty()) {
type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
// getMimeType may sometime return incorrect results in the context of NativeScript
// e.g. `.ts` returns video/MP2TS
switch (extension) {
case "js":
type = "text/javascript";
break;
case "json":
type = "application/json";
break;
case "css":
type = "text/css";
break;
case "ts":
type = "text/typescript";
break;
// handle shared libraries so they are marked properly and don't appear in the sources tab
case "so":
type = "application/binary";
break;
}
}
return type;
}
// pause the main thread for 30 seconds (30 * 1000 ms)
// allowing the devtools frontend to establish connection with the inspector
protected void waitForDebugger(boolean shouldBreak) {
if (shouldBreak) {
synchronized (this.debugBrkLock) {
try {
this.debugBrkLock.wait(1000 * 30);
} catch (InterruptedException e) {
if (com.tns.Runtime.isDebuggable()) {
e.printStackTrace();
}
} finally {
AndroidJsV8Inspector.ReadyToProcessMessages.set(true);
this.processDebugBreak();
}
}
} else {
AndroidJsV8Inspector.ReadyToProcessMessages.set(true);
}
}
// process all messages coming from the frontend necessary to initialize the inspector backend
// schedule a debug line break at first convenience
private void processDebugBreak() {
processDebugBreakMessages();
scheduleBreak();
}
private void processDebugBreakMessages() {
while (!pendingInspectorMessages.isEmpty()) {
String inspectorMessage = pendingInspectorMessages.poll();
dispatchMessage(inspectorMessage);
}
}
private class JsV8InspectorServer extends NanoWSD {
private Logger currentRuntimeLogger;
JsV8InspectorServer(String name, Logger runtimeLogger) {
super(name);
currentRuntimeLogger = runtimeLogger;
}
@Override
protected Response serveHttp(IHTTPSession session) {
if (currentRuntimeLogger.isEnabled()) {
Log.d("{N}.v8-inspector", "http request for " + session.getUri());
}
return super.serveHttp(session);
}
private JsV8InspectorWebSocket webSocket;
@Override
protected WebSocket openWebSocket(IHTTPSession handshake) {
// close the previous webSocket
if(this.webSocket != null) {
try {
this.webSocket.close(WebSocketFrame.CloseCode.NormalClosure, "New browser connection is open", false);
} catch (IOException ioException) {
if(this.webSocket.getState() != State.CLOSED) {
Log.e("{N}.v8-inspector", "Error closing previous connection", ioException);
}
}
}
this.webSocket = new JsV8InspectorWebSocket(handshake, currentRuntimeLogger);
return this.webSocket;
}
}
private class JsV8InspectorWebSocket extends NanoWSD.WebSocket {
private Logger currentRuntimeLogger;
JsV8InspectorWebSocket(NanoHTTPD.IHTTPSession handshakeRequest, Logger runtimeLogger) {
super(handshakeRequest);
currentRuntimeLogger = runtimeLogger;
}
@Override
protected void onOpen() {
if (currentRuntimeLogger.isEnabled()) {
Log.d("V8Inspector", "onOpen: ThreadID: " + Thread.currentThread().getId());
}
connect(JsV8InspectorWebSocket.this);
}
@Override
protected void onClose(NanoWSD.WebSocketFrame.CloseCode code, String reason, boolean initiatedByRemote) {
if (currentRuntimeLogger.isEnabled()) {
Log.d("V8Inspector", "onClose");
}
mainHandler.post(new Runnable() {
@Override
public void run() {
if (currentRuntimeLogger.isEnabled()) {
Log.d("V8Inspector", "Disconnecting");
}
disconnect();
}
});
}
@Override
protected void onMessage(final NanoWSD.WebSocketFrame message) {
if (currentRuntimeLogger.isEnabled()) {
Log.d("V8Inspector", "To dbg backend: " + message.getTextPayload() + " ThreadId:" + Thread.currentThread().getId());
}
inspectorMessages.offer(message.getTextPayload());
if (!AndroidJsV8Inspector.ReadyToProcessMessages.get()) {
String nextMessage = inspectorMessages.poll();
while (nextMessage != null) {
pendingInspectorMessages.offer(nextMessage);
nextMessage = inspectorMessages.poll();
}
if (message.getTextPayload().contains("Debugger.enable")) {
synchronized (debugBrkLock) {
debugBrkLock.notify();
}
}
} else {
mainHandler.postAtFrontOfQueue(new Runnable() {
@Override
public void run() {
String nextMessage = inspectorMessages.poll();
while (nextMessage != null) {
dispatchMessage(nextMessage);
nextMessage = inspectorMessages.poll();
}
}
});
}
}
@Override
public void send(String payload) throws IOException {
if (currentRuntimeLogger.isEnabled()) {
Log.d("V8Inspector", "To dbg client: " + payload);
}
super.send(payload);
}
public String getInspectorMessage() {
try {
return inspectorMessages.take();
} catch (InterruptedException e) {
if (com.tns.Runtime.isDebuggable()) {
e.printStackTrace();
}
}
return null;
}
@Override
protected void onPong(NanoWSD.WebSocketFrame pong) {
}
@Override
protected void onException(IOException exception) {
// when the chrome inspector is disconnected by closing the tab a "Broken pipe" exception is thrown which we don't need to log, only in verbose logging mode
if(!exception.getMessage().equals("Broken pipe") || currentRuntimeLogger.isEnabled()) {
if (com.tns.Runtime.isDebuggable()) {
exception.printStackTrace();
}
}
disconnect();
}
}
}