Merge "Fix error printing code."
diff --git a/adb/Android.bp b/adb/Android.bp
index 114eb2a..b6aff3e 100644
--- a/adb/Android.bp
+++ b/adb/Android.bp
@@ -344,6 +344,7 @@
generated_headers: ["platform_tools_version"],
static_libs: [
+ "libadbconnection_server",
"libdiagnose_usb",
],
@@ -395,6 +396,7 @@
],
static_libs: [
+ "libadbconnection_server",
"libadbd_core",
"libdiagnose_usb",
],
@@ -531,6 +533,7 @@
},
static_libs: [
+ "libadbconnection_server",
"libadbd",
"libadbd_services",
"libasyncio",
diff --git a/adb/daemon/include/adbd/usb.h b/adb/daemon/include/adbd/usb.h
index fca3c58..2204246 100644
--- a/adb/daemon/include/adbd/usb.h
+++ b/adb/daemon/include/adbd/usb.h
@@ -16,6 +16,8 @@
* limitations under the License.
*/
+#include <linux/usb/functionfs.h>
+
#include <atomic>
#include <condition_variable>
#include <mutex>
diff --git a/adb/daemon/jdwp_service.cpp b/adb/daemon/jdwp_service.cpp
index cd9b669..b92a7de 100644
--- a/adb/daemon/jdwp_service.cpp
+++ b/adb/daemon/jdwp_service.cpp
@@ -30,15 +30,21 @@
#include <list>
#include <memory>
+#include <thread>
#include <vector>
+#include <adbconnection/server.h>
#include <android-base/cmsg.h>
+#include <android-base/unique_fd.h>
#include "adb.h"
#include "adb_io.h"
#include "adb_unique_fd.h"
#include "adb_utils.h"
+using android::base::borrowed_fd;
+using android::base::unique_fd;
+
/* here's how these things work.
when adbd starts, it creates a unix server socket
@@ -133,16 +139,16 @@
static auto& _jdwp_list = *new std::list<std::unique_ptr<JdwpProcess>>();
struct JdwpProcess {
- explicit JdwpProcess(int socket) {
+ JdwpProcess(unique_fd socket, pid_t pid) {
+ CHECK(pid != 0);
+
this->socket = socket;
- this->fde = fdevent_create(socket, jdwp_process_event, this);
+ this->pid = pid;
+ this->fde = fdevent_create(socket.release(), jdwp_process_event, this);
if (!this->fde) {
LOG(FATAL) << "could not create fdevent for new JDWP process";
}
-
- /* start by waiting for the PID */
- fdevent_add(this->fde, FDE_READ);
}
~JdwpProcess() {
@@ -160,18 +166,12 @@
}
void RemoveFromList() {
- if (this->pid >= 0) {
- D("removing pid %d from jdwp process list", this->pid);
- } else {
- D("removing transient JdwpProcess from list");
- }
-
auto pred = [this](const auto& proc) { return proc.get() == this; };
_jdwp_list.remove_if(pred);
}
+ borrowed_fd socket = -1;
int32_t pid = -1;
- int socket = -1;
fdevent* fde = nullptr;
std::vector<unique_fd> out_fds;
@@ -181,11 +181,6 @@
std::string temp;
for (auto& proc : _jdwp_list) {
- /* skip transient connections */
- if (proc->pid < 0) {
- continue;
- }
-
std::string next = std::to_string(proc->pid) + "\n";
if (temp.length() + next.length() > bufferlen) {
D("truncating JDWP process list (max len = %zu)", bufferlen);
@@ -214,24 +209,12 @@
static void jdwp_process_event(int socket, unsigned events, void* _proc) {
JdwpProcess* proc = reinterpret_cast<JdwpProcess*>(_proc);
- CHECK_EQ(socket, proc->socket);
+ CHECK_EQ(socket, proc->socket.get());
if (events & FDE_READ) {
- if (proc->pid < 0) {
- ssize_t rc = TEMP_FAILURE_RETRY(recv(socket, &proc->pid, sizeof(proc->pid), 0));
- if (rc != sizeof(proc->pid)) {
- D("failed to read jdwp pid: rc = %zd, errno = %s", rc, strerror(errno));
- goto CloseProcess;
- }
-
- /* all is well, keep reading to detect connection closure */
- D("Adding pid %d to jdwp process list", proc->pid);
- jdwp_process_list_updated();
- } else {
- // We already have the PID, if we can read from the socket, we've probably hit EOF.
- D("terminating JDWP connection %d", proc->pid);
- goto CloseProcess;
- }
+ // We already have the PID, if we can read from the socket, we've probably hit EOF.
+ D("terminating JDWP connection %d", proc->pid);
+ goto CloseProcess;
}
if (events & FDE_WRITE) {
@@ -284,98 +267,6 @@
return unique_fd{};
}
-/** VM DEBUG CONTROL SOCKET
- **
- ** we do implement a custom asocket to receive the data
- **/
-
-/* name of the debug control Unix socket */
-#define JDWP_CONTROL_NAME "\0jdwp-control"
-#define JDWP_CONTROL_NAME_LEN (sizeof(JDWP_CONTROL_NAME) - 1)
-
-struct JdwpControl {
- int listen_socket;
- fdevent* fde;
-};
-
-static JdwpControl _jdwp_control;
-
-static void jdwp_control_event(int s, unsigned events, void* user);
-
-static int jdwp_control_init(JdwpControl* control, const char* sockname, int socknamelen) {
- sockaddr_un addr;
- socklen_t addrlen;
- int maxpath = sizeof(addr.sun_path);
- int pathlen = socknamelen;
-
- if (pathlen >= maxpath) {
- D("vm debug control socket name too long (%d extra chars)", pathlen + 1 - maxpath);
- return -1;
- }
-
- memset(&addr, 0, sizeof(addr));
- addr.sun_family = AF_UNIX;
- memcpy(addr.sun_path, sockname, socknamelen);
-
- unique_fd s(socket(AF_UNIX, SOCK_SEQPACKET | SOCK_CLOEXEC, 0));
- if (s < 0) {
- D("could not create vm debug control socket. %d: %s", errno, strerror(errno));
- return -1;
- }
-
- addrlen = pathlen + sizeof(addr.sun_family);
-
- if (bind(s.get(), reinterpret_cast<sockaddr*>(&addr), addrlen) < 0) {
- D("could not bind vm debug control socket: %d: %s", errno, strerror(errno));
- return -1;
- }
-
- if (listen(s.get(), 4) < 0) {
- D("listen failed in jdwp control socket: %d: %s", errno, strerror(errno));
- return -1;
- }
-
- control->listen_socket = s.release();
- control->fde = fdevent_create(control->listen_socket, jdwp_control_event, control);
- if (control->fde == nullptr) {
- D("could not create fdevent for jdwp control socket");
- return -1;
- }
-
- /* only wait for incoming connections */
- fdevent_add(control->fde, FDE_READ);
-
- D("jdwp control socket started (%d)", control->listen_socket);
- return 0;
-}
-
-static void jdwp_control_event(int fd, unsigned events, void* _control) {
- JdwpControl* control = (JdwpControl*)_control;
-
- CHECK_EQ(fd, control->listen_socket);
- if (events & FDE_READ) {
- int s = adb_socket_accept(control->listen_socket, nullptr, nullptr);
- if (s < 0) {
- if (errno == ECONNABORTED) {
- /* oops, the JDWP process died really quick */
- D("oops, the JDWP process died really quick");
- return;
- } else {
- /* the socket is probably closed ? */
- D("weird accept() failed on jdwp control socket: %s", strerror(errno));
- return;
- }
- }
-
- auto proc = std::make_unique<JdwpProcess>(s);
- if (!proc) {
- LOG(FATAL) << "failed to allocate JdwpProcess";
- }
-
- _jdwp_list.emplace_back(std::move(proc));
- }
-}
-
/** "jdwp" local service implementation
** this simply returns the list of known JDWP process pids
**/
@@ -526,7 +417,22 @@
}
int init_jdwp(void) {
- return jdwp_control_init(&_jdwp_control, JDWP_CONTROL_NAME, JDWP_CONTROL_NAME_LEN);
+ std::thread([]() {
+ adb_thread_setname("jdwp control");
+ adbconnection_listen([](int fd, pid_t pid) {
+ LOG(INFO) << "jdwp connection from " << pid;
+ fdevent_run_on_main_thread([fd, pid] {
+ unique_fd ufd(fd);
+ auto proc = std::make_unique<JdwpProcess>(std::move(ufd), pid);
+ if (!proc) {
+ LOG(FATAL) << "failed to allocate JdwpProcess";
+ }
+ _jdwp_list.emplace_back(std::move(proc));
+ jdwp_process_list_updated();
+ });
+ });
+ }).detach();
+ return 0;
}
#endif /* !ADB_HOST */
diff --git a/base/Android.bp b/base/Android.bp
index 58b6fb5..357ce01 100644
--- a/base/Android.bp
+++ b/base/Android.bp
@@ -53,6 +53,7 @@
"logging.cpp",
"mapped_file.cpp",
"parsenetaddress.cpp",
+ "process.cpp",
"properties.cpp",
"quick_exit.cpp",
"stringprintf.cpp",
@@ -145,6 +146,7 @@
"parsedouble_test.cpp",
"parseint_test.cpp",
"parsenetaddress_test.cpp",
+ "process_test.cpp",
"properties_test.cpp",
"quick_exit_test.cpp",
"result_test.cpp",
diff --git a/base/include/android-base/process.h b/base/include/android-base/process.h
new file mode 100644
index 0000000..69ed3fb
--- /dev/null
+++ b/base/include/android-base/process.h
@@ -0,0 +1,60 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include <dirent.h>
+#include <sys/types.h>
+
+#include <iterator>
+#include <memory>
+#include <vector>
+
+namespace android {
+namespace base {
+
+class AllPids {
+ class PidIterator {
+ public:
+ PidIterator(DIR* dir) : dir_(dir, closedir) { Increment(); }
+ PidIterator& operator++() {
+ Increment();
+ return *this;
+ }
+ bool operator==(const PidIterator& other) const { return pid_ == other.pid_; }
+ bool operator!=(const PidIterator& other) const { return !(*this == other); }
+ long operator*() const { return pid_; }
+ // iterator traits
+ using difference_type = pid_t;
+ using value_type = pid_t;
+ using pointer = const pid_t*;
+ using reference = const pid_t&;
+ using iterator_category = std::input_iterator_tag;
+
+ private:
+ void Increment();
+
+ pid_t pid_ = -1;
+ std::unique_ptr<DIR, decltype(&closedir)> dir_;
+ };
+
+ public:
+ PidIterator begin() { return opendir("/proc"); }
+ PidIterator end() { return nullptr; }
+};
+
+} // namespace base
+} // namespace android
diff --git a/base/process.cpp b/base/process.cpp
new file mode 100644
index 0000000..b8cabf6
--- /dev/null
+++ b/base/process.cpp
@@ -0,0 +1,39 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "android-base/process.h"
+
+namespace android {
+namespace base {
+
+void AllPids::PidIterator::Increment() {
+ if (!dir_) {
+ return;
+ }
+
+ dirent* de;
+ while ((de = readdir(dir_.get())) != nullptr) {
+ pid_t pid = atoi(de->d_name);
+ if (pid != 0) {
+ pid_ = pid;
+ return;
+ }
+ }
+ pid_ = -1;
+}
+
+} // namespace base
+} // namespace android
diff --git a/base/process_test.cpp b/base/process_test.cpp
new file mode 100644
index 0000000..056f667
--- /dev/null
+++ b/base/process_test.cpp
@@ -0,0 +1,35 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "android-base/process.h"
+
+#include <unistd.h>
+
+#include <gtest/gtest.h>
+
+TEST(process, find_ourselves) {
+#if defined(__linux__)
+ bool found_our_pid = false;
+ for (const auto& pid : android::base::AllPids{}) {
+ if (pid == getpid()) {
+ found_our_pid = true;
+ }
+ }
+
+ EXPECT_TRUE(found_our_pid);
+
+#endif
+}
diff --git a/fastboot/fastboot.cpp b/fastboot/fastboot.cpp
index 39abc4a..c436be3 100644
--- a/fastboot/fastboot.cpp
+++ b/fastboot/fastboot.cpp
@@ -389,6 +389,8 @@
" set_active SLOT Set the active slot.\n"
" oem [COMMAND...] Execute OEM-specific command.\n"
" gsi wipe|disable Wipe or disable a GSI installation (fastbootd only).\n"
+ " wipe-super [SUPER_EMPTY] Wipe the super partition. This will reset it to\n"
+ " contain an empty set of default dynamic partitions.\n"
"\n"
"boot image:\n"
" boot KERNEL [RAMDISK [SECOND]]\n"
@@ -1582,6 +1584,76 @@
return false;
}
+static bool wipe_super(const android::fs_mgr::LpMetadata& metadata, const std::string& slot,
+ std::string* message) {
+ auto super_device = GetMetadataSuperBlockDevice(metadata);
+ auto block_size = metadata.geometry.logical_block_size;
+ auto super_bdev_name = android::fs_mgr::GetBlockDevicePartitionName(*super_device);
+
+ if (super_bdev_name != "super") {
+ // retrofit devices do not allow flashing to the retrofit partitions,
+ // so enable it if we can.
+ fb->RawCommand("oem allow-flash-super");
+ }
+
+ // Note: do not use die() in here, since we want TemporaryDir's destructor
+ // to be called.
+ TemporaryDir temp_dir;
+
+ bool ok;
+ if (metadata.block_devices.size() > 1) {
+ ok = WriteSplitImageFiles(temp_dir.path, metadata, block_size, {}, true);
+ } else {
+ auto image_path = temp_dir.path + "/"s + super_bdev_name + ".img";
+ ok = WriteToImageFile(image_path, metadata, block_size, {}, true);
+ }
+ if (!ok) {
+ *message = "Could not generate a flashable super image file";
+ return false;
+ }
+
+ for (const auto& block_device : metadata.block_devices) {
+ auto partition = android::fs_mgr::GetBlockDevicePartitionName(block_device);
+ bool force_slot = !!(block_device.flags & LP_BLOCK_DEVICE_SLOT_SUFFIXED);
+
+ std::string image_name;
+ if (metadata.block_devices.size() > 1) {
+ image_name = "super_" + partition + ".img";
+ } else {
+ image_name = partition + ".img";
+ }
+
+ auto image_path = temp_dir.path + "/"s + image_name;
+ auto flash = [&](const std::string& partition_name) {
+ do_flash(partition_name.c_str(), image_path.c_str());
+ };
+ do_for_partitions(partition, slot, flash, force_slot);
+
+ unlink(image_path.c_str());
+ }
+ return true;
+}
+
+static void do_wipe_super(const std::string& image, const std::string& slot_override) {
+ if (access(image.c_str(), R_OK) != 0) {
+ die("Could not read image: %s", image.c_str());
+ }
+ auto metadata = android::fs_mgr::ReadFromImageFile(image);
+ if (!metadata) {
+ die("Could not parse image: %s", image.c_str());
+ }
+
+ auto slot = slot_override;
+ if (slot.empty()) {
+ slot = get_current_slot();
+ }
+
+ std::string message;
+ if (!wipe_super(*metadata.get(), slot, &message)) {
+ die(message);
+ }
+}
+
int FastBootTool::Main(int argc, char* argv[]) {
bool wants_wipe = false;
bool wants_reboot = false;
@@ -1958,6 +2030,14 @@
} else {
syntax_error("expected 'wipe' or 'disable'");
}
+ } else if (command == "wipe-super") {
+ std::string image;
+ if (args.empty()) {
+ image = find_item_given_name("super_empty.img");
+ } else {
+ image = next_arg(&args);
+ }
+ do_wipe_super(image, slot_override);
} else {
syntax_error("unknown command %s", command.c_str());
}
diff --git a/fastboot/util.cpp b/fastboot/util.cpp
index d02b37f..900d6ea 100644
--- a/fastboot/util.cpp
+++ b/fastboot/util.cpp
@@ -53,6 +53,10 @@
exit(EXIT_FAILURE);
}
+void die(const std::string& str) {
+ die("%s", str.c_str());
+}
+
void set_verbose() {
g_verbose = true;
}
diff --git a/fastboot/util.h b/fastboot/util.h
index 2535414..c719df2 100644
--- a/fastboot/util.h
+++ b/fastboot/util.h
@@ -15,4 +15,7 @@
// use the same attribute for compile-time format string checking.
void die(const char* fmt, ...) __attribute__((__noreturn__))
__attribute__((__format__(__printf__, 1, 2)));
+
void verbose(const char* fmt, ...) __attribute__((__format__(__printf__, 1, 2)));
+
+void die(const std::string& str) __attribute__((__noreturn__));
diff --git a/init/host_init_verifier.cpp b/init/host_init_verifier.cpp
index 9323aa0..8aa3509 100644
--- a/init/host_init_verifier.cpp
+++ b/init/host_init_verifier.cpp
@@ -129,6 +129,23 @@
return nullptr;
}
+static std::optional<std::set<std::string>> ReadKnownInterfaces(
+ const std::string& known_interfaces_file) {
+ if (known_interfaces_file.empty()) {
+ LOG(WARNING) << "Missing a known interfaces file.";
+ return {};
+ }
+
+ std::string known_interfaces;
+ if (!ReadFileToString(known_interfaces_file, &known_interfaces)) {
+ LOG(ERROR) << "Failed to read known interfaces file '" << known_interfaces_file << "'";
+ return {};
+ }
+
+ auto interfaces = Split(known_interfaces, " ");
+ return std::set<std::string>(interfaces.begin(), interfaces.end());
+}
+
namespace android {
namespace init {
@@ -139,11 +156,12 @@
#include "generated_stub_builtin_function_map.h"
void PrintUsage() {
- std::cout << "usage: host_init_verifier [-p FILE] <init rc file>\n"
+ std::cout << "usage: host_init_verifier [-p FILE] -k FILE <init rc file>\n"
"\n"
"Tests an init script for correctness\n"
"\n"
"-p FILE\tSearch this passwd file for users and groups\n"
+ "-k FILE\tUse this file as a space-separated list of known interfaces\n"
<< std::endl;
}
@@ -151,13 +169,15 @@
android::base::InitLogging(argv, &android::base::StdioLogger);
android::base::SetMinimumLogSeverity(android::base::ERROR);
+ std::string known_interfaces_file;
+
while (true) {
static const struct option long_options[] = {
{"help", no_argument, nullptr, 'h'},
{nullptr, 0, nullptr, 0},
};
- int arg = getopt_long(argc, argv, "p:", long_options, nullptr);
+ int arg = getopt_long(argc, argv, "p:k:", long_options, nullptr);
if (arg == -1) {
break;
@@ -170,6 +190,9 @@
case 'p':
passwd_files.emplace_back(optarg);
break;
+ case 'k':
+ known_interfaces_file = optarg;
+ break;
default:
std::cerr << "getprop: getopt returned invalid result: " << arg << std::endl;
return EXIT_FAILURE;
@@ -189,7 +212,9 @@
ActionManager& am = ActionManager::GetInstance();
ServiceList& sl = ServiceList::GetInstance();
Parser parser;
- parser.AddSectionParser("service", std::make_unique<ServiceParser>(&sl, nullptr));
+ parser.AddSectionParser(
+ "service", std::make_unique<ServiceParser>(&sl, nullptr,
+ ReadKnownInterfaces(known_interfaces_file)));
parser.AddSectionParser("on", std::make_unique<ActionParser>(&am, nullptr));
parser.AddSectionParser("import", std::make_unique<HostImportParser>());
diff --git a/init/init.cpp b/init/init.cpp
index b6911e5..675f3e5 100644
--- a/init/init.cpp
+++ b/init/init.cpp
@@ -113,7 +113,8 @@
Parser CreateParser(ActionManager& action_manager, ServiceList& service_list) {
Parser parser;
- parser.AddSectionParser("service", std::make_unique<ServiceParser>(&service_list, subcontexts));
+ parser.AddSectionParser(
+ "service", std::make_unique<ServiceParser>(&service_list, subcontexts, std::nullopt));
parser.AddSectionParser("on", std::make_unique<ActionParser>(&action_manager, subcontexts));
parser.AddSectionParser("import", std::make_unique<ImportParser>(&parser));
@@ -124,7 +125,8 @@
Parser CreateServiceOnlyParser(ServiceList& service_list) {
Parser parser;
- parser.AddSectionParser("service", std::make_unique<ServiceParser>(&service_list, subcontexts));
+ parser.AddSectionParser(
+ "service", std::make_unique<ServiceParser>(&service_list, subcontexts, std::nullopt));
return parser;
}
diff --git a/init/init_test.cpp b/init/init_test.cpp
index 1bcc5ef..a09db18 100644
--- a/init/init_test.cpp
+++ b/init/init_test.cpp
@@ -44,7 +44,8 @@
Action::set_function_map(&test_function_map);
Parser parser;
- parser.AddSectionParser("service", std::make_unique<ServiceParser>(service_list, nullptr));
+ parser.AddSectionParser("service",
+ std::make_unique<ServiceParser>(service_list, nullptr, std::nullopt));
parser.AddSectionParser("on", std::make_unique<ActionParser>(&am, nullptr));
parser.AddSectionParser("import", std::make_unique<ImportParser>(&parser));
diff --git a/init/service_parser.cpp b/init/service_parser.cpp
index 33ed050..ba35104 100644
--- a/init/service_parser.cpp
+++ b/init/service_parser.cpp
@@ -152,6 +152,12 @@
return Error() << "Interface name must not be a value name '" << interface_name << "'";
}
+ if (known_interfaces_ && known_interfaces_->count(interface_name) == 0) {
+ return Error() << "Interface is not in the known set of hidl_interfaces: '"
+ << interface_name << "'. Please ensure the interface is built "
+ << "by a hidl_interface target.";
+ }
+
const std::string fullname = interface_name + "/" + instance_name;
for (const auto& svc : *service_list_) {
diff --git a/init/service_parser.h b/init/service_parser.h
index 0a5b291..5a16768 100644
--- a/init/service_parser.h
+++ b/init/service_parser.h
@@ -28,8 +28,12 @@
class ServiceParser : public SectionParser {
public:
- ServiceParser(ServiceList* service_list, std::vector<Subcontext>* subcontexts)
- : service_list_(service_list), subcontexts_(subcontexts), service_(nullptr) {}
+ ServiceParser(ServiceList* service_list, std::vector<Subcontext>* subcontexts,
+ const std::optional<std::set<std::string>>& known_interfaces)
+ : service_list_(service_list),
+ subcontexts_(subcontexts),
+ known_interfaces_(known_interfaces),
+ service_(nullptr) {}
Result<void> ParseSection(std::vector<std::string>&& args, const std::string& filename,
int line) override;
Result<void> ParseLineSection(std::vector<std::string>&& args, int line) override;
@@ -81,6 +85,7 @@
ServiceList* service_list_;
std::vector<Subcontext>* subcontexts_;
+ std::optional<std::set<std::string>> known_interfaces_;
std::unique_ptr<Service> service_;
std::string filename_;
};
diff --git a/libmeminfo/libdmabufinfo/include/dmabufinfo/dmabufinfo.h b/libmeminfo/libdmabufinfo/include/dmabufinfo/dmabufinfo.h
index a16c3fd..a6e7f69 100644
--- a/libmeminfo/libdmabufinfo/include/dmabufinfo/dmabufinfo.h
+++ b/libmeminfo/libdmabufinfo/include/dmabufinfo/dmabufinfo.h
@@ -19,6 +19,7 @@
#include <sys/types.h>
#include <unistd.h>
+#include <set>
#include <string>
#include <vector>
#include <unordered_map>
@@ -33,6 +34,7 @@
: inode_(inode), size_(size), count_(count), exporter_(exporter), name_(name) {
total_refs_ = 0;
}
+ DmaBuffer() = default;
~DmaBuffer() = default;
// Adds one file descriptor reference for the given pid
@@ -54,11 +56,13 @@
ino_t inode() const { return inode_; }
uint64_t total_refs() const { return total_refs_; }
uint64_t count() const { return count_; };
+ const std::set<pid_t>& pids() const { return pids_; }
const std::string& name() const { return name_; }
const std::string& exporter() const { return exporter_; }
void SetName(const std::string& name) { name_ = name; }
void SetExporter(const std::string& exporter) { exporter_ = exporter; }
void SetCount(uint64_t count) { count_ = count; }
+ uint64_t Pss() const { return size_ / pids_.size(); }
bool operator==(const DmaBuffer& rhs) {
return (inode_ == rhs.inode()) && (size_ == rhs.size()) && (name_ == rhs.name()) &&
@@ -70,6 +74,7 @@
uint64_t size_;
uint64_t count_;
uint64_t total_refs_;
+ std::set<pid_t> pids_;
std::string exporter_;
std::string name_;
std::unordered_map<pid_t, int> fdrefs_;
@@ -80,6 +85,7 @@
auto [it, inserted] = map->insert(std::make_pair(pid, 1));
if (!inserted)
it->second++;
+ pids_.insert(pid);
}
};
diff --git a/libmeminfo/libdmabufinfo/tools/dmabuf_dump.cpp b/libmeminfo/libdmabufinfo/tools/dmabuf_dump.cpp
index 9a80c82..48901b1 100644
--- a/libmeminfo/libdmabufinfo/tools/dmabuf_dump.cpp
+++ b/libmeminfo/libdmabufinfo/tools/dmabuf_dump.cpp
@@ -16,6 +16,7 @@
#include <dirent.h>
#include <errno.h>
+#include <getopt.h>
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
@@ -36,9 +37,10 @@
[[noreturn]] static void usage(int exit_status) {
fprintf(stderr,
- "Usage: %s [PID] \n"
- "\t If PID is supplied, the dmabuf information for this process is shown.\n"
- "\t Otherwise, shows the information for all processes.\n",
+ "Usage: %s [-ah] [PID] \n"
+ "-a\t show all dma buffers (ion) in big table, [buffer x process] grid \n"
+ "-h\t show this help\n"
+ " \t If PID is supplied, the dmabuf information for that process is shown.\n",
getprogname());
exit(exit_status);
@@ -54,11 +56,7 @@
return line;
}
-static void AddPidsToSet(const std::unordered_map<pid_t, int>& map, std::set<pid_t>* set) {
- for (auto it = map.begin(); it != map.end(); ++it) set->insert(it->first);
-}
-
-static void PrintDmaBufInfo(const std::vector<DmaBuffer>& bufs) {
+static void PrintDmaBufTable(const std::vector<DmaBuffer>& bufs) {
if (bufs.empty()) {
printf("dmabuf info not found ¯\\_(ツ)_/¯\n");
return;
@@ -66,9 +64,8 @@
// Find all unique pids in the input vector, create a set
std::set<pid_t> pid_set;
- for (int i = 0; i < bufs.size(); i++) {
- AddPidsToSet(bufs[i].fdrefs(), &pid_set);
- AddPidsToSet(bufs[i].maprefs(), &pid_set);
+ for (auto& buf : bufs) {
+ pid_set.insert(buf.pids().begin(), buf.pids().end());
}
// Format the header string spaced and separated with '|'
@@ -126,50 +123,144 @@
return;
}
-int main(int argc, char* argv[]) {
- pid_t pid = -1;
- std::vector<DmaBuffer> bufs;
- bool show_all = true;
+static void PrintDmaBufPerProcess(const std::vector<DmaBuffer>& bufs) {
+ if (bufs.empty()) {
+ printf("dmabuf info not found ¯\\_(ツ)_/¯\n");
+ return;
+ }
- if (argc > 1) {
- if (sscanf(argv[1], "%d", &pid) == 1) {
- show_all = false;
- } else {
+ // Create a reverse map from pid to dmabufs
+ std::unordered_map<pid_t, std::set<ino_t>> pid_to_inodes = {};
+ uint64_t total_size = 0; // Total size of dmabufs in the system
+ uint64_t kernel_rss = 0; // Total size of dmabufs NOT mapped or opened by a process
+ for (auto& buf : bufs) {
+ for (auto pid : buf.pids()) {
+ pid_to_inodes[pid].insert(buf.inode());
+ }
+ total_size += buf.size();
+ if (buf.fdrefs().empty() && buf.maprefs().empty()) {
+ kernel_rss += buf.size();
+ }
+ }
+ // Create an inode to dmabuf map. We know inodes are unique..
+ std::unordered_map<ino_t, DmaBuffer> inode_to_dmabuf;
+ for (auto buf : bufs) {
+ inode_to_dmabuf[buf.inode()] = buf;
+ }
+
+ uint64_t total_rss = 0, total_pss = 0;
+ for (auto& [pid, inodes] : pid_to_inodes) {
+ uint64_t pss = 0;
+ uint64_t rss = 0;
+
+ printf("%16s:%-5d\n", GetProcessComm(pid).c_str(), pid);
+ printf("%22s %16s %16s %16s %16s\n", "Name", "Rss", "Pss", "nr_procs", "Inode");
+ for (auto& inode : inodes) {
+ DmaBuffer& buf = inode_to_dmabuf[inode];
+ printf("%22s %13" PRIu64 " kB %13" PRIu64 " kB %16zu %16" PRIuMAX "\n",
+ buf.name().empty() ? "<unknown>" : buf.name().c_str(), buf.size() / 1024,
+ buf.Pss() / 1024, buf.pids().size(), static_cast<uintmax_t>(buf.inode()));
+ rss += buf.size();
+ pss += buf.Pss();
+ }
+ printf("%22s %13" PRIu64 " kB %13" PRIu64 " kB %16s\n", "PROCESS TOTAL", rss / 1024,
+ pss / 1024, "");
+ printf("----------------------\n");
+ total_rss += rss;
+ total_pss += pss;
+ }
+ printf("dmabuf total: %" PRIu64 " kB kernel_rss: %" PRIu64 " kB userspace_rss: %" PRIu64
+ " kB userspace_pss: %" PRIu64 " kB\n ",
+ total_size / 1024, kernel_rss / 1024, total_rss / 1024, total_pss / 1024);
+}
+
+static bool ReadDmaBufs(std::vector<DmaBuffer>* bufs) {
+ bufs->clear();
+
+ if (!ReadDmaBufInfo(bufs)) {
+ fprintf(stderr, "debugfs entry for dmabuf not available, skipping\n");
+ return false;
+ }
+
+ std::unique_ptr<DIR, int (*)(DIR*)> dir(opendir("/proc"), closedir);
+ if (!dir) {
+ fprintf(stderr, "Failed to open /proc directory\n");
+ bufs->clear();
+ return false;
+ }
+
+ struct dirent* dent;
+ while ((dent = readdir(dir.get()))) {
+ if (dent->d_type != DT_DIR) continue;
+
+ int pid = atoi(dent->d_name);
+ if (pid == 0) {
+ continue;
+ }
+
+ if (!AppendDmaBufInfo(pid, bufs)) {
+ fprintf(stderr, "Unable to read dmabuf info for pid %d\n", pid);
+ bufs->clear();
+ return false;
+ }
+ }
+
+ return true;
+}
+
+int main(int argc, char* argv[]) {
+ struct option longopts[] = {{"all", no_argument, nullptr, 'a'},
+ {"help", no_argument, nullptr, 'h'},
+ {0, 0, nullptr, 0}};
+
+ int opt;
+ bool show_table = false;
+ while ((opt = getopt_long(argc, argv, "ah", longopts, nullptr)) != -1) {
+ switch (opt) {
+ case 'a':
+ show_table = true;
+ break;
+ case 'h':
+ usage(EXIT_SUCCESS);
+ default:
+ usage(EXIT_FAILURE);
+ }
+ }
+
+ pid_t pid = -1;
+ if (optind < argc) {
+ if (show_table) {
+ fprintf(stderr, "Invalid arguments: -a does not need arguments\n");
+ usage(EXIT_FAILURE);
+ }
+ if (optind != (argc - 1)) {
+ fprintf(stderr, "Invalid arguments - only one [PID] argument is allowed\n");
+ usage(EXIT_FAILURE);
+ }
+ pid = atoi(argv[optind]);
+ if (pid == 0) {
+ fprintf(stderr, "Invalid process id %s\n", argv[optind]);
usage(EXIT_FAILURE);
}
}
- if (show_all) {
- if (!ReadDmaBufInfo(&bufs)) {
- std::cerr << "debugfs entry for dmabuf not available, skipping" << std::endl;
- bufs.clear();
- }
- std::unique_ptr<DIR, int (*)(DIR*)> dir(opendir("/proc"), closedir);
- if (!dir) {
- std::cerr << "Failed to open /proc directory" << std::endl;
+ std::vector<DmaBuffer> bufs;
+ if (pid != -1) {
+ if (!ReadDmaBufInfo(pid, &bufs)) {
+ fprintf(stderr, "Unable to read dmabuf info for %d\n", pid);
exit(EXIT_FAILURE);
}
- struct dirent* dent;
- while ((dent = readdir(dir.get()))) {
- if (dent->d_type != DT_DIR) continue;
-
- int matched = sscanf(dent->d_name, "%d", &pid);
- if (matched != 1) {
- continue;
- }
-
- if (!AppendDmaBufInfo(pid, &bufs)) {
- std::cerr << "Unable to read dmabuf info for pid " << pid << std::endl;
- exit(EXIT_FAILURE);
- }
- }
} else {
- if (!ReadDmaBufInfo(pid, &bufs)) {
- std::cerr << "Unable to read dmabuf info" << std::endl;
- exit(EXIT_FAILURE);
- }
+ if (!ReadDmaBufs(&bufs)) exit(EXIT_FAILURE);
}
- PrintDmaBufInfo(bufs);
+ // Show the old dmabuf table, inode x process
+ if (show_table) {
+ PrintDmaBufTable(bufs);
+ return 0;
+ }
+
+ PrintDmaBufPerProcess(bufs);
+
return 0;
}
diff --git a/libutils/String8.cpp b/libutils/String8.cpp
index 0025c56..d13548e 100644
--- a/libutils/String8.cpp
+++ b/libutils/String8.cpp
@@ -468,21 +468,6 @@
unlockBuffer(len);
}
-size_t String8::getUtf32Length() const
-{
- return utf8_to_utf32_length(mString, length());
-}
-
-int32_t String8::getUtf32At(size_t index, size_t *next_index) const
-{
- return utf32_from_utf8_at(mString, length(), index, next_index);
-}
-
-void String8::getUtf32(char32_t* dst) const
-{
- utf8_to_utf32(mString, length(), dst);
-}
-
// ---------------------------------------------------------------------------
// Path functions
diff --git a/libutils/include/utils/String8.h b/libutils/include/utils/String8.h
index c8f584e..0ddcbb2 100644
--- a/libutils/include/utils/String8.h
+++ b/libutils/include/utils/String8.h
@@ -95,13 +95,6 @@
__attribute__((format (printf, 2, 3)));
status_t appendFormatV(const char* fmt, va_list args);
- // Note that this function takes O(N) time to calculate the value.
- // No cache value is stored.
- size_t getUtf32Length() const;
- int32_t getUtf32At(size_t index,
- size_t *next_index) const;
- void getUtf32(char32_t* dst) const;
-
inline String8& operator=(const String8& other);
inline String8& operator=(const char* other);
diff --git a/logd/Android.bp b/logd/Android.bp
index 9b86258..b337b7c 100644
--- a/logd/Android.bp
+++ b/logd/Android.bp
@@ -39,7 +39,6 @@
"FlushCommand.cpp",
"LogBuffer.cpp",
"LogBufferElement.cpp",
- "LogBufferInterface.cpp",
"LogTimes.cpp",
"LogStatistics.cpp",
"LogWhiteBlackList.cpp",
diff --git a/logd/LogBuffer.h b/logd/LogBuffer.h
index 774d4ab..c2d5b97 100644
--- a/logd/LogBuffer.h
+++ b/logd/LogBuffer.h
@@ -27,7 +27,6 @@
#include <sysutils/SocketClient.h>
#include "LogBufferElement.h"
-#include "LogBufferInterface.h"
#include "LogStatistics.h"
#include "LogTags.h"
#include "LogTimes.h"
@@ -75,7 +74,7 @@
typedef std::list<LogBufferElement*> LogBufferElementCollection;
-class LogBuffer : public LogBufferInterface {
+class LogBuffer {
LogBufferElementCollection mLogElements;
pthread_rwlock_t mLogElementsLock;
@@ -108,14 +107,14 @@
LastLogTimes& mTimes;
explicit LogBuffer(LastLogTimes* times);
- ~LogBuffer() override;
+ ~LogBuffer();
void init();
bool isMonotonic() {
return monotonic;
}
- int log(log_id_t log_id, log_time realtime, uid_t uid, pid_t pid, pid_t tid,
- const char* msg, uint16_t len) override;
+ int log(log_id_t log_id, log_time realtime, uid_t uid, pid_t pid, pid_t tid, const char* msg,
+ uint16_t len);
// lastTid is an optional context to help detect if the last previous
// valid message was from the same source so we can differentiate chatty
// filter types (identical or expired)
@@ -159,12 +158,7 @@
const char* pidToName(pid_t pid) {
return stats.pidToName(pid);
}
- virtual uid_t pidToUid(pid_t pid) override {
- return stats.pidToUid(pid);
- }
- virtual pid_t tidToPid(pid_t tid) override {
- return stats.tidToPid(tid);
- }
+ uid_t pidToUid(pid_t pid) { return stats.pidToUid(pid); }
const char* uidToName(uid_t uid) {
return stats.uidToName(uid);
}
diff --git a/logd/LogBufferInterface.cpp b/logd/LogBufferInterface.cpp
deleted file mode 100644
index 4b6d363..0000000
--- a/logd/LogBufferInterface.cpp
+++ /dev/null
@@ -1,29 +0,0 @@
-/*
- * Copyright (C) 2017 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include "LogBufferInterface.h"
-#include "LogUtils.h"
-
-LogBufferInterface::LogBufferInterface() {
-}
-LogBufferInterface::~LogBufferInterface() {
-}
-uid_t LogBufferInterface::pidToUid(pid_t pid) {
- return android::pidToUid(pid);
-}
-pid_t LogBufferInterface::tidToPid(pid_t tid) {
- return android::tidToPid(tid);
-}
diff --git a/logd/LogBufferInterface.h b/logd/LogBufferInterface.h
deleted file mode 100644
index f31e244..0000000
--- a/logd/LogBufferInterface.h
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * Copyright (C) 2012-2014 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef _LOGD_LOG_BUFFER_INTERFACE_H__
-#define _LOGD_LOG_BUFFER_INTERFACE_H__
-
-#include <sys/types.h>
-
-#include <android-base/macros.h>
-#include <log/log_id.h>
-#include <log/log_time.h>
-
-// Abstract interface that handles log when log available.
-class LogBufferInterface {
- public:
- LogBufferInterface();
- virtual ~LogBufferInterface();
- // Handles a log entry when available in LogListener.
- // Returns the size of the handled log message.
- virtual int log(log_id_t log_id, log_time realtime, uid_t uid, pid_t pid,
- pid_t tid, const char* msg, uint16_t len) = 0;
-
- virtual uid_t pidToUid(pid_t pid);
- virtual pid_t tidToPid(pid_t tid);
-
- private:
- DISALLOW_COPY_AND_ASSIGN(LogBufferInterface);
-};
-
-#endif // _LOGD_LOG_BUFFER_INTERFACE_H__
diff --git a/logd/LogListener.cpp b/logd/LogListener.cpp
index 2f22778..443570f 100644
--- a/logd/LogListener.cpp
+++ b/logd/LogListener.cpp
@@ -14,9 +14,7 @@
* limitations under the License.
*/
-#include <ctype.h>
#include <limits.h>
-#include <stdio.h>
#include <sys/cdefs.h>
#include <sys/prctl.h>
#include <sys/socket.h>
@@ -32,9 +30,8 @@
#include "LogListener.h"
#include "LogUtils.h"
-LogListener::LogListener(LogBufferInterface* buf, LogReader* reader)
- : SocketListener(getLogSocket(), false), logbuf(buf), reader(reader) {
-}
+LogListener::LogListener(LogBuffer* buf, LogReader* reader)
+ : SocketListener(getLogSocket(), false), logbuf(buf), reader(reader) {}
bool LogListener::onDataAvailable(SocketClient* cli) {
static bool name_set;
@@ -78,11 +75,8 @@
cmsg = CMSG_NXTHDR(&hdr, cmsg);
}
- struct ucred fake_cred;
if (cred == nullptr) {
- cred = &fake_cred;
- cred->pid = 0;
- cred->uid = DEFAULT_OVERFLOWUID;
+ return false;
}
if (cred->uid == AID_LOGD) {
@@ -106,40 +100,16 @@
return false;
}
- // Check credential validity, acquire corrected details if not supplied.
- if (cred->pid == 0) {
- cred->pid = logbuf ? logbuf->tidToPid(header->tid)
- : android::tidToPid(header->tid);
- if (cred->pid == getpid()) {
- // We expect that /proc/<tid>/ is accessible to self even without
- // readproc group, so that we will always drop messages that come
- // from any of our logd threads and their library calls.
- return false; // ignore self
- }
- }
- if (cred->uid == DEFAULT_OVERFLOWUID) {
- uid_t uid =
- logbuf ? logbuf->pidToUid(cred->pid) : android::pidToUid(cred->pid);
- if (uid == AID_LOGD) {
- uid = logbuf ? logbuf->pidToUid(header->tid)
- : android::pidToUid(cred->pid);
- }
- if (uid != AID_LOGD) cred->uid = uid;
- }
-
char* msg = ((char*)buffer) + sizeof(android_log_header_t);
n -= sizeof(android_log_header_t);
// NB: hdr.msg_flags & MSG_TRUNC is not tested, silently passing a
// truncated message to the logs.
- if (logbuf != nullptr) {
- int res = logbuf->log(
- logId, header->realtime, cred->uid, cred->pid, header->tid, msg,
- ((size_t)n <= UINT16_MAX) ? (uint16_t)n : UINT16_MAX);
- if (res > 0 && reader != nullptr) {
- reader->notifyNewLog(static_cast<log_mask_t>(1 << logId));
- }
+ int res = logbuf->log(logId, header->realtime, cred->uid, cred->pid, header->tid, msg,
+ ((size_t)n <= UINT16_MAX) ? (uint16_t)n : UINT16_MAX);
+ if (res > 0) {
+ reader->notifyNewLog(static_cast<log_mask_t>(1 << logId));
}
return true;
diff --git a/logd/LogListener.h b/logd/LogListener.h
index a562a54..8fe3da4 100644
--- a/logd/LogListener.h
+++ b/logd/LogListener.h
@@ -20,22 +20,12 @@
#include <sysutils/SocketListener.h>
#include "LogReader.h"
-// DEFAULT_OVERFLOWUID is defined in linux/highuid.h, which is not part of
-// the uapi headers for userspace to use. This value is filled in on the
-// out-of-band socket credentials if the OS fails to find one available.
-// One of the causes of this is if SO_PASSCRED is set, all the packets before
-// that point will have this value. We also use it in a fake credential if
-// no socket credentials are supplied.
-#ifndef DEFAULT_OVERFLOWUID
-#define DEFAULT_OVERFLOWUID 65534
-#endif
-
class LogListener : public SocketListener {
- LogBufferInterface* logbuf;
+ LogBuffer* logbuf;
LogReader* reader;
public:
- LogListener(LogBufferInterface* buf, LogReader* reader /* nullable */);
+ LogListener(LogBuffer* buf, LogReader* reader);
protected:
virtual bool onDataAvailable(SocketClient* cli);
diff --git a/logd/LogStatistics.cpp b/logd/LogStatistics.cpp
index 116e08e..431b778 100644
--- a/logd/LogStatistics.cpp
+++ b/logd/LogStatistics.cpp
@@ -837,35 +837,12 @@
}
return AID_LOGD; // associate this with the logger
}
-
-pid_t tidToPid(pid_t tid) {
- char buffer[512];
- snprintf(buffer, sizeof(buffer), "/proc/%u/status", tid);
- FILE* fp = fopen(buffer, "r");
- if (fp) {
- while (fgets(buffer, sizeof(buffer), fp)) {
- int pid = tid;
- char space = 0;
- if ((sscanf(buffer, "Tgid: %d%c", &pid, &space) == 2) &&
- isspace(space)) {
- fclose(fp);
- return pid;
- }
- }
- fclose(fp);
- }
- return tid;
-}
}
uid_t LogStatistics::pidToUid(pid_t pid) {
return pidTable.add(pid)->second.getUid();
}
-pid_t LogStatistics::tidToPid(pid_t tid) {
- return tidTable.add(tid)->second.getPid();
-}
-
// caller must free character string
const char* LogStatistics::pidToName(pid_t pid) const {
// An inconvenient truth ... getName() can alter the object
diff --git a/logd/LogStatistics.h b/logd/LogStatistics.h
index 469f6dc..0782de3 100644
--- a/logd/LogStatistics.h
+++ b/logd/LogStatistics.h
@@ -306,6 +306,10 @@
std::string format(const LogStatistics& stat, log_id_t id) const;
};
+namespace android {
+uid_t pidToUid(pid_t pid);
+}
+
struct PidEntry : public EntryBaseDropped {
const pid_t pid;
uid_t uid;
@@ -385,13 +389,6 @@
uid(android::pidToUid(tid)),
name(android::tidToName(tid)) {
}
- TidEntry(pid_t tid)
- : EntryBaseDropped(),
- tid(tid),
- pid(android::tidToPid(tid)),
- uid(android::pidToUid(tid)),
- name(android::tidToName(tid)) {
- }
explicit TidEntry(const LogBufferElement* element)
: EntryBaseDropped(element),
tid(element->getTid()),
@@ -787,7 +784,6 @@
// helper (must be locked directly or implicitly by mLogElementsLock)
const char* pidToName(pid_t pid) const;
uid_t pidToUid(pid_t pid);
- pid_t tidToPid(pid_t tid);
const char* uidToName(uid_t uid) const;
};
diff --git a/logd/LogUtils.h b/logd/LogUtils.h
index 4dcd3e7..fa9f398 100644
--- a/logd/LogUtils.h
+++ b/logd/LogUtils.h
@@ -38,8 +38,6 @@
// Caller must own and free returned value
char* pidToName(pid_t pid);
char* tidToName(pid_t tid);
-uid_t pidToUid(pid_t pid);
-pid_t tidToPid(pid_t tid);
// Furnished in LogTags.cpp. Thread safe.
const char* tagToName(uint32_t tag);