microsoft/vscode-react-native

Public

mirrored from https://github.com/microsoft/vscode-react-nativeAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
0.1.2

Branches

Tags

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

Clone

HTTPS

Download ZIP

src/debugger/ios/deviceRunner.ts

286lines · modeblame

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