microsoft/vscode-react-native

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
5ebdd1c6eb62eea535ec44afef3158dc72f62d51

Branches

Tags

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

Clone

HTTPS

Download ZIP

src/debugger/ios/deviceRunner.ts

278lines · 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 "../../common/node/node";
9import {PlistBuddy} from "../../common/ios/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 const error = new Error("Unable to launch application.");
85 deferred1.reject(error);
86 deferred2.reject(error);
87 deferred3.reject(error);
88 }
89 }
90 });
91
92 socket.on("end", function(): void {
93 const error = new Error("Unable to launch application.");
94 deferred1.reject(error);
95 deferred2.reject(error);
96 deferred3.reject(error);
97 });
98
99 socket.on("error", function(err: Error): void {
100 deferred1.reject(err);
101 deferred2.reject(err);
102 deferred3.reject(err);
103 });
104
105 socket.connect(portNumber, "localhost", () => {
106 // set argument 0 to the (encoded) path of the app
107 const cmd: string = this.makeGdbCommand("A" + encodedPath.length + ",0," + encodedPath);
108 initState++;
109 socket.write(cmd);
110 setTimeout(function(): void {
111 deferred1.reject(new Error("Timeout launching application. Is the device locked?"));
112 }, appLaunchStepTimeout);
113 });
114
115 return deferred1.promise.then((sock: net.Socket): Q.Promise<net.Socket> => {
116 // Set the step and continue thread to any thread
117 const cmd: string = this.makeGdbCommand("Hc0");
118 initState++;
119 sock.write(cmd);
120 setTimeout(function(): void {
121 deferred2.reject(new Error("Timeout launching application. Is the device locked?"));
122 }, appLaunchStepTimeout);
123 return deferred2.promise;
124 }).then((sock: net.Socket): Q.Promise<net.Socket> => {
125 // Continue execution; actually start the app running.
126 const cmd: string = this.makeGdbCommand("c");
127 initState++;
128 sock.write(cmd);
129 setTimeout(function(): void {
130 deferred3.reject(new Error("Timeout launching application. Is the device locked?"));
131 }, appLaunchStepTimeout);
132 return deferred3.promise;
133 }).then(() => packagePath);
134 }
135
136 public encodePath(packagePath: string): string {
137 // Encode the path by converting each character value to hex
138 return packagePath.split("").map((c: string) => c.charCodeAt(0).toString(16)).join("").toUpperCase();
139 }
140
141 private cleanup(): void {
142 if (this.nativeDebuggerProxyInstance) {
143 this.nativeDebuggerProxyInstance.kill("SIGHUP");
144 this.nativeDebuggerProxyInstance = null;
145 }
146 }
147
148 private startNativeDebugProxy(proxyPort: number): Q.Promise<void> {
149 this.cleanup();
150
151 return this.mountDeveloperImage().then(function(): Q.Promise<any> {
152 let result = new Node.ChildProcess().spawnWaitUntilStarted("idevicedebugserverproxy", [proxyPort.toString()]);
153 return result.outcome.then(() => this.nativeDebuggerProxyInstance = result.spawnedProcess);
154 });
155 }
156
157 private mountDeveloperImage(): Q.Promise<void> {
158 return this.getDiskImage().then(function(path: string): Q.Promise<void> {
159 const imagemounter = new Node.ChildProcess().spawnWaitUntilFinished("ideviceimagemounter", [path]).spawnedProcess;
160 const deferred = Q.defer<void>();
161 let stdout: string = "";
162 imagemounter.stdout.on("data", function(data: any): void {
163 stdout += data.toString();
164 });
165 imagemounter.on("exit", function(code: number): void {
166 if (code !== 0) {
167 if (stdout.indexOf("Error:") !== -1) {
168 deferred.resolve(void 0); // Technically failed, but likely caused by the image already being mounted.
169 } else if (stdout.indexOf("No device found, is it plugged in?") !== -1) {
170 deferred.reject(new Error("Unable to find device. Is the device plugged in?"));
171 }
172
173 deferred.reject(new Error("Unable to mount developer disk image."));
174 } else {
175 deferred.resolve(void 0);
176 }
177 });
178 imagemounter.on("error", function(err: any): void {
179 deferred.reject(err);
180 });
181 return deferred.promise;
182 });
183 }
184
185 private getDiskImage(): Q.Promise<string> {
186 const nodeChildProcess = new Node.ChildProcess();
187 // Attempt to find the OS version of the iDevice, e.g. 7.1
188 const versionInfo = nodeChildProcess.exec("ideviceinfo -s -k ProductVersion").outcome.then((stdout: Buffer) => {
189 return stdout.toString().trim().substring(0, 3); // Versions for DeveloperDiskImage seem to be X.Y, while some device versions are X.Y.Z
190 // NOTE: This will almost certainly be wrong in the next few years, once we hit version 10.0
191 }, function(): string {
192 throw new Error("Unable to get device OS version");
193 });
194
195 // Attempt to find the path where developer resources exist.
196 const pathInfo = nodeChildProcess.exec("xcrun -sdk iphoneos --show-sdk-platform-path").outcome.then((stdout: Buffer) => {
197 return stdout.toString().trim();
198 });
199
200 // Attempt to find the developer disk image for the appropriate
201 return Q.all([versionInfo, pathInfo]).spread<string>(function(version: string, sdkpath: string): Q.Promise<string> {
202 const find = nodeChildProcess.spawnWaitUntilFinished("find", [sdkpath, "-path", "*" + version + "*", "-name", "DeveloperDiskImage.dmg"]).spawnedProcess;
203 const deferred = Q.defer<string>();
204
205 find.stdout.on("data", function(data: any): void {
206 const dataStr: string = data.toString();
207 const path: string = dataStr.split("\n")[0].trim();
208 if (!path) {
209 deferred.reject(new Error("Unable to find developer disk image"));
210 } else {
211 deferred.resolve(path);
212 }
213 });
214 find.on("exit", function(code: number): void {
215 deferred.reject(new Error("Unable to find developer disk image"));
216 });
217
218 return deferred.promise;
219 });
220 }
221
222 private getPathOnDevice(packageId: string): Q.Promise<string> {
223 const nodeChildProcess = new Node.ChildProcess();
224 const nodeFileSystem = new Node.FileSystem();
225 return nodeChildProcess.execToString("ideviceinstaller -l -o xml > /tmp/$$.ideviceinstaller && echo /tmp/$$.ideviceinstaller")
226 .catch(function(err: any): any {
227 if (err.code === "ENOENT") {
228 throw new Error("Unable to find ideviceinstaller.");
229 }
230 throw err;
231 }).then((stdout: string): Q.Promise<string> => {
232 // First find the path of the app on the device
233 let filename: string = stdout.trim();
234 if (!/^\/tmp\/[0-9]+\.ideviceinstaller$/.test(filename)) {
235 throw new Error("Unable to list installed applications on device");
236 }
237
238 const plistBuddy = new PlistBuddy();
239 // Search thrown the unknown-length array until we find the package
240 const findPackageEntry = (index: number): Q.Promise<string> => {
241 return plistBuddy.readPlistProperty(filename, `:${index}:CFBundleIdentifier`)
242 .then((bundleId: string) => {
243 if (bundleId === packageId) {
244 return plistBuddy.readPlistProperty(filename, `:${index}:Path`);
245 }
246 return findPackageEntry(index + 1);
247 });
248 };
249
250 return findPackageEntry(0)
251 .finally(() => {
252 nodeFileSystem.unlink(filename);
253 }).catch((): string => {
254 throw new Error("Application not installed on the device");
255 });
256 });
257 }
258
259 private makeGdbCommand(command: string): string {
260 let commandString: string = `$${command}#`;
261 let stringSum: number = 0;
262 for (let i: number = 0; i < command.length; i++) {
263 stringSum += command.charCodeAt(i);
264 }
265
266 /* tslint:disable:no-bitwise */
267 // We need some bitwise operations to calculate the checksum
268 stringSum = stringSum & 0xFF;
269 /* tslint:enable:no-bitwise */
270 let checksum: string = stringSum.toString(16).toUpperCase();
271 if (checksum.length < 2) {
272 checksum = "0" + checksum;
273 }
274
275 commandString += checksum;
276 return commandString;
277 }
278}