diff --git a/tools/DEPS b/tools/DEPS
deleted file mode 100644
index dc04e3dfc6..0000000000
--- a/tools/DEPS
+++ /dev/null
@@ -1,6 +0,0 @@
-# checkdeps.py shouldn't check include paths for files in these dirs:
-skip_child_includes = [
- "clang",
- "gyp",
- "traceline",
-]
diff --git a/tools/OWNERS b/tools/OWNERS
deleted file mode 100644
index 4cd808f040..0000000000
--- a/tools/OWNERS
+++ /dev/null
@@ -1,3 +0,0 @@
-*
-
-per-file bisect-builds.py=rsesek@chromium.org
diff --git a/tools/PRESUBMIT.py b/tools/PRESUBMIT.py
deleted file mode 100644
index 01572314c0..0000000000
--- a/tools/PRESUBMIT.py
+++ /dev/null
@@ -1,48 +0,0 @@
-# Copyright (c) 2013 The Chromium Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-"""Top-level presubmit script for bisect trybot.
-
-See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts for
-details on the presubmit API built into gcl.
-"""
-
-import imp
-
-def _ExamineBisectConfigFile(input_api, output_api):
- for f in input_api.AffectedFiles():
- if not f.LocalPath().endswith('run-bisect-perf-regression.cfg'):
- continue
-
- try:
- cfg_file = imp.load_source('config', 'run-bisect-perf-regression.cfg')
-
- for k, v in cfg_file.config.iteritems():
- if v:
- return f.LocalPath()
- except (IOError, AttributeError, TypeError):
- return f.LocalPath()
-
- return None
-
-def _CheckNoChangesToBisectConfigFile(input_api, output_api):
- results = _ExamineBisectConfigFile(input_api, output_api)
- if results:
- return [output_api.PresubmitError(
- 'The bisection config file should only contain a config dict with '
- 'empty fields. Changes to this file should never be submitted.',
- items=[results])]
-
- return []
-
-def CommonChecks(input_api, output_api):
- results = []
- results.extend(_CheckNoChangesToBisectConfigFile(input_api, output_api))
- return results
-
-def CheckChangeOnUpload(input_api, output_api):
- return CommonChecks(input_api, output_api)
-
-def CheckChangeOnCommit(input_api, output_api):
- return CommonChecks(input_api, output_api)
diff --git a/tools/android/OWNERS b/tools/android/OWNERS
deleted file mode 100644
index e911c595c5..0000000000
--- a/tools/android/OWNERS
+++ /dev/null
@@ -1,6 +0,0 @@
-bulach@chromium.org
-digit@chromium.org
-michaelbai@chromium.org
-pliard@chromium.org
-wangxianzhu@chromium.org
-yfriedman@chromium.org
diff --git a/tools/android/adb_reboot/adb_reboot.c b/tools/android/adb_reboot/adb_reboot.c
deleted file mode 100644
index 48c5cbe58f..0000000000
--- a/tools/android/adb_reboot/adb_reboot.c
+++ /dev/null
@@ -1,43 +0,0 @@
-// Copyright (c) 2013 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include
-#include
-#include
-#include
-#include
-#include
-
-int main(int argc, char ** argv) {
- int i = fork();
- struct stat ft;
- time_t ct;
-
- if (i < 0) {
- printf("fork error");
- return 1;
- }
- if (i > 0)
- return 0;
-
- /* child (daemon) continues */
- int j;
- for (j = 0; j < getdtablesize(); j++)
- close(j);
-
- setsid(); /* obtain a new process group */
-
- while (1) {
- sleep(120);
-
- stat("/sdcard/host_heartbeat", &ft);
- time(&ct);
- if (ct - ft.st_mtime > 120) {
- /* File was not touched for some time. */
- system("su -c reboot");
- }
- }
-
- return 0;
-}
diff --git a/tools/android/adb_reboot/adb_reboot.gyp b/tools/android/adb_reboot/adb_reboot.gyp
deleted file mode 100644
index 85134b9906..0000000000
--- a/tools/android/adb_reboot/adb_reboot.gyp
+++ /dev/null
@@ -1,14 +0,0 @@
-# Copyright (c) 2013 The Chromium Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-{
- 'targets': [
- {
- 'target_name': 'adb_reboot',
- 'type': 'executable',
- 'sources': [
- 'adb_reboot.c',
- ],
- },
- ],
-}
diff --git a/tools/android/android_tools.gyp b/tools/android/android_tools.gyp
deleted file mode 100644
index c38cd70d58..0000000000
--- a/tools/android/android_tools.gyp
+++ /dev/null
@@ -1,27 +0,0 @@
-# Copyright (c) 2012 The Chromium Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-{
- 'targets': [
- # Intermediate target grouping the android tools needed to run native
- # unittests and instrumentation test apks.
- {
- 'target_name': 'android_tools',
- 'type': 'none',
- 'dependencies': [
- 'fake_dns/fake_dns.gyp:fake_dns',
- 'forwarder2/forwarder.gyp:forwarder2',
- 'md5sum/md5sum.gyp:md5sum',
- 'adb_reboot/adb_reboot.gyp:adb_reboot',
- ],
- },
- {
- 'target_name': 'memdump',
- 'type': 'none',
- 'dependencies': [
- 'memdump/memdump.gyp:memdump',
- ],
- }
- ],
-}
diff --git a/tools/android/asan/asanwrapper.sh b/tools/android/asan/asanwrapper.sh
deleted file mode 100755
index 2392d2ca44..0000000000
--- a/tools/android/asan/asanwrapper.sh
+++ /dev/null
@@ -1,9 +0,0 @@
-#!/system/bin/sh
-# Copyright (c) 2012 The Chromium Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-ASAN_OPTIONS=debug=1,verbosity=1,strict_memcmp=0 \
-LD_LIBRARY_PATH=/data/local/tmp/asan:$LD_LIBRARY_PATH \
-LD_PRELOAD=libclang_rt.asan-arm-android.so \
-exec $@
diff --git a/tools/android/common/adb_connection.cc b/tools/android/common/adb_connection.cc
deleted file mode 100644
index 91c25fed20..0000000000
--- a/tools/android/common/adb_connection.cc
+++ /dev/null
@@ -1,107 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "tools/android/common/adb_connection.h"
-
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-
-#include "base/logging.h"
-#include "base/posix/eintr_wrapper.h"
-#include "tools/android/common/net.h"
-
-namespace tools {
-namespace {
-
-void CloseSocket(int fd) {
- if (fd >= 0) {
- int old_errno = errno;
- (void) HANDLE_EINTR(close(fd));
- errno = old_errno;
- }
-}
-
-} // namespace
-
-int ConnectAdbHostSocket(const char* forward_to) {
- // ADB port forward request format: HHHHtcp:port:address.
- // HHHH is the hexidecimal length of the "tcp:port:address" part.
- const size_t kBufferMaxLength = 30;
- const size_t kLengthOfLength = 4;
- const size_t kAddressMaxLength = kBufferMaxLength - kLengthOfLength;
-
- const char kAddressPrefix[] = { 't', 'c', 'p', ':' };
- size_t address_length = arraysize(kAddressPrefix) + strlen(forward_to);
- if (address_length > kBufferMaxLength - kLengthOfLength) {
- LOG(ERROR) << "Forward to address is too long: " << forward_to;
- return -1;
- }
-
- char request[kBufferMaxLength];
- memcpy(request + kLengthOfLength, kAddressPrefix, arraysize(kAddressPrefix));
- memcpy(request + kLengthOfLength + arraysize(kAddressPrefix),
- forward_to, strlen(forward_to));
-
- char length_buffer[kLengthOfLength + 1];
- snprintf(length_buffer, arraysize(length_buffer), "%04X",
- static_cast(address_length));
- memcpy(request, length_buffer, kLengthOfLength);
-
- int host_socket = socket(AF_INET, SOCK_STREAM, 0);
- if (host_socket < 0) {
- LOG(ERROR) << "Failed to create adb socket: " << strerror(errno);
- return -1;
- }
-
- DisableNagle(host_socket);
-
- const int kAdbPort = 5037;
- sockaddr_in addr;
- memset(&addr, 0, sizeof(addr));
- addr.sin_family = AF_INET;
- addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
- addr.sin_port = htons(kAdbPort);
- if (HANDLE_EINTR(connect(host_socket, reinterpret_cast(&addr),
- sizeof(addr))) < 0) {
- LOG(ERROR) << "Failed to connect adb socket: " << strerror(errno);
- CloseSocket(host_socket);
- return -1;
- }
-
- size_t bytes_remaining = address_length + kLengthOfLength;
- size_t bytes_sent = 0;
- while (bytes_remaining > 0) {
- int ret = HANDLE_EINTR(send(host_socket, request + bytes_sent,
- bytes_remaining, 0));
- if (ret < 0) {
- LOG(ERROR) << "Failed to send request: " << strerror(errno);
- CloseSocket(host_socket);
- return -1;
- }
-
- bytes_sent += ret;
- bytes_remaining -= ret;
- }
-
- const size_t kAdbStatusLength = 4;
- char response[kBufferMaxLength];
- int response_length = HANDLE_EINTR(recv(host_socket, response,
- kBufferMaxLength, 0));
- if (response_length < kAdbStatusLength ||
- strncmp("OKAY", response, kAdbStatusLength) != 0) {
- LOG(ERROR) << "Bad response from ADB: length: " << response_length
- << " data: " << DumpBinary(response, response_length);
- CloseSocket(host_socket);
- return -1;
- }
-
- return host_socket;
-}
-
-} // namespace tools
diff --git a/tools/android/common/adb_connection.h b/tools/android/common/adb_connection.h
deleted file mode 100644
index 3fa0fb396f..0000000000
--- a/tools/android/common/adb_connection.h
+++ /dev/null
@@ -1,18 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef TOOLS_ANDROID_COMMON_ADB_CONNECTION_H_
-#define TOOLS_ANDROID_COMMON_ADB_CONNECTION_H_
-
-namespace tools {
-
-// Creates a socket that can forward to a host socket through ADB.
-// The format of forward_to is :.
-// Returns the socket handle, or -1 on any error.
-int ConnectAdbHostSocket(const char* forward_to);
-
-} // namespace tools
-
-#endif // TOOLS_ANDROID_COMMON_ADB_CONNECTION_H_
-
diff --git a/tools/android/common/common.gyp b/tools/android/common/common.gyp
deleted file mode 100644
index 8622625844..0000000000
--- a/tools/android/common/common.gyp
+++ /dev/null
@@ -1,26 +0,0 @@
-# Copyright (c) 2012 The Chromium Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-{
- 'targets': [
- {
- 'target_name': 'android_tools_common',
- 'type': 'static_library',
- 'toolsets': ['host', 'target'],
- 'include_dirs': [
- '..',
- '../../..',
- ],
- 'sources': [
- 'adb_connection.cc',
- 'adb_connection.h',
- 'daemon.cc',
- 'daemon.h',
- 'net.cc',
- 'net.h',
- ],
- },
- ],
-}
-
diff --git a/tools/android/common/daemon.cc b/tools/android/common/daemon.cc
deleted file mode 100644
index 9eafdbce05..0000000000
--- a/tools/android/common/daemon.cc
+++ /dev/null
@@ -1,75 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "tools/android/common/daemon.h"
-
-#include
-#include
-#include
-#include
-
-#include "base/command_line.h"
-#include "base/logging.h"
-#include "base/posix/eintr_wrapper.h"
-
-namespace {
-
-const char kNoSpawnDaemon[] = "D";
-
-int g_exit_status = 0;
-
-void Exit(int unused) {
- _exit(g_exit_status);
-}
-
-void CloseFileDescriptor(int fd) {
- int old_errno = errno;
- (void) HANDLE_EINTR(close(fd));
- errno = old_errno;
-}
-
-} // namespace
-
-namespace tools {
-
-bool HasHelpSwitch(const CommandLine& command_line) {
- return command_line.HasSwitch("h") || command_line.HasSwitch("help");
-}
-
-bool HasNoSpawnDaemonSwitch(const CommandLine& command_line) {
- return command_line.HasSwitch(kNoSpawnDaemon);
-}
-
-void ShowHelp(const char* program,
- const char* extra_title,
- const char* extra_descriptions) {
- printf("Usage: %s [-%s] %s\n"
- " -%s stops from spawning a daemon process\n%s",
- program, kNoSpawnDaemon, extra_title, kNoSpawnDaemon,
- extra_descriptions);
-}
-
-void SpawnDaemon(int exit_status) {
- g_exit_status = exit_status;
- signal(SIGUSR1, Exit);
-
- if (fork()) {
- // In parent process.
- sleep(10); // Wait for the child process to finish setsid().
- NOTREACHED();
- }
-
- // In child process.
- setsid(); // Detach the child process from its parent.
- kill(getppid(), SIGUSR1); // Inform the parent process to exit.
-
- // Close the standard input and outputs, otherwise the process may block
- // adbd when the shell exits.
- // Comment out these lines if you want to see outputs for debugging.
- CloseFileDescriptor(0);
- CloseFileDescriptor(1);
- CloseFileDescriptor(2);
-}
-
-} // namespace tools
diff --git a/tools/android/common/daemon.h b/tools/android/common/daemon.h
deleted file mode 100644
index 0c1640107d..0000000000
--- a/tools/android/common/daemon.h
+++ /dev/null
@@ -1,28 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef TOOLS_ANDROID_COMMON_DAEMON_H_
-#define TOOLS_ANDROID_COMMON_DAEMON_H_
-
-class CommandLine;
-
-namespace tools {
-
-bool HasHelpSwitch(const CommandLine& command_line);
-
-bool HasNoSpawnDaemonSwitch(const CommandLine& command_line);
-
-void ShowHelp(const char* program,
- const char* extra_title,
- const char* extra_descriptions);
-
-// Spawns a daemon process and exits the current process with exit_status.
-// Any code executed after this function returns will be executed in the
-// spawned daemon process.
-void SpawnDaemon(int exit_status);
-
-} // namespace tools
-
-#endif // TOOLS_ANDROID_COMMON_DAEMON_H_
-
diff --git a/tools/android/common/net.cc b/tools/android/common/net.cc
deleted file mode 100644
index 3b9ef15bc3..0000000000
--- a/tools/android/common/net.cc
+++ /dev/null
@@ -1,40 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "tools/android/common/net.h"
-
-#include
-#include
-#include
-#include
-
-#include "base/strings/stringprintf.h"
-
-namespace tools {
-
-int DisableNagle(int socket) {
- int on = 1;
- return setsockopt(socket, IPPROTO_TCP, TCP_NODELAY, &on, sizeof(on));
-}
-
-int DeferAccept(int socket) {
- int on = 1;
- return setsockopt(socket, IPPROTO_TCP, TCP_DEFER_ACCEPT, &on, sizeof(on));
-}
-
-std::string DumpBinary(const char* buffer, size_t length) {
- std::string result = "[";
- for (int i = 0; i < length; ++i) {
- base::StringAppendF(&result, "%02x,",
- static_cast(buffer[i]));
- }
-
- if (length)
- result.erase(result.length() - 1);
-
- return result + "]";
-}
-
-} // namespace tools
-
diff --git a/tools/android/common/net.h b/tools/android/common/net.h
deleted file mode 100644
index e3619548ab..0000000000
--- a/tools/android/common/net.h
+++ /dev/null
@@ -1,25 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef TOOLS_ANDROID_COMMON_NET_H_
-#define TOOLS_ANDROID_COMMON_NET_H_
-
-#include
-
-namespace tools {
-
-// DisableNagle can improve TCP transmission performance. Both Chrome net stack
-// and adb tool use it.
-int DisableNagle(int socket);
-
-// Wake up listener only when data arrive.
-int DeferAccept(int socket);
-
-// Dumps a binary buffer into a string in a human-readable format.
-std::string DumpBinary(const char* buffer, size_t length);
-
-} // namespace tools
-
-#endif // TOOLS_ANDROID_COMMON_NET_H_
-
diff --git a/tools/android/device_stats_monitor/device_stats_monitor.cc b/tools/android/device_stats_monitor/device_stats_monitor.cc
deleted file mode 100644
index 6388cdaf43..0000000000
--- a/tools/android/device_stats_monitor/device_stats_monitor.cc
+++ /dev/null
@@ -1,108 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-// Dumps CPU and IO stats to a file at a regular interval.
-//
-// Output may be post processed by host to get top/iotop style information.
-
-#include
-#include
-
-#include
-#include
-#include
-
-#include "base/command_line.h"
-#include "base/file_util.h"
-#include "base/strings/string_split.h"
-
-namespace {
-
-const char kIOStatsPath[] = "/proc/diskstats";
-const char kCPUStatsPath[] = "/proc/stat";
-
-class DeviceStatsMonitor {
- public:
- explicit DeviceStatsMonitor(const std::string& out_path)
- : out_path_(out_path),
- record_(true) {
- CHECK(!out_path_.empty());
- samples_.reserve(1024 * 1024);
- }
-
- // Records stats continuously at |hz| cycles per second util
- // StopRecordingAndDumpStats() is called.
- //
- // Yes, this buffers everything in memory, so it cannot be used for extended
- // durations without OOM. But that beats writing during the trace which
- // would affect the results.
- void Start(int hz) {
- const int sample_interval = 1000000 / hz;
- const base::FilePath io_stats_path(kIOStatsPath);
- const base::FilePath cpu_stats_path(kCPUStatsPath);
- std::string out;
- while (record_) {
- out.clear();
- CHECK(file_util::ReadFileToString(io_stats_path, &out));
- CHECK(file_util::ReadFileToString(cpu_stats_path, &out));
- samples_.push_back(out);
- usleep(sample_interval);
- }
- }
-
- // Stops recording and saves samples to file.
- void StopAndDumpStats() {
- record_ = false;
- usleep(250 * 1000);
- std::ofstream out_stream;
- out_stream.open(out_path_.value().c_str(), std::ios::out);
- for (std::vector::const_iterator i = samples_.begin();
- i != samples_.end(); ++i) {
- out_stream << i->c_str() << std::endl;
- }
- out_stream.close();
- }
-
- private:
- const base::FilePath out_path_;
- std::vector samples_;
- bool record_;
-
- DISALLOW_COPY_AND_ASSIGN(DeviceStatsMonitor);
-};
-
-DeviceStatsMonitor* g_device_stats_monitor = NULL;
-
-void SigTermHandler(int unused) {
- printf("Stopping device stats monitor\n");
- g_device_stats_monitor->StopAndDumpStats();
-}
-
-} // namespace
-
-int main(int argc, char** argv) {
- const int kDefaultHz = 20;
-
- CommandLine command_line(argc, argv);
- CommandLine::StringVector args = command_line.GetArgs();
- if (command_line.HasSwitch("h") || command_line.HasSwitch("help") ||
- args.size() != 1) {
- printf("Usage: %s OUTPUT_FILE\n"
- " --hz=HZ Number of samples/second. default=%d\n",
- argv[0], kDefaultHz);
- return 1;
- }
-
- int hz = command_line.HasSwitch("hz") ?
- atoi(command_line.GetSwitchValueNative("hz").c_str()) :
- kDefaultHz;
-
- printf("Starting device stats monitor\n");
- g_device_stats_monitor = new DeviceStatsMonitor(args[0]);
- signal(SIGTERM, SigTermHandler);
- g_device_stats_monitor->Start(hz);
- delete g_device_stats_monitor;
-
- return 0;
-}
diff --git a/tools/android/device_stats_monitor/device_stats_monitor.gyp b/tools/android/device_stats_monitor/device_stats_monitor.gyp
deleted file mode 100644
index f9bd9e8e4b..0000000000
--- a/tools/android/device_stats_monitor/device_stats_monitor.gyp
+++ /dev/null
@@ -1,41 +0,0 @@
-# Copyright (c) 2012 The Chromium Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-{
- 'targets': [
- {
- 'target_name': 'device_stats_monitor',
- 'type': 'none',
- 'dependencies': [
- 'device_stats_monitor_symbols',
- ],
- 'actions': [
- {
- 'action_name': 'strip_device_stats_monitor',
- 'inputs': ['<(PRODUCT_DIR)/device_stats_monitor_symbols'],
- 'outputs': ['<(PRODUCT_DIR)/device_stats_monitor'],
- 'action': [
- '<(android_strip)',
- '--strip-unneeded',
- '<@(_inputs)',
- '-o',
- '<@(_outputs)',
- ],
- },
- ],
- }, {
- 'target_name': 'device_stats_monitor_symbols',
- 'type': 'executable',
- 'dependencies': [
- '../../../base/base.gyp:base',
- ],
- 'include_dirs': [
- '../../..',
- ],
- 'sources': [
- 'device_stats_monitor.cc',
- ],
- },
- ],
-}
diff --git a/tools/android/fake_dns/DEPS b/tools/android/fake_dns/DEPS
deleted file mode 100644
index 8fa9d48d88..0000000000
--- a/tools/android/fake_dns/DEPS
+++ /dev/null
@@ -1,3 +0,0 @@
-include_rules = [
- "+net",
-]
diff --git a/tools/android/fake_dns/fake_dns.cc b/tools/android/fake_dns/fake_dns.cc
deleted file mode 100644
index 9a055bfd37..0000000000
--- a/tools/android/fake_dns/fake_dns.cc
+++ /dev/null
@@ -1,238 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-
-#include
-
-#include "base/basictypes.h"
-#include "base/command_line.h"
-#include "base/logging.h"
-#include "base/posix/eintr_wrapper.h"
-#include "base/safe_strerror_posix.h"
-#include "net/base/big_endian.h"
-#include "net/base/net_util.h"
-#include "net/dns/dns_protocol.h"
-#include "tools/android/common/daemon.h"
-#include "tools/android/common/net.h"
-
-namespace {
-
-// Mininum request size: 1 question containing 1 QNAME, 1 TYPE and 1 CLASS.
-const size_t kMinRequestSize = sizeof(net::dns_protocol::Header) + 6;
-
-// The name reference in the answer pointing to the name in the query.
-// Its format is: highest two bits set to 1, then the offset of the name
-// which just follows the header.
-const uint16 kPointerToQueryName =
- static_cast(0xc000 | sizeof(net::dns_protocol::Header));
-
-const uint32 kTTL = 86400; // One day.
-
-void PError(const char* msg) {
- int current_errno = errno;
- LOG(ERROR) << "ERROR: " << msg << ": " << safe_strerror(current_errno);
-}
-
-void SendTo(int sockfd, const void* buf, size_t len, int flags,
- const sockaddr* dest_addr, socklen_t addrlen) {
- if (HANDLE_EINTR(sendto(sockfd, buf, len, flags, dest_addr, addrlen)) == -1)
- PError("sendto()");
-}
-
-void CloseFileDescriptor(int fd) {
- int old_errno = errno;
- (void) HANDLE_EINTR(close(fd));
- errno = old_errno;
-}
-
-void SendRefusedResponse(int sock, const sockaddr_in& client_addr, uint16 id) {
- net::dns_protocol::Header response;
- response.id = htons(id);
- response.flags = htons(net::dns_protocol::kFlagResponse |
- net::dns_protocol::kFlagAA |
- net::dns_protocol::kFlagRD |
- net::dns_protocol::kFlagRA |
- net::dns_protocol::kRcodeREFUSED);
- response.qdcount = 0;
- response.ancount = 0;
- response.nscount = 0;
- response.arcount = 0;
- SendTo(sock, &response, sizeof(response), 0,
- reinterpret_cast(&client_addr), sizeof(client_addr));
-}
-
-void SendResponse(int sock, const sockaddr_in& client_addr, uint16 id,
- uint16 qtype, const char* question, size_t question_length) {
- net::dns_protocol::Header header;
- header.id = htons(id);
- header.flags = htons(net::dns_protocol::kFlagResponse |
- net::dns_protocol::kFlagAA |
- net::dns_protocol::kFlagRD |
- net::dns_protocol::kFlagRA |
- net::dns_protocol::kRcodeNOERROR);
- header.qdcount = htons(1);
- header.ancount = htons(1);
- header.nscount = 0;
- header.arcount = 0;
-
- // Size of RDATA which is a IPv4 or IPv6 address.
- size_t rdata_size = qtype == net::dns_protocol::kTypeA ?
- net::kIPv4AddressSize : net::kIPv6AddressSize;
-
- // Size of the whole response which contains the header, the question and
- // the answer. 12 is the sum of sizes of the compressed name reference, TYPE,
- // CLASS, TTL and RDLENGTH.
- size_t response_size = sizeof(header) + question_length + 12 + rdata_size;
-
- if (response_size > net::dns_protocol::kMaxUDPSize) {
- LOG(ERROR) << "Response is too large: " << response_size;
- SendRefusedResponse(sock, client_addr, id);
- return;
- }
-
- char response[net::dns_protocol::kMaxUDPSize];
- net::BigEndianWriter writer(response, arraysize(response));
- writer.WriteBytes(&header, sizeof(header));
-
- // Repeat the question in the response. Some clients (e.g. ping) needs this.
- writer.WriteBytes(question, question_length);
-
- // Construct the answer.
- writer.WriteU16(kPointerToQueryName);
- writer.WriteU16(qtype);
- writer.WriteU16(net::dns_protocol::kClassIN);
- writer.WriteU32(kTTL);
- writer.WriteU16(rdata_size);
- if (qtype == net::dns_protocol::kTypeA)
- writer.WriteU32(INADDR_LOOPBACK);
- else
- writer.WriteBytes(&in6addr_loopback, sizeof(in6_addr));
- DCHECK(writer.ptr() - response == response_size);
-
- SendTo(sock, response, response_size, 0,
- reinterpret_cast(&client_addr), sizeof(client_addr));
-}
-
-void HandleRequest(int sock, const char* request, size_t size,
- const sockaddr_in& client_addr) {
- if (size < kMinRequestSize) {
- LOG(ERROR) << "Request is too small " << size
- << "\n" << tools::DumpBinary(request, size);
- return;
- }
-
- net::BigEndianReader reader(request, size);
- net::dns_protocol::Header header;
- reader.ReadBytes(&header, sizeof(header));
- uint16 id = ntohs(header.id);
- uint16 flags = ntohs(header.flags);
- uint16 qdcount = ntohs(header.qdcount);
- uint16 ancount = ntohs(header.ancount);
- uint16 nscount = ntohs(header.nscount);
- uint16 arcount = ntohs(header.arcount);
-
- const uint16 kAllowedFlags = 0x07ff;
- if ((flags & ~kAllowedFlags) ||
- qdcount != 1 || ancount || nscount || arcount) {
- LOG(ERROR) << "Unsupported request: FLAGS=" << flags
- << " QDCOUNT=" << qdcount
- << " ANCOUNT=" << ancount
- << " NSCOUNT=" << nscount
- << " ARCOUNT=" << arcount
- << "\n" << tools::DumpBinary(request, size);
- SendRefusedResponse(sock, client_addr, id);
- return;
- }
-
- // request[size - 5] should be the end of the QNAME (a zero byte).
- // We don't care about the validity of QNAME because we don't parse it.
- const char* qname_end = &request[size - 5];
- if (*qname_end) {
- LOG(ERROR) << "Error parsing QNAME\n" << tools::DumpBinary(request, size);
- SendRefusedResponse(sock, client_addr, id);
- return;
- }
-
- reader.Skip(qname_end - reader.ptr() + 1);
-
- uint16 qtype;
- uint16 qclass;
- reader.ReadU16(&qtype);
- reader.ReadU16(&qclass);
- if ((qtype != net::dns_protocol::kTypeA &&
- qtype != net::dns_protocol::kTypeAAAA) ||
- qclass != net::dns_protocol::kClassIN) {
- LOG(ERROR) << "Unsupported query: QTYPE=" << qtype << " QCLASS=" << qclass
- << "\n" << tools::DumpBinary(request, size);
- SendRefusedResponse(sock, client_addr, id);
- return;
- }
-
- SendResponse(sock, client_addr, id, qtype,
- request + sizeof(header), size - sizeof(header));
-}
-
-} // namespace
-
-int main(int argc, char** argv) {
- printf("Fake DNS server\n");
-
- CommandLine command_line(argc, argv);
- if (tools::HasHelpSwitch(command_line) || command_line.GetArgs().size()) {
- tools::ShowHelp(argv[0], "", "");
- return 0;
- }
-
- int sock = socket(AF_INET, SOCK_DGRAM, 0);
- if (sock < 0) {
- PError("create socket");
- return 1;
- }
-
- sockaddr_in addr;
- memset(&addr, 0, sizeof(addr));
- addr.sin_family = AF_INET;
- addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
- addr.sin_port = htons(53);
- int reuse_addr = 1;
- if (HANDLE_EINTR(bind(sock, reinterpret_cast(&addr),
- sizeof(addr))) < 0) {
- PError("server bind");
- CloseFileDescriptor(sock);
- return 1;
- }
-
- if (!tools::HasNoSpawnDaemonSwitch(command_line))
- tools::SpawnDaemon(0);
-
- while (true) {
- sockaddr_in client_addr;
- socklen_t client_addr_len = sizeof(client_addr);
- char request[net::dns_protocol::kMaxUDPSize];
- int size = HANDLE_EINTR(recvfrom(sock, request, sizeof(request),
- MSG_WAITALL,
- reinterpret_cast(&client_addr),
- &client_addr_len));
- if (size < 0) {
- // Unrecoverable error, can only exit.
- LOG(ERROR) << "Failed to receive a request: " << strerror(errno);
- CloseFileDescriptor(sock);
- return 1;
- }
-
- if (size > 0)
- HandleRequest(sock, request, size, client_addr);
- }
-}
-
diff --git a/tools/android/fake_dns/fake_dns.gyp b/tools/android/fake_dns/fake_dns.gyp
deleted file mode 100644
index 0edacfadf0..0000000000
--- a/tools/android/fake_dns/fake_dns.gyp
+++ /dev/null
@@ -1,44 +0,0 @@
-# Copyright (c) 2012 The Chromium Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-{
- 'targets': [
- {
- 'target_name': 'fake_dns',
- 'type': 'none',
- 'dependencies': [
- 'fake_dns_symbols',
- ],
- 'actions': [
- {
- 'action_name': 'strip_fake_dns',
- 'inputs': ['<(PRODUCT_DIR)/fake_dns_symbols'],
- 'outputs': ['<(PRODUCT_DIR)/fake_dns'],
- 'action': [
- '<(android_strip)',
- '--strip-unneeded',
- '<@(_inputs)',
- '-o',
- '<@(_outputs)',
- ],
- },
- ],
- }, {
- 'target_name': 'fake_dns_symbols',
- 'type': 'executable',
- 'dependencies': [
- '../../../base/base.gyp:base',
- '../../../net/net.gyp:net',
- '../common/common.gyp:android_tools_common',
- ],
- 'include_dirs': [
- '../../..',
- ],
- 'sources': [
- 'fake_dns.cc',
- ],
- },
- ],
-}
-
diff --git a/tools/android/find_unused_resources.py b/tools/android/find_unused_resources.py
deleted file mode 100755
index da86e73415..0000000000
--- a/tools/android/find_unused_resources.py
+++ /dev/null
@@ -1,126 +0,0 @@
-#!/usr/bin/python
-# Copyright (c) 2013 The Chromium Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-"""Lists unused Java strings and other resources."""
-
-import optparse
-import re
-import subprocess
-import sys
-
-
-def GetApkResources(apk_path):
- """Returns the types and names of resources packaged in an APK.
-
- Args:
- apk_path: path to the APK.
-
- Returns:
- The resources in the APK as a list of tuples (type, name). Example:
- [('drawable', 'arrow'), ('layout', 'month_picker'), ...]
- """
- p = subprocess.Popen(
- ['aapt', 'dump', 'resources', apk_path],
- stdout=subprocess.PIPE)
- dump_out, _ = p.communicate()
- assert p.returncode == 0, 'aapt dump failed'
- matches = re.finditer(
- r'^\s+spec resource 0x[0-9a-fA-F]+ [\w.]+:(?P\w+)/(?P\w+)',
- dump_out, re.MULTILINE)
- return [m.group('type', 'name') for m in matches]
-
-
-def GetUsedResources(source_paths, resource_types):
- """Returns the types and names of resources used in Java or resource files.
-
- Args:
- source_paths: a list of files or folders collectively containing all the
- Java files, resource files, and the AndroidManifest.xml.
- resource_types: a list of resource types to look for. Example:
- ['string', 'drawable']
-
- Returns:
- The resources referenced by the Java and resource files as a list of tuples
- (type, name). Example:
- [('drawable', 'app_icon'), ('layout', 'month_picker'), ...]
- """
- type_regex = '|'.join(map(re.escape, resource_types))
- patterns = [r'@(())(%s)/(\w+)' % type_regex,
- r'\b((\w+\.)*)R\.(%s)\.(\w+)' % type_regex]
- resources = []
- for pattern in patterns:
- p = subprocess.Popen(
- ['grep', '-REIhoe', pattern] + source_paths,
- stdout=subprocess.PIPE)
- grep_out, grep_err = p.communicate()
- # Check stderr instead of return code, since return code is 1 when no
- # matches are found.
- assert not grep_err, 'grep failed'
- matches = re.finditer(pattern, grep_out)
- for match in matches:
- package = match.group(1)
- if package == 'android.':
- continue
- type_ = match.group(3)
- name = match.group(4)
- resources.append((type_, name))
- return resources
-
-
-def FormatResources(resources):
- """Formats a list of resources for printing.
-
- Args:
- resources: a list of resources, given as (type, name) tuples.
- """
- return '\n'.join(['%-12s %s' % (t, n) for t, n in sorted(resources)])
-
-
-def ParseArgs(args):
- usage = 'usage: %prog [-v] APK_PATH SOURCE_PATH...'
- parser = optparse.OptionParser(usage=usage)
- parser.add_option('-v', help='Show verbose output', action='store_true')
- options, args = parser.parse_args(args=args)
- if len(args) < 2:
- parser.error('must provide APK_PATH and SOURCE_PATH arguments')
- return options.v, args[0], args[1:]
-
-
-def main(args=None):
- verbose, apk_path, source_paths = ParseArgs(args)
- apk_resources = GetApkResources(apk_path)
- resource_types = list(set([r[0] for r in apk_resources]))
- used_resources = GetUsedResources(source_paths, resource_types)
- unused_resources = set(apk_resources) - set(used_resources)
- undefined_resources = set(used_resources) - set(apk_resources)
-
- # aapt dump fails silently. Notify the user if things look wrong.
- if not apk_resources:
- print >> sys.stderr, (
- 'Warning: No resources found in the APK. Did you provide the correct '
- 'APK path?')
- if not used_resources:
- print >> sys.stderr, (
- 'Warning: No resources references from Java or resource files. Did you '
- 'provide the correct source paths?')
- if undefined_resources:
- print >> sys.stderr, (
- 'Warning: found %d "undefined" resources that are referenced by Java '
- 'files or by other resources, but are not in the APK. Run with -v to '
- 'see them.' % len(undefined_resources))
-
- if verbose:
- print '%d undefined resources:' % len(undefined_resources)
- print FormatResources(undefined_resources), '\n'
- print '%d resources packaged into the APK:' % len(apk_resources)
- print FormatResources(apk_resources), '\n'
- print '%d used resources:' % len(used_resources)
- print FormatResources(used_resources), '\n'
- print '%d unused resources:' % len(unused_resources)
- print FormatResources(unused_resources)
-
-
-if __name__ == '__main__':
- main()
diff --git a/tools/android/findbugs_plugin/README b/tools/android/findbugs_plugin/README
deleted file mode 100644
index 3ba3f53085..0000000000
--- a/tools/android/findbugs_plugin/README
+++ /dev/null
@@ -1,15 +0,0 @@
-This is the FindBugs plugin for chrome on android.
-
-Currently it detects:
-- synchronized method
-- synchronized 'this'
-
-We don't want the synchronized method and synchronized 'this' to be
-used, the exception is the synchronized method defined in Android
-API.
-
-The plugin jar file was prebuilt and checked in, to rebuild the
-plugin, you need ant, and run below command, the new jar file will
-be in lib directory.
-
-ant install
diff --git a/tools/android/findbugs_plugin/build.xml b/tools/android/findbugs_plugin/build.xml
deleted file mode 100644
index 09ee13c41f..0000000000
--- a/tools/android/findbugs_plugin/build.xml
+++ /dev/null
@@ -1,48 +0,0 @@
-
-
-
-
-
-
- Build findbugs_plugin for Chromium Android
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/tools/android/findbugs_plugin/findbugs.xml b/tools/android/findbugs_plugin/findbugs.xml
deleted file mode 100644
index 43b1f3417d..0000000000
--- a/tools/android/findbugs_plugin/findbugs.xml
+++ /dev/null
@@ -1,18 +0,0 @@
-
-
-
-
-
-
-
-
-
-
diff --git a/tools/android/findbugs_plugin/findbugs_plugin.gyp b/tools/android/findbugs_plugin/findbugs_plugin.gyp
deleted file mode 100644
index 16d06e6c25..0000000000
--- a/tools/android/findbugs_plugin/findbugs_plugin.gyp
+++ /dev/null
@@ -1,16 +0,0 @@
-# Copyright (c) 2012 The Chromium Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-{
- 'targets': [
- {
- 'target_name': 'findbugs_plugin_test',
- 'type': 'none',
- 'variables': {
- 'java_in_dir': 'test/java/',
- },
- 'includes': [ '../../../build/java.gypi' ],
- }
- ]
-}
diff --git a/tools/android/findbugs_plugin/lib/chromiumPlugin.jar b/tools/android/findbugs_plugin/lib/chromiumPlugin.jar
deleted file mode 100644
index 6ccf61b430..0000000000
Binary files a/tools/android/findbugs_plugin/lib/chromiumPlugin.jar and /dev/null differ
diff --git a/tools/android/findbugs_plugin/messages.xml b/tools/android/findbugs_plugin/messages.xml
deleted file mode 100644
index aea983bc24..0000000000
--- a/tools/android/findbugs_plugin/messages.xml
+++ /dev/null
@@ -1,56 +0,0 @@
-
-
-
-
-
-
-
- Chromium FindBugs Plugin
- Adds style checks enforced in the chromium project.
-
-
-
-
-
-
-
-
-
-
- Shouldn't use synchronized(this)
- Shouldn't use synchronized(this), please narrow down the synchronization scope.
-
-Shouldn't use synchronized(this), please narrow down the synchronization scope.
-]]>
-
-
-
-
-
-
-
-
-
-
-
- Shouldn't use synchronized method
- Shouldn't use synchronized method, please narrow down the synchronization scope.
-
-Shouldn't use synchronized method, please narrow down the synchronization scope.
-]]>
-
-
-
- CHROMIUM
-
diff --git a/tools/android/findbugs_plugin/src/org/chromium/tools/findbugs/plugin/SynchronizedMethodDetector.java b/tools/android/findbugs_plugin/src/org/chromium/tools/findbugs/plugin/SynchronizedMethodDetector.java
deleted file mode 100644
index 7a879f6644..0000000000
--- a/tools/android/findbugs_plugin/src/org/chromium/tools/findbugs/plugin/SynchronizedMethodDetector.java
+++ /dev/null
@@ -1,38 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-package org.chromium.tools.findbugs.plugin;
-
-import edu.umd.cs.findbugs.BugInstance;
-import edu.umd.cs.findbugs.BugReporter;
-import edu.umd.cs.findbugs.bcel.OpcodeStackDetector;
-
-import org.apache.bcel.classfile.Code;
-
-/**
- * This class detects the synchronized method.
- */
-public class SynchronizedMethodDetector extends OpcodeStackDetector {
-
- private BugReporter mBugReporter;
-
- public SynchronizedMethodDetector(BugReporter bugReporter) {
- this.mBugReporter = bugReporter;
- }
-
- @Override
- public void visit(Code code) {
- if (getMethod().isSynchronized()) {
- mBugReporter.reportBug(new BugInstance(this, "CHROMIUM_SYNCHRONIZED_METHOD",
- NORMAL_PRIORITY)
- .addClassAndMethod(this)
- .addSourceLine(this));
- }
- super.visit(code);
- }
-
- @Override
- public void sawOpcode(int arg0) {
- }
-}
diff --git a/tools/android/findbugs_plugin/src/org/chromium/tools/findbugs/plugin/SynchronizedThisDetector.java b/tools/android/findbugs_plugin/src/org/chromium/tools/findbugs/plugin/SynchronizedThisDetector.java
deleted file mode 100644
index 330431ba7c..0000000000
--- a/tools/android/findbugs_plugin/src/org/chromium/tools/findbugs/plugin/SynchronizedThisDetector.java
+++ /dev/null
@@ -1,73 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-package org.chromium.tools.findbugs.plugin;
-
-import org.apache.bcel.classfile.Code;
-
-import edu.umd.cs.findbugs.BugInstance;
-import edu.umd.cs.findbugs.BugReporter;
-import edu.umd.cs.findbugs.bcel.OpcodeStackDetector;
-
-/**
- * This class detects the synchronized(this).
- *
- * The pattern of byte code of synchronized(this) is
- * aload_0 # Load the 'this' pointer on top of stack
- * dup # Duplicate the 'this' pointer
- * astore_x # Store this for late use, it might be astore.
- * monitorenter
- */
-public class SynchronizedThisDetector extends OpcodeStackDetector {
- private final int PATTERN[] = {ALOAD_0, DUP, 0xff, 0xff, MONITORENTER};
-
- private int mStep = 0;
- private BugReporter mBugReporter;
-
- public SynchronizedThisDetector(BugReporter bugReporter) {
- mBugReporter = bugReporter;
- }
-
- @Override
- public void visit(Code code) {
- mStep = 0;
- super.visit(code);
- }
-
- @Override
- public void sawOpcode(int seen) {
- if (PATTERN[mStep] == seen) {
- mStep++;
- if (mStep == PATTERN.length) {
- mBugReporter.reportBug(new BugInstance(this, "CHROMIUM_SYNCHRONIZED_THIS",
- NORMAL_PRIORITY)
- .addClassAndMethod(this)
- .addSourceLine(this));
- mStep = 0;
- return;
- }
- } else if (mStep == 2) {
- // This could be astore_x
- switch (seen) {
- case ASTORE_0:
- case ASTORE_1:
- case ASTORE_2:
- case ASTORE_3:
- mStep += 2;
- break;
- case ASTORE:
- mStep++;
- break;
- default:
- mStep = 0;
- break;
- }
- } else if (mStep == 3) {
- // Could be any byte following the ASTORE.
- mStep++;
- } else {
- mStep = 0;
- }
- }
-}
diff --git a/tools/android/findbugs_plugin/test/expected_result.txt b/tools/android/findbugs_plugin/test/expected_result.txt
deleted file mode 100644
index 076b00703c..0000000000
--- a/tools/android/findbugs_plugin/test/expected_result.txt
+++ /dev/null
@@ -1,3 +0,0 @@
-M C CSM: Shouldn't use synchronized method, please narrow down the synchronization scope. At SimpleSynchronizedMethod.java
-M C CSM: Shouldn't use synchronized method, please narrow down the synchronization scope. At SimpleSynchronizedStaticMethod.java
-M C CST: Shouldn't use synchronized(this), please narrow down the synchronization scope. At SimpleSynchronizedThis.java
diff --git a/tools/android/findbugs_plugin/test/java/src/org/chromium/tools/findbugs/plugin/SimpleSynchronizedMethod.java b/tools/android/findbugs_plugin/test/java/src/org/chromium/tools/findbugs/plugin/SimpleSynchronizedMethod.java
deleted file mode 100644
index c04a35cb02..0000000000
--- a/tools/android/findbugs_plugin/test/java/src/org/chromium/tools/findbugs/plugin/SimpleSynchronizedMethod.java
+++ /dev/null
@@ -1,16 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-package org.chromium.tools.findbugs.plugin;
-
-/**
- * This class has synchronized method and is used to test
- * SynchronizedMethodDetector.
- */
-class SimpleSynchronizedMethod {
- private int i = 0;
- synchronized void synchronizedMethod() {
- i++;
- }
-}
diff --git a/tools/android/findbugs_plugin/test/java/src/org/chromium/tools/findbugs/plugin/SimpleSynchronizedStaticMethod.java b/tools/android/findbugs_plugin/test/java/src/org/chromium/tools/findbugs/plugin/SimpleSynchronizedStaticMethod.java
deleted file mode 100644
index 0af6582fa0..0000000000
--- a/tools/android/findbugs_plugin/test/java/src/org/chromium/tools/findbugs/plugin/SimpleSynchronizedStaticMethod.java
+++ /dev/null
@@ -1,15 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-package org.chromium.tools.findbugs.plugin;
-
-/**
- * This class is used to test SynchronizedMethodDetector
- */
-class SimpleSynchronizedStaticMethod {
- private static int i = 0;
- synchronized static void synchronizedStaticMethod() {
- i++;
- }
-}
diff --git a/tools/android/findbugs_plugin/test/java/src/org/chromium/tools/findbugs/plugin/SimpleSynchronizedThis.java b/tools/android/findbugs_plugin/test/java/src/org/chromium/tools/findbugs/plugin/SimpleSynchronizedThis.java
deleted file mode 100644
index 2c7e6fdfb4..0000000000
--- a/tools/android/findbugs_plugin/test/java/src/org/chromium/tools/findbugs/plugin/SimpleSynchronizedThis.java
+++ /dev/null
@@ -1,19 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-package org.chromium.tools.findbugs.plugin;
-
-/**
- * This class has synchronized(this) statement and is used to test
- * SynchronizedThisDetector.
- */
-class SimpleSynchronizedThis {
- private int i = 0;
-
- void synchronizedThis() {
- synchronized(this) {
- i++;
- }
- }
-}
diff --git a/tools/android/findbugs_plugin/test/run_findbugs_plugin_tests.py b/tools/android/findbugs_plugin/test/run_findbugs_plugin_tests.py
deleted file mode 100755
index c2e1531484..0000000000
--- a/tools/android/findbugs_plugin/test/run_findbugs_plugin_tests.py
+++ /dev/null
@@ -1,44 +0,0 @@
-#!/usr/bin/env python
-#
-# Copyright (c) 2012 The Chromium Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-# This is used to test the findbugs plugin, it calls
-# build/android/pylib/utils/findbugs.py to analyze the classes in
-# org.chromium.tools.findbugs.plugin package, and expects to get the same
-# issue with those in expected_result.txt.
-#
-# Useful command line:
-# --rebaseline to generate the expected_result.txt, please make sure don't
-# remove the expected result of exsting tests.
-
-
-import optparse
-import os
-import sys
-
-sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__),
- '..', '..', '..', '..',
- 'build', 'android')))
-
-from pylib import constants
-from pylib.utils import findbugs
-
-
-def main(argv):
- parser = findbugs.GetCommonParser()
-
- options, _ = parser.parse_args()
-
- if not options.known_bugs:
- options.known_bugs = os.path.join(constants.DIR_SOURCE_ROOT, 'tools',
- 'android', 'findbugs_plugin', 'test',
- 'expected_result.txt')
- if not options.only_analyze:
- options.only_analyze = 'org.chromium.tools.findbugs.plugin.*'
-
- return findbugs.Run(options)
-
-if __name__ == '__main__':
- sys.exit(main(sys.argv))
diff --git a/tools/android/forwarder/forwarder.cc b/tools/android/forwarder/forwarder.cc
deleted file mode 100644
index e77c8065ff..0000000000
--- a/tools/android/forwarder/forwarder.cc
+++ /dev/null
@@ -1,426 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-
-#include "base/command_line.h"
-#include "base/logging.h"
-#include "base/posix/eintr_wrapper.h"
-#include "tools/android/common/adb_connection.h"
-#include "tools/android/common/daemon.h"
-#include "tools/android/common/net.h"
-
-namespace {
-
-const pthread_t kInvalidThread = static_cast(-1);
-volatile bool g_killed = false;
-
-void CloseSocket(int fd) {
- if (fd >= 0) {
- int old_errno = errno;
- (void) HANDLE_EINTR(close(fd));
- errno = old_errno;
- }
-}
-
-class Buffer {
- public:
- Buffer()
- : bytes_read_(0),
- write_offset_(0) {
- }
-
- bool CanRead() {
- return bytes_read_ == 0;
- }
-
- bool CanWrite() {
- return write_offset_ < bytes_read_;
- }
-
- int Read(int fd) {
- int ret = -1;
- if (CanRead()) {
- ret = HANDLE_EINTR(read(fd, buffer_, kBufferSize));
- if (ret > 0)
- bytes_read_ = ret;
- }
- return ret;
- }
-
- int Write(int fd) {
- int ret = -1;
- if (CanWrite()) {
- ret = HANDLE_EINTR(write(fd, buffer_ + write_offset_,
- bytes_read_ - write_offset_));
- if (ret > 0) {
- write_offset_ += ret;
- if (write_offset_ == bytes_read_) {
- write_offset_ = 0;
- bytes_read_ = 0;
- }
- }
- }
- return ret;
- }
-
- private:
- // A big buffer to let our file-over-http bridge work more like real file.
- static const int kBufferSize = 1024 * 128;
- int bytes_read_;
- int write_offset_;
- char buffer_[kBufferSize];
-
- DISALLOW_COPY_AND_ASSIGN(Buffer);
-};
-
-class Server;
-
-struct ForwarderThreadInfo {
- ForwarderThreadInfo(Server* a_server, int a_forwarder_index)
- : server(a_server),
- forwarder_index(a_forwarder_index) {
- }
- Server* server;
- int forwarder_index;
-};
-
-struct ForwarderInfo {
- time_t start_time;
- int socket1;
- time_t socket1_last_byte_time;
- size_t socket1_bytes;
- int socket2;
- time_t socket2_last_byte_time;
- size_t socket2_bytes;
-};
-
-class Server {
- public:
- Server()
- : thread_(kInvalidThread),
- socket_(-1) {
- memset(forward_to_, 0, sizeof(forward_to_));
- memset(&forwarders_, 0, sizeof(forwarders_));
- }
-
- int GetFreeForwarderIndex() {
- for (int i = 0; i < kMaxForwarders; i++) {
- if (forwarders_[i].start_time == 0)
- return i;
- }
- return -1;
- }
-
- void DisposeForwarderInfo(int index) {
- forwarders_[index].start_time = 0;
- }
-
- ForwarderInfo* GetForwarderInfo(int index) {
- return &forwarders_[index];
- }
-
- void DumpInformation() {
- LOG(INFO) << "Server information: " << forward_to_;
- LOG(INFO) << "No.: age up(bytes,idle) down(bytes,idle)";
- int count = 0;
- time_t now = time(NULL);
- for (int i = 0; i < kMaxForwarders; i++) {
- const ForwarderInfo& info = forwarders_[i];
- if (info.start_time) {
- count++;
- LOG(INFO) << count << ": " << now - info.start_time << " up("
- << info.socket1_bytes << ","
- << now - info.socket1_last_byte_time << " down("
- << info.socket2_bytes << ","
- << now - info.socket2_last_byte_time << ")";
- }
- }
- }
-
- void Shutdown() {
- if (socket_ >= 0)
- shutdown(socket_, SHUT_RDWR);
- }
-
- bool InitSocket(const char* arg);
-
- void StartThread() {
- pthread_create(&thread_, NULL, ServerThread, this);
- }
-
- void JoinThread() {
- if (thread_ != kInvalidThread)
- pthread_join(thread_, NULL);
- }
-
- private:
- static void* ServerThread(void* arg);
-
- // There are 3 kinds of threads that will access the array:
- // 1. Server thread will get a free ForwarderInfo and initialize it;
- // 2. Forwarder threads will dispose the ForwarderInfo when it finishes;
- // 3. Main thread will iterate and print the forwarders.
- // Using an array is not optimal, but can avoid locks or other complex
- // inter-thread communication.
- static const int kMaxForwarders = 512;
- ForwarderInfo forwarders_[kMaxForwarders];
-
- pthread_t thread_;
- int socket_;
- char forward_to_[40];
-
- DISALLOW_COPY_AND_ASSIGN(Server);
-};
-
-// Forwards all outputs from one socket to another socket.
-void* ForwarderThread(void* arg) {
- ForwarderThreadInfo* thread_info =
- reinterpret_cast(arg);
- Server* server = thread_info->server;
- int index = thread_info->forwarder_index;
- delete thread_info;
- ForwarderInfo* info = server->GetForwarderInfo(index);
- int socket1 = info->socket1;
- int socket2 = info->socket2;
- int nfds = socket1 > socket2 ? socket1 + 1 : socket2 + 1;
- fd_set read_fds;
- fd_set write_fds;
- Buffer buffer1;
- Buffer buffer2;
-
- while (!g_killed) {
- FD_ZERO(&read_fds);
- if (buffer1.CanRead())
- FD_SET(socket1, &read_fds);
- if (buffer2.CanRead())
- FD_SET(socket2, &read_fds);
-
- FD_ZERO(&write_fds);
- if (buffer1.CanWrite())
- FD_SET(socket2, &write_fds);
- if (buffer2.CanWrite())
- FD_SET(socket1, &write_fds);
-
- if (HANDLE_EINTR(select(nfds, &read_fds, &write_fds, NULL, NULL)) <= 0) {
- LOG(ERROR) << "Select error: " << strerror(errno);
- break;
- }
-
- int now = time(NULL);
- if (FD_ISSET(socket1, &read_fds)) {
- info->socket1_last_byte_time = now;
- int bytes = buffer1.Read(socket1);
- if (bytes <= 0)
- break;
- info->socket1_bytes += bytes;
- }
- if (FD_ISSET(socket2, &read_fds)) {
- info->socket2_last_byte_time = now;
- int bytes = buffer2.Read(socket2);
- if (bytes <= 0)
- break;
- info->socket2_bytes += bytes;
- }
- if (FD_ISSET(socket1, &write_fds)) {
- if (buffer2.Write(socket1) <= 0)
- break;
- }
- if (FD_ISSET(socket2, &write_fds)) {
- if (buffer1.Write(socket2) <= 0)
- break;
- }
- }
-
- CloseSocket(socket1);
- CloseSocket(socket2);
- server->DisposeForwarderInfo(index);
- return NULL;
-}
-
-// Listens to a server socket. On incoming request, forward it to the host.
-// static
-void* Server::ServerThread(void* arg) {
- Server* server = reinterpret_cast(arg);
- while (!g_killed) {
- int forwarder_index = server->GetFreeForwarderIndex();
- if (forwarder_index < 0) {
- LOG(ERROR) << "Too many forwarders";
- continue;
- }
-
- struct sockaddr_in addr;
- socklen_t addr_len = sizeof(addr);
- int socket = HANDLE_EINTR(accept(server->socket_,
- reinterpret_cast(&addr),
- &addr_len));
- if (socket < 0) {
- LOG(ERROR) << "Failed to accept: " << strerror(errno);
- break;
- }
- tools::DisableNagle(socket);
-
- int host_socket = tools::ConnectAdbHostSocket(server->forward_to_);
- if (host_socket >= 0) {
- // Set NONBLOCK flag because we use select().
- fcntl(socket, F_SETFL, fcntl(socket, F_GETFL) | O_NONBLOCK);
- fcntl(host_socket, F_SETFL, fcntl(host_socket, F_GETFL) | O_NONBLOCK);
-
- ForwarderInfo* forwarder_info = server->GetForwarderInfo(forwarder_index);
- time_t now = time(NULL);
- forwarder_info->start_time = now;
- forwarder_info->socket1 = socket;
- forwarder_info->socket1_last_byte_time = now;
- forwarder_info->socket1_bytes = 0;
- forwarder_info->socket2 = host_socket;
- forwarder_info->socket2_last_byte_time = now;
- forwarder_info->socket2_bytes = 0;
-
- pthread_t thread;
- pthread_create(&thread, NULL, ForwarderThread,
- new ForwarderThreadInfo(server, forwarder_index));
- } else {
- // Close the unused client socket which is failed to connect to host.
- CloseSocket(socket);
- }
- }
-
- CloseSocket(server->socket_);
- server->socket_ = -1;
- return NULL;
-}
-
-// Format of arg: [::]
-bool Server::InitSocket(const char* arg) {
- char* endptr;
- int local_port = static_cast(strtol(arg, &endptr, 10));
- if (local_port < 0)
- return false;
-
- if (*endptr != ':') {
- snprintf(forward_to_, sizeof(forward_to_), "%d:127.0.0.1", local_port);
- } else {
- strncpy(forward_to_, endptr + 1, sizeof(forward_to_) - 1);
- }
-
- socket_ = socket(AF_INET, SOCK_STREAM, 0);
- if (socket_ < 0) {
- perror("server socket");
- return false;
- }
- tools::DisableNagle(socket_);
-
- sockaddr_in addr;
- memset(&addr, 0, sizeof(addr));
- addr.sin_family = AF_INET;
- addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
- addr.sin_port = htons(local_port);
- int reuse_addr = 1;
- setsockopt(socket_, SOL_SOCKET, SO_REUSEADDR,
- &reuse_addr, sizeof(reuse_addr));
- tools::DeferAccept(socket_);
- if (HANDLE_EINTR(bind(socket_, reinterpret_cast(&addr),
- sizeof(addr))) < 0 ||
- HANDLE_EINTR(listen(socket_, 5)) < 0) {
- perror("server bind");
- CloseSocket(socket_);
- socket_ = -1;
- return false;
- }
-
- if (local_port == 0) {
- socklen_t addrlen = sizeof(addr);
- if (getsockname(socket_, reinterpret_cast(&addr), &addrlen)
- != 0) {
- perror("get listen address");
- CloseSocket(socket_);
- socket_ = -1;
- return false;
- }
- local_port = ntohs(addr.sin_port);
- }
-
- printf("Forwarding device port %d to host %s\n", local_port, forward_to_);
- return true;
-}
-
-int g_server_count = 0;
-Server* g_servers = NULL;
-
-void KillHandler(int unused) {
- g_killed = true;
- for (int i = 0; i < g_server_count; i++)
- g_servers[i].Shutdown();
-}
-
-void DumpInformation(int unused) {
- for (int i = 0; i < g_server_count; i++)
- g_servers[i].DumpInformation();
-}
-
-} // namespace
-
-int main(int argc, char** argv) {
- printf("Android device to host TCP forwarder\n");
- printf("Like 'adb forward' but in the reverse direction\n");
-
- CommandLine command_line(argc, argv);
- CommandLine::StringVector server_args = command_line.GetArgs();
- if (tools::HasHelpSwitch(command_line) || server_args.empty()) {
- tools::ShowHelp(
- argv[0],
- "[::] ...",
- " default is \n"
- " default is 127.0.0.1\n"
- "If is 0, a port will by dynamically allocated.\n");
- return 0;
- }
-
- g_servers = new Server[server_args.size()];
- g_server_count = 0;
- int failed_count = 0;
- for (size_t i = 0; i < server_args.size(); i++) {
- if (!g_servers[g_server_count].InitSocket(server_args[i].c_str())) {
- printf("Couldn't start forwarder server for port spec: %s\n",
- server_args[i].c_str());
- ++failed_count;
- } else {
- ++g_server_count;
- }
- }
-
- if (g_server_count == 0) {
- printf("No forwarder servers could be started. Exiting.\n");
- delete [] g_servers;
- return failed_count;
- }
-
- if (!tools::HasNoSpawnDaemonSwitch(command_line))
- tools::SpawnDaemon(failed_count);
-
- signal(SIGTERM, KillHandler);
- signal(SIGUSR2, DumpInformation);
-
- for (int i = 0; i < g_server_count; i++)
- g_servers[i].StartThread();
- for (int i = 0; i < g_server_count; i++)
- g_servers[i].JoinThread();
- g_server_count = 0;
- delete [] g_servers;
-
- return 0;
-}
-
diff --git a/tools/android/forwarder/forwarder.gyp b/tools/android/forwarder/forwarder.gyp
deleted file mode 100644
index 1df518b1bb..0000000000
--- a/tools/android/forwarder/forwarder.gyp
+++ /dev/null
@@ -1,43 +0,0 @@
-# Copyright (c) 2012 The Chromium Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-{
- 'targets': [
- {
- 'target_name': 'forwarder',
- 'type': 'none',
- 'dependencies': [
- 'forwarder_symbols',
- ],
- 'actions': [
- {
- 'action_name': 'strip_forwarder',
- 'inputs': ['<(PRODUCT_DIR)/forwarder_symbols'],
- 'outputs': ['<(PRODUCT_DIR)/forwarder'],
- 'action': [
- '<(android_strip)',
- '--strip-unneeded',
- '<@(_inputs)',
- '-o',
- '<@(_outputs)',
- ],
- },
- ],
- }, {
- 'target_name': 'forwarder_symbols',
- 'type': 'executable',
- 'dependencies': [
- '../../../base/base.gyp:base',
- '../common/common.gyp:android_tools_common',
- ],
- 'include_dirs': [
- '../../..',
- ],
- 'sources': [
- 'forwarder.cc',
- ],
- },
- ],
-}
-
diff --git a/tools/android/forwarder2/command.cc b/tools/android/forwarder2/command.cc
deleted file mode 100644
index 9b0aa24cfb..0000000000
--- a/tools/android/forwarder2/command.cc
+++ /dev/null
@@ -1,96 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "tools/android/forwarder2/command.h"
-
-#include
-#include
-#include
-#include
-
-#include "base/logging.h"
-#include "base/safe_strerror_posix.h"
-#include "base/strings/string_number_conversions.h"
-#include "base/strings/string_piece.h"
-#include "tools/android/forwarder2/socket.h"
-
-using base::StringPiece;
-
-namespace {
-
-
-// Command format:
-// :
-//
-// Where:
-// is a 5-chars zero-padded ASCII decimal integer
-// matching the target port for the command (e.g.
-// '08080' for port 8080)
-// is a 3-char zero-padded ASCII decimal integer
-// matching a command::Type value (e.g. 002 for
-// ACK).
-// The column (:) is used as a separator for easier reading.
-const int kPortStringSize = 5;
-const int kCommandTypeStringSize = 2;
-// Command string size also includes the ':' separator char.
-const int kCommandStringSize = kPortStringSize + kCommandTypeStringSize + 1;
-
-} // namespace
-
-namespace forwarder2 {
-
-bool ReadCommand(Socket* socket,
- int* port_out,
- command::Type* command_type_out) {
- char command_buffer[kCommandStringSize + 1];
- // To make logging easier.
- command_buffer[kCommandStringSize] = '\0';
-
- int bytes_read = socket->ReadNumBytes(command_buffer, kCommandStringSize);
- if (bytes_read != kCommandStringSize) {
- if (bytes_read < 0)
- LOG(ERROR) << "Read() error: " << safe_strerror(errno);
- else if (!bytes_read)
- LOG(ERROR) << "Read() error, endpoint was unexpectedly closed.";
- else
- LOG(ERROR) << "Read() error, not enough data received from the socket.";
- return false;
- }
-
- StringPiece port_str(command_buffer, kPortStringSize);
- if (!StringToInt(port_str, port_out)) {
- LOG(ERROR) << "Could not parse the command port string: "
- << port_str;
- return false;
- }
-
- StringPiece command_type_str(
- &command_buffer[kPortStringSize + 1], kCommandTypeStringSize);
- int command_type;
- if (!StringToInt(command_type_str, &command_type)) {
- LOG(ERROR) << "Could not parse the command type string: "
- << command_type_str;
- return false;
- }
- *command_type_out = static_cast(command_type);
- return true;
-}
-
-bool SendCommand(command::Type command, int port, Socket* socket) {
- char buffer[kCommandStringSize + 1];
- int len = snprintf(buffer, sizeof(buffer), "%05d:%02d", port, command);
- CHECK_EQ(len, kCommandStringSize);
- // Write the full command minus the leading \0 char.
- return socket->WriteNumBytes(buffer, len) == len;
-}
-
-bool ReceivedCommand(command::Type command, Socket* socket) {
- int port;
- command::Type received_command;
- if (!ReadCommand(socket, &port, &received_command))
- return false;
- return received_command == command;
-}
-
-} // namespace forwarder
diff --git a/tools/android/forwarder2/command.h b/tools/android/forwarder2/command.h
deleted file mode 100644
index 8e222ef7bb..0000000000
--- a/tools/android/forwarder2/command.h
+++ /dev/null
@@ -1,48 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef TOOLS_ANDROID_FORWARDER2_COMMAND_H_
-#define TOOLS_ANDROID_FORWARDER2_COMMAND_H_
-
-#include "base/basictypes.h"
-
-namespace forwarder2 {
-
-class Socket;
-
-namespace command {
-
-enum Type {
- ACCEPT_ERROR = 0,
- ACCEPT_SUCCESS,
- ACK,
- ADB_DATA_SOCKET_ERROR,
- ADB_DATA_SOCKET_SUCCESS,
- BIND_ERROR,
- BIND_SUCCESS,
- DATA_CONNECTION,
- HOST_SERVER_ERROR,
- HOST_SERVER_SUCCESS,
- KILL_ALL_LISTENERS,
- LISTEN,
- UNLISTEN,
- UNLISTEN_ERROR,
- UNLISTEN_SUCCESS,
-};
-
-} // namespace command
-
-bool ReadCommand(Socket* socket,
- int* port_out,
- command::Type* command_type_out);
-
-// Helper function to read the command from the |socket| and return true if the
-// |command| is equal to the given command parameter.
-bool ReceivedCommand(command::Type command, Socket* socket);
-
-bool SendCommand(command::Type command, int port, Socket* socket);
-
-} // namespace forwarder
-
-#endif // TOOLS_ANDROID_FORWARDER2_COMMAND_H_
diff --git a/tools/android/forwarder2/common.cc b/tools/android/forwarder2/common.cc
deleted file mode 100644
index c97ed8056b..0000000000
--- a/tools/android/forwarder2/common.cc
+++ /dev/null
@@ -1,28 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "tools/android/forwarder2/common.h"
-
-#include
-#include
-
-#include "base/logging.h"
-#include "base/posix/eintr_wrapper.h"
-#include "base/safe_strerror_posix.h"
-
-namespace forwarder2 {
-
-void PError(const char* msg) {
- LOG(ERROR) << msg << ": " << safe_strerror(errno);
-}
-
-void CloseFD(int fd) {
- const int errno_copy = errno;
- if (HANDLE_EINTR(close(fd)) < 0) {
- PError("close");
- errno = errno_copy;
- }
-}
-
-} // namespace forwarder2
diff --git a/tools/android/forwarder2/common.h b/tools/android/forwarder2/common.h
deleted file mode 100644
index 43de57b160..0000000000
--- a/tools/android/forwarder2/common.h
+++ /dev/null
@@ -1,89 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-// Common helper functions/classes used both in the host and device forwarder.
-
-#ifndef TOOLS_ANDROID_FORWARDER2_COMMON_H_
-#define TOOLS_ANDROID_FORWARDER2_COMMON_H_
-
-#include
-#include
-#include
-
-#include "base/basictypes.h"
-#include "base/compiler_specific.h"
-#include "base/logging.h"
-#include "base/posix/eintr_wrapper.h"
-
-// Preserving errno for Close() is important because the function is very often
-// used in cleanup code, after an error occurred, and it is very easy to pass an
-// invalid file descriptor to close() in this context, or more rarely, a
-// spurious signal might make close() return -1 + setting errno to EINTR,
-// masking the real reason for the original error. This leads to very unpleasant
-// debugging sessions.
-#define PRESERVE_ERRNO_HANDLE_EINTR(Func) \
- do { \
- int local_errno = errno; \
- (void) HANDLE_EINTR(Func); \
- errno = local_errno; \
- } while (false);
-
-// Wrapper around RAW_LOG() which is signal-safe. The only purpose of this macro
-// is to avoid documenting uses of RawLog().
-#define SIGNAL_SAFE_LOG(Level, Msg) \
- RAW_LOG(Level, Msg);
-
-namespace forwarder2 {
-
-// Note that the two following functions are not signal-safe.
-
-// Chromium logging-aware implementation of libc's perror().
-void PError(const char* msg);
-
-// Closes the provided file descriptor and logs an error if it failed.
-void CloseFD(int fd);
-
-// Helps build a formatted C-string allocated in a fixed-size array. This is
-// useful in signal handlers where base::StringPrintf() can't be used safely
-// (due to its use of LOG()).
-template
-class FixedSizeStringBuilder {
- public:
- FixedSizeStringBuilder() {
- Reset();
- }
-
- const char* buffer() const { return buffer_; }
-
- void Reset() {
- buffer_[0] = 0;
- write_ptr_ = buffer_;
- }
-
- // Returns the number of bytes appended to the underlying buffer or -1 if it
- // failed.
- int Append(const char* format, ...) PRINTF_FORMAT(/* + 1 for 'this' */ 2, 3) {
- if (write_ptr_ >= buffer_ + BufferSize)
- return -1;
- va_list ap;
- va_start(ap, format);
- const int bytes_written = vsnprintf(
- write_ptr_, BufferSize - (write_ptr_ - buffer_), format, ap);
- va_end(ap);
- if (bytes_written > 0)
- write_ptr_ += bytes_written;
- return bytes_written;
- }
-
- private:
- char* write_ptr_;
- char buffer_[BufferSize];
-
- COMPILE_ASSERT(BufferSize >= 1, Size_of_buffer_must_be_at_least_one);
- DISALLOW_COPY_AND_ASSIGN(FixedSizeStringBuilder);
-};
-
-} // namespace forwarder2
-
-#endif // TOOLS_ANDROID_FORWARDER2_COMMON_H_
diff --git a/tools/android/forwarder2/daemon.cc b/tools/android/forwarder2/daemon.cc
deleted file mode 100644
index 0ca89d1a5f..0000000000
--- a/tools/android/forwarder2/daemon.cc
+++ /dev/null
@@ -1,288 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "tools/android/forwarder2/daemon.h"
-
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-
-#include
-#include
-#include
-
-#include "base/basictypes.h"
-#include "base/file_util.h"
-#include "base/files/file_path.h"
-#include "base/logging.h"
-#include "base/memory/scoped_ptr.h"
-#include "base/posix/eintr_wrapper.h"
-#include "base/safe_strerror_posix.h"
-#include "base/strings/string_number_conversions.h"
-#include "base/strings/stringprintf.h"
-#include "tools/android/forwarder2/common.h"
-#include "tools/android/forwarder2/socket.h"
-
-namespace forwarder2 {
-namespace {
-
-const int kBufferSize = 256;
-
-// Timeout constant used for polling when connecting to the daemon's Unix Domain
-// Socket and also when waiting for its death when it is killed.
-const int kNumTries = 100;
-const int kIdleTimeMSec = 20;
-
-void InitLoggingForDaemon(const std::string& log_file) {
- logging::LoggingSettings settings;
- settings.logging_dest =
- log_file.empty() ?
- logging::LOG_TO_SYSTEM_DEBUG_LOG : logging::LOG_TO_FILE;
- settings.log_file = log_file.c_str();
- settings.lock_log = logging::DONT_LOCK_LOG_FILE;
- settings.dcheck_state =
- logging::ENABLE_DCHECK_FOR_NON_OFFICIAL_RELEASE_BUILDS;
- CHECK(logging::InitLogging(settings));
-}
-
-bool RunServerAcceptLoop(const std::string& welcome_message,
- Socket* server_socket,
- Daemon::ServerDelegate* server_delegate) {
- bool failed = false;
- for (;;) {
- scoped_ptr client_socket(new Socket());
- if (!server_socket->Accept(client_socket.get())) {
- if (server_socket->DidReceiveEvent())
- break;
- PError("Accept()");
- failed = true;
- break;
- }
- if (!client_socket->Write(welcome_message.c_str(),
- welcome_message.length() + 1)) {
- PError("Write()");
- failed = true;
- continue;
- }
- server_delegate->OnClientConnected(client_socket.Pass());
- }
- return !failed;
-}
-
-void SigChildHandler(int signal_number) {
- DCHECK_EQ(signal_number, SIGCHLD);
- int status;
- pid_t child_pid = waitpid(-1 /* any child */, &status, WNOHANG);
- if (child_pid < 0) {
- PError("waitpid");
- return;
- }
- if (child_pid == 0)
- return;
- if (WIFEXITED(status) && WEXITSTATUS(status) == 0)
- return;
- // Avoid using StringAppendF() since it's unsafe in a signal handler due to
- // its use of LOG().
- FixedSizeStringBuilder<256> string_builder;
- string_builder.Append("Daemon (pid=%d) died unexpectedly with ", child_pid);
- if (WIFEXITED(status))
- string_builder.Append("status %d.", WEXITSTATUS(status));
- else if (WIFSIGNALED(status))
- string_builder.Append("signal %d.", WTERMSIG(status));
- else
- string_builder.Append("unknown reason.");
- SIGNAL_SAFE_LOG(ERROR, string_builder.buffer());
-}
-
-// Note that 0 is written to |lock_owner_pid| in case the file is not locked.
-bool GetFileLockOwnerPid(int fd, pid_t* lock_owner_pid) {
- struct flock lock_info = {};
- lock_info.l_type = F_WRLCK;
- lock_info.l_whence = SEEK_CUR;
- const int ret = HANDLE_EINTR(fcntl(fd, F_GETLK, &lock_info));
- if (ret < 0) {
- if (errno == EBADF) {
- // Assume that the provided file descriptor corresponding to the PID file
- // was valid until the daemon removed this file.
- *lock_owner_pid = 0;
- return true;
- }
- PError("fcntl");
- return false;
- }
- if (lock_info.l_type == F_UNLCK) {
- *lock_owner_pid = 0;
- return true;
- }
- CHECK_EQ(F_WRLCK /* exclusive lock */, lock_info.l_type);
- *lock_owner_pid = lock_info.l_pid;
- return true;
-}
-
-scoped_ptr ConnectToUnixDomainSocket(
- const std::string& socket_name,
- int tries_count,
- int idle_time_msec,
- const std::string& expected_welcome_message) {
- for (int i = 0; i < tries_count; ++i) {
- scoped_ptr socket(new Socket());
- if (!socket->ConnectUnix(socket_name)) {
- if (idle_time_msec)
- usleep(idle_time_msec * 1000);
- continue;
- }
- char buf[kBufferSize];
- DCHECK(expected_welcome_message.length() + 1 <= sizeof(buf));
- memset(buf, 0, sizeof(buf));
- if (socket->Read(buf, expected_welcome_message.length() + 1) < 0) {
- perror("read");
- continue;
- }
- if (expected_welcome_message != buf) {
- LOG(ERROR) << "Unexpected message read from daemon: " << buf;
- break;
- }
- return socket.Pass();
- }
- return scoped_ptr();
-}
-
-} // namespace
-
-Daemon::Daemon(const std::string& log_file_path,
- const std::string& identifier,
- ClientDelegate* client_delegate,
- ServerDelegate* server_delegate,
- GetExitNotifierFDCallback get_exit_fd_callback)
- : log_file_path_(log_file_path),
- identifier_(identifier),
- client_delegate_(client_delegate),
- server_delegate_(server_delegate),
- get_exit_fd_callback_(get_exit_fd_callback) {
- DCHECK(client_delegate_);
- DCHECK(server_delegate_);
- DCHECK(get_exit_fd_callback_);
-}
-
-Daemon::~Daemon() {}
-
-bool Daemon::SpawnIfNeeded() {
- const int kSingleTry = 1;
- const int kNoIdleTime = 0;
- scoped_ptr client_socket = ConnectToUnixDomainSocket(
- identifier_, kSingleTry, kNoIdleTime, identifier_);
- if (!client_socket) {
- switch (fork()) {
- case -1:
- PError("fork()");
- return false;
- // Child.
- case 0: {
- if (setsid() < 0) { // Detach the child process from its parent.
- PError("setsid()");
- exit(1);
- }
- InitLoggingForDaemon(log_file_path_);
- CloseFD(STDIN_FILENO);
- CloseFD(STDOUT_FILENO);
- CloseFD(STDERR_FILENO);
- const int null_fd = open("/dev/null", O_RDWR);
- CHECK_EQ(null_fd, STDIN_FILENO);
- CHECK_EQ(dup(null_fd), STDOUT_FILENO);
- CHECK_EQ(dup(null_fd), STDERR_FILENO);
- Socket command_socket;
- if (!command_socket.BindUnix(identifier_)) {
- scoped_ptr client_socket = ConnectToUnixDomainSocket(
- identifier_, kSingleTry, kNoIdleTime, identifier_);
- if (client_socket.get()) {
- // The daemon was spawned by a concurrent process.
- exit(0);
- }
- PError("bind()");
- exit(1);
- }
- server_delegate_->Init();
- command_socket.AddEventFd(get_exit_fd_callback_());
- return RunServerAcceptLoop(
- identifier_, &command_socket, server_delegate_);
- }
- default:
- break;
- }
- }
- // Parent.
- // Install the custom SIGCHLD handler.
- sigset_t blocked_signals_set;
- if (sigprocmask(0 /* first arg ignored */, NULL, &blocked_signals_set) < 0) {
- PError("sigprocmask()");
- return false;
- }
- struct sigaction old_action;
- struct sigaction new_action;
- memset(&new_action, 0, sizeof(new_action));
- new_action.sa_handler = SigChildHandler;
- new_action.sa_flags = SA_NOCLDSTOP;
- sigemptyset(&new_action.sa_mask);
- if (sigaction(SIGCHLD, &new_action, &old_action) < 0) {
- PError("sigaction()");
- return false;
- }
- // Connect to the daemon's Unix Domain Socket.
- bool failed = false;
- if (!client_socket) {
- client_socket = ConnectToUnixDomainSocket(
- identifier_, kNumTries, kIdleTimeMSec, identifier_);
- if (!client_socket) {
- LOG(ERROR) << "Could not connect to daemon's Unix Daemon socket";
- failed = true;
- }
- }
- if (!failed)
- client_delegate_->OnDaemonReady(client_socket.get());
- // Restore the previous signal action for SIGCHLD.
- if (sigaction(SIGCHLD, &old_action, NULL) < 0) {
- PError("sigaction");
- failed = true;
- }
- return !failed;
-}
-
-bool Daemon::Kill() {
- pid_t daemon_pid = Socket::GetUnixDomainSocketProcessOwner(identifier_);
- if (daemon_pid < 0)
- return true; // No daemon running.
- if (kill(daemon_pid, SIGTERM) < 0) {
- if (errno == ESRCH /* invalid PID */)
- // The daemon exited for some reason (e.g. kill by a process other than
- // us) right before the call to kill() above.
- return true;
- PError("kill");
- return false;
- }
- for (int i = 0; i < kNumTries; ++i) {
- const pid_t previous_pid = daemon_pid;
- daemon_pid = Socket::GetUnixDomainSocketProcessOwner(identifier_);
- if (daemon_pid < 0)
- return true;
- // Since we are polling we might not see the 'daemon exited' event if
- // another daemon was spawned during our idle period.
- if (daemon_pid != previous_pid) {
- LOG(WARNING) << "Daemon (pid=" << previous_pid
- << ") was successfully killed but a new daemon (pid="
- << daemon_pid << ") seems to be running now.";
- return true;
- }
- usleep(kIdleTimeMSec * 1000);
- }
- LOG(ERROR) << "Timed out while killing daemon. "
- "It might still be tearing down.";
- return false;
-}
-
-} // namespace forwarder2
diff --git a/tools/android/forwarder2/daemon.h b/tools/android/forwarder2/daemon.h
deleted file mode 100644
index 4b05ea423c..0000000000
--- a/tools/android/forwarder2/daemon.h
+++ /dev/null
@@ -1,75 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef TOOLS_ANDROID_FORWARDER2_DAEMON_H_
-#define TOOLS_ANDROID_FORWARDER2_DAEMON_H_
-
-#include
-
-#include "base/basictypes.h"
-#include "base/memory/scoped_ptr.h"
-
-namespace forwarder2 {
-
-class Socket;
-
-// Provides a way to spawn a daemon and communicate with it.
-class Daemon {
- public:
- // Callback used by the daemon to shutdown properly. See pipe_notifier.h for
- // more details.
- typedef int (*GetExitNotifierFDCallback)();
-
- class ClientDelegate {
- public:
- virtual ~ClientDelegate() {}
-
- // Called after the daemon is ready to receive commands.
- virtual void OnDaemonReady(Socket* daemon_socket) = 0;
- };
-
- class ServerDelegate {
- public:
- virtual ~ServerDelegate() {}
-
- // Called after the daemon bound its Unix Domain Socket. This can be used to
- // setup signal handlers or perform global initialization.
- virtual void Init() = 0;
-
- virtual void OnClientConnected(scoped_ptr client_socket) = 0;
- };
-
- // |identifier| should be a unique string identifier. It is used to
- // bind/connect the underlying Unix Domain Socket.
- // Note that this class does not take ownership of |client_delegate| and
- // |server_delegate|.
- Daemon(const std::string& log_file_path,
- const std::string& identifier,
- ClientDelegate* client_delegate,
- ServerDelegate* server_delegate,
- GetExitNotifierFDCallback get_exit_fd_callback);
-
- ~Daemon();
-
- // Returns whether the daemon was successfully spawned. Note that this does
- // not necessarily mean that the current process was forked in case the daemon
- // is already running.
- bool SpawnIfNeeded();
-
- // Kills the daemon and blocks until it exited. Returns whether it succeeded.
- bool Kill();
-
- private:
- const std::string log_file_path_;
- const std::string identifier_;
- ClientDelegate* const client_delegate_;
- ServerDelegate* const server_delegate_;
- const GetExitNotifierFDCallback get_exit_fd_callback_;
-
- DISALLOW_COPY_AND_ASSIGN(Daemon);
-};
-
-} // namespace forwarder2
-
-#endif // TOOLS_ANDROID_FORWARDER2_DAEMON_H_
diff --git a/tools/android/forwarder2/device_controller.cc b/tools/android/forwarder2/device_controller.cc
deleted file mode 100644
index 87d0e17143..0000000000
--- a/tools/android/forwarder2/device_controller.cc
+++ /dev/null
@@ -1,154 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "tools/android/forwarder2/device_controller.h"
-
-#include
-
-#include "base/bind.h"
-#include "base/bind_helpers.h"
-#include "base/logging.h"
-#include "base/memory/scoped_ptr.h"
-#include "base/message_loop/message_loop_proxy.h"
-#include "base/single_thread_task_runner.h"
-#include "tools/android/forwarder2/command.h"
-#include "tools/android/forwarder2/device_listener.h"
-#include "tools/android/forwarder2/socket.h"
-
-namespace forwarder2 {
-
-// static
-scoped_ptr DeviceController::Create(
- const std::string& adb_unix_socket,
- int exit_notifier_fd) {
- scoped_ptr device_controller;
- scoped_ptr host_socket(new Socket());
- if (!host_socket->BindUnix(adb_unix_socket)) {
- PLOG(ERROR) << "Could not BindAndListen DeviceController socket on port "
- << adb_unix_socket << ": ";
- return device_controller.Pass();
- }
- LOG(INFO) << "Listening on Unix Domain Socket " << adb_unix_socket;
- device_controller.reset(
- new DeviceController(host_socket.Pass(), exit_notifier_fd));
- return device_controller.Pass();
-}
-
-DeviceController::~DeviceController() {
- DCHECK(construction_task_runner_->RunsTasksOnCurrentThread());
-}
-
-void DeviceController::Start() {
- AcceptHostCommandSoon();
-}
-
-DeviceController::DeviceController(scoped_ptr host_socket,
- int exit_notifier_fd)
- : host_socket_(host_socket.Pass()),
- exit_notifier_fd_(exit_notifier_fd),
- construction_task_runner_(base::MessageLoopProxy::current()),
- weak_ptr_factory_(this) {
- host_socket_->AddEventFd(exit_notifier_fd);
-}
-
-void DeviceController::AcceptHostCommandSoon() {
- base::MessageLoopProxy::current()->PostTask(
- FROM_HERE,
- base::Bind(&DeviceController::AcceptHostCommandInternal,
- base::Unretained(this)));
-}
-
-void DeviceController::AcceptHostCommandInternal() {
- scoped_ptr socket(new Socket);
- if (!host_socket_->Accept(socket.get())) {
- if (!host_socket_->DidReceiveEvent())
- PLOG(ERROR) << "Could not Accept DeviceController socket";
- else
- LOG(INFO) << "Received exit notification";
- return;
- }
- base::ScopedClosureRunner accept_next_client(
- base::Bind(&DeviceController::AcceptHostCommandSoon,
- base::Unretained(this)));
- // So that |socket| doesn't block on read if it has notifications.
- socket->AddEventFd(exit_notifier_fd_);
- int port;
- command::Type command;
- if (!ReadCommand(socket.get(), &port, &command)) {
- LOG(ERROR) << "Invalid command received.";
- return;
- }
- const ListenersMap::iterator listener_it = listeners_.find(port);
- DeviceListener* const listener = listener_it == listeners_.end()
- ? static_cast(NULL) : listener_it->second.get();
- switch (command) {
- case command::LISTEN: {
- if (listener != NULL) {
- LOG(WARNING) << "Already forwarding port " << port
- << ". Attempting to restart the listener.\n";
- // Note that this deletes the listener object.
- listeners_.erase(listener_it);
- }
- scoped_ptr new_listener(
- DeviceListener::Create(
- socket.Pass(), port, base::Bind(&DeviceController::DeleteListener,
- weak_ptr_factory_.GetWeakPtr())));
- if (!new_listener)
- return;
- new_listener->Start();
- // |port| can be zero, to allow dynamically allocated port, so instead, we
- // call DeviceListener::listener_port() to retrieve the currently
- // allocated port to this new listener.
- const int listener_port = new_listener->listener_port();
- listeners_.insert(
- std::make_pair(listener_port,
- linked_ptr(new_listener.release())));
- LOG(INFO) << "Forwarding device port " << listener_port << " to host.";
- break;
- }
- case command::DATA_CONNECTION:
- if (listener == NULL) {
- LOG(ERROR) << "Data Connection command received, but "
- << "listener has not been set up yet for port " << port;
- // After this point it is assumed that, once we close our Adb Data
- // socket, the Adb forwarder command will propagate the closing of
- // sockets all the way to the host side.
- break;
- }
- listener->SetAdbDataSocket(socket.Pass());
- break;
- case command::UNLISTEN:
- if (!listener) {
- SendCommand(command::UNLISTEN_ERROR, port, socket.get());
- break;
- }
- listeners_.erase(listener_it);
- SendCommand(command::UNLISTEN_SUCCESS, port, socket.get());
- break;
- default:
- // TODO(felipeg): add a KillAllListeners command.
- LOG(ERROR) << "Invalid command received. Port: " << port
- << " Command: " << command;
- }
-}
-
-// static
-void DeviceController::DeleteListener(
- const base::WeakPtr& device_controller_ptr,
- int listener_port) {
- DeviceController* const controller = device_controller_ptr.get();
- if (!controller)
- return;
- DCHECK(controller->construction_task_runner_->RunsTasksOnCurrentThread());
- const ListenersMap::iterator listener_it = controller->listeners_.find(
- listener_port);
- if (listener_it == controller->listeners_.end())
- return;
- const linked_ptr listener = listener_it->second;
- // Note that the listener is removed from the map before it gets destroyed in
- // case its destructor would access the map.
- controller->listeners_.erase(listener_it);
-}
-
-} // namespace forwarder
diff --git a/tools/android/forwarder2/device_controller.h b/tools/android/forwarder2/device_controller.h
deleted file mode 100644
index 3daedb3688..0000000000
--- a/tools/android/forwarder2/device_controller.h
+++ /dev/null
@@ -1,66 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef TOOLS_ANDROID_FORWARDER2_DEVICE_CONTROLLER_H_
-#define TOOLS_ANDROID_FORWARDER2_DEVICE_CONTROLLER_H_
-
-#include
-
-#include "base/basictypes.h"
-#include "base/containers/hash_tables.h"
-#include "base/memory/linked_ptr.h"
-#include "base/memory/ref_counted.h"
-#include "base/memory/scoped_ptr.h"
-#include "base/memory/weak_ptr.h"
-#include "tools/android/forwarder2/socket.h"
-
-namespace base {
-class SingleThreadTaskRunner;
-} // namespace base
-
-namespace forwarder2 {
-
-class DeviceListener;
-
-// There is a single DeviceController per device_forwarder process, and it is in
-// charge of managing all active redirections on the device side (one
-// DeviceListener each).
-class DeviceController {
- public:
- static scoped_ptr Create(const std::string& adb_unix_socket,
- int exit_notifier_fd);
- ~DeviceController();
-
- void Start();
-
- private:
- typedef base::hash_map<
- int /* port */, linked_ptr > ListenersMap;
-
- DeviceController(scoped_ptr host_socket, int exit_notifier_fd);
-
- void AcceptHostCommandSoon();
- void AcceptHostCommandInternal();
-
- // Note that this can end up being called after the DeviceController is
- // destroyed which is why a weak pointer is used.
- static void DeleteListener(
- const base::WeakPtr& device_controller_ptr,
- int listener_port);
-
- const scoped_ptr host_socket_;
- // Used to notify the controller to exit.
- const int exit_notifier_fd_;
- // Lets ensure DeviceListener instances are deleted on the thread they were
- // created on.
- const scoped_refptr construction_task_runner_;
- base::WeakPtrFactory weak_ptr_factory_;
- ListenersMap listeners_;
-
- DISALLOW_COPY_AND_ASSIGN(DeviceController);
-};
-
-} // namespace forwarder
-
-#endif // TOOLS_ANDROID_FORWARDER2_DEVICE_CONTROLLER_H_
diff --git a/tools/android/forwarder2/device_forwarder_main.cc b/tools/android/forwarder2/device_forwarder_main.cc
deleted file mode 100644
index cad46f465a..0000000000
--- a/tools/android/forwarder2/device_forwarder_main.cc
+++ /dev/null
@@ -1,169 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include
-#include
-
-#include
-#include
-
-#include "base/at_exit.h"
-#include "base/bind.h"
-#include "base/command_line.h"
-#include "base/compiler_specific.h"
-#include "base/logging.h"
-#include "base/strings/string_piece.h"
-#include "base/strings/stringprintf.h"
-#include "base/threading/thread.h"
-#include "tools/android/forwarder2/common.h"
-#include "tools/android/forwarder2/daemon.h"
-#include "tools/android/forwarder2/device_controller.h"
-#include "tools/android/forwarder2/pipe_notifier.h"
-
-namespace forwarder2 {
-namespace {
-
-// Leaky global instance, accessed from the signal handler.
-forwarder2::PipeNotifier* g_notifier = NULL;
-
-const int kBufSize = 256;
-
-const char kUnixDomainSocketPath[] = "chrome_device_forwarder";
-const char kDaemonIdentifier[] = "chrome_device_forwarder_daemon";
-
-void KillHandler(int /* unused */) {
- CHECK(g_notifier);
- if (!g_notifier->Notify())
- exit(1);
-}
-
-// Lets the daemon fetch the exit notifier file descriptor.
-int GetExitNotifierFD() {
- DCHECK(g_notifier);
- return g_notifier->receiver_fd();
-}
-
-class ServerDelegate : public Daemon::ServerDelegate {
- public:
- ServerDelegate() : initialized_(false) {}
-
- virtual ~ServerDelegate() {
- if (!controller_thread_.get())
- return;
- // The DeviceController instance, if any, is constructed on the controller
- // thread. Make sure that it gets deleted on that same thread. Note that
- // DeleteSoon() is not used here since it would imply reading |controller_|
- // from the main thread while it's set on the internal thread.
- controller_thread_->message_loop_proxy()->PostTask(
- FROM_HERE,
- base::Bind(&ServerDelegate::DeleteControllerOnInternalThread,
- base::Unretained(this)));
- }
-
- void DeleteControllerOnInternalThread() {
- DCHECK(
- controller_thread_->message_loop_proxy()->RunsTasksOnCurrentThread());
- controller_.reset();
- }
-
- // Daemon::ServerDelegate:
- virtual void Init() OVERRIDE {
- DCHECK(!g_notifier);
- g_notifier = new forwarder2::PipeNotifier();
- signal(SIGTERM, KillHandler);
- signal(SIGINT, KillHandler);
- controller_thread_.reset(new base::Thread("controller_thread"));
- controller_thread_->Start();
- }
-
- virtual void OnClientConnected(scoped_ptr client_socket) OVERRIDE {
- if (initialized_) {
- client_socket->WriteString("OK");
- return;
- }
- controller_thread_->message_loop()->PostTask(
- FROM_HERE,
- base::Bind(&ServerDelegate::StartController, base::Unretained(this),
- GetExitNotifierFD(), base::Passed(&client_socket)));
- initialized_ = true;
- }
-
- private:
- void StartController(int exit_notifier_fd, scoped_ptr client_socket) {
- DCHECK(!controller_.get());
- scoped_ptr controller(
- DeviceController::Create(kUnixDomainSocketPath, exit_notifier_fd));
- if (!controller.get()) {
- client_socket->WriteString(
- base::StringPrintf("ERROR: Could not initialize device controller "
- "with ADB socket path: %s",
- kUnixDomainSocketPath));
- return;
- }
- controller_.swap(controller);
- controller_->Start();
- client_socket->WriteString("OK");
- client_socket->Close();
- }
-
- scoped_ptr controller_;
- scoped_ptr controller_thread_;
- bool initialized_;
-};
-
-class ClientDelegate : public Daemon::ClientDelegate {
- public:
- ClientDelegate() : has_failed_(false) {}
-
- bool has_failed() const { return has_failed_; }
-
- // Daemon::ClientDelegate:
- virtual void OnDaemonReady(Socket* daemon_socket) OVERRIDE {
- char buf[kBufSize];
- const int bytes_read = daemon_socket->Read(
- buf, sizeof(buf) - 1 /* leave space for null terminator */);
- CHECK_GT(bytes_read, 0);
- DCHECK(bytes_read < sizeof(buf));
- buf[bytes_read] = 0;
- base::StringPiece msg(buf, bytes_read);
- if (msg.starts_with("ERROR")) {
- LOG(ERROR) << msg;
- has_failed_ = true;
- return;
- }
- }
-
- private:
- bool has_failed_;
-};
-
-int RunDeviceForwarder(int argc, char** argv) {
- CommandLine::Init(argc, argv); // Needed by logging.
- const bool kill_server = CommandLine::ForCurrentProcess()->HasSwitch(
- "kill-server");
- if ((kill_server && argc != 2) || (!kill_server && argc != 1)) {
- std::cerr << "Usage: device_forwarder [--kill-server]" << std::endl;
- return 1;
- }
- base::AtExitManager at_exit_manager; // Used by base::Thread.
- ClientDelegate client_delegate;
- ServerDelegate daemon_delegate;
- const char kLogFilePath[] = ""; // Log to logcat.
- Daemon daemon(kLogFilePath, kDaemonIdentifier, &client_delegate,
- &daemon_delegate, &GetExitNotifierFD);
-
- if (kill_server)
- return !daemon.Kill();
-
- if (!daemon.SpawnIfNeeded())
- return 1;
- return client_delegate.has_failed();
-}
-
-} // namespace
-} // namespace forwarder2
-
-int main(int argc, char** argv) {
- return forwarder2::RunDeviceForwarder(argc, argv);
-}
diff --git a/tools/android/forwarder2/device_listener.cc b/tools/android/forwarder2/device_listener.cc
deleted file mode 100644
index 1819a8a6ed..0000000000
--- a/tools/android/forwarder2/device_listener.cc
+++ /dev/null
@@ -1,148 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "tools/android/forwarder2/device_listener.h"
-
-#include "base/bind.h"
-#include "base/bind_helpers.h"
-#include "base/callback.h"
-#include "base/logging.h"
-#include "base/memory/scoped_ptr.h"
-#include "base/message_loop/message_loop_proxy.h"
-#include "base/single_thread_task_runner.h"
-#include "tools/android/forwarder2/command.h"
-#include "tools/android/forwarder2/forwarder.h"
-#include "tools/android/forwarder2/socket.h"
-
-namespace forwarder2 {
-
-// static
-scoped_ptr DeviceListener::Create(
- scoped_ptr host_socket,
- int listener_port,
- const DeleteCallback& delete_callback) {
- scoped_ptr listener_socket(new Socket());
- scoped_ptr device_listener;
- if (!listener_socket->BindTcp("", listener_port)) {
- LOG(ERROR) << "Device could not bind and listen to local port "
- << listener_port;
- SendCommand(command::BIND_ERROR, listener_port, host_socket.get());
- return device_listener.Pass();
- }
- // In case the |listener_port_| was zero, GetPort() will return the
- // currently (non-zero) allocated port for this socket.
- listener_port = listener_socket->GetPort();
- SendCommand(command::BIND_SUCCESS, listener_port, host_socket.get());
- device_listener.reset(
- new DeviceListener(
- scoped_ptr(new PipeNotifier()), listener_socket.Pass(),
- host_socket.Pass(), listener_port, delete_callback));
- return device_listener.Pass();
-}
-
-DeviceListener::~DeviceListener() {
- DCHECK(deletion_task_runner_->RunsTasksOnCurrentThread());
- exit_notifier_->Notify();
-}
-
-void DeviceListener::Start() {
- thread_.Start();
- AcceptNextClientSoon();
-}
-
-void DeviceListener::SetAdbDataSocket(scoped_ptr adb_data_socket) {
- thread_.message_loop_proxy()->PostTask(
- FROM_HERE,
- base::Bind(&DeviceListener::OnAdbDataSocketReceivedOnInternalThread,
- base::Unretained(this), base::Passed(&adb_data_socket)));
-}
-
-DeviceListener::DeviceListener(scoped_ptr pipe_notifier,
- scoped_ptr listener_socket,
- scoped_ptr host_socket,
- int port,
- const DeleteCallback& delete_callback)
- : exit_notifier_(pipe_notifier.Pass()),
- listener_socket_(listener_socket.Pass()),
- host_socket_(host_socket.Pass()),
- listener_port_(port),
- delete_callback_(delete_callback),
- deletion_task_runner_(base::MessageLoopProxy::current()),
- thread_("DeviceListener") {
- CHECK(host_socket_.get());
- DCHECK(deletion_task_runner_.get());
- DCHECK(exit_notifier_.get());
- host_socket_->AddEventFd(exit_notifier_->receiver_fd());
- listener_socket_->AddEventFd(exit_notifier_->receiver_fd());
-}
-
-void DeviceListener::AcceptNextClientSoon() {
- thread_.message_loop_proxy()->PostTask(
- FROM_HERE,
- base::Bind(&DeviceListener::AcceptClientOnInternalThread,
- base::Unretained(this)));
-}
-
-void DeviceListener::AcceptClientOnInternalThread() {
- device_data_socket_.reset(new Socket());
- if (!listener_socket_->Accept(device_data_socket_.get())) {
- if (listener_socket_->DidReceiveEvent()) {
- LOG(INFO) << "Received exit notification, stopped accepting clients.";
- SelfDelete();
- return;
- }
- LOG(WARNING) << "Could not Accept in ListenerSocket.";
- SendCommand(command::ACCEPT_ERROR, listener_port_, host_socket_.get());
- SelfDelete();
- return;
- }
- SendCommand(command::ACCEPT_SUCCESS, listener_port_, host_socket_.get());
- if (!ReceivedCommand(command::HOST_SERVER_SUCCESS,
- host_socket_.get())) {
- SendCommand(command::ACK, listener_port_, host_socket_.get());
- LOG(ERROR) << "Host could not connect to server.";
- device_data_socket_->Close();
- if (host_socket_->has_error()) {
- LOG(ERROR) << "Adb Control connection lost. "
- << "Listener port: " << listener_port_;
- SelfDelete();
- return;
- }
- // It can continue if the host forwarder could not connect to the host
- // server but the control connection is still alive (no errors). The device
- // acknowledged that (above), and it can re-try later.
- AcceptNextClientSoon();
- return;
- }
-}
-
-void DeviceListener::OnAdbDataSocketReceivedOnInternalThread(
- scoped_ptr adb_data_socket) {
- adb_data_socket_.swap(adb_data_socket);
- SendCommand(command::ADB_DATA_SOCKET_SUCCESS, listener_port_,
- host_socket_.get());
- CHECK(adb_data_socket_.get());
- StartForwarder(device_data_socket_.Pass(), adb_data_socket_.Pass());
- AcceptNextClientSoon();
-}
-
-void DeviceListener::SelfDelete() {
- if (!deletion_task_runner_->RunsTasksOnCurrentThread()) {
- deletion_task_runner_->PostTask(
- FROM_HERE,
- base::Bind(&DeviceListener::SelfDeleteOnDeletionTaskRunner,
- delete_callback_, listener_port_));
- return;
- }
- SelfDeleteOnDeletionTaskRunner(delete_callback_, listener_port_);
-}
-
-// static
-void DeviceListener::SelfDeleteOnDeletionTaskRunner(
- const DeleteCallback& delete_callback,
- int listener_port) {
- delete_callback.Run(listener_port);
-}
-
-} // namespace forwarder
diff --git a/tools/android/forwarder2/device_listener.h b/tools/android/forwarder2/device_listener.h
deleted file mode 100644
index 2a69823196..0000000000
--- a/tools/android/forwarder2/device_listener.h
+++ /dev/null
@@ -1,114 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef TOOLS_ANDROID_FORWARDER2_DEVICE_LISTENER_H_
-#define TOOLS_ANDROID_FORWARDER2_DEVICE_LISTENER_H_
-
-#include "base/basictypes.h"
-#include "base/callback.h"
-#include "base/compiler_specific.h"
-#include "base/logging.h"
-#include "base/memory/ref_counted.h"
-#include "base/memory/scoped_ptr.h"
-#include "base/threading/thread.h"
-#include "tools/android/forwarder2/pipe_notifier.h"
-#include "tools/android/forwarder2/socket.h"
-
-namespace base {
-class SingleThreadTaskRunner;
-} // namespace base
-
-namespace forwarder2 {
-
-class Forwarder;
-
-// A DeviceListener instance is used in the device_forwarder program to bind to
-// a specific device-side |port| and wait for client connections. When a
-// connection happens, it informs the corresponding HostController instance
-// running on the host, through |host_socket|. Then the class expects a call to
-// its SetAdbDataSocket() method (performed by the device controller) once the
-// host opened a new connection to the device. When this happens, a new internal
-// Forwarder instance is started.
-// Note that instances of this class are owned by the device controller which
-// creates and destroys them on the same thread. In case an internal error
-// happens on the DeviceListener's internal thread, the DeviceListener
-// can also self-delete by executing the user-provided callback on the thread
-// the DeviceListener was created on.
-// Note that the DeviceListener's destructor joins its internal thread (i.e.
-// waits for its completion) which means that the internal thread is guaranteed
-// not to be running anymore once the object is deleted.
-class DeviceListener {
- public:
- // Callback that is used for self-deletion as a way to let the device
- // controller perform some additional cleanup work (e.g. removing the device
- // listener instance from its internal map before deleting it).
- typedef base::Callback DeleteCallback;
-
- static scoped_ptr Create(
- scoped_ptr host_socket,
- int port,
- const DeleteCallback& delete_callback);
-
- ~DeviceListener();
-
- void Start();
-
- void SetAdbDataSocket(scoped_ptr adb_data_socket);
-
- int listener_port() const { return listener_port_; }
-
- private:
- DeviceListener(scoped_ptr pipe_notifier,
- scoped_ptr listener_socket,
- scoped_ptr host_socket,
- int port,
- const DeleteCallback& delete_callback);
-
- // Pushes an AcceptClientOnInternalThread() task to the internal thread's
- // message queue in order to wait for a new client soon.
- void AcceptNextClientSoon();
-
- void AcceptClientOnInternalThread();
-
- void OnAdbDataSocketReceivedOnInternalThread(
- scoped_ptr adb_data_socket);
-
- void SelfDelete();
-
- // Note that this can be called after the DeviceListener instance gets deleted
- // which is why this method is static.
- static void SelfDeleteOnDeletionTaskRunner(
- const DeleteCallback& delete_callback,
- int listener_port);
-
- // Used for the listener thread to be notified on destruction. We have one
- // notifier per Listener thread since each Listener thread may be requested to
- // exit for different reasons independently from each other and independent
- // from the main program, ex. when the host requests to forward/listen the
- // same port again. Both the |host_socket_| and |listener_socket_|
- // must share the same receiver file descriptor from |exit_notifier_| and it
- // is set in the constructor.
- const scoped_ptr exit_notifier_;
- // The local device listener socket for accepting connections from the local
- // port (listener_port_).
- const scoped_ptr listener_socket_;
- // The listener socket for sending control commands.
- const scoped_ptr host_socket_;
- scoped_ptr device_data_socket_;
- // This is the adb connection to transport the actual data, used for creating
- // the forwarder. Ownership transferred to the Forwarder.
- scoped_ptr adb_data_socket_;
- const int listener_port_;
- const DeleteCallback delete_callback_;
- // Task runner used for deletion set at construction time (i.e. the object is
- // deleted on the same thread it is created on).
- scoped_refptr deletion_task_runner_;
- base::Thread thread_;
-
- DISALLOW_COPY_AND_ASSIGN(DeviceListener);
-};
-
-} // namespace forwarder
-
-#endif // TOOLS_ANDROID_FORWARDER2_DEVICE_LISTENER_H_
diff --git a/tools/android/forwarder2/forwarder.cc b/tools/android/forwarder2/forwarder.cc
deleted file mode 100644
index df4c29cf9f..0000000000
--- a/tools/android/forwarder2/forwarder.cc
+++ /dev/null
@@ -1,171 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "tools/android/forwarder2/forwarder.h"
-
-#include "base/basictypes.h"
-#include "base/bind.h"
-#include "base/logging.h"
-#include "base/memory/ref_counted.h"
-#include "base/posix/eintr_wrapper.h"
-#include "base/single_thread_task_runner.h"
-#include "tools/android/forwarder2/socket.h"
-
-namespace forwarder2 {
-namespace {
-
-// Helper class to buffer reads and writes from one socket to another.
-class BufferedCopier {
- public:
- // Does NOT own the pointers.
- BufferedCopier(Socket* socket_from,
- Socket* socket_to)
- : socket_from_(socket_from),
- socket_to_(socket_to),
- bytes_read_(0),
- write_offset_(0) {
- }
-
- bool AddToReadSet(fd_set* read_fds) {
- if (bytes_read_ == 0)
- return socket_from_->AddFdToSet(read_fds);
- return false;
- }
-
- bool AddToWriteSet(fd_set* write_fds) {
- if (write_offset_ < bytes_read_)
- return socket_to_->AddFdToSet(write_fds);
- return false;
- }
-
- bool TryRead(const fd_set& read_fds) {
- if (!socket_from_->IsFdInSet(read_fds))
- return false;
- if (bytes_read_ != 0) // Can't read.
- return false;
- int ret = socket_from_->Read(buffer_, kBufferSize);
- if (ret > 0) {
- bytes_read_ = ret;
- return true;
- }
- return false;
- }
-
- bool TryWrite(const fd_set& write_fds) {
- if (!socket_to_->IsFdInSet(write_fds))
- return false;
- if (write_offset_ >= bytes_read_) // Nothing to write.
- return false;
- int ret = socket_to_->Write(buffer_ + write_offset_,
- bytes_read_ - write_offset_);
- if (ret > 0) {
- write_offset_ += ret;
- if (write_offset_ == bytes_read_) {
- write_offset_ = 0;
- bytes_read_ = 0;
- }
- return true;
- }
- return false;
- }
-
- private:
- // Not owned.
- Socket* socket_from_;
- Socket* socket_to_;
-
- // A big buffer to let our file-over-http bridge work more like real file.
- static const int kBufferSize = 1024 * 128;
- int bytes_read_;
- int write_offset_;
- char buffer_[kBufferSize];
-
- DISALLOW_COPY_AND_ASSIGN(BufferedCopier);
-};
-
-// Internal class that wraps a helper thread to forward traffic between
-// |socket1| and |socket2|. After creating a new instance, call its Start()
-// method to launch operations. Thread stops automatically if one of the socket
-// disconnects, but ensures that all buffered writes to the other, still alive,
-// socket, are written first. When this happens, the instance will delete itself
-// automatically.
-// Note that the instance will always be destroyed on the same thread that
-// created it.
-class Forwarder {
- public:
- Forwarder(scoped_ptr socket1, scoped_ptr socket2)
- : socket1_(socket1.Pass()),
- socket2_(socket2.Pass()),
- destructor_runner_(base::MessageLoopProxy::current()),
- thread_("ForwarderThread") {
- }
-
- void Start() {
- thread_.Start();
- thread_.message_loop_proxy()->PostTask(
- FROM_HERE,
- base::Bind(&Forwarder::ThreadHandler, base::Unretained(this)));
- }
-
- private:
- void ThreadHandler() {
- const int nfds = Socket::GetHighestFileDescriptor(*socket1_, *socket2_) + 1;
- fd_set read_fds;
- fd_set write_fds;
-
- // Copy from socket1 to socket2
- BufferedCopier buffer1(socket1_.get(), socket2_.get());
- // Copy from socket2 to socket1
- BufferedCopier buffer2(socket2_.get(), socket1_.get());
-
- bool run = true;
- while (run) {
- FD_ZERO(&read_fds);
- FD_ZERO(&write_fds);
-
- buffer1.AddToReadSet(&read_fds);
- buffer2.AddToReadSet(&read_fds);
- buffer1.AddToWriteSet(&write_fds);
- buffer2.AddToWriteSet(&write_fds);
-
- if (HANDLE_EINTR(select(nfds, &read_fds, &write_fds, NULL, NULL)) <= 0) {
- PLOG(ERROR) << "select";
- break;
- }
- // When a socket in the read set closes the connection, select() returns
- // with that socket descriptor set as "ready to read". When we call
- // TryRead() below, it will return false, but the while loop will continue
- // to run until all the write operations are finished, to make sure the
- // buffers are completely flushed out.
-
- // Keep running while we have some operation to do.
- run = buffer1.TryRead(read_fds);
- run = run || buffer2.TryRead(read_fds);
- run = run || buffer1.TryWrite(write_fds);
- run = run || buffer2.TryWrite(write_fds);
- }
-
- // Note that the thread that |destruction_runner_| runs tasks on could be
- // temporarily blocked on I/O (e.g. select()) therefore it is safer to close
- // the sockets now rather than relying on the destructor.
- socket1_.reset();
- socket2_.reset();
-
- // Note that base::Thread must be destroyed on the thread it was created on.
- destructor_runner_->DeleteSoon(FROM_HERE, this);
- }
-
- scoped_ptr socket1_;
- scoped_ptr socket2_;
- scoped_refptr destructor_runner_;
- base::Thread thread_;
-};
-
-} // namespace
-
-void StartForwarder(scoped_ptr socket1, scoped_ptr socket2) {
- (new Forwarder(socket1.Pass(), socket2.Pass()))->Start();
-}
-
-} // namespace forwarder2
diff --git a/tools/android/forwarder2/forwarder.gyp b/tools/android/forwarder2/forwarder.gyp
deleted file mode 100644
index fdc19aa4ce..0000000000
--- a/tools/android/forwarder2/forwarder.gyp
+++ /dev/null
@@ -1,85 +0,0 @@
-# Copyright (c) 2012 The Chromium Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-{
- 'targets': [
- {
- 'target_name': 'forwarder2',
- 'type': 'none',
- 'dependencies': [
- 'device_forwarder',
- 'host_forwarder#host',
- ],
- # For the component build, ensure dependent shared libraries are stripped
- # and put alongside forwarder to simplify pushing to the device.
- 'variables': {
- 'output_dir': '<(PRODUCT_DIR)/forwarder_dist/',
- 'native_binary': '<(PRODUCT_DIR)/device_forwarder',
- },
- 'includes': ['../../../build/android/native_app_dependencies.gypi'],
- },
- {
- 'target_name': 'device_forwarder',
- 'type': 'executable',
- 'toolsets': ['target'],
- 'dependencies': [
- '../../../base/base.gyp:base',
- '../common/common.gyp:android_tools_common',
- ],
- 'include_dirs': [
- '../../..',
- ],
- 'conditions': [
- # Warning: A PIE tool cannot run on ICS 4.0.4, so only
- # build it as position-independent when ASAN
- # is activated. See b/6587214 for details.
- [ 'asan==1', {
- 'cflags': [
- '-fPIE',
- ],
- 'ldflags': [
- '-pie',
- ],
- }],
- ],
- 'sources': [
- 'command.cc',
- 'common.cc',
- 'daemon.cc',
- 'device_controller.cc',
- 'device_forwarder_main.cc',
- 'device_listener.cc',
- 'forwarder.cc',
- 'pipe_notifier.cc',
- 'socket.cc',
- ],
- },
- {
- 'target_name': 'host_forwarder',
- 'type': 'executable',
- 'toolsets': ['host'],
- 'dependencies': [
- '../../../base/base.gyp:base',
- '../common/common.gyp:android_tools_common',
- ],
- 'include_dirs': [
- '../../..',
- ],
- 'sources': [
- 'command.cc',
- 'common.cc',
- 'daemon.cc',
- 'forwarder.cc',
- 'host_controller.cc',
- 'host_forwarder_main.cc',
- 'pipe_notifier.cc',
- 'socket.cc',
- # TODO(pliard): Remove this. This is needed to avoid undefined
- # references at link time.
- '../../../base/message_loop/message_pump_glib.cc',
- '../../../base/message_loop/message_pump_gtk.cc',
- ],
- },
- ],
-}
diff --git a/tools/android/forwarder2/forwarder.h b/tools/android/forwarder2/forwarder.h
deleted file mode 100644
index 651b5e80f7..0000000000
--- a/tools/android/forwarder2/forwarder.h
+++ /dev/null
@@ -1,19 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef TOOLS_ANDROID_FORWARDER2_FORWARDER_H_
-#define TOOLS_ANDROID_FORWARDER2_FORWARDER_H_
-
-#include "base/memory/scoped_ptr.h"
-#include "base/threading/thread.h"
-
-namespace forwarder2 {
-
-class Socket;
-
-void StartForwarder(scoped_ptr socket1, scoped_ptr socket2);
-
-} // namespace forwarder2
-
-#endif // TOOLS_ANDROID_FORWARDER2_FORWARDER_H_
diff --git a/tools/android/forwarder2/host_controller.cc b/tools/android/forwarder2/host_controller.cc
deleted file mode 100644
index 1588e7291b..0000000000
--- a/tools/android/forwarder2/host_controller.cc
+++ /dev/null
@@ -1,186 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "tools/android/forwarder2/host_controller.h"
-
-#include
-
-#include "base/bind.h"
-#include "base/bind_helpers.h"
-#include "base/logging.h"
-#include "base/memory/scoped_ptr.h"
-#include "tools/android/forwarder2/command.h"
-#include "tools/android/forwarder2/forwarder.h"
-#include "tools/android/forwarder2/socket.h"
-
-namespace forwarder2 {
-
-// static
-scoped_ptr HostController::Create(
- int device_port,
- int host_port,
- int adb_port,
- int exit_notifier_fd,
- const DeletionCallback& deletion_callback) {
- scoped_ptr host_controller;
- scoped_ptr delete_controller_notifier(new PipeNotifier());
- scoped_ptr adb_control_socket(new Socket());
- adb_control_socket->AddEventFd(exit_notifier_fd);
- adb_control_socket->AddEventFd(delete_controller_notifier->receiver_fd());
- if (!adb_control_socket->ConnectTcp(std::string(), adb_port)) {
- LOG(ERROR) << "Could not connect HostController socket on port: "
- << adb_port;
- return host_controller.Pass();
- }
- // Send the command to the device start listening to the "device_forward_port"
- bool send_command_success = SendCommand(
- command::LISTEN, device_port, adb_control_socket.get());
- CHECK(send_command_success);
- int device_port_allocated;
- command::Type command;
- if (!ReadCommand(
- adb_control_socket.get(), &device_port_allocated, &command) ||
- command != command::BIND_SUCCESS) {
- LOG(ERROR) << "Device binding error using port " << device_port;
- return host_controller.Pass();
- }
- host_controller.reset(
- new HostController(
- device_port_allocated, host_port, adb_port, exit_notifier_fd,
- deletion_callback, adb_control_socket.Pass(),
- delete_controller_notifier.Pass()));
- return host_controller.Pass();
-}
-
-HostController::~HostController() {
- DCHECK(deletion_task_runner_->RunsTasksOnCurrentThread());
- delete_controller_notifier_->Notify();
- // Note that the Forwarder instance (that also received a delete notification)
- // might still be running on its own thread at this point. This is not a
- // problem since it will self-delete once the socket that it is operating on
- // is closed.
-}
-
-void HostController::Start() {
- thread_.Start();
- ReadNextCommandSoon();
-}
-
-HostController::HostController(
- int device_port,
- int host_port,
- int adb_port,
- int exit_notifier_fd,
- const DeletionCallback& deletion_callback,
- scoped_ptr adb_control_socket,
- scoped_ptr delete_controller_notifier)
- : device_port_(device_port),
- host_port_(host_port),
- adb_port_(adb_port),
- global_exit_notifier_fd_(exit_notifier_fd),
- deletion_callback_(deletion_callback),
- adb_control_socket_(adb_control_socket.Pass()),
- delete_controller_notifier_(delete_controller_notifier.Pass()),
- deletion_task_runner_(base::MessageLoopProxy::current()),
- thread_("HostControllerThread") {
-}
-
-void HostController::ReadNextCommandSoon() {
- thread_.message_loop_proxy()->PostTask(
- FROM_HERE,
- base::Bind(&HostController::ReadCommandOnInternalThread,
- base::Unretained(this)));
-}
-
-void HostController::ReadCommandOnInternalThread() {
- if (!ReceivedCommand(command::ACCEPT_SUCCESS, adb_control_socket_.get())) {
- SelfDelete();
- return;
- }
- // Try to connect to host server.
- scoped_ptr host_server_data_socket(CreateSocket());
- if (!host_server_data_socket->ConnectTcp(std::string(), host_port_)) {
- LOG(ERROR) << "Could not Connect HostServerData socket on port: "
- << host_port_;
- SendCommand(
- command::HOST_SERVER_ERROR, device_port_, adb_control_socket_.get());
- if (ReceivedCommand(command::ACK, adb_control_socket_.get())) {
- // It can continue if the host forwarder could not connect to the host
- // server but the device acknowledged that, so that the device could
- // re-try later.
- ReadNextCommandSoon();
- return;
- }
- SelfDelete();
- return;
- }
- SendCommand(
- command::HOST_SERVER_SUCCESS, device_port_, adb_control_socket_.get());
- StartForwarder(host_server_data_socket.Pass());
- ReadNextCommandSoon();
-}
-
-void HostController::StartForwarder(
- scoped_ptr host_server_data_socket) {
- scoped_ptr adb_data_socket(CreateSocket());
- if (!adb_data_socket->ConnectTcp("", adb_port_)) {
- LOG(ERROR) << "Could not connect AdbDataSocket on port: " << adb_port_;
- SelfDelete();
- return;
- }
- // Open the Adb data connection, and send a command with the
- // |device_forward_port| as a way for the device to identify the connection.
- SendCommand(command::DATA_CONNECTION, device_port_, adb_data_socket.get());
-
- // Check that the device received the new Adb Data Connection. Note that this
- // check is done through the |adb_control_socket_| that is handled in the
- // DeviceListener thread just after the call to WaitForAdbDataSocket().
- if (!ReceivedCommand(command::ADB_DATA_SOCKET_SUCCESS,
- adb_control_socket_.get())) {
- LOG(ERROR) << "Device could not handle the new Adb Data Connection.";
- SelfDelete();
- return;
- }
- forwarder2::StartForwarder(
- host_server_data_socket.Pass(), adb_data_socket.Pass());
-}
-
-scoped_ptr HostController::CreateSocket() {
- scoped_ptr socket(new Socket());
- socket->AddEventFd(global_exit_notifier_fd_);
- socket->AddEventFd(delete_controller_notifier_->receiver_fd());
- return socket.Pass();
-}
-
-void HostController::SelfDelete() {
- scoped_ptr self_deleter(this);
- deletion_task_runner_->PostTask(
- FROM_HERE,
- base::Bind(&HostController::SelfDeleteOnDeletionTaskRunner,
- deletion_callback_, base::Passed(&self_deleter)));
- // Tell the device to delete its corresponding controller instance before we
- // self-delete.
- Socket socket;
- if (!socket.ConnectTcp("", adb_port_)) {
- LOG(ERROR) << "Could not connect to device on port " << adb_port_;
- return;
- }
- if (!SendCommand(command::UNLISTEN, device_port_, &socket)) {
- LOG(ERROR) << "Could not send unmap command for port " << device_port_;
- return;
- }
- if (!ReceivedCommand(command::UNLISTEN_SUCCESS, &socket)) {
- LOG(ERROR) << "Unamp command failed for port " << device_port_;
- return;
- }
-}
-
-// static
-void HostController::SelfDeleteOnDeletionTaskRunner(
- const DeletionCallback& deletion_callback,
- scoped_ptr controller) {
- deletion_callback.Run(controller.Pass());
-}
-
-} // namespace forwarder2
diff --git a/tools/android/forwarder2/host_controller.h b/tools/android/forwarder2/host_controller.h
deleted file mode 100644
index aaedb945e8..0000000000
--- a/tools/android/forwarder2/host_controller.h
+++ /dev/null
@@ -1,99 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef TOOLS_ANDROID_FORWARDER2_HOST_CONTROLLER_H_
-#define TOOLS_ANDROID_FORWARDER2_HOST_CONTROLLER_H_
-
-#include
-
-#include "base/basictypes.h"
-#include "base/callback.h"
-#include "base/compiler_specific.h"
-#include "base/memory/scoped_ptr.h"
-#include "base/threading/thread.h"
-#include "tools/android/forwarder2/pipe_notifier.h"
-#include "tools/android/forwarder2/socket.h"
-
-namespace forwarder2 {
-
-// This class partners with DeviceController and has the same lifetime and
-// threading characteristics as DeviceListener. In a nutshell, this class
-// operates on its own thread and is destroyed on the thread it was constructed
-// on. The class' deletion can happen in two different ways:
-// - Its destructor was called by its owner (HostControllersManager).
-// - Its internal thread requested self-deletion after an error happened. In
-// this case the owner (HostControllersManager) is notified on the
-// construction thread through the provided DeletionCallback invoked with the
-// HostController instance. When this callback is invoked, it's up to the
-// owner to delete the instance.
-class HostController {
- public:
- // Callback used for self-deletion that lets the client perform some cleanup
- // work before deleting the HostController instance.
- typedef base::Callback)> DeletionCallback;
-
- // If |device_port| is zero then a dynamic port is allocated (and retrievable
- // through device_port() below).
- static scoped_ptr Create(
- int device_port,
- int host_port,
- int adb_port,
- int exit_notifier_fd,
- const DeletionCallback& deletion_callback);
-
- ~HostController();
-
- // Starts the internal controller thread.
- void Start();
-
- int adb_port() const { return adb_port_; }
-
- int device_port() const { return device_port_; }
-
- private:
- HostController(int device_port,
- int host_port,
- int adb_port,
- int exit_notifier_fd,
- const DeletionCallback& deletion_callback,
- scoped_ptr adb_control_socket,
- scoped_ptr delete_controller_notifier);
-
- void ReadNextCommandSoon();
- void ReadCommandOnInternalThread();
-
- void StartForwarder(scoped_ptr host_server_data_socket);
-
- // Helper method that creates a socket and adds the appropriate event file
- // descriptors.
- scoped_ptr CreateSocket();
-
- void SelfDelete();
-
- static void SelfDeleteOnDeletionTaskRunner(
- const DeletionCallback& deletion_callback,
- scoped_ptr controller);
-
- const int device_port_;
- const int host_port_;
- const int adb_port_;
- // Used to notify the controller when the process is killed.
- const int global_exit_notifier_fd_;
- // Used to let the client delete the instance in case an error happened.
- const DeletionCallback deletion_callback_;
- scoped_ptr adb_control_socket_;
- scoped_ptr delete_controller_notifier_;
- // Used to cancel the pending blocking IO operations when the host controller
- // instance is deleted.
- // Task runner used for deletion set at construction time (i.e. the object is
- // deleted on the same thread it is created on).
- const scoped_refptr deletion_task_runner_;
- base::Thread thread_;
-
- DISALLOW_COPY_AND_ASSIGN(HostController);
-};
-
-} // namespace forwarder2
-
-#endif // TOOLS_ANDROID_FORWARDER2_HOST_CONTROLLER_H_
diff --git a/tools/android/forwarder2/host_forwarder_main.cc b/tools/android/forwarder2/host_forwarder_main.cc
deleted file mode 100644
index 1071aa7dd4..0000000000
--- a/tools/android/forwarder2/host_forwarder_main.cc
+++ /dev/null
@@ -1,414 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include
-#include
-#include
-#include
-#include
-
-#include
-#include
-#include
-#include
-#include
-#include
-
-#include "base/at_exit.h"
-#include "base/basictypes.h"
-#include "base/bind.h"
-#include "base/command_line.h"
-#include "base/compiler_specific.h"
-#include "base/containers/hash_tables.h"
-#include "base/file_util.h"
-#include "base/files/file_path.h"
-#include "base/logging.h"
-#include "base/memory/linked_ptr.h"
-#include "base/memory/scoped_vector.h"
-#include "base/memory/weak_ptr.h"
-#include "base/pickle.h"
-#include "base/posix/eintr_wrapper.h"
-#include "base/safe_strerror_posix.h"
-#include "base/strings/string_number_conversions.h"
-#include "base/strings/string_piece.h"
-#include "base/strings/string_split.h"
-#include "base/strings/string_util.h"
-#include "base/strings/stringprintf.h"
-#include "base/task_runner.h"
-#include "base/threading/thread.h"
-#include "tools/android/forwarder2/common.h"
-#include "tools/android/forwarder2/daemon.h"
-#include "tools/android/forwarder2/host_controller.h"
-#include "tools/android/forwarder2/pipe_notifier.h"
-#include "tools/android/forwarder2/socket.h"
-
-namespace forwarder2 {
-namespace {
-
-const char kLogFilePath[] = "/tmp/host_forwarder_log";
-const char kDaemonIdentifier[] = "chrome_host_forwarder_daemon";
-
-const char kKillServerCommand[] = "kill-server";
-const char kForwardCommand[] = "forward";
-
-const int kBufSize = 256;
-
-// Needs to be global to be able to be accessed from the signal handler.
-PipeNotifier* g_notifier = NULL;
-
-// Lets the daemon fetch the exit notifier file descriptor.
-int GetExitNotifierFD() {
- DCHECK(g_notifier);
- return g_notifier->receiver_fd();
-}
-
-void KillHandler(int signal_number) {
- char buf[kBufSize];
- if (signal_number != SIGTERM && signal_number != SIGINT) {
- snprintf(buf, sizeof(buf), "Ignoring unexpected signal %d.", signal_number);
- SIGNAL_SAFE_LOG(WARNING, buf);
- return;
- }
- snprintf(buf, sizeof(buf), "Received signal %d.", signal_number);
- SIGNAL_SAFE_LOG(WARNING, buf);
- static int s_kill_handler_count = 0;
- CHECK(g_notifier);
- // If for some reason the forwarder get stuck in any socket waiting forever,
- // we can send a SIGKILL or SIGINT three times to force it die
- // (non-nicely). This is useful when debugging.
- ++s_kill_handler_count;
- if (!g_notifier->Notify() || s_kill_handler_count > 2)
- exit(1);
-}
-
-// Manages HostController instances. There is one HostController instance for
-// each connection being forwarded. Note that forwarding can happen with many
-// devices (identified with a serial id).
-class HostControllersManager {
- public:
- HostControllersManager()
- : weak_ptr_factory_(this),
- controllers_(new HostControllerMap()),
- has_failed_(false) {
- }
-
- ~HostControllersManager() {
- if (!thread_.get())
- return;
- // Delete the controllers on the thread they were created on.
- thread_->message_loop_proxy()->DeleteSoon(
- FROM_HERE, controllers_.release());
- }
-
- void HandleRequest(const std::string& device_serial,
- int device_port,
- int host_port,
- scoped_ptr client_socket) {
- // Lazy initialize so that the CLI process doesn't get this thread created.
- InitOnce();
- thread_->message_loop_proxy()->PostTask(
- FROM_HERE,
- base::Bind(
- &HostControllersManager::HandleRequestOnInternalThread,
- base::Unretained(this), device_serial, device_port, host_port,
- base::Passed(&client_socket)));
- }
-
- bool has_failed() const { return has_failed_; }
-
- private:
- typedef base::hash_map<
- std::string, linked_ptr > HostControllerMap;
-
- static std::string MakeHostControllerMapKey(int adb_port, int device_port) {
- return base::StringPrintf("%d:%d", adb_port, device_port);
- }
-
- void InitOnce() {
- if (thread_.get())
- return;
- at_exit_manager_.reset(new base::AtExitManager());
- thread_.reset(new base::Thread("HostControllersManagerThread"));
- thread_->Start();
- }
-
- // Invoked when a HostController instance reports an error (e.g. due to a
- // device connectivity issue). Note that this could be called after the
- // controller manager was destroyed which is why a weak pointer is used.
- static void DeleteHostController(
- const base::WeakPtr& manager_ptr,
- scoped_ptr host_controller) {
- HostController* const controller = host_controller.release();
- HostControllersManager* const manager = manager_ptr.get();
- if (!manager) {
- // Note that |controller| is not leaked in this case since the host
- // controllers manager owns the controllers. If the manager was deleted
- // then all the controllers (including |controller|) were also deleted.
- return;
- }
- DCHECK(manager->thread_->message_loop_proxy()->RunsTasksOnCurrentThread());
- // Note that this will delete |controller| which is owned by the map.
- manager->controllers_->erase(
- MakeHostControllerMapKey(controller->adb_port(),
- controller->device_port()));
- }
-
- void HandleRequestOnInternalThread(const std::string& device_serial,
- int device_port,
- int host_port,
- scoped_ptr client_socket) {
- const int adb_port = GetAdbPortForDevice(device_serial);
- if (adb_port < 0) {
- SendMessage(
- "ERROR: could not get adb port for device. You might need to add "
- "'adb' to your PATH or provide the device serial id.",
- client_socket.get());
- return;
- }
- if (device_port < 0) {
- // Remove the previously created host controller.
- const std::string controller_key = MakeHostControllerMapKey(
- adb_port, -device_port);
- const HostControllerMap::size_type removed_elements = controllers_->erase(
- controller_key);
- SendMessage(
- !removed_elements ? "ERROR: could not unmap port" : "OK",
- client_socket.get());
- return;
- }
- if (host_port < 0) {
- SendMessage("ERROR: missing host port", client_socket.get());
- return;
- }
- const bool use_dynamic_port_allocation = device_port == 0;
- if (!use_dynamic_port_allocation) {
- const std::string controller_key = MakeHostControllerMapKey(
- adb_port, device_port);
- if (controllers_->find(controller_key) != controllers_->end()) {
- LOG(INFO) << "Already forwarding device port " << device_port
- << " to host port " << host_port;
- SendMessage(base::StringPrintf("%d:%d", device_port, host_port),
- client_socket.get());
- return;
- }
- }
- // Create a new host controller.
- scoped_ptr host_controller(
- HostController::Create(
- device_port, host_port, adb_port, GetExitNotifierFD(),
- base::Bind(&HostControllersManager::DeleteHostController,
- weak_ptr_factory_.GetWeakPtr())));
- if (!host_controller.get()) {
- has_failed_ = true;
- SendMessage("ERROR: Connection to device failed.", client_socket.get());
- return;
- }
- // Get the current allocated port.
- device_port = host_controller->device_port();
- LOG(INFO) << "Forwarding device port " << device_port << " to host port "
- << host_port;
- const std::string msg = base::StringPrintf("%d:%d", device_port, host_port);
- if (!SendMessage(msg, client_socket.get()))
- return;
- host_controller->Start();
- controllers_->insert(
- std::make_pair(MakeHostControllerMapKey(adb_port, device_port),
- linked_ptr(host_controller.release())));
- }
-
- int GetAdbPortForDevice(const std::string& device_serial) {
- base::hash_map::const_iterator it =
- device_serial_to_adb_port_map_.find(device_serial);
- if (it != device_serial_to_adb_port_map_.end())
- return it->second;
- Socket bind_socket;
- CHECK(bind_socket.BindTcp("127.0.0.1", 0));
- const int port = bind_socket.GetPort();
- bind_socket.Close();
- const std::string serial_part = device_serial.empty() ?
- std::string() : std::string("-s ") + device_serial;
- const std::string command = base::StringPrintf(
- "adb %s forward tcp:%d localabstract:chrome_device_forwarder",
- device_serial.empty() ? "" : serial_part.c_str(),
- port);
- LOG(INFO) << command;
- const int ret = system(command.c_str());
- if (ret < 0 || !WIFEXITED(ret) || WEXITSTATUS(ret) != 0)
- return -1;
- device_serial_to_adb_port_map_[device_serial] = port;
- return port;
- }
-
- bool SendMessage(const std::string& msg, Socket* client_socket) {
- bool result = client_socket->WriteString(msg);
- DCHECK(result);
- if (!result)
- has_failed_ = true;
- return result;
- }
-
- base::WeakPtrFactory weak_ptr_factory_;
- base::hash_map device_serial_to_adb_port_map_;
- scoped_ptr controllers_;
- bool has_failed_;
- scoped_ptr at_exit_manager_; // Needed by base::Thread.
- scoped_ptr thread_;
-};
-
-class ServerDelegate : public Daemon::ServerDelegate {
- public:
- ServerDelegate() : has_failed_(false) {}
-
- bool has_failed() const {
- return has_failed_ || controllers_manager_.has_failed();
- }
-
- // Daemon::ServerDelegate:
- virtual void Init() OVERRIDE {
- LOG(INFO) << "Starting host process daemon (pid=" << getpid() << ")";
- DCHECK(!g_notifier);
- g_notifier = new PipeNotifier();
- signal(SIGTERM, KillHandler);
- signal(SIGINT, KillHandler);
- }
-
- virtual void OnClientConnected(scoped_ptr client_socket) OVERRIDE {
- char buf[kBufSize];
- const int bytes_read = client_socket->Read(buf, sizeof(buf));
- if (bytes_read <= 0) {
- if (client_socket->DidReceiveEvent())
- return;
- PError("Read()");
- has_failed_ = true;
- return;
- }
- const Pickle command_pickle(buf, bytes_read);
- PickleIterator pickle_it(command_pickle);
- std::string device_serial;
- CHECK(pickle_it.ReadString(&device_serial));
- int device_port;
- if (!pickle_it.ReadInt(&device_port)) {
- client_socket->WriteString("ERROR: missing device port");
- return;
- }
- int host_port;
- if (!pickle_it.ReadInt(&host_port))
- host_port = -1;
- controllers_manager_.HandleRequest(
- device_serial, device_port, host_port, client_socket.Pass());
- }
-
- private:
- bool has_failed_;
- HostControllersManager controllers_manager_;
-
- DISALLOW_COPY_AND_ASSIGN(ServerDelegate);
-};
-
-class ClientDelegate : public Daemon::ClientDelegate {
- public:
- ClientDelegate(const Pickle& command_pickle)
- : command_pickle_(command_pickle),
- has_failed_(false) {
- }
-
- bool has_failed() const { return has_failed_; }
-
- // Daemon::ClientDelegate:
- virtual void OnDaemonReady(Socket* daemon_socket) OVERRIDE {
- // Send the forward command to the daemon.
- CHECK_EQ(command_pickle_.size(),
- daemon_socket->WriteNumBytes(command_pickle_.data(),
- command_pickle_.size()));
- char buf[kBufSize];
- const int bytes_read = daemon_socket->Read(
- buf, sizeof(buf) - 1 /* leave space for null terminator */);
- CHECK_GT(bytes_read, 0);
- DCHECK(bytes_read < sizeof(buf));
- buf[bytes_read] = 0;
- base::StringPiece msg(buf, bytes_read);
- if (msg.starts_with("ERROR")) {
- LOG(ERROR) << msg;
- has_failed_ = true;
- return;
- }
- printf("%s\n", buf);
- }
-
- private:
- const Pickle command_pickle_;
- bool has_failed_;
-};
-
-void ExitWithUsage() {
- std::cerr << "Usage: host_forwarder [options]\n\n"
- "Options:\n"
- " --serial-id=[0-9A-Z]{16}]\n"
- " --map DEVICE_PORT HOST_PORT\n"
- " --unmap DEVICE_PORT\n"
- " --kill-server\n";
- exit(1);
-}
-
-int PortToInt(const std::string& s) {
- int value;
- // Note that 0 is a valid port (used for dynamic port allocation).
- if (!base::StringToInt(s, &value) || value < 0 ||
- value > std::numeric_limits::max()) {
- LOG(ERROR) << "Could not convert string " << s << " to port";
- ExitWithUsage();
- }
- return value;
-}
-
-int RunHostForwarder(int argc, char** argv) {
- CommandLine::Init(argc, argv);
- const CommandLine& cmd_line = *CommandLine::ForCurrentProcess();
- bool kill_server = false;
-
- Pickle pickle;
- pickle.WriteString(
- cmd_line.HasSwitch("serial-id") ?
- cmd_line.GetSwitchValueASCII("serial-id") : std::string());
-
- const std::vector args = cmd_line.GetArgs();
- if (cmd_line.HasSwitch("kill-server")) {
- kill_server = true;
- } else if (cmd_line.HasSwitch("unmap")) {
- if (args.size() != 1)
- ExitWithUsage();
- // Note the minus sign below.
- pickle.WriteInt(-PortToInt(args[0]));
- } else if (cmd_line.HasSwitch("map")) {
- if (args.size() != 2)
- ExitWithUsage();
- pickle.WriteInt(PortToInt(args[0]));
- pickle.WriteInt(PortToInt(args[1]));
- } else {
- ExitWithUsage();
- }
-
- if (kill_server && args.size() > 0)
- ExitWithUsage();
-
- ClientDelegate client_delegate(pickle);
- ServerDelegate daemon_delegate;
- Daemon daemon(
- kLogFilePath, kDaemonIdentifier, &client_delegate, &daemon_delegate,
- &GetExitNotifierFD);
-
- if (kill_server)
- return !daemon.Kill();
- if (!daemon.SpawnIfNeeded())
- return 1;
-
- return client_delegate.has_failed() || daemon_delegate.has_failed();
-}
-
-} // namespace
-} // namespace forwarder2
-
-int main(int argc, char** argv) {
- return forwarder2::RunHostForwarder(argc, argv);
-}
diff --git a/tools/android/forwarder2/pipe_notifier.cc b/tools/android/forwarder2/pipe_notifier.cc
deleted file mode 100644
index 3aba18b0d0..0000000000
--- a/tools/android/forwarder2/pipe_notifier.cc
+++ /dev/null
@@ -1,43 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "tools/android/forwarder2/pipe_notifier.h"
-
-#include
-#include
-#include
-#include
-
-#include "base/logging.h"
-#include "base/posix/eintr_wrapper.h"
-#include "base/safe_strerror_posix.h"
-
-namespace forwarder2 {
-
-PipeNotifier::PipeNotifier() {
- int pipe_fd[2];
- int ret = pipe(pipe_fd);
- CHECK_EQ(0, ret);
- receiver_fd_ = pipe_fd[0];
- sender_fd_ = pipe_fd[1];
- fcntl(sender_fd_, F_SETFL, O_NONBLOCK);
-}
-
-PipeNotifier::~PipeNotifier() {
- (void) HANDLE_EINTR(close(receiver_fd_));
- (void) HANDLE_EINTR(close(sender_fd_));
-}
-
-bool PipeNotifier::Notify() {
- CHECK_NE(-1, sender_fd_);
- errno = 0;
- int ret = HANDLE_EINTR(write(sender_fd_, "1", 1));
- if (ret < 0) {
- LOG(WARNING) << "Error while notifying pipe. " << safe_strerror(errno);
- return false;
- }
- return true;
-}
-
-} // namespace forwarder
diff --git a/tools/android/forwarder2/pipe_notifier.h b/tools/android/forwarder2/pipe_notifier.h
deleted file mode 100644
index efe303b2c1..0000000000
--- a/tools/android/forwarder2/pipe_notifier.h
+++ /dev/null
@@ -1,35 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef TOOLS_ANDROID_FORWARDER2_PIPE_NOTIFIER_H_
-#define TOOLS_ANDROID_FORWARDER2_PIPE_NOTIFIER_H_
-
-#include "base/basictypes.h"
-
-namespace forwarder2 {
-
-// Helper class used to create a unix pipe that sends notifications to the
-// |receiver_fd_| file descriptor when called |Notify()|. This should be used
-// by the main thread to notify other threads that it must exit.
-// The |receiver_fd_| can be put into a fd_set and used in a select together
-// with a socket waiting to accept or read.
-class PipeNotifier {
- public:
- PipeNotifier();
- ~PipeNotifier();
-
- bool Notify();
-
- int receiver_fd() const { return receiver_fd_; }
-
- private:
- int sender_fd_;
- int receiver_fd_;
-
- DISALLOW_COPY_AND_ASSIGN(PipeNotifier);
-};
-
-} // namespace forwarder
-
-#endif // TOOLS_ANDROID_FORWARDER2_PIPE_NOTIFIER_H_
diff --git a/tools/android/forwarder2/socket.cc b/tools/android/forwarder2/socket.cc
deleted file mode 100644
index 9564e98634..0000000000
--- a/tools/android/forwarder2/socket.cc
+++ /dev/null
@@ -1,422 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "tools/android/forwarder2/socket.h"
-
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-
-#include "base/logging.h"
-#include "base/posix/eintr_wrapper.h"
-#include "base/safe_strerror_posix.h"
-#include "tools/android/common/net.h"
-#include "tools/android/forwarder2/common.h"
-
-namespace {
-const int kNoTimeout = -1;
-const int kConnectTimeOut = 10; // Seconds.
-
-bool FamilyIsTCP(int family) {
- return family == AF_INET || family == AF_INET6;
-}
-} // namespace
-
-namespace forwarder2 {
-
-bool Socket::BindUnix(const std::string& path) {
- errno = 0;
- if (!InitUnixSocket(path) || !BindAndListen()) {
- Close();
- return false;
- }
- return true;
-}
-
-bool Socket::BindTcp(const std::string& host, int port) {
- errno = 0;
- if (!InitTcpSocket(host, port) || !BindAndListen()) {
- Close();
- return false;
- }
- return true;
-}
-
-bool Socket::ConnectUnix(const std::string& path) {
- errno = 0;
- if (!InitUnixSocket(path) || !Connect()) {
- Close();
- return false;
- }
- return true;
-}
-
-bool Socket::ConnectTcp(const std::string& host, int port) {
- errno = 0;
- if (!InitTcpSocket(host, port) || !Connect()) {
- Close();
- return false;
- }
- return true;
-}
-
-Socket::Socket()
- : socket_(-1),
- port_(0),
- socket_error_(false),
- family_(AF_INET),
- addr_ptr_(reinterpret_cast(&addr_.addr4)),
- addr_len_(sizeof(sockaddr)) {
- memset(&addr_, 0, sizeof(addr_));
-}
-
-Socket::~Socket() {
- Close();
-}
-
-void Socket::Shutdown() {
- if (!IsClosed()) {
- PRESERVE_ERRNO_HANDLE_EINTR(shutdown(socket_, SHUT_RDWR));
- }
-}
-
-void Socket::Close() {
- if (!IsClosed()) {
- CloseFD(socket_);
- socket_ = -1;
- }
-}
-
-bool Socket::InitSocketInternal() {
- socket_ = socket(family_, SOCK_STREAM, 0);
- if (socket_ < 0)
- return false;
- tools::DisableNagle(socket_);
- int reuse_addr = 1;
- setsockopt(socket_, SOL_SOCKET, SO_REUSEADDR,
- &reuse_addr, sizeof(reuse_addr));
- return true;
-}
-
-bool Socket::InitUnixSocket(const std::string& path) {
- static const size_t kPathMax = sizeof(addr_.addr_un.sun_path);
- // For abstract sockets we need one extra byte for the leading zero.
- if (path.size() + 2 /* '\0' */ > kPathMax) {
- LOG(ERROR) << "The provided path is too big to create a unix "
- << "domain socket: " << path;
- return false;
- }
- family_ = PF_UNIX;
- addr_.addr_un.sun_family = family_;
- // Copied from net/socket/unix_domain_socket_posix.cc
- // Convert the path given into abstract socket name. It must start with
- // the '\0' character, so we are adding it. |addr_len| must specify the
- // length of the structure exactly, as potentially the socket name may
- // have '\0' characters embedded (although we don't support this).
- // Note that addr_.addr_un.sun_path is already zero initialized.
- memcpy(addr_.addr_un.sun_path + 1, path.c_str(), path.size());
- addr_len_ = path.size() + offsetof(struct sockaddr_un, sun_path) + 1;
- addr_ptr_ = reinterpret_cast(&addr_.addr_un);
- return InitSocketInternal();
-}
-
-bool Socket::InitTcpSocket(const std::string& host, int port) {
- port_ = port;
- if (host.empty()) {
- // Use localhost: INADDR_LOOPBACK
- family_ = AF_INET;
- addr_.addr4.sin_family = family_;
- addr_.addr4.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
- } else if (!Resolve(host)) {
- return false;
- }
- CHECK(FamilyIsTCP(family_)) << "Invalid socket family.";
- if (family_ == AF_INET) {
- addr_.addr4.sin_port = htons(port_);
- addr_ptr_ = reinterpret_cast(&addr_.addr4);
- addr_len_ = sizeof(addr_.addr4);
- } else if (family_ == AF_INET6) {
- addr_.addr6.sin6_port = htons(port_);
- addr_ptr_ = reinterpret_cast(&addr_.addr6);
- addr_len_ = sizeof(addr_.addr6);
- }
- return InitSocketInternal();
-}
-
-bool Socket::BindAndListen() {
- errno = 0;
- if (HANDLE_EINTR(bind(socket_, addr_ptr_, addr_len_)) < 0 ||
- HANDLE_EINTR(listen(socket_, SOMAXCONN)) < 0) {
- SetSocketError();
- return false;
- }
- if (port_ == 0 && FamilyIsTCP(family_)) {
- SockAddr addr;
- memset(&addr, 0, sizeof(addr));
- socklen_t addrlen = 0;
- sockaddr* addr_ptr = NULL;
- uint16* port_ptr = NULL;
- if (family_ == AF_INET) {
- addr_ptr = reinterpret_cast(&addr.addr4);
- port_ptr = &addr.addr4.sin_port;
- addrlen = sizeof(addr.addr4);
- } else if (family_ == AF_INET6) {
- addr_ptr = reinterpret_cast(&addr.addr6);
- port_ptr = &addr.addr6.sin6_port;
- addrlen = sizeof(addr.addr6);
- }
- errno = 0;
- if (getsockname(socket_, addr_ptr, &addrlen) != 0) {
- LOG(ERROR) << "getsockname error: " << safe_strerror(errno);;
- SetSocketError();
- return false;
- }
- port_ = ntohs(*port_ptr);
- }
- return true;
-}
-
-bool Socket::Accept(Socket* new_socket) {
- DCHECK(new_socket != NULL);
- if (!WaitForEvent(READ, kNoTimeout)) {
- SetSocketError();
- return false;
- }
- errno = 0;
- int new_socket_fd = HANDLE_EINTR(accept(socket_, NULL, NULL));
- if (new_socket_fd < 0) {
- SetSocketError();
- return false;
- }
-
- tools::DisableNagle(new_socket_fd);
- new_socket->socket_ = new_socket_fd;
- return true;
-}
-
-bool Socket::Connect() {
- // Set non-block because we use select for connect.
- const int kFlags = fcntl(socket_, F_GETFL);
- DCHECK(!(kFlags & O_NONBLOCK));
- fcntl(socket_, F_SETFL, kFlags | O_NONBLOCK);
- errno = 0;
- if (HANDLE_EINTR(connect(socket_, addr_ptr_, addr_len_)) < 0 &&
- errno != EINPROGRESS) {
- SetSocketError();
- PRESERVE_ERRNO_HANDLE_EINTR(fcntl(socket_, F_SETFL, kFlags));
- return false;
- }
- // Wait for connection to complete, or receive a notification.
- if (!WaitForEvent(WRITE, kConnectTimeOut)) {
- SetSocketError();
- PRESERVE_ERRNO_HANDLE_EINTR(fcntl(socket_, F_SETFL, kFlags));
- return false;
- }
- int socket_errno;
- socklen_t opt_len = sizeof(socket_errno);
- if (getsockopt(socket_, SOL_SOCKET, SO_ERROR, &socket_errno, &opt_len) < 0) {
- LOG(ERROR) << "getsockopt(): " << safe_strerror(errno);
- SetSocketError();
- PRESERVE_ERRNO_HANDLE_EINTR(fcntl(socket_, F_SETFL, kFlags));
- return false;
- }
- if (socket_errno != 0) {
- LOG(ERROR) << "Could not connect to host: " << safe_strerror(socket_errno);
- SetSocketError();
- PRESERVE_ERRNO_HANDLE_EINTR(fcntl(socket_, F_SETFL, kFlags));
- return false;
- }
- fcntl(socket_, F_SETFL, kFlags);
- return true;
-}
-
-bool Socket::Resolve(const std::string& host) {
- struct addrinfo hints;
- struct addrinfo* res;
- memset(&hints, 0, sizeof(hints));
- hints.ai_family = AF_UNSPEC;
- hints.ai_socktype = SOCK_STREAM;
- hints.ai_flags |= AI_CANONNAME;
-
- int errcode = getaddrinfo(host.c_str(), NULL, &hints, &res);
- if (errcode != 0) {
- SetSocketError();
- freeaddrinfo(res);
- return false;
- }
- family_ = res->ai_family;
- switch (res->ai_family) {
- case AF_INET:
- memcpy(&addr_.addr4,
- reinterpret_cast(res->ai_addr),
- sizeof(sockaddr_in));
- break;
- case AF_INET6:
- memcpy(&addr_.addr6,
- reinterpret_cast(res->ai_addr),
- sizeof(sockaddr_in6));
- break;
- }
- freeaddrinfo(res);
- return true;
-}
-
-int Socket::GetPort() {
- if (!FamilyIsTCP(family_)) {
- LOG(ERROR) << "Can't call GetPort() on an unix domain socket.";
- return 0;
- }
- return port_;
-}
-
-bool Socket::IsFdInSet(const fd_set& fds) const {
- if (IsClosed())
- return false;
- return FD_ISSET(socket_, &fds);
-}
-
-bool Socket::AddFdToSet(fd_set* fds) const {
- if (IsClosed())
- return false;
- FD_SET(socket_, fds);
- return true;
-}
-
-int Socket::ReadNumBytes(void* buffer, size_t num_bytes) {
- int bytes_read = 0;
- int ret = 1;
- while (bytes_read < num_bytes && ret > 0) {
- ret = Read(static_cast(buffer) + bytes_read, num_bytes - bytes_read);
- if (ret >= 0)
- bytes_read += ret;
- }
- return bytes_read;
-}
-
-void Socket::SetSocketError() {
- socket_error_ = true;
- // We never use non-blocking socket.
- DCHECK(errno != EAGAIN && errno != EWOULDBLOCK);
- Close();
-}
-
-int Socket::Read(void* buffer, size_t buffer_size) {
- if (!WaitForEvent(READ, kNoTimeout)) {
- SetSocketError();
- return 0;
- }
- int ret = HANDLE_EINTR(read(socket_, buffer, buffer_size));
- if (ret < 0)
- SetSocketError();
- return ret;
-}
-
-int Socket::Write(const void* buffer, size_t count) {
- int ret = HANDLE_EINTR(send(socket_, buffer, count, MSG_NOSIGNAL));
- if (ret < 0)
- SetSocketError();
- return ret;
-}
-
-int Socket::WriteString(const std::string& buffer) {
- return WriteNumBytes(buffer.c_str(), buffer.size());
-}
-
-void Socket::AddEventFd(int event_fd) {
- Event event;
- event.fd = event_fd;
- event.was_fired = false;
- events_.push_back(event);
-}
-
-bool Socket::DidReceiveEventOnFd(int fd) const {
- for (size_t i = 0; i < events_.size(); ++i)
- if (events_[i].fd == fd)
- return events_[i].was_fired;
- return false;
-}
-
-bool Socket::DidReceiveEvent() const {
- for (size_t i = 0; i < events_.size(); ++i)
- if (events_[i].was_fired)
- return true;
- return false;
-}
-
-int Socket::WriteNumBytes(const void* buffer, size_t num_bytes) {
- int bytes_written = 0;
- int ret = 1;
- while (bytes_written < num_bytes && ret > 0) {
- ret = Write(static_cast(buffer) + bytes_written,
- num_bytes - bytes_written);
- if (ret >= 0)
- bytes_written += ret;
- }
- return bytes_written;
-}
-
-bool Socket::WaitForEvent(EventType type, int timeout_secs) {
- if (events_.empty() || socket_ == -1)
- return true;
- fd_set read_fds;
- fd_set write_fds;
- FD_ZERO(&read_fds);
- FD_ZERO(&write_fds);
- if (type == READ)
- FD_SET(socket_, &read_fds);
- else
- FD_SET(socket_, &write_fds);
- for (size_t i = 0; i < events_.size(); ++i)
- FD_SET(events_[i].fd, &read_fds);
- timeval tv = {};
- timeval* tv_ptr = NULL;
- if (timeout_secs > 0) {
- tv.tv_sec = timeout_secs;
- tv.tv_usec = 0;
- tv_ptr = &tv;
- }
- int max_fd = socket_;
- for (size_t i = 0; i < events_.size(); ++i)
- if (events_[i].fd > max_fd)
- max_fd = events_[i].fd;
- if (HANDLE_EINTR(
- select(max_fd + 1, &read_fds, &write_fds, NULL, tv_ptr)) <= 0) {
- return false;
- }
- bool event_was_fired = false;
- for (size_t i = 0; i < events_.size(); ++i) {
- if (FD_ISSET(events_[i].fd, &read_fds)) {
- events_[i].was_fired = true;
- event_was_fired = true;
- }
- }
- return !event_was_fired;
-}
-
-// static
-int Socket::GetHighestFileDescriptor(const Socket& s1, const Socket& s2) {
- return std::max(s1.socket_, s2.socket_);
-}
-
-// static
-pid_t Socket::GetUnixDomainSocketProcessOwner(const std::string& path) {
- Socket socket;
- if (!socket.ConnectUnix(path))
- return -1;
- ucred ucred;
- socklen_t len = sizeof(ucred);
- if (getsockopt(socket.socket_, SOL_SOCKET, SO_PEERCRED, &ucred, &len) == -1) {
- CHECK_NE(ENOPROTOOPT, errno);
- return -1;
- }
- return ucred.pid;
-}
-
-} // namespace forwarder2
diff --git a/tools/android/forwarder2/socket.h b/tools/android/forwarder2/socket.h
deleted file mode 100644
index b86fd9e7aa..0000000000
--- a/tools/android/forwarder2/socket.h
+++ /dev/null
@@ -1,145 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef TOOLS_ANDROID_FORWARDER2_SOCKET_H_
-#define TOOLS_ANDROID_FORWARDER2_SOCKET_H_
-
-#include
-#include
-#include
-#include
-
-#include
-#include
-
-#include "base/basictypes.h"
-
-namespace forwarder2 {
-
-// Wrapper class around unix socket api. Can be used to create, bind or
-// connect to both Unix domain sockets and TCP sockets.
-// TODO(pliard): Split this class into TCPSocket and UnixDomainSocket.
-class Socket {
- public:
- Socket();
- ~Socket();
-
- bool BindUnix(const std::string& path);
- bool BindTcp(const std::string& host, int port);
- bool ConnectUnix(const std::string& path);
- bool ConnectTcp(const std::string& host, int port);
-
- // Just a wrapper around unix socket shutdown(), see man 2 shutdown.
- void Shutdown();
-
- // Just a wrapper around unix socket close(), see man 2 close.
- void Close();
- bool IsClosed() const { return socket_ < 0; }
-
- bool Accept(Socket* new_socket);
-
- // Returns the port allocated to this socket or zero on error.
- int GetPort();
-
- bool IsFdInSet(const fd_set& fds) const;
- bool AddFdToSet(fd_set* fds) const;
-
- // Just a wrapper around unix read() function.
- // Reads up to buffer_size, but may read less then buffer_size.
- // Returns the number of bytes read.
- int Read(void* buffer, size_t buffer_size);
-
- // Same as Read(), just a wrapper around write().
- int Write(const void* buffer, size_t count);
-
- // Calls Read() multiple times until num_bytes is written to the provided
- // buffer. No bounds checking is performed.
- // Returns number of bytes read, which can be different from num_bytes in case
- // of errror.
- int ReadNumBytes(void* buffer, size_t num_bytes);
-
- // Calls Write() multiple times until num_bytes is written. No bounds checking
- // is performed. Returns number of bytes written, which can be different from
- // num_bytes in case of errror.
- int WriteNumBytes(const void* buffer, size_t num_bytes);
-
- // Calls WriteNumBytes for the given std::string. Note that the null
- // terminator is not written to the socket.
- int WriteString(const std::string& buffer);
-
- bool has_error() const { return socket_error_; }
-
- // |event_fd| must be a valid pipe file descriptor created from the
- // PipeNotifier and must live (not be closed) at least as long as this socket
- // is alive.
- void AddEventFd(int event_fd);
-
- // Returns whether Accept() or Connect() was interrupted because the socket
- // received an external event fired through the provided fd.
- bool DidReceiveEventOnFd(int fd) const;
-
- bool DidReceiveEvent() const;
-
- static int GetHighestFileDescriptor(const Socket& s1, const Socket& s2);
-
- static pid_t GetUnixDomainSocketProcessOwner(const std::string& path);
-
- private:
- enum EventType {
- READ,
- WRITE
- };
-
- union SockAddr {
- // IPv4 sockaddr
- sockaddr_in addr4;
- // IPv6 sockaddr
- sockaddr_in6 addr6;
- // Unix Domain sockaddr
- sockaddr_un addr_un;
- };
-
- struct Event {
- int fd;
- bool was_fired;
- };
-
- // If |host| is empty, use localhost.
- bool InitTcpSocket(const std::string& host, int port);
- bool InitUnixSocket(const std::string& path);
- bool BindAndListen();
- bool Connect();
-
- bool Resolve(const std::string& host);
- bool InitSocketInternal();
- void SetSocketError();
-
- // Waits until either the Socket or the |exit_notifier_fd_| has received an
- // event.
- bool WaitForEvent(EventType type, int timeout_secs);
-
- int socket_;
- int port_;
- bool socket_error_;
-
- // Family of the socket (PF_INET, PF_INET6 or PF_UNIX).
- int family_;
-
- SockAddr addr_;
-
- // Points to one of the members of the above union depending on the family.
- sockaddr* addr_ptr_;
- // Length of one of the members of the above union depending on the family.
- socklen_t addr_len_;
-
- // Used to listen for external events (e.g. process received a SIGTERM) while
- // blocking on I/O operations.
- std::vector events_;
-
- DISALLOW_COPY_AND_ASSIGN(Socket);
-};
-
-} // namespace forwarder
-
-#endif // TOOLS_ANDROID_FORWARDER2_SOCKET_H_
diff --git a/tools/android/md5sum/md5sum.cc b/tools/android/md5sum/md5sum.cc
deleted file mode 100644
index bc4ca071b8..0000000000
--- a/tools/android/md5sum/md5sum.cc
+++ /dev/null
@@ -1,93 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-// Md5sum implementation for Android. This version handles files as well as
-// directories. Its output is sorted by file path.
-
-#include
-#include
-#include
-#include
-
-#include "base/file_util.h"
-#include "base/files/file_enumerator.h"
-#include "base/files/file_path.h"
-#include "base/logging.h"
-#include "base/md5.h"
-
-namespace {
-
-const int kBufferSize = 1024;
-
-// Returns whether |path|'s MD5 was successfully written to |digest_string|.
-bool MD5Sum(const char* path, std::string* digest_string) {
- std::ifstream stream(path);
- if (!stream.good()) {
- LOG(ERROR) << "Could not open file " << path;
- return false;
- }
- base::MD5Context ctx;
- base::MD5Init(&ctx);
- char buf[kBufferSize];
- while (stream.good()) {
- std::streamsize bytes_read = stream.readsome(buf, sizeof(buf));
- if (bytes_read == 0)
- break;
- base::MD5Update(&ctx, base::StringPiece(buf, bytes_read));
- }
- if (stream.fail()) {
- LOG(ERROR) << "Error reading file " << path;
- return false;
- }
- base::MD5Digest digest;
- base::MD5Final(&digest, &ctx);
- *digest_string = base::MD5DigestToBase16(digest);
- return true;
-}
-
-// Returns the set of all files contained in |files|. This handles directories
-// by walking them recursively. Excludes, .svn directories and file under them.
-std::set MakeFileSet(const char** files) {
- const std::string svn_dir_component = FILE_PATH_LITERAL("/.svn/");
- std::set file_set;
- for (const char** file = files; *file; ++file) {
- base::FilePath file_path(*file);
- if (base::DirectoryExists(file_path)) {
- base::FileEnumerator file_enumerator(
- file_path, true /* recurse */, base::FileEnumerator::FILES);
- for (base::FilePath child, empty;
- (child = file_enumerator.Next()) != empty; ) {
- // If the path contains /.svn/, ignore it.
- if (child.value().find(svn_dir_component) == std::string::npos) {
- child = base::MakeAbsoluteFilePath(child);
- file_set.insert(child.value());
- }
- }
- } else {
- file_set.insert(*file);
- }
- }
- return file_set;
-}
-
-} // namespace
-
-int main(int argc, const char* argv[]) {
- if (argc < 2) {
- LOG(ERROR) << "Usage: md5sum ...";
- return 1;
- }
- const std::set files = MakeFileSet(argv + 1);
- bool failed = false;
- std::string digest;
- for (std::set::const_iterator it = files.begin();
- it != files.end(); ++it) {
- if (!MD5Sum(it->c_str(), &digest))
- failed = true;
- base::FilePath file_path(*it);
- std::cout << digest << " "
- << base::MakeAbsoluteFilePath(file_path).value() << std::endl;
- }
- return failed;
-}
diff --git a/tools/android/md5sum/md5sum.gyp b/tools/android/md5sum/md5sum.gyp
deleted file mode 100644
index 2c4ccc84dd..0000000000
--- a/tools/android/md5sum/md5sum.gyp
+++ /dev/null
@@ -1,77 +0,0 @@
-# Copyright (c) 2012 The Chromium Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-{
- 'targets': [
- {
- 'target_name': 'md5sum',
- 'type': 'none',
- 'dependencies': [
- 'md5sum_stripped_device_bin',
- 'md5sum_bin_host#host',
- ],
- # For the component build, ensure dependent shared libraries are stripped
- # and put alongside md5sum to simplify pushing to the device.
- 'variables': {
- 'output_dir': '<(PRODUCT_DIR)/md5sum_dist/',
- 'native_binary': '<(PRODUCT_DIR)/md5sum_bin',
- },
- 'includes': ['../../../build/android/native_app_dependencies.gypi'],
- },
- {
- 'target_name': 'md5sum_device_bin',
- 'type': 'executable',
- 'dependencies': [
- '../../../base/base.gyp:base',
- ],
- 'include_dirs': [
- '../../..',
- ],
- 'sources': [
- 'md5sum.cc',
- ],
- 'conditions': [
- [ 'order_profiling!=0 and OS=="android"', {
- 'dependencies': [ '../../../tools/cygprofile/cygprofile.gyp:cygprofile', ],
- }],
- ],
- },
- {
- 'target_name': 'md5sum_stripped_device_bin',
- 'type': 'none',
- 'dependencies': [
- 'md5sum_device_bin',
- ],
- 'actions': [
- {
- 'action_name': 'strip_md5sum_device_bin',
- 'inputs': ['<(PRODUCT_DIR)/md5sum_device_bin'],
- 'outputs': ['<(PRODUCT_DIR)/md5sum_bin'],
- 'action': [
- '<(android_strip)',
- '--strip-unneeded',
- '<@(_inputs)',
- '-o',
- '<@(_outputs)',
- ],
- },
- ],
- },
- # Same binary but for the host rather than the device.
- {
- 'target_name': 'md5sum_bin_host',
- 'toolsets': ['host'],
- 'type': 'executable',
- 'dependencies': [
- '../../../base/base.gyp:base',
- ],
- 'include_dirs': [
- '../../..',
- ],
- 'sources': [
- 'md5sum.cc',
- ],
- },
- ],
-}
diff --git a/tools/android/memdump/memdump.cc b/tools/android/memdump/memdump.cc
deleted file mode 100644
index 26035b29b0..0000000000
--- a/tools/android/memdump/memdump.cc
+++ /dev/null
@@ -1,555 +0,0 @@
-// Copyright (c) 2013 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include
-#include
-#include
-#include
-
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-
-#include "base/base64.h"
-#include "base/basictypes.h"
-#include "base/bind.h"
-#include "base/bind_helpers.h"
-#include "base/containers/hash_tables.h"
-#include "base/file_util.h"
-#include "base/logging.h"
-#include "base/memory/scoped_ptr.h"
-#include "base/strings/string_number_conversions.h"
-#include "base/strings/string_piece.h"
-#include "base/strings/string_split.h"
-#include "base/strings/stringprintf.h"
-
-namespace {
-
-class BitSet {
- public:
- void resize(size_t nbits) {
- data_.resize((nbits + 7) / 8);
- }
-
- void set(uint32 bit) {
- const uint32 byte_idx = bit / 8;
- CHECK(byte_idx < data_.size());
- data_[byte_idx] |= (1 << (bit & 7));
- }
-
- std::string AsB64String() const {
- std::string bits(&data_[0], data_.size());
- std::string b64_string;
- base::Base64Encode(bits, &b64_string);
- return b64_string;
- }
-
- private:
- std::vector data_;
-};
-
-// An entry in /proc//pagemap.
-struct PageMapEntry {
- uint64 page_frame_number : 55;
- uint unused : 8;
- uint present : 1;
-};
-
-// Describes a memory page.
-struct PageInfo {
- int64 page_frame_number; // Physical page id, also known as PFN.
- int64 flags;
- int32 times_mapped;
-};
-
-struct MemoryMap {
- std::string name;
- std::string flags;
- uint start_address;
- uint end_address;
- uint offset;
- int private_count;
- int unevictable_private_count;
- int other_shared_count;
- int unevictable_other_shared_count;
- // app_shared_counts[i] contains the number of pages mapped in i+2 processes
- // (only among the processes that are being analyzed).
- std::vector app_shared_counts;
- std::vector committed_pages;
- // committed_pages_bits is a bitset reflecting the present bit for all the
- // virtual pages of the mapping.
- BitSet committed_pages_bits;
-};
-
-struct ProcessMemory {
- pid_t pid;
- std::vector memory_maps;
-};
-
-bool PageIsUnevictable(const PageInfo& page_info) {
- // These constants are taken from kernel-page-flags.h.
- const int KPF_DIRTY = 4; // Note that only file-mapped pages can be DIRTY.
- const int KPF_ANON = 12; // Anonymous pages are dirty per definition.
- const int KPF_UNEVICTABLE = 18;
- const int KPF_MLOCKED = 33;
-
- return (page_info.flags & ((1ll << KPF_DIRTY) |
- (1ll << KPF_ANON) |
- (1ll << KPF_UNEVICTABLE) |
- (1ll << KPF_MLOCKED))) ?
- true : false;
-}
-
-// Number of times a physical page is mapped in a process.
-typedef base::hash_map PFNMap;
-
-// Parses lines from /proc//maps, e.g.:
-// 401e7000-401f5000 r-xp 00000000 103:02 158 /system/bin/linker
-bool ParseMemoryMapLine(const std::string& line,
- std::vector* tokens,
- MemoryMap* memory_map) {
- tokens->clear();
- base::SplitString(line, ' ', tokens);
- if (tokens->size() < 2)
- return false;
- const int addr_len = 8;
- const std::string& addr_range = tokens->at(0);
- if (addr_range.length() != addr_len + 1 + addr_len)
- return false;
- uint64 tmp = 0;
- if (!base::HexStringToUInt64(
- base::StringPiece(
- addr_range.begin(), addr_range.begin() + addr_len),
- &tmp)) {
- return false;
- }
- memory_map->start_address = static_cast(tmp);
- const int end_addr_start_pos = addr_len + 1;
- if (!base::HexStringToUInt64(
- base::StringPiece(
- addr_range.begin() + end_addr_start_pos,
- addr_range.begin() + end_addr_start_pos + addr_len),
- &tmp)) {
- return false;
- }
- memory_map->end_address = static_cast(tmp);
- if (tokens->at(1).size() != strlen("rwxp"))
- return false;
- memory_map->flags.swap(tokens->at(1));
- if (!base::HexStringToUInt64(tokens->at(2), &tmp))
- return false;
- memory_map->offset = static_cast(tmp);
- memory_map->committed_pages_bits.resize(
- (memory_map->end_address - memory_map->start_address) / PAGE_SIZE);
- const int map_name_index = 5;
- if (tokens->size() >= map_name_index + 1) {
- for (std::vector::const_iterator it =
- tokens->begin() + map_name_index; it != tokens->end(); ++it) {
- if (!it->empty()) {
- if (!memory_map->name.empty())
- memory_map->name.append(" ");
- memory_map->name.append(*it);
- }
- }
- }
- return true;
-}
-
-// Reads sizeof(T) bytes from file |fd| at |offset|.
-template
-bool ReadFromFileAtOffset(int fd, off_t offset, T* value) {
- if (lseek64(fd, offset * sizeof(*value), SEEK_SET) < 0) {
- PLOG(ERROR) << "lseek";
- return false;
- }
- ssize_t bytes = read(fd, value, sizeof(*value));
- if (bytes != sizeof(*value) && bytes != 0) {
- PLOG(ERROR) << "read";
- return false;
- }
- return true;
-}
-
-// Fills |process_maps| in with the process memory maps identified by |pid|.
-bool GetProcessMaps(pid_t pid, std::vector* process_maps) {
- std::ifstream maps_file(base::StringPrintf("/proc/%d/maps", pid).c_str());
- if (!maps_file.good()) {
- PLOG(ERROR) << "open";
- return false;
- }
- std::string line;
- std::vector tokens;
- while (std::getline(maps_file, line) && !line.empty()) {
- MemoryMap memory_map = {};
- if (!ParseMemoryMapLine(line, &tokens, &memory_map)) {
- LOG(ERROR) << "Could not parse line: " << line;
- return false;
- }
- process_maps->push_back(memory_map);
- }
- return true;
-}
-
-// Fills |committed_pages| in with the set of committed pages contained in the
-// provided memory map.
-bool GetPagesForMemoryMap(int pagemap_fd,
- const MemoryMap& memory_map,
- std::vector* committed_pages,
- BitSet* committed_pages_bits) {
- for (uint addr = memory_map.start_address, page_index = 0;
- addr < memory_map.end_address;
- addr += PAGE_SIZE, ++page_index) {
- DCHECK_EQ(0, addr % PAGE_SIZE);
- PageMapEntry page_map_entry = {};
- COMPILE_ASSERT(sizeof(PageMapEntry) == sizeof(uint64), unexpected_size);
- const off64_t offset = addr / PAGE_SIZE;
- if (!ReadFromFileAtOffset(pagemap_fd, offset, &page_map_entry))
- return false;
- if (page_map_entry.present) { // Ignore non-committed pages.
- if (page_map_entry.page_frame_number == 0)
- continue;
- PageInfo page_info = {};
- page_info.page_frame_number = page_map_entry.page_frame_number;
- committed_pages->push_back(page_info);
- committed_pages_bits->set(page_index);
- }
- }
- return true;
-}
-
-// Fills |committed_pages| with mapping count and flags information gathered
-// looking-up /proc/kpagecount and /proc/kpageflags.
-bool SetPagesInfo(int pagecount_fd,
- int pageflags_fd,
- std::vector* pages) {
- for (std::vector::iterator it = pages->begin();
- it != pages->end(); ++it) {
- PageInfo* const page_info = &*it;
-
- int64 times_mapped;
- if (!ReadFromFileAtOffset(
- pagecount_fd, page_info->page_frame_number, ×_mapped)) {
- return false;
- }
- DCHECK(times_mapped <= std::numeric_limits::max());
- page_info->times_mapped = static_cast(times_mapped);
-
- int64 page_flags;
- if (!ReadFromFileAtOffset(
- pageflags_fd, page_info->page_frame_number, &page_flags)) {
- return false;
- }
- page_info->flags = page_flags;
- }
- return true;
-}
-
-// Fills in the provided vector of Page Frame Number maps. This lets
-// ClassifyPages() know how many times each page is mapped in the processes.
-void FillPFNMaps(const std::vector& processes_memory,
- std::vector* pfn_maps) {
- int current_process_index = 0;
- for (std::vector::const_iterator it = processes_memory.begin();
- it != processes_memory.end(); ++it, ++current_process_index) {
- const std::vector& memory_maps = it->memory_maps;
- for (std::vector::const_iterator it = memory_maps.begin();
- it != memory_maps.end(); ++it) {
- const std::vector