diff options
author | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-28 14:29:10 +0000 |
---|---|---|
committer | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-28 14:29:10 +0000 |
commit | 2aa4a82499d4becd2284cdb482213d541b8804dd (patch) | |
tree | b80bf8bf13c3766139fbacc530efd0dd9d54394c /devtools/client/shared/remote-debugging/adb | |
parent | Initial commit. (diff) | |
download | firefox-upstream.tar.xz firefox-upstream.zip |
Adding upstream version 86.0.1.upstream/86.0.1upstream
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'devtools/client/shared/remote-debugging/adb')
23 files changed, 2090 insertions, 0 deletions
diff --git a/devtools/client/shared/remote-debugging/adb/adb-addon.js b/devtools/client/shared/remote-debugging/adb/adb-addon.js new file mode 100644 index 0000000000..b7f9fb6721 --- /dev/null +++ b/devtools/client/shared/remote-debugging/adb/adb-addon.js @@ -0,0 +1,180 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +"use strict"; + +const { AddonManager } = require("resource://gre/modules/AddonManager.jsm"); +const Services = require("Services"); +const EventEmitter = require("devtools/shared/event-emitter"); + +const PREF_ADB_EXTENSION_URL = "devtools.remote.adb.extensionURL"; +const PREF_ADB_EXTENSION_ID = "devtools.remote.adb.extensionID"; + +const ADB_ADDON_STATES = { + DOWNLOADING: "downloading", + INSTALLED: "installed", + INSTALLING: "installing", + PREPARING: "preparing", + UNINSTALLED: "uninstalled", + UNKNOWN: "unknown", +}; +exports.ADB_ADDON_STATES = ADB_ADDON_STATES; + +/** + * Wrapper around the ADB Extension providing ADB binaries for devtools remote debugging. + * Fires the following events: + * - "update": the status of the addon was updated + * - "failure": addon installation failed + * - "progress": addon download in progress + * + * AdbAddon::state can take any of the values from ADB_ADDON_STATES. + */ +class ADBAddon extends EventEmitter { + constructor() { + super(); + + this._status = ADB_ADDON_STATES.UNKNOWN; + + const addonsListener = {}; + addonsListener.onEnabled = addonsListener.onDisabled = addonsListener.onInstalled = addonsListener.onUninstalled = () => + this.updateInstallStatus(); + AddonManager.addAddonListener(addonsListener); + + this.updateInstallStatus(); + } + + set status(value) { + if (this._status != value) { + this._status = value; + this.emit("update"); + } + } + + get status() { + return this._status; + } + + async _getAddon() { + const addonId = Services.prefs.getCharPref(PREF_ADB_EXTENSION_ID); + return AddonManager.getAddonByID(addonId); + } + + async updateInstallStatus() { + const addon = await this._getAddon(); + if (addon && !addon.userDisabled) { + this.status = ADB_ADDON_STATES.INSTALLED; + } else { + this.status = ADB_ADDON_STATES.UNINSTALLED; + } + } + + /** + * Returns the platform specific download link for the ADB extension. + */ + _getXpiLink() { + const platform = Services.appShell.hiddenDOMWindow.navigator.platform; + let OS = ""; + if (platform.includes("Win")) { + OS = "win32"; + } else if (platform.includes("Mac")) { + OS = "mac64"; + } else if (platform.includes("Linux")) { + if (platform.includes("x86_64")) { + OS = "linux64"; + } else { + OS = "linux"; + } + } + + const xpiLink = Services.prefs.getCharPref(PREF_ADB_EXTENSION_URL); + return xpiLink.replace(/#OS#/g, OS); + } + + /** + * Install and enable the adb extension. Returns a promise that resolves when ADB is + * enabled. + * + * @param {String} source + * String passed to the AddonManager for telemetry. + */ + async install(source) { + if (!source) { + throw new Error( + "Missing mandatory `source` parameter for adb-addon.install" + ); + } + + const addon = await this._getAddon(); + if (addon && !addon.userDisabled) { + this.status = ADB_ADDON_STATES.INSTALLED; + return; + } + this.status = ADB_ADDON_STATES.PREPARING; + if (addon?.userDisabled) { + await addon.enable(); + } else { + const install = await AddonManager.getInstallForURL(this._getXpiLink(), { + telemetryInfo: { source }, + }); + install.addListener(this); + install.install(); + } + } + + async uninstall() { + const addon = await this._getAddon(); + addon.uninstall(); + } + + installFailureHandler(install, message) { + this.status = ADB_ADDON_STATES.UNINSTALLED; + this.emit("failure", message); + } + + // Expected AddonManager install listener. + onDownloadStarted() { + this.status = ADB_ADDON_STATES.DOWNLOADING; + } + + // Expected AddonManager install listener. + onDownloadProgress(install) { + if (install.maxProgress == -1) { + this.emit("progress", -1); + } else { + this.emit("progress", install.progress / install.maxProgress); + } + } + + // Expected AddonManager install listener. + onDownloadCancelled(install) { + this.installFailureHandler(install, "Download cancelled"); + } + + // Expected AddonManager install listener. + onDownloadFailed(install) { + this.installFailureHandler(install, "Download failed"); + } + + // Expected AddonManager install listener. + onInstallStarted() { + this.status = ADB_ADDON_STATES.INSTALLING; + } + + // Expected AddonManager install listener. + onInstallCancelled(install) { + this.installFailureHandler(install, "Install cancelled"); + } + + // Expected AddonManager install listener. + onInstallFailed(install) { + this.installFailureHandler(install, "Install failed"); + } + + // Expected AddonManager install listener. + onInstallEnded({ addon }) { + addon.enable(); + } +} + +exports.adbAddon = new ADBAddon(); diff --git a/devtools/client/shared/remote-debugging/adb/adb-binary.js b/devtools/client/shared/remote-debugging/adb/adb-binary.js new file mode 100644 index 0000000000..960fd72732 --- /dev/null +++ b/devtools/client/shared/remote-debugging/adb/adb-binary.js @@ -0,0 +1,251 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +"use strict"; + +const { dumpn } = require("devtools/shared/DevToolsUtils"); + +loader.lazyImporter(this, "OS", "resource://gre/modules/osfile.jsm"); +loader.lazyImporter( + this, + "ExtensionParent", + "resource://gre/modules/ExtensionParent.jsm" +); +loader.lazyRequireGetter(this, "Services"); +loader.lazyRequireGetter( + this, + "FileUtils", + "resource://gre/modules/FileUtils.jsm", + true +); +loader.lazyRequireGetter( + this, + "NetUtil", + "resource://gre/modules/NetUtil.jsm", + true +); +loader.lazyGetter(this, "UNPACKED_ROOT_PATH", () => { + return OS.Path.join(OS.Constants.Path.localProfileDir, "adb"); +}); +loader.lazyGetter(this, "EXTENSION_ID", () => { + return Services.prefs.getCharPref("devtools.remote.adb.extensionID"); +}); +loader.lazyGetter(this, "ADB_BINARY_PATH", () => { + let adbBinaryPath = OS.Path.join(UNPACKED_ROOT_PATH, "adb"); + if (Services.appinfo.OS === "WINNT") { + adbBinaryPath += ".exe"; + } + return adbBinaryPath; +}); + +const MANIFEST = "manifest.json"; + +/** + * Read contents from a given uri in the devtools-adb-extension and parse the + * contents as JSON. + */ +async function readFromExtension(fileUri) { + return new Promise(resolve => { + NetUtil.asyncFetch( + { + uri: fileUri, + loadUsingSystemPrincipal: true, + }, + input => { + try { + const string = NetUtil.readInputStreamToString( + input, + input.available() + ); + resolve(JSON.parse(string)); + } catch (e) { + dumpn(`Could not read ${fileUri} in the extension: ${e}`); + resolve(null); + } + } + ); + }); +} + +/** + * Unpack file from the extension. + * Uses NetUtil to read and write, since it's required for reading. + * + * @param {string} file + * The path name of the file in the extension. + */ +async function unpackFile(file) { + const policy = ExtensionParent.WebExtensionPolicy.getByID(EXTENSION_ID); + if (!policy) { + return; + } + + // Assumes that destination dir already exists. + const basePath = file.substring(file.lastIndexOf("/") + 1); + const filePath = OS.Path.join(UNPACKED_ROOT_PATH, basePath); + await new Promise((resolve, reject) => { + NetUtil.asyncFetch( + { + uri: policy.getURL(file), + loadUsingSystemPrincipal: true, + }, + input => { + try { + // Since we have to use NetUtil to read, probably it's okay to use for + // writing, rather than bouncing to OS.File...? + const outputFile = new FileUtils.File(filePath); + const output = FileUtils.openAtomicFileOutputStream(outputFile); + NetUtil.asyncCopy(input, output, resolve); + } catch (e) { + dumpn(`Could not unpack file ${file} in the extension: ${e}`); + reject(e); + } + } + ); + }); + // Mark binaries as executable. + await OS.File.setPermissions(filePath, { unixMode: 0o744 }); +} + +/** + * Extract files in the extension into local profile directory and returns + * if it fails. + */ +async function extractFiles() { + const policy = ExtensionParent.WebExtensionPolicy.getByID(EXTENSION_ID); + if (!policy) { + return false; + } + const uri = policy.getURL("adb.json"); + const adbInfo = await readFromExtension(uri); + if (!adbInfo) { + return false; + } + + let filesForAdb; + try { + // The adbInfo is an object looks like this; + // + // { + // "Linux": { + // "x86": [ + // "linux/adb" + // ], + // "x86_64": [ + // "linux64/adb" + // ] + // }, + // ... + + // XPCOMABI looks this; x86_64-gcc3, so drop the compiler name. + let architecture = Services.appinfo.XPCOMABI.split("-")[0]; + if (architecture === "aarch64") { + // Reuse x86 binaries for aarch64 - See Bug 1522149 + architecture = "x86"; + } + filesForAdb = adbInfo[Services.appinfo.OS][architecture]; + } catch (e) { + return false; + } + + // manifest.json isn't in adb.json but has to be unpacked for version + // comparison + filesForAdb.push(MANIFEST); + + await OS.File.makeDir(UNPACKED_ROOT_PATH); + + for (const file of filesForAdb) { + try { + await unpackFile(file); + } catch (e) { + return false; + } + } + + return true; +} + +/** + * Read the manifest from inside the devtools-adb-extension. + * Uses NetUtil since data is packed inside the extension, not a local file. + */ +async function getManifestFromExtension() { + const policy = ExtensionParent.WebExtensionPolicy.getByID(EXTENSION_ID); + if (!policy) { + return null; + } + + const manifestUri = policy.getURL(MANIFEST); + return readFromExtension(manifestUri); +} + +/** + * Returns whether manifest.json has already been unpacked. + */ +async function isManifestUnpacked() { + const manifestPath = OS.Path.join(UNPACKED_ROOT_PATH, MANIFEST); + return OS.File.exists(manifestPath); +} + +/** + * Read the manifest from the unpacked binary directory. + * Uses OS.File since this is a local file. + */ +async function getManifestFromUnpacked() { + if (!(await isManifestUnpacked())) { + throw new Error("Manifest doesn't exist at unpacked path"); + } + + const manifestPath = OS.Path.join(UNPACKED_ROOT_PATH, MANIFEST); + const binary = await OS.File.read(manifestPath); + const json = new TextDecoder().decode(binary); + let data; + try { + data = JSON.parse(json); + } catch (e) {} + return data; +} + +/** + * Check state of binary unpacking, including the location and manifest. + */ +async function isUnpacked() { + if (!(await isManifestUnpacked())) { + dumpn("Needs unpacking, no manifest found"); + return false; + } + + const manifestInExtension = await getManifestFromExtension(); + const unpackedManifest = await getManifestFromUnpacked(); + if (manifestInExtension.version != unpackedManifest.version) { + dumpn( + `Needs unpacking, extension version ${manifestInExtension.version} != ` + + `unpacked version ${unpackedManifest.version}` + ); + return false; + } + dumpn("Already unpacked"); + return true; +} + +/** + * Get a file object for the adb binary from the 'adb@mozilla.org' extension + * which has been already installed. + * + * @return {nsIFile} + * File object for the binary. + */ +async function getFileForBinary() { + if (!(await isUnpacked()) && !(await extractFiles())) { + return null; + } + + const file = new FileUtils.File(ADB_BINARY_PATH); + if (!file.exists()) { + return null; + } + return file; +} + +exports.getFileForBinary = getFileForBinary; diff --git a/devtools/client/shared/remote-debugging/adb/adb-client.js b/devtools/client/shared/remote-debugging/adb/adb-client.js new file mode 100644 index 0000000000..fbd42e63c1 --- /dev/null +++ b/devtools/client/shared/remote-debugging/adb/adb-client.js @@ -0,0 +1,82 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +/* + * A module to track device changes + * Adapted from adb.js at + * https://github.com/mozilla/adbhelper/tree/f44386c2d8cb7635a7d2c5a51191c89b886f8327 + */ + +"use strict"; + +const { + AdbSocket, +} = require("devtools/client/shared/remote-debugging/adb/adb-socket"); +const { dumpn } = require("devtools/shared/DevToolsUtils"); + +const OKAY = 0x59414b4f; +const FAIL = 0x4c494146; + +// Return buffer, which differs between Gecko versions +function getBuffer(packet) { + return packet.buffer ? packet.buffer : packet; +} + +// @param aPacket The packet to get the length from. +// @param aIgnoreResponse True if this packet has no OKAY/FAIL. +// @return A js object { length:...; data:... } +function unpackPacket(packet, ignoreResponse) { + const buffer = getBuffer(packet); + dumpn("Len buffer: " + buffer.byteLength); + if (buffer.byteLength === 4 && !ignoreResponse) { + dumpn("Packet empty"); + return { length: 0, data: "" }; + } + const lengthView = new Uint8Array(buffer, ignoreResponse ? 0 : 4, 4); + const decoder = new TextDecoder(); + const length = parseInt(decoder.decode(lengthView), 16); + const text = new Uint8Array(buffer, ignoreResponse ? 4 : 8, length); + return { length, data: decoder.decode(text) }; +} + +// Checks if the response is expected (defaults to OKAY). +// @return true if response equals expected. +function checkResponse(packet, expected = OKAY) { + const buffer = getBuffer(packet); + const view = new Uint32Array(buffer, 0, 1); + if (view[0] == FAIL) { + dumpn("Response: FAIL"); + } + dumpn("view[0] = " + view[0]); + return view[0] == expected; +} + +// @param aCommand A protocol-level command as described in +// http://androidxref.com/4.0.4/xref/system/core/adb/OVERVIEW.TXT and +// http://androidxref.com/4.0.4/xref/system/core/adb/SERVICES.TXT +// @return A 8 bit typed array. +function createRequest(command) { + let length = command.length.toString(16).toUpperCase(); + while (length.length < 4) { + length = "0" + length; + } + + const encoder = new TextEncoder(); + dumpn("Created request: " + length + command); + return encoder.encode(length + command); +} + +function connect() { + return new AdbSocket(); +} + +const client = { + getBuffer, + unpackPacket, + checkResponse, + createRequest, + connect, +}; + +module.exports = client; diff --git a/devtools/client/shared/remote-debugging/adb/adb-device.js b/devtools/client/shared/remote-debugging/adb/adb-device.js new file mode 100644 index 0000000000..3f83572a92 --- /dev/null +++ b/devtools/client/shared/remote-debugging/adb/adb-device.js @@ -0,0 +1,53 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +"use strict"; + +const { + shell, +} = require("devtools/client/shared/remote-debugging/adb/commands/index"); + +/** + * A Device instance is created and registered with the Devices module whenever + * ADB notices a new device is connected. + */ +class AdbDevice { + constructor(id) { + this.id = id; + } + + async initialize() { + const model = await shell(this.id, "getprop ro.product.model"); + this.model = model.trim(); + } + + get name() { + return this.model || this.id; + } + + async getRuntimeSocketPaths() { + // A matching entry looks like: + // 00000000: 00000002 00000000 00010000 0001 01 6551588 + // /data/data/org.mozilla.fennec/firefox-debugger-socket + const query = "cat /proc/net/unix"; + const rawSocketInfo = await shell(this.id, query); + + // Filter to lines with "firefox-debugger-socket" + let socketInfos = rawSocketInfo.split(/\r?\n/); + socketInfos = socketInfos.filter(l => + l.includes("firefox-debugger-socket") + ); + + // It's possible to have multiple lines with the same path, so de-dupe them + const socketPaths = new Set(); + for (const socketInfo of socketInfos) { + const socketPath = socketInfo.split(" ").pop(); + socketPaths.add(socketPath); + } + + return socketPaths; + } +} + +module.exports = AdbDevice; diff --git a/devtools/client/shared/remote-debugging/adb/adb-process.js b/devtools/client/shared/remote-debugging/adb/adb-process.js new file mode 100644 index 0000000000..8e27520ef8 --- /dev/null +++ b/devtools/client/shared/remote-debugging/adb/adb-process.js @@ -0,0 +1,154 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +"use strict"; + +const { Cc, Ci } = require("chrome"); +const { dumpn } = require("devtools/shared/DevToolsUtils"); +const EventEmitter = require("devtools/shared/event-emitter"); +const { + getFileForBinary, +} = require("devtools/client/shared/remote-debugging/adb/adb-binary"); +const { setTimeout } = require("resource://gre/modules/Timer.jsm"); + +loader.lazyRequireGetter( + this, + "runCommand", + "devtools/client/shared/remote-debugging/adb/commands/index", + true +); +loader.lazyRequireGetter( + this, + "check", + "devtools/client/shared/remote-debugging/adb/adb-running-checker", + true +); + +// Waits until a predicate returns true or re-tries the predicate calls +// |retry| times, we wait for 100ms between each calls. +async function waitUntil(predicate, retry = 20) { + let count = 0; + while (count++ < retry) { + if (await predicate()) { + return true; + } + // Wait for 100 milliseconds. + await new Promise(resolve => setTimeout(resolve, 100)); + } + // Timed out after trying too many times. + return false; +} + +// Class representing the ADB process. +class AdbProcess extends EventEmitter { + constructor() { + super(); + + this._ready = false; + this._didRunInitially = false; + } + + get ready() { + return this._ready; + } + + _getAdbFile() { + if (this._adbFilePromise) { + return this._adbFilePromise; + } + this._adbFilePromise = getFileForBinary(); + return this._adbFilePromise; + } + + async _runProcess(process, params) { + return new Promise((resolve, reject) => { + process.runAsync( + params, + params.length, + { + observe(subject, topic, data) { + switch (topic) { + case "process-finished": + resolve(); + break; + case "process-failed": + reject(); + break; + } + }, + }, + false + ); + }); + } + + // We startup by launching adb in server mode, and setting + // the tcp socket preference to |true| + async start() { + const onSuccessfulStart = () => { + this._ready = true; + this.emit("adb-ready"); + }; + + const isAdbRunning = await check(); + if (isAdbRunning) { + dumpn("Found ADB process running, not restarting"); + onSuccessfulStart(); + return; + } + dumpn("Didn't find ADB process running, restarting"); + + this._didRunInitially = true; + const process = Cc["@mozilla.org/process/util;1"].createInstance( + Ci.nsIProcess + ); + + // FIXME: Bug 1481691 - We should avoid extracting files every time. + const adbFile = await this._getAdbFile(); + process.init(adbFile); + // Hide command prompt window on Windows + process.startHidden = true; + process.noShell = true; + const params = ["start-server"]; + let isStarted = false; + try { + await this._runProcess(process, params); + isStarted = await waitUntil(check); + } catch (e) {} + + if (isStarted) { + onSuccessfulStart(); + } else { + this._ready = false; + throw new Error("ADB Process didn't start"); + } + } + + /** + * Stop the ADB server, but only if we started it. If it was started before + * us, we return immediately. + */ + async stop() { + if (!this._didRunInitially) { + return; // We didn't start the server, nothing to do + } + await this.kill(); + } + + /** + * Kill the ADB server. + */ + async kill() { + try { + await runCommand("host:kill"); + } catch (e) { + dumpn("Failed to send host:kill command"); + } + dumpn("adb server was terminated by host:kill"); + this._ready = false; + this._didRunInitially = false; + } +} + +exports.adbProcess = new AdbProcess(); diff --git a/devtools/client/shared/remote-debugging/adb/adb-running-checker.js b/devtools/client/shared/remote-debugging/adb/adb-running-checker.js new file mode 100644 index 0000000000..bcce50d91c --- /dev/null +++ b/devtools/client/shared/remote-debugging/adb/adb-running-checker.js @@ -0,0 +1,91 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +/* + * Uses host:version service to detect if ADB is running + * Modified from adb-file-transfer from original ADB + */ + +"use strict"; + +const client = require("devtools/client/shared/remote-debugging/adb/adb-client"); +const { dumpn } = require("devtools/shared/DevToolsUtils"); + +exports.check = async function check() { + let socket; + let state; + let timerID; + const TIMEOUT_TIME = 1000; + + dumpn("Asking for host:version"); + + return new Promise(resolve => { + // On MacOSX connecting to a port which is not started listening gets + // stuck (bug 1481963), to avoid the stuck, we do forcibly fail the + // connection after |TIMEOUT_TIME| elapsed. + timerID = setTimeout(() => { + socket.close(); + resolve(false); + }, TIMEOUT_TIME); + + function finish(returnValue) { + clearTimeout(timerID); + resolve(returnValue); + } + + const runFSM = function runFSM(packetData) { + dumpn("runFSM " + state); + switch (state) { + case "start": + const req = client.createRequest("host:version"); + socket.send(req); + state = "wait-version"; + break; + case "wait-version": + // TODO: Actually check the version number to make sure the daemon + // supports the commands we want to use + const { length, data } = client.unpackPacket(packetData); + dumpn("length: ", length, "data: ", data); + socket.close(); + const version = parseInt(data, 16); + if (version >= 31) { + finish(true); + } else { + dumpn("killing existing adb as we need version >= 31"); + finish(false); + } + break; + default: + dumpn("Unexpected State: " + state); + finish(false); + } + }; + + const setupSocket = function() { + socket.s.onerror = function(event) { + dumpn("running checker onerror"); + finish(false); + }; + + socket.s.onopen = function(event) { + dumpn("running checker onopen"); + state = "start"; + runFSM(); + }; + + socket.s.onclose = function(event) { + dumpn("running checker onclose"); + }; + + socket.s.ondata = function(event) { + dumpn("running checker ondata"); + runFSM(event.data); + }; + }; + + socket = client.connect(); + setupSocket(); + }); +}; diff --git a/devtools/client/shared/remote-debugging/adb/adb-runtime.js b/devtools/client/shared/remote-debugging/adb/adb-runtime.js new file mode 100644 index 0000000000..72217a7957 --- /dev/null +++ b/devtools/client/shared/remote-debugging/adb/adb-runtime.js @@ -0,0 +1,129 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +"use strict"; + +const { + prepareTCPConnection, +} = require("devtools/client/shared/remote-debugging/adb/commands/index"); +const { + shell, +} = require("devtools/client/shared/remote-debugging/adb/commands/index"); + +class AdbRuntime { + constructor(adbDevice, socketPath) { + this._adbDevice = adbDevice; + this._socketPath = socketPath; + // Set a default version name in case versionName cannot be parsed. + this._versionName = ""; + } + + async init() { + const packageName = this._packageName(); + const query = `dumpsys package ${packageName} | grep versionName`; + const versionNameString = await shell(this._adbDevice.id, query); + + // The versionName can have different formats depending on the channel + // - `versionName=Nightly 191016 06:01\n` on Nightly + // - `versionName=2.1.0\n` on Release + // We use a very flexible regular expression to accommodate for those + // different formats. + const matches = versionNameString.match(/versionName=(.*)\n/); + if (matches?.[1]) { + this._versionName = matches[1]; + } + } + + get id() { + return this._adbDevice.id + "|" + this._socketPath; + } + + get isFenix() { + // Firefox Release uses "org.mozilla.firefox" + // Firefox Beta uses "org.mozilla.firefox_beta" + // Firefox Nightly uses "org.mozilla.fenix" + const isFirefox = + this._packageName().includes("org.mozilla.firefox") || + this._packageName().includes("org.mozilla.fenix"); + + if (!isFirefox) { + return false; + } + + // Firefox Release (based on Fenix) is not released in all regions yet, so + // we should still check for Fennec using the version number. + // Note that Fennec's versionName followed Firefox versions (eg "68.11.0"). + // We can find the main version number in it. Fenix on the other hand has + // version names such as "Nightly 200730 06:21". + const mainVersion = Number(this.versionName.split(".")[0]); + const isFennec = mainVersion === 68; + + // Application is Fenix if this is a Firefox application with a version + // different from the Fennec version. + return !isFennec; + } + + get deviceId() { + return this._adbDevice.id; + } + + get deviceName() { + return this._adbDevice.name; + } + + get versionName() { + return this._versionName; + } + + get shortName() { + const packageName = this._packageName(); + + switch (packageName) { + case "org.mozilla.firefox": + if (!this.isFenix) { + // Old Fennec release + return "Firefox (Fennec)"; + } + // Official Firefox app, based on Fenix + return "Firefox"; + case "org.mozilla.firefox_beta": + // Official Firefox Beta app, based on Fenix + return "Firefox Beta"; + case "org.mozilla.fenix": + case "org.mozilla.fenix.nightly": + // Official Firefox Nightly app, based on Fenix + return "Firefox Nightly"; + default: + // Unknown package name + return `Firefox (${packageName})`; + } + } + + get socketPath() { + return this._socketPath; + } + + get name() { + return `${this.shortName} on Android (${this.deviceName})`; + } + + connect(connection) { + return prepareTCPConnection(this.deviceId, this._socketPath).then(port => { + connection.host = "localhost"; + connection.port = port; + connection.connect(); + }); + } + + _packageName() { + // If using abstract socket address, it is "@org.mozilla.firefox/..." + // If using path base socket, it is "/data/data/<package>..."" + // Until Fennec 62 only supports path based UNIX domain socket, but + // Fennec 63+ supports both path based and abstract socket. + return this._socketPath.startsWith("@") + ? this._socketPath.substr(1).split("/")[0] + : this._socketPath.split("/")[3]; + } +} +exports.AdbRuntime = AdbRuntime; diff --git a/devtools/client/shared/remote-debugging/adb/adb-socket.js b/devtools/client/shared/remote-debugging/adb/adb-socket.js new file mode 100644 index 0000000000..b28556c05d --- /dev/null +++ b/devtools/client/shared/remote-debugging/adb/adb-socket.js @@ -0,0 +1,74 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +"use strict"; + +const ChromeUtils = require("ChromeUtils"); +const { Cu } = require("chrome"); +const { dumpn } = require("devtools/shared/DevToolsUtils"); + +function createTCPSocket(location, port, options) { + const { TCPSocket } = Cu.getGlobalForObject( + ChromeUtils.import("resource://gre/modules/Services.jsm") + ); + + return new TCPSocket(location, port, options); +} + +// Creates a socket connected to the adb instance. +// This instantiation is sync, and returns before we know if opening the +// connection succeeds. Callers must attach handlers to the s field. +class AdbSocket { + constructor() { + this.s = createTCPSocket("127.0.0.1", 5037, { binaryType: "arraybuffer" }); + } + + /** + * Dump the first few bytes of the given array to the console. + * + * @param {TypedArray} inputArray + * the array to dump + */ + _hexdump(inputArray) { + const decoder = new TextDecoder("windows-1252"); + const array = new Uint8Array(inputArray.buffer); + const s = decoder.decode(array); + const len = array.length; + let dbg = "len=" + len + " "; + const l = len > 20 ? 20 : len; + + for (let i = 0; i < l; i++) { + let c = array[i].toString(16); + if (c.length == 1) { + c = "0" + c; + } + dbg += c; + } + dbg += " "; + for (let i = 0; i < l; i++) { + const c = array[i]; + if (c < 32 || c > 127) { + dbg += "."; + } else { + dbg += s[i]; + } + } + dumpn(dbg); + } + + // debugging version of tcpsocket.send() + send(array) { + this._hexdump(array); + + this.s.send(array.buffer, array.byteOffset, array.byteLength); + } + + close() { + if (this.s.readyState === "open" || this.s.readyState === "connecting") { + this.s.close(); + } + } +} + +exports.AdbSocket = AdbSocket; diff --git a/devtools/client/shared/remote-debugging/adb/adb.js b/devtools/client/shared/remote-debugging/adb/adb.js new file mode 100644 index 0000000000..25ba178cff --- /dev/null +++ b/devtools/client/shared/remote-debugging/adb/adb.js @@ -0,0 +1,177 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +"use strict"; + +const { + clearInterval, + setInterval, +} = require("resource://gre/modules/Timer.jsm"); + +const EventEmitter = require("devtools/shared/event-emitter"); +const { + adbProcess, +} = require("devtools/client/shared/remote-debugging/adb/adb-process"); +const { + adbAddon, +} = require("devtools/client/shared/remote-debugging/adb/adb-addon"); +const AdbDevice = require("devtools/client/shared/remote-debugging/adb/adb-device"); +const { + AdbRuntime, +} = require("devtools/client/shared/remote-debugging/adb/adb-runtime"); +const { + TrackDevicesCommand, +} = require("devtools/client/shared/remote-debugging/adb/commands/track-devices"); +loader.lazyRequireGetter( + this, + "check", + "devtools/client/shared/remote-debugging/adb/adb-running-checker", + true +); + +// Duration in milliseconds of the runtime polling. We resort to polling here because we +// have no event to know when a runtime started on an already discovered ADB device. +const UPDATE_RUNTIMES_INTERVAL = 3000; + +class Adb extends EventEmitter { + constructor() { + super(); + + this._trackDevicesCommand = new TrackDevicesCommand(); + + this._isTrackingDevices = false; + this._isUpdatingRuntimes = false; + + this._listeners = new Set(); + this._devices = new Map(); + this._runtimes = []; + + this._updateAdbProcess = this._updateAdbProcess.bind(this); + this._onDeviceConnected = this._onDeviceConnected.bind(this); + this._onDeviceDisconnected = this._onDeviceDisconnected.bind(this); + this._onNoDevicesDetected = this._onNoDevicesDetected.bind(this); + + this._trackDevicesCommand.on("device-connected", this._onDeviceConnected); + this._trackDevicesCommand.on( + "device-disconnected", + this._onDeviceDisconnected + ); + this._trackDevicesCommand.on( + "no-devices-detected", + this._onNoDevicesDetected + ); + adbAddon.on("update", this._updateAdbProcess); + } + + registerListener(listener) { + this._listeners.add(listener); + this.on("runtime-list-updated", listener); + this._updateAdbProcess(); + } + + unregisterListener(listener) { + this._listeners.delete(listener); + this.off("runtime-list-updated", listener); + this._updateAdbProcess(); + } + + async updateRuntimes() { + try { + const devices = [...this._devices.values()]; + const promises = devices.map(d => this._getDeviceRuntimes(d)); + const allRuntimes = await Promise.all(promises); + + this._runtimes = allRuntimes.flat(); + this.emit("runtime-list-updated"); + } catch (e) { + console.error(e); + } + } + + getRuntimes() { + return this._runtimes; + } + + getDevices() { + return [...this._devices.values()]; + } + + async isProcessStarted() { + return check(); + } + + async _startTracking() { + this._isTrackingDevices = true; + await adbProcess.start(); + + this._trackDevicesCommand.run(); + + // Device runtimes are detected by running a shell command and checking for + // "firefox-debugger-socket" in the list of currently running processes. + this._timer = setInterval( + this.updateRuntimes.bind(this), + UPDATE_RUNTIMES_INTERVAL + ); + } + + async _stopTracking() { + clearInterval(this._timer); + this._isTrackingDevices = false; + this._trackDevicesCommand.stop(); + + this._devices = new Map(); + this._runtimes = []; + this.updateRuntimes(); + } + + _shouldTrack() { + return adbAddon.status === "installed" && this._listeners.size > 0; + } + + /** + * This method will emit "runtime-list-ready" to notify the consumer that the list of + * runtimes is ready to be retrieved. + */ + async _updateAdbProcess() { + if (!this._isTrackingDevices && this._shouldTrack()) { + const onRuntimesUpdated = this.once("runtime-list-updated"); + this._startTracking(); + // If we are starting to track runtimes, the list of runtimes will only be ready + // once the first "runtime-list-updated" event has been processed. + await onRuntimesUpdated; + } else if (this._isTrackingDevices && !this._shouldTrack()) { + this._stopTracking(); + } + this.emit("runtime-list-ready"); + } + + async _onDeviceConnected(deviceId) { + const adbDevice = new AdbDevice(deviceId); + await adbDevice.initialize(); + this._devices.set(deviceId, adbDevice); + this.updateRuntimes(); + } + + _onDeviceDisconnected(deviceId) { + this._devices.delete(deviceId); + this.updateRuntimes(); + } + + _onNoDevicesDetected() { + this.updateRuntimes(); + } + + async _getDeviceRuntimes(device) { + const socketPaths = [...(await device.getRuntimeSocketPaths())]; + const runtimes = []; + for (const socketPath of socketPaths) { + const runtime = new AdbRuntime(device, socketPath); + await runtime.init(); + runtimes.push(runtime); + } + return runtimes; + } +} + +exports.adb = new Adb(); diff --git a/devtools/client/shared/remote-debugging/adb/commands/index.js b/devtools/client/shared/remote-debugging/adb/commands/index.js new file mode 100644 index 0000000000..ee4e15f9b2 --- /dev/null +++ b/devtools/client/shared/remote-debugging/adb/commands/index.js @@ -0,0 +1,29 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +"use strict"; + +const { + listDevices, +} = require("devtools/client/shared/remote-debugging/adb/commands/list-devices"); +const { + prepareTCPConnection, +} = require("devtools/client/shared/remote-debugging/adb/commands/prepare-tcp-connection"); +const { + runCommand, +} = require("devtools/client/shared/remote-debugging/adb/commands/run-command"); +const { + shell, +} = require("devtools/client/shared/remote-debugging/adb/commands/shell"); +const { + TrackDevicesCommand, +} = require("devtools/client/shared/remote-debugging/adb/commands/track-devices"); + +module.exports = { + listDevices, + prepareTCPConnection, + runCommand, + shell, + TrackDevicesCommand, +}; diff --git a/devtools/client/shared/remote-debugging/adb/commands/list-devices.js b/devtools/client/shared/remote-debugging/adb/commands/list-devices.js new file mode 100644 index 0000000000..ed2d586673 --- /dev/null +++ b/devtools/client/shared/remote-debugging/adb/commands/list-devices.js @@ -0,0 +1,29 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +"use strict"; + +const { dumpn } = require("devtools/shared/DevToolsUtils"); +/** + * The listDevices command is currently unused in DevTools. We are keeping it while + * working on RemoteDebugging NG, in case it becomes needed later. We will remove it from + * the codebase if unused at the end of the project. See Bug 1511779. + */ +const listDevices = function() { + dumpn("listDevices"); + + return this.runCommand("host:devices").then(function onSuccess(data) { + const lines = data.split("\n"); + const res = []; + lines.forEach(function(line) { + if (line.length == 0) { + return; + } + const [device] = line.split("\t"); + res.push(device); + }); + return res; + }); +}; +exports.listDevices = listDevices; diff --git a/devtools/client/shared/remote-debugging/adb/commands/moz.build b/devtools/client/shared/remote-debugging/adb/commands/moz.build new file mode 100644 index 0000000000..ecd3428a1b --- /dev/null +++ b/devtools/client/shared/remote-debugging/adb/commands/moz.build @@ -0,0 +1,12 @@ +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +DevToolsModules( + "index.js", + "list-devices.js", + "prepare-tcp-connection.js", + "run-command.js", + "shell.js", + "track-devices.js", +) diff --git a/devtools/client/shared/remote-debugging/adb/commands/prepare-tcp-connection.js b/devtools/client/shared/remote-debugging/adb/commands/prepare-tcp-connection.js new file mode 100644 index 0000000000..478b16b15c --- /dev/null +++ b/devtools/client/shared/remote-debugging/adb/commands/prepare-tcp-connection.js @@ -0,0 +1,47 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +"use strict"; + +const { Cc, Ci } = require("chrome"); +const { dumpn } = require("devtools/shared/DevToolsUtils"); +const { + runCommand, +} = require("devtools/client/shared/remote-debugging/adb/commands/run-command"); + +// sends adb forward deviceId, localPort and devicePort +const forwardPort = function(deviceId, localPort, devicePort) { + dumpn("forwardPort " + localPort + " -- " + devicePort); + // Send "host-serial:<serial-number>:<request>", + // with <request> set to "forward:<local>;<remote>" + // See https://android.googlesource.com/platform/system/core/+/jb-dev/adb/SERVICES.TXT + return runCommand( + `host-serial:${deviceId}:forward:${localPort};${devicePort}` + ).then(function onSuccess(data) { + return data; + }); +}; + +const getFreeTCPPort = function() { + const serv = Cc["@mozilla.org/network/server-socket;1"].createInstance( + Ci.nsIServerSocket + ); + serv.init(-1, true, -1); + const port = serv.port; + serv.close(); + return port; +}; + +// Prepare TCP connection for provided device id and socket path. +// The returned value is a port number of localhost for the connection. +const prepareTCPConnection = async function(deviceId, socketPath) { + const port = getFreeTCPPort(); + const local = `tcp:${port}`; + const remote = socketPath.startsWith("@") + ? `localabstract:${socketPath.substring(1)}` + : `localfilesystem:${socketPath}`; + await forwardPort(deviceId, local, remote); + return port; +}; +exports.prepareTCPConnection = prepareTCPConnection; diff --git a/devtools/client/shared/remote-debugging/adb/commands/run-command.js b/devtools/client/shared/remote-debugging/adb/commands/run-command.js new file mode 100644 index 0000000000..d17bb1d6e6 --- /dev/null +++ b/devtools/client/shared/remote-debugging/adb/commands/run-command.js @@ -0,0 +1,64 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +// Wrapper around the ADB utility. + +"use strict"; + +const { dumpn } = require("devtools/shared/DevToolsUtils"); +const { setTimeout } = require("resource://gre/modules/Timer.jsm"); +const { + adbProcess, +} = require("devtools/client/shared/remote-debugging/adb/adb-process"); +const client = require("devtools/client/shared/remote-debugging/adb/adb-client"); + +const OKAY = 0x59414b4f; + +// Asynchronously runs an adb command. +// @param command The command as documented in +// http://androidxref.com/4.0.4/xref/system/core/adb/SERVICES.TXT +const runCommand = function(command) { + dumpn("runCommand " + command); + return new Promise((resolve, reject) => { + if (!adbProcess.ready) { + setTimeout(function() { + reject("ADB_NOT_READY"); + }); + return; + } + + const socket = client.connect(); + + socket.s.onopen = function() { + dumpn("runCommand onopen"); + const req = client.createRequest(command); + socket.send(req); + }; + + socket.s.onerror = function() { + dumpn("runCommand onerror"); + reject("NETWORK_ERROR"); + }; + + socket.s.onclose = function() { + dumpn("runCommand onclose"); + }; + + socket.s.ondata = function(event) { + dumpn("runCommand ondata"); + const data = event.data; + + const packet = client.unpackPacket(data, false); + if (!client.checkResponse(data, OKAY)) { + socket.close(); + dumpn("Error: " + packet.data); + reject("PROTOCOL_ERROR"); + return; + } + + resolve(packet.data); + }; + }); +}; +exports.runCommand = runCommand; diff --git a/devtools/client/shared/remote-debugging/adb/commands/shell.js b/devtools/client/shared/remote-debugging/adb/commands/shell.js new file mode 100644 index 0000000000..dbe1beffe8 --- /dev/null +++ b/devtools/client/shared/remote-debugging/adb/commands/shell.js @@ -0,0 +1,107 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +// Wrapper around the ADB utility. + +"use strict"; + +const { dumpn } = require("devtools/shared/DevToolsUtils"); +const client = require("devtools/client/shared/remote-debugging/adb/adb-client"); + +const OKAY = 0x59414b4f; + +const shell = async function(deviceId, command) { + if (!deviceId) { + throw new Error("ADB shell command needs the device id"); + } + + let state; + let stdout = ""; + + dumpn("shell " + command + " on " + deviceId); + + return new Promise((resolve, reject) => { + const shutdown = function() { + dumpn("shell shutdown"); + socket.close(); + reject("BAD_RESPONSE"); + }; + + const runFSM = function runFSM(data) { + dumpn("runFSM " + state); + let req; + let ignoreResponseCode = false; + switch (state) { + case "start": + state = "send-transport"; + runFSM(); + break; + case "send-transport": + req = client.createRequest("host:transport:" + deviceId); + socket.send(req); + state = "wait-transport"; + break; + case "wait-transport": + if (!client.checkResponse(data, OKAY)) { + shutdown(); + return; + } + state = "send-shell"; + runFSM(); + break; + case "send-shell": + req = client.createRequest("shell:" + command); + socket.send(req); + state = "rec-shell"; + break; + case "rec-shell": + if (!client.checkResponse(data, OKAY)) { + shutdown(); + return; + } + state = "decode-shell"; + if (client.getBuffer(data).byteLength == 4) { + break; + } + ignoreResponseCode = true; + // eslint-disable-next-lined no-fallthrough + case "decode-shell": + const decoder = new TextDecoder(); + const text = new Uint8Array( + client.getBuffer(data), + ignoreResponseCode ? 4 : 0 + ); + stdout += decoder.decode(text); + break; + default: + dumpn("shell Unexpected State: " + state); + reject("UNEXPECTED_STATE"); + } + }; + + const socket = client.connect(); + socket.s.onerror = function(event) { + dumpn("shell onerror"); + reject("SOCKET_ERROR"); + }; + + socket.s.onopen = function(event) { + dumpn("shell onopen"); + state = "start"; + runFSM(); + }; + + socket.s.onclose = function(event) { + resolve(stdout); + dumpn("shell onclose"); + }; + + socket.s.ondata = function(event) { + dumpn("shell ondata"); + runFSM(event.data); + }; + }); +}; + +exports.shell = shell; diff --git a/devtools/client/shared/remote-debugging/adb/commands/track-devices.js b/devtools/client/shared/remote-debugging/adb/commands/track-devices.js new file mode 100644 index 0000000000..8bbdce7d4e --- /dev/null +++ b/devtools/client/shared/remote-debugging/adb/commands/track-devices.js @@ -0,0 +1,161 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +// Wrapper around the ADB utility. + +"use strict"; + +const EventEmitter = require("devtools/shared/event-emitter"); +const { dumpn } = require("devtools/shared/DevToolsUtils"); +const { setTimeout } = require("resource://gre/modules/Timer.jsm"); + +const { + adbProcess, +} = require("devtools/client/shared/remote-debugging/adb/adb-process"); +const client = require("devtools/client/shared/remote-debugging/adb/adb-client"); + +const ADB_STATUS_OFFLINE = "offline"; +const OKAY = 0x59414b4f; + +// Start tracking devices connecting and disconnecting from the host. +// We can't reuse runCommand here because we keep the socket alive. +class TrackDevicesCommand extends EventEmitter { + run() { + this._waitForFirst = true; + // Hold device statuses. key: device id, value: status. + this._devices = new Map(); + this._socket = client.connect(); + + this._socket.s.onopen = this._onOpen.bind(this); + this._socket.s.onerror = this._onError.bind(this); + this._socket.s.onclose = this._onClose.bind(this); + this._socket.s.ondata = this._onData.bind(this); + } + + stop() { + if (this._socket) { + this._socket.close(); + + this._socket.s.onopen = null; + this._socket.s.onerror = null; + this._socket.s.onclose = null; + this._socket.s.ondata = null; + } + } + + _onOpen() { + dumpn("trackDevices onopen"); + const req = client.createRequest("host:track-devices"); + this._socket.send(req); + } + + _onError(event) { + dumpn("trackDevices onerror: " + event); + } + + _onClose() { + dumpn("trackDevices onclose"); + + // Report all devices as disconnected + this._disconnectAllDevices(); + + // When we lose connection to the server, + // and the adb is still on, we most likely got our server killed + // by local adb. So we do try to reconnect to it. + + // Give some time to the new adb to start + setTimeout(() => { + // Only try to reconnect/restart if the add-on is still enabled + if (adbProcess.ready) { + // try to connect to the new local adb server or spawn a new one + adbProcess.start().then(() => { + // Re-track devices + this.run(); + }); + } + }, 2000); + } + + _onData(event) { + dumpn("trackDevices ondata"); + const data = event.data; + dumpn("length=" + data.byteLength); + const dec = new TextDecoder(); + dumpn(dec.decode(new Uint8Array(data)).trim()); + + // check the OKAY or FAIL on first packet. + if (this._waitForFirst) { + if (!client.checkResponse(data, OKAY)) { + this._socket.close(); + return; + } + } + + const packet = client.unpackPacket(data, !this._waitForFirst); + this._waitForFirst = false; + + if (packet.data == "") { + // All devices got disconnected. + this._disconnectAllDevices(); + } else { + // One line per device, each line being $DEVICE\t(offline|device) + const lines = packet.data.split("\n"); + const newDevices = new Map(); + lines.forEach(function(line) { + if (line.length == 0) { + return; + } + + const [deviceId, status] = line.split("\t"); + newDevices.set(deviceId, status); + }); + + // Fire events if needed. + const deviceIds = new Set([ + ...this._devices.keys(), + ...newDevices.keys(), + ]); + for (const deviceId of deviceIds) { + const currentStatus = this._devices.get(deviceId); + const newStatus = newDevices.get(deviceId); + this._fireConnectionEventIfNeeded(deviceId, currentStatus, newStatus); + } + + // Update devices. + this._devices = newDevices; + } + } + + _disconnectAllDevices() { + if (this._devices.size === 0) { + // If no devices were detected, fire an event to let consumer resume. + this.emit("no-devices-detected"); + } else { + for (const [deviceId, status] of this._devices.entries()) { + if (status !== ADB_STATUS_OFFLINE) { + this.emit("device-disconnected", deviceId); + } + } + } + this._devices = new Map(); + } + + _fireConnectionEventIfNeeded(deviceId, currentStatus, newStatus) { + const isCurrentOnline = !!( + currentStatus && currentStatus !== ADB_STATUS_OFFLINE + ); + const isNewOnline = !!(newStatus && newStatus !== ADB_STATUS_OFFLINE); + + if (isCurrentOnline === isNewOnline) { + return; + } + + if (isNewOnline) { + this.emit("device-connected", deviceId); + } else { + this.emit("device-disconnected", deviceId); + } + } +} +exports.TrackDevicesCommand = TrackDevicesCommand; diff --git a/devtools/client/shared/remote-debugging/adb/moz.build b/devtools/client/shared/remote-debugging/adb/moz.build new file mode 100644 index 0000000000..9210dec08e --- /dev/null +++ b/devtools/client/shared/remote-debugging/adb/moz.build @@ -0,0 +1,24 @@ +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +DIRS += [ + "commands", +] + +DevToolsModules( + "adb-addon.js", + "adb-binary.js", + "adb-client.js", + "adb-device.js", + "adb-process.js", + "adb-running-checker.js", + "adb-runtime.js", + "adb-socket.js", + "adb.js", +) + +with Files("**"): + BUG_COMPONENT = ("DevTools", "about:debugging") + +XPCSHELL_TESTS_MANIFESTS += ["xpcshell/xpcshell.ini"] diff --git a/devtools/client/shared/remote-debugging/adb/xpcshell/.eslintrc.js b/devtools/client/shared/remote-debugging/adb/xpcshell/.eslintrc.js new file mode 100644 index 0000000000..e4da98dd14 --- /dev/null +++ b/devtools/client/shared/remote-debugging/adb/xpcshell/.eslintrc.js @@ -0,0 +1,9 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +"use strict"; + +module.exports = { + extends: "../../../../../.eslintrc.xpcshell.js", +}; diff --git a/devtools/client/shared/remote-debugging/adb/xpcshell/adb.py b/devtools/client/shared/remote-debugging/adb/xpcshell/adb.py new file mode 100644 index 0000000000..d4a515c6e2 --- /dev/null +++ b/devtools/client/shared/remote-debugging/adb/xpcshell/adb.py @@ -0,0 +1,74 @@ +#!/usr/bin/env python +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +""" +A fake ADB binary +""" + +from __future__ import absolute_import + +import os +import SocketServer +import sys + +HOST = "127.0.0.1" +PORT = 5037 + + +class ADBRequestHandler(SocketServer.BaseRequestHandler): + def sendData(self, data): + header = "OKAY%04x" % len(data) + all_data = header + data + total_length = len(all_data) + sent_length = 0 + # Make sure send all data to the client. + # Though the data length here is pretty small but sometimes when the + # client is on heavy load (e.g. MOZ_CHAOSMODE) we can't send the whole + # data at once. + while sent_length < total_length: + sent = self.request.send(all_data[sent_length:]) + sent_length = sent_length + sent + + def handle(self): + while True: + data = self.request.recv(4096) + if "host:kill" in data: + self.sendData("") + # Implicitly close all open sockets by exiting the program. + # This should be done ASAP, because upon receiving the OKAY, + # the client expects adb to have released the server's port. + os._exit(0) + break + elif "host:version" in data: + self.sendData("001F") + self.request.close() + break + elif "host:track-devices" in data: + self.sendData("1234567890\tdevice") + break + + +class ADBServer(SocketServer.TCPServer): + def __init__(self, server_address): + # Create a SocketServer with bind_and_activate 'False' to set + # allow_reuse_address before binding. + SocketServer.TCPServer.__init__( + self, server_address, ADBRequestHandler, bind_and_activate=False + ) + + +if len(sys.argv) == 2 and sys.argv[1] == "start-server": + # daemonize + if os.fork() > 0: + sys.exit(0) + os.setsid() + if os.fork() > 0: + sys.exit(0) + + server = ADBServer((HOST, PORT)) + server.allow_reuse_address = True + server.server_bind() + server.server_activate() + server.serve_forever() diff --git a/devtools/client/shared/remote-debugging/adb/xpcshell/test_adb.js b/devtools/client/shared/remote-debugging/adb/xpcshell/test_adb.js new file mode 100644 index 0000000000..eb212c355d --- /dev/null +++ b/devtools/client/shared/remote-debugging/adb/xpcshell/test_adb.js @@ -0,0 +1,245 @@ +/* Any copyright is dedicated to the Public Domain. + http://creativecommons.org/publicdomain/zero/1.0/ */ + +"use strict"; + +const { ExtensionTestUtils } = ChromeUtils.import( + "resource://testing-common/ExtensionXPCShellUtils.jsm" +); +const { NetUtil } = require("resource://gre/modules/NetUtil.jsm"); +const { + getFileForBinary, +} = require("devtools/client/shared/remote-debugging/adb/adb-binary"); +const { + check, +} = require("devtools/client/shared/remote-debugging/adb/adb-running-checker"); +const { + adbProcess, +} = require("devtools/client/shared/remote-debugging/adb/adb-process"); +const { + TrackDevicesCommand, +} = require("devtools/client/shared/remote-debugging/adb/commands/index"); + +const ADB_JSON = { + Linux: { + x86: ["linux/adb"], + x86_64: ["linux64/adb"], + }, + Darwin: { + x86_64: ["mac64/adb"], + }, + WINNT: { + x86: ["win32/adb.exe", "win32/AdbWinApi.dll", "win32/AdbWinUsbApi.dll"], + x86_64: ["win32/adb.exe", "win32/AdbWinApi.dll", "win32/AdbWinUsbApi.dll"], + }, +}; +let extension_version = 1.0; + +ExtensionTestUtils.init(this); + +function readAdbMockContent() { + const adbMockFile = do_get_file("adb.py", false); + const s = Cc["@mozilla.org/network/file-input-stream;1"].createInstance( + Ci.nsIFileInputStream + ); + s.init(adbMockFile, -1, -1, false); + try { + return NetUtil.readInputStreamToString(s, s.available()); + } finally { + s.close(); + } +} + +const adbMock = readAdbMockContent(); + +add_task(async function setup() { + // Prepare the profile directory where the adb extension will be installed. + do_get_profile(); +}); + +add_task(async function testAdbIsNotRunningInitially() { + const isAdbRunning = await check(); + // Assume that no adb server running. + ok(!isAdbRunning, "adb is not running initially"); +}); + +add_task(async function testNoAdbExtension() { + const extension = ExtensionTestUtils.loadExtension({ + manifest: { + version: (extension_version++).toString(), + applications: { + gecko: { id: "not-adb@mozilla.org" }, + }, + }, + }); + + await extension.startup(); + + const adbBinary = await getFileForBinary(); + equal(adbBinary, null); + + await extension.unload(); +}); + +add_task(async function testNoAdbJSON() { + const extension = ExtensionTestUtils.loadExtension({ + manifest: { + version: (extension_version++).toString(), + applications: { + // The extension id here and in later test cases should match the + // corresponding prefrece value. + gecko: { id: "adb@mozilla.org" }, + }, + }, + }); + + await extension.startup(); + + const adbBinary = await getFileForBinary(); + equal(adbBinary, null); + + await extension.unload(); +}); + +add_task(async function testNoTargetBinaries() { + const extension = ExtensionTestUtils.loadExtension({ + manifest: { + version: (extension_version++).toString(), + applications: { + gecko: { id: "adb@mozilla.org" }, + }, + }, + files: { + "adb.json": JSON.stringify(ADB_JSON), + }, + }); + + await extension.startup(); + + const adbBinary = await getFileForBinary(); + equal(adbBinary, null); + + await extension.unload(); +}); + +add_task(async function testExtract() { + const extension = ExtensionTestUtils.loadExtension({ + manifest: { + version: (extension_version++).toString(), + applications: { + gecko: { id: "adb@mozilla.org" }, + }, + }, + files: { + "adb.json": JSON.stringify(ADB_JSON), + "linux/adb": "adb", + "linux64/adb": "adb", + "mac64/adb": "adb", + "win32/adb.exe": "adb.exe", + "win32/AdbWinApi.dll": "AdbWinApi.dll", + "win32/AdbWinUsbApi.dll": "AdbWinUsbApi.dll", + }, + }); + + await extension.startup(); + + const adbBinary = await getFileForBinary(); + ok(await adbBinary.exists()); + + await extension.unload(); +}); + +add_task( + { + skip_if: () => mozinfo.os == "win", // bug 1482008 + }, + async function testStartAndStop() { + const extension = ExtensionTestUtils.loadExtension({ + manifest: { + version: (extension_version++).toString(), + applications: { + gecko: { id: "adb@mozilla.org" }, + }, + }, + files: { + "adb.json": JSON.stringify(ADB_JSON), + "linux/adb": adbMock, + "linux64/adb": adbMock, + "mac64/adb": adbMock, + "win32/adb.exe": adbMock, + "win32/AdbWinApi.dll": "dummy", + "win32/AdbWinUsbApi.dll": "dummy", + }, + }); + + await extension.startup(); + + // Call start() once and call stop() afterwards. + await adbProcess.start(); + ok(adbProcess.ready); + ok(await check(), "adb is now running"); + + await adbProcess.stop(); + ok(!adbProcess.ready); + ok(!(await check()), "adb is no longer running"); + + // Call start() twice and call stop() afterwards. + await adbProcess.start(); + await adbProcess.start(); + ok(adbProcess.ready); + ok(await check(), "adb is now running"); + + await adbProcess.stop(); + ok(!adbProcess.ready); + ok(!(await check()), "adb is no longer running"); + + await extension.unload(); + } +); + +add_task( + { + skip_if: () => mozinfo.os == "win", // bug 1482008 + }, + async function testTrackDevices() { + const extension = ExtensionTestUtils.loadExtension({ + manifest: { + version: (extension_version++).toString(), + applications: { + gecko: { id: "adb@mozilla.org" }, + }, + }, + files: { + "adb.json": JSON.stringify(ADB_JSON), + "linux/adb": adbMock, + "linux64/adb": adbMock, + "mac64/adb": adbMock, + "win32/adb.exe": adbMock, + "win32/AdbWinApi.dll": "dummy", + "win32/AdbWinUsbApi.dll": "dummy", + }, + }); + + await extension.startup(); + + await adbProcess.start(); + ok(adbProcess.ready); + + ok(await check(), "adb is now running"); + + const receivedDeviceId = await new Promise(resolve => { + const trackDevicesCommand = new TrackDevicesCommand(); + trackDevicesCommand.on("device-connected", deviceId => { + resolve(deviceId); + }); + trackDevicesCommand.run(); + }); + + equal(receivedDeviceId, "1234567890"); + + await adbProcess.stop(); + ok(!adbProcess.ready); + + await extension.unload(); + } +); diff --git a/devtools/client/shared/remote-debugging/adb/xpcshell/test_prepare-tcp-connection.js b/devtools/client/shared/remote-debugging/adb/xpcshell/test_prepare-tcp-connection.js new file mode 100644 index 0000000000..c3f2b2f7e0 --- /dev/null +++ b/devtools/client/shared/remote-debugging/adb/xpcshell/test_prepare-tcp-connection.js @@ -0,0 +1,79 @@ +"use strict"; + +const DEVICE_ID = "FAKE_DEVICE_ID"; +const SOCKET_PATH = "fake/socket/path"; + +/** + * Test the prepare-tcp-connection command in isolation. + */ +add_task(async function testParseFileUri() { + info("Enable devtools.testing for this test to allow mocked modules"); + const Services = require("Services"); + Services.prefs.setBoolPref("devtools.testing", true); + registerCleanupFunction(() => { + Services.prefs.clearUserPref("devtools.testing"); + }); + + // Mocks are not supported for the regular DevTools loader. + info("Create a BrowserLoader to enable mocks in the test"); + const { BrowserLoader } = ChromeUtils.import( + "resource://devtools/client/shared/browser-loader.js" + ); + const mockedRequire = BrowserLoader({ + baseURI: "resource://devtools/client/shared/remote-debugging/adb", + window: {}, + }).require; + + // Prepare a mocked version of the run-command.js module to test + // prepare-tcp-connection in isolation. + info("Create a run-command module mock"); + let createdPort; + const mock = { + runCommand: command => { + // Check that we only receive the expected command and extract the port + // number. + + // The command should follow the pattern + // `host-serial:${deviceId}:forward:tcp:${localPort};${devicePort}` + // with devicePort = `localfilesystem:${socketPath}` + const socketPathRe = SOCKET_PATH.replace(/\//g, "\\/"); + const regexp = new RegExp( + `host-serial:${DEVICE_ID}:forward:tcp:(\\d+);localfilesystem:${socketPathRe}` + ); + const matches = regexp.exec(command); + equal(matches.length, 2, "The command is the expected"); + createdPort = matches[1]; + + // Finally return a Promise-like object. + return { + then: () => {}, + }; + }, + }; + + info("Enable the mocked run-command module"); + const { setMockedModule, removeMockedModule } = mockedRequire( + "devtools/client/shared/browser-loader-mocks" + ); + setMockedModule( + mock, + "devtools/client/shared/remote-debugging/adb/commands/run-command" + ); + registerCleanupFunction(() => { + removeMockedModule( + "devtools/client/shared/remote-debugging/adb/commands/run-command" + ); + }); + + const { prepareTCPConnection } = mockedRequire( + "devtools/client/shared/remote-debugging/adb/commands/prepare-tcp-connection" + ); + + const port = await prepareTCPConnection(DEVICE_ID, SOCKET_PATH); + ok(!Number.isNaN(port), "prepareTCPConnection returned a valid port"); + equal( + port, + Number(createdPort), + "prepareTCPConnection returned the port sent to the host-serial command" + ); +}); diff --git a/devtools/client/shared/remote-debugging/adb/xpcshell/xpcshell-head.js b/devtools/client/shared/remote-debugging/adb/xpcshell/xpcshell-head.js new file mode 100644 index 0000000000..93a0b0881f --- /dev/null +++ b/devtools/client/shared/remote-debugging/adb/xpcshell/xpcshell-head.js @@ -0,0 +1,8 @@ +/* Any copyright is dedicated to the Public Domain. + http://creativecommons.org/publicdomain/zero/1.0/ */ + +"use strict"; + +/* eslint no-unused-vars: [2, {"vars": "local"}] */ + +const { require } = ChromeUtils.import("resource://devtools/shared/Loader.jsm"); diff --git a/devtools/client/shared/remote-debugging/adb/xpcshell/xpcshell.ini b/devtools/client/shared/remote-debugging/adb/xpcshell/xpcshell.ini new file mode 100644 index 0000000000..d2b34c105a --- /dev/null +++ b/devtools/client/shared/remote-debugging/adb/xpcshell/xpcshell.ini @@ -0,0 +1,11 @@ +[DEFAULT] +tags = devtools +head = xpcshell-head.js +firefox-appdir = browser +skip-if = toolkit == 'android' || socketprocess_networking +support-files = + adb.py + +[test_adb.js] +run-sequentially = An extension having the same id is installed/uninstalled in different tests +[test_prepare-tcp-connection.js] |