microsoft/vscode-react-native

Public

mirrored fromhttps://github.com/microsoft/vscode-react-nativeAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
52bf0a75506c1b3b1cecc9ad89937e596d1bc22a

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

src/debugger/ios/deviceRunner.ts

284lines · modecode

1// Copyright (c) Microsoft Corporation. All rights reserved.
2// Licensed under the MIT license. See LICENSE file in the project root for details.
3
4import {ChildProcess} from "child_process";
5import * as net from "net";
6import * as Q from "q";
7
8import {Node} from "../../utils/node/node";
9import {PlistBuddy} from "./plistBuddy";
10
11export class DeviceRunner {
12 private projectRoot: string;
13 private nativeDebuggerProxyInstance: ChildProcess;
14
15 constructor(projectRoot: string) {
16 this.projectRoot = projectRoot;
17 process.on("exit", () => this.cleanup());
18 }
19
20 public run(): Q.Promise<void> {
21 const proxyPort = 9999;
22 const appLaunchStepTimeout = 5000;
23 return new PlistBuddy().getBundleId(this.projectRoot, /*simulator=*/false)
24 .then((bundleId: string) => this.getPathOnDevice(bundleId))
25 .then((path: string) =>
26 this.startNativeDebugProxy(proxyPort).then(() =>
27 this.startAppViaDebugger(proxyPort, path, appLaunchStepTimeout)
28 )
29 )
30 .then(() => { });
31 }
32
33 // Attempt to start the app on the device, using the debug server proxy on a given port.
34 // Returns a socket speaking remote gdb protocol with the debug server proxy.
35 public startAppViaDebugger(portNumber: number, packagePath: string, appLaunchStepTimeout: number): Q.Promise<string> {
36 const encodedPath: string = this.encodePath(packagePath);
37
38 // We need to send 3 messages to the proxy, waiting for responses between each message:
39 // A(length of encoded path),0,(encoded path)
40 // Hc0
41 // c
42 // We expect a '+' for each message sent, followed by a $OK#9a to indicate that everything has worked.
43 // For more info, see http://www.opensource.apple.com/source/lldb/lldb-167.2/docs/lldb-gdb-remote.txt
44 const socket: net.Socket = new net.Socket();
45 let initState: number = 0;
46 let endStatus: number = null;
47 let endSignal: number = null;
48
49 const deferred1: Q.Deferred<net.Socket> = Q.defer<net.Socket>();
50 const deferred2: Q.Deferred<net.Socket> = Q.defer<net.Socket>();
51 const deferred3: Q.Deferred<net.Socket> = Q.defer<net.Socket>();
52
53 socket.on("data", function(data: any): void {
54 data = data.toString();
55 while (data[0] === "+") { data = data.substring(1); }
56 // Acknowledge any packets sent our way
57 if (data[0] === "$") {
58 socket.write("+");
59 if (data[1] === "W") {
60 // The app process has exited, with hex status given by data[2-3]
61 let status: number = parseInt(data.substring(2, 4), 16);
62 endStatus = status;
63 socket.end();
64 } else if (data[1] === "X") {
65 // The app rocess exited because of signal given by data[2-3]
66 let signal: number = parseInt(data.substring(2, 4), 16);
67 endSignal = signal;
68 socket.end();
69 } else if (data.substring(1, 3) === "OK") {
70 // last command was received OK;
71 if (initState === 1) {
72 deferred1.resolve(socket);
73 } else if (initState === 2) {
74 deferred2.resolve(socket);
75 }
76 } else if (data[1] === "O") {
77 // STDOUT was written to, and the rest of the input until reaching a "#" is a hex-encoded string of that output
78 if (initState === 3) {
79 deferred3.resolve(socket);
80 initState++;
81 }
82 } else if (data[1] === "E") {
83 // An error has occurred, with error code given by data[2-3]: parseInt(data.substring(2, 4), 16)
84 deferred1.reject("Unable to launch application.");
85 deferred2.reject("Unable to launch application.");
86 deferred3.reject("Unable to launch application.");
87 }
88 }
89 });
90
91 socket.on("end", function(): void {
92 deferred1.reject("Unable to launch application.");
93 deferred2.reject("Unable to launch application.");
94 deferred3.reject("Unable to launch application.");
95 });
96
97 socket.on("error", function(err: Error): void {
98 deferred1.reject(err);
99 deferred2.reject(err);
100 deferred3.reject(err);
101 });
102
103 socket.connect(portNumber, "localhost", () => {
104 // set argument 0 to the (encoded) path of the app
105 const cmd: string = this.makeGdbCommand("A" + encodedPath.length + ",0," + encodedPath);
106 initState++;
107 socket.write(cmd);
108 setTimeout(function(): void {
109 deferred1.reject("Timeout launching application. Is the device locked?");
110 }, appLaunchStepTimeout);
111 });
112
113 return deferred1.promise.then((sock: net.Socket): Q.Promise<net.Socket> => {
114 // Set the step and continue thread to any thread
115 const cmd: string = this.makeGdbCommand("Hc0");
116 initState++;
117 sock.write(cmd);
118 setTimeout(function(): void {
119 deferred2.reject("Timeout launching application. Is the device locked?");
120 }, appLaunchStepTimeout);
121 return deferred2.promise;
122 }).then((sock: net.Socket): Q.Promise<net.Socket> => {
123 // Continue execution; actually start the app running.
124 const cmd: string = this.makeGdbCommand("c");
125 initState++;
126 sock.write(cmd);
127 setTimeout(function(): void {
128 deferred3.reject("Timeout launching application. Is the device locked?");
129 }, appLaunchStepTimeout);
130 return deferred3.promise;
131 }).then(() => packagePath);
132 }
133
134 private cleanup(): void {
135 if (this.nativeDebuggerProxyInstance) {
136 this.nativeDebuggerProxyInstance.kill("SIGHUP");
137 this.nativeDebuggerProxyInstance = null;
138 }
139 }
140
141 private startNativeDebugProxy(proxyPort: number): Q.Promise<void> {
142 this.cleanup();
143
144 return this.mountDeveloperImage().then(function(): Q.Promise<void> {
145 const {spawnedProcess} = new Node.ChildProcess().spawn("idevicedebugserverproxy", [proxyPort.toString()]);
146 this.nativeDebuggerProxyInstance = spawnedProcess;
147 const deferred = Q.defer<ChildProcess>();
148
149 spawnedProcess.on("error", (err: Error) => {
150 deferred.reject(err);
151 });
152
153 // Allow 200ms for the spawn to error out
154 return Q.delay(200);
155 });
156 }
157
158 private mountDeveloperImage(): Q.Promise<void> {
159 return this.getDiskImage().then(function(path: string): Q.Promise<void> {
160 const imagemounter = new Node.ChildProcess().spawn("ideviceimagemounter", [path]).spawnedProcess;
161 const deferred = Q.defer<void>();
162 let stdout: string = "";
163 imagemounter.stdout.on("data", function(data: any): void {
164 stdout += data.toString();
165 });
166 imagemounter.on("exit", function(code: number): void {
167 if (code !== 0) {
168 if (stdout.indexOf("Error:") !== -1) {
169 deferred.resolve(void 0); // Technically failed, but likely caused by the image already being mounted.
170 } else if (stdout.indexOf("No device found, is it plugged in?") !== -1) {
171 deferred.reject("Unable to find device. Is the device plugged in?");
172 }
173
174 deferred.reject("Unable to mount developer disk image.");
175 } else {
176 deferred.resolve(void 0);
177 }
178 });
179 imagemounter.on("error", function(err: any): void {
180 deferred.reject(err);
181 });
182 return deferred.promise;
183 });
184 }
185
186 private getDiskImage(): Q.Promise<string> {
187 const nodeChildProcess = new Node.ChildProcess();
188 // Attempt to find the OS version of the iDevice, e.g. 7.1
189 const versionInfo = nodeChildProcess.exec("ideviceinfo -s -k ProductVersion").outcome.then((stdout: Buffer) => {
190 return stdout.toString().trim().substring(0, 3); // Versions for DeveloperDiskImage seem to be X.Y, while some device versions are X.Y.Z
191 // NOTE: This will almost certainly be wrong in the next few years, once we hit version 10.0
192 }, function(): string {
193 throw new Error("Unable to get device OS version");
194 });
195
196 // Attempt to find the path where developer resources exist.
197 const pathInfo = nodeChildProcess.exec("xcrun -sdk iphoneos --show-sdk-platform-path").outcome.then((stdout: Buffer) => {
198 return stdout.toString().trim();
199 });
200
201 // Attempt to find the developer disk image for the appropriate
202 return Q.all([versionInfo, pathInfo]).spread<string>(function(version: string, sdkpath: string): Q.Promise<string> {
203 const find = nodeChildProcess.spawn("find", [sdkpath, "-path", "*" + version + "*", "-name", "DeveloperDiskImage.dmg"]).spawnedProcess;
204 const deferred = Q.defer<string>();
205
206 find.stdout.on("data", function(data: any): void {
207 const dataStr: string = data.toString();
208 const path: string = dataStr.split("\n")[0].trim();
209 if (!path) {
210 deferred.reject("Unable to find developer disk image");
211 } else {
212 deferred.resolve(path);
213 }
214 });
215 find.on("exit", function(code: number): void {
216 deferred.reject("Unable to find developer disk image");
217 });
218
219 return deferred.promise;
220 });
221 }
222
223 private getPathOnDevice(packageId: string): Q.Promise<string> {
224 const nodeChildProcess = new Node.ChildProcess();
225 const nodeFileSystem = new Node.FileSystem();
226 return nodeChildProcess.execToString("ideviceinstaller -l -o xml > /tmp/$$.ideviceinstaller && echo /tmp/$$.ideviceinstaller")
227 .catch(function(err: any): any {
228 if (err.code === "ENOENT") {
229 throw new Error("Unable to find ideviceinstaller.");
230 }
231 throw err;
232 }).then((stdout: string): Q.Promise<string> => {
233 // First find the path of the app on the device
234 let filename: string = stdout.trim();
235 if (!/^\/tmp\/[0-9]+\.ideviceinstaller$/.test(filename)) {
236 throw new Error("Unable to list installed applications on device");
237 }
238
239 const plistBuddy = new PlistBuddy();
240 // Search thrown the unknown-length array until we find the package
241 const findPackageEntry = (index: number): Q.Promise<string> => {
242 return plistBuddy.readPlistProperty(filename, `:${index}:CFBundleIdentifier`)
243 .then((bundleId: string) => {
244 if (bundleId === packageId) {
245 return plistBuddy.readPlistProperty(filename, `:${index}:Path`);
246 }
247 return findPackageEntry(index + 1);
248 });
249 };
250
251 return findPackageEntry(0)
252 .finally(() => {
253 nodeFileSystem.unlink(filename);
254 }).catch((): string => {
255 throw new Error("Application not installed on the device");
256 });
257 });
258 }
259
260 private encodePath(packagePath: string): string {
261 // Encode the path by converting each character value to hex
262 return packagePath.split("").map((c: string) => c.charCodeAt(0).toString(16)).join("").toUpperCase();
263 }
264
265 private makeGdbCommand(command: string): string {
266 let commandString: string = `$${command}#`;
267 let stringSum: number = 0;
268 for (let i: number = 0; i < command.length; i++) {
269 stringSum += command.charCodeAt(i);
270 }
271
272 /* tslint:disable:no-bitwise */
273 // We need some bitwise operations to calculate the checksum
274 stringSum = stringSum & 0xFF;
275 /* tslint:enable:no-bitwise */
276 let checksum: string = stringSum.toString(16).toUpperCase();
277 if (checksum.length < 2) {
278 checksum = "0" + checksum;
279 }
280
281 commandString += checksum;
282 return commandString;
283 }
284}