microsoft/vscode-react-native

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
398e2b0b72a5c6d40ff7912643fed1123c69d867

Branches

Tags

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

Clone

HTTPS

Download ZIP

src/debugger/ios/deviceRunner.ts

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