Merge "Add Android.bp for liblog"
diff --git a/adb/Android.mk b/adb/Android.mk
index 6d68bec..5786d18 100644
--- a/adb/Android.mk
+++ b/adb/Android.mk
@@ -74,9 +74,11 @@
LIBADB_TEST_linux_SRCS := \
fdevent_test.cpp \
+ socket_test.cpp \
LIBADB_TEST_darwin_SRCS := \
fdevent_test.cpp \
+ socket_test.cpp \
LIBADB_TEST_windows_SRCS := \
sysdeps_win32_test.cpp \
diff --git a/adb/adb.cpp b/adb/adb.cpp
index 1249822..60966d6 100644
--- a/adb/adb.cpp
+++ b/adb/adb.cpp
@@ -162,6 +162,9 @@
// adbd's comes from the system property persist.adb.trace_mask.
static void setup_trace_mask() {
const std::string trace_setting = get_trace_setting();
+ if (trace_setting.empty()) {
+ return;
+ }
std::unordered_map<std::string, int> trace_flags = {
{"1", 0},
@@ -184,7 +187,7 @@
for (const auto& elem : elements) {
const auto& flag = trace_flags.find(elem);
if (flag == trace_flags.end()) {
- D("Unknown trace flag: %s", flag->first.c_str());
+ D("Unknown trace flag: %s", elem.c_str());
continue;
}
@@ -582,15 +585,27 @@
#ifdef _WIN32
-static bool _make_handle_noninheritable(HANDLE h) {
+// Try to make a handle non-inheritable and if there is an error, don't output
+// any error info, but leave GetLastError() for the caller to read. This is
+// convenient if the caller is expecting that this may fail and they'd like to
+// ignore such a failure.
+static bool _try_make_handle_noninheritable(HANDLE h) {
if (h != INVALID_HANDLE_VALUE && h != NULL) {
- if (!SetHandleInformation(h, HANDLE_FLAG_INHERIT, 0)) {
- // Show the handle value to give us a clue in case we have problems
- // with pseudo-handle values.
- fprintf(stderr, "Cannot make handle 0x%p non-inheritable: %s\n",
- h, SystemErrorCodeToString(GetLastError()).c_str());
- return false;
- }
+ return SetHandleInformation(h, HANDLE_FLAG_INHERIT, 0) ? true : false;
+ }
+
+ return true;
+}
+
+// Try to make a handle non-inheritable with the expectation that this should
+// succeed, so if this fails, output error info.
+static bool _make_handle_noninheritable(HANDLE h) {
+ if (!_try_make_handle_noninheritable(h)) {
+ // Show the handle value to give us a clue in case we have problems
+ // with pseudo-handle values.
+ fprintf(stderr, "Cannot make handle 0x%p non-inheritable: %s\n",
+ h, SystemErrorCodeToString(GetLastError()).c_str());
+ return false;
}
return true;
@@ -742,16 +757,13 @@
* If we're still having problems with inheriting random handles in the
* future, consider using PROC_THREAD_ATTRIBUTE_HANDLE_LIST to explicitly
* specify which handles should be inherited: http://blogs.msdn.com/b/oldnewthing/archive/2011/12/16/10248328.aspx
+ *
+ * Older versions of Windows return console pseudo-handles that cannot be
+ * made non-inheritable, so ignore those failures.
*/
- if (!_make_handle_noninheritable(GetStdHandle(STD_INPUT_HANDLE))) {
- return -1;
- }
- if (!_make_handle_noninheritable(GetStdHandle(STD_OUTPUT_HANDLE))) {
- return -1;
- }
- if (!_make_handle_noninheritable(GetStdHandle(STD_ERROR_HANDLE))) {
- return -1;
- }
+ _try_make_handle_noninheritable(GetStdHandle(STD_INPUT_HANDLE));
+ _try_make_handle_noninheritable(GetStdHandle(STD_OUTPUT_HANDLE));
+ _try_make_handle_noninheritable(GetStdHandle(STD_ERROR_HANDLE));
STARTUPINFOW startup;
ZeroMemory( &startup, sizeof(startup) );
diff --git a/adb/adb.h b/adb/adb.h
index 4922040..037c010 100644
--- a/adb/adb.h
+++ b/adb/adb.h
@@ -26,6 +26,7 @@
#include "adb_trace.h"
#include "fdevent.h"
+#include "socket.h"
constexpr size_t MAX_PAYLOAD_V1 = 4 * 1024;
constexpr size_t MAX_PAYLOAD_V2 = 256 * 1024;
@@ -74,80 +75,6 @@
unsigned char data[MAX_PAYLOAD];
};
-/* An asocket represents one half of a connection between a local and
-** remote entity. A local asocket is bound to a file descriptor. A
-** remote asocket is bound to the protocol engine.
-*/
-struct asocket {
- /* chain pointers for the local/remote list of
- ** asockets that this asocket lives in
- */
- asocket *next;
- asocket *prev;
-
- /* the unique identifier for this asocket
- */
- unsigned id;
-
- /* flag: set when the socket's peer has closed
- ** but packets are still queued for delivery
- */
- int closing;
-
- /* flag: quit adbd when both ends close the
- ** local service socket
- */
- int exit_on_close;
-
- /* the asocket we are connected to
- */
-
- asocket *peer;
-
- /* For local asockets, the fde is used to bind
- ** us to our fd event system. For remote asockets
- ** these fields are not used.
- */
- fdevent fde;
- int fd;
-
- /* queue of apackets waiting to be written
- */
- apacket *pkt_first;
- apacket *pkt_last;
-
- /* enqueue is called by our peer when it has data
- ** for us. It should return 0 if we can accept more
- ** data or 1 if not. If we return 1, we must call
- ** peer->ready() when we once again are ready to
- ** receive data.
- */
- int (*enqueue)(asocket *s, apacket *pkt);
-
- /* ready is called by the peer when it is ready for
- ** us to send data via enqueue again
- */
- void (*ready)(asocket *s);
-
- /* shutdown is called by the peer before it goes away.
- ** the socket should not do any further calls on its peer.
- ** Always followed by a call to close. Optional, i.e. can be NULL.
- */
- void (*shutdown)(asocket *s);
-
- /* close is called by the peer when it has gone away.
- ** we are not allowed to make any further calls on the
- ** peer once our close method is called.
- */
- void (*close)(asocket *s);
-
- /* A socket is bound to atransport */
- atransport *transport;
-
- size_t get_max_payload() const;
-};
-
-
/* the adisconnect structure is used to record a callback that
** will be called whenever a transport is disconnected (e.g. by the user)
** this should be used to cleanup objects that depend on the
@@ -215,18 +142,7 @@
void print_packet(const char *label, apacket *p);
-asocket *find_local_socket(unsigned local_id, unsigned remote_id);
-void install_local_socket(asocket *s);
-void remove_socket(asocket *s);
-void close_all_sockets(atransport *t);
-asocket *create_local_socket(int fd);
-asocket *create_local_service_socket(const char* destination,
- const atransport* transport);
-
-asocket *create_remote_socket(unsigned id, atransport *t);
-void connect_to_remote(asocket *s, const char *destination);
-void connect_to_smartsocket(asocket *s);
void fatal(const char *fmt, ...) __attribute__((noreturn));
void fatal_errno(const char *fmt, ...) __attribute__((noreturn));
diff --git a/adb/fdevent.cpp b/adb/fdevent.cpp
index dc03807..666a15f 100644
--- a/adb/fdevent.cpp
+++ b/adb/fdevent.cpp
@@ -119,10 +119,10 @@
fde->func = func;
fde->arg = arg;
if (fcntl(fd, F_SETFL, O_NONBLOCK) != 0) {
- // Here is not proper to handle the error. If it fails here, some error is
- // likely to be detected by poll(), then we can let the callback function
- // to handle it.
- LOG(ERROR) << "failed to fcntl(" << fd << ") to be nonblock";
+ // Here is not proper to handle the error. If it fails here, some error is
+ // likely to be detected by poll(), then we can let the callback function
+ // to handle it.
+ LOG(ERROR) << "failed to fcntl(" << fd << ") to be nonblock";
}
auto pair = g_poll_node_map.emplace(fde->fd, PollNode(fde));
CHECK(pair.second) << "install existing fd " << fd;
@@ -215,10 +215,13 @@
D("poll(), pollfds = %s", dump_pollfds(pollfds).c_str());
int ret = TEMP_FAILURE_RETRY(poll(&pollfds[0], pollfds.size(), -1));
if (ret == -1) {
- PLOG(ERROR) << "poll(), ret = " << ret;
- return;
+ PLOG(ERROR) << "poll(), ret = " << ret;
+ return;
}
for (auto& pollfd : pollfds) {
+ if (pollfd.revents != 0) {
+ D("for fd %d, revents = %x", pollfd.fd, pollfd.revents);
+ }
unsigned events = 0;
if (pollfd.revents & POLLIN) {
events |= FDE_READ;
@@ -337,3 +340,12 @@
}
}
}
+
+size_t fdevent_installed_count() {
+ return g_poll_node_map.size();
+}
+
+void fdevent_reset() {
+ g_poll_node_map.clear();
+ g_pending_list.clear();
+}
diff --git a/adb/fdevent.h b/adb/fdevent.h
index ca1494c..657fde5 100644
--- a/adb/fdevent.h
+++ b/adb/fdevent.h
@@ -17,6 +17,7 @@
#ifndef __FDEVENT_H
#define __FDEVENT_H
+#include <stddef.h>
#include <stdint.h> /* for int64_t */
/* events that may be observed */
@@ -27,10 +28,22 @@
/* features that may be set (via the events set/add/del interface) */
#define FDE_DONT_CLOSE 0x0080
-struct fdevent;
-
typedef void (*fd_func)(int fd, unsigned events, void *userdata);
+struct fdevent {
+ fdevent *next;
+ fdevent *prev;
+
+ int fd;
+ int force_eof;
+
+ uint16_t state;
+ uint16_t events;
+
+ fd_func func;
+ void *arg;
+};
+
/* Allocate and initialize a new fdevent object
* Note: use FD_TIMER as 'fd' to create a fd-less object
* (used to implement timers).
@@ -63,18 +76,9 @@
*/
void fdevent_loop();
-struct fdevent {
- fdevent *next;
- fdevent *prev;
-
- int fd;
- int force_eof;
-
- uint16_t state;
- uint16_t events;
-
- fd_func func;
- void *arg;
-};
+// For debugging only.
+size_t fdevent_installed_count();
+// For debugging only.
+void fdevent_reset();
#endif
diff --git a/adb/fdevent_test.cpp b/adb/fdevent_test.cpp
index 33034d8..7457712 100644
--- a/adb/fdevent_test.cpp
+++ b/adb/fdevent_test.cpp
@@ -28,25 +28,6 @@
#include "adb_io.h"
-class SignalHandlerRegister {
- public:
- SignalHandlerRegister(const std::vector<int>& signums, void (*handler)(int)) {
- for (auto& sig : signums) {
- sig_t old_handler = signal(sig, handler);
- saved_signal_handlers_.push_back(std::make_pair(sig, old_handler));
- }
- }
-
- ~SignalHandlerRegister() {
- for (auto& pair : saved_signal_handlers_) {
- signal(pair.first, pair.second);
- }
- }
-
- private:
- std::vector<std::pair<int, sig_t>> saved_signal_handlers_;
-};
-
class FdHandler {
public:
FdHandler(int read_fd, int write_fd) : read_fd_(read_fd), write_fd_(write_fd) {
@@ -95,6 +76,19 @@
pthread_exit(nullptr);
}
+class FdeventTest : public ::testing::Test {
+ protected:
+ static void SetUpTestCase() {
+ ASSERT_NE(SIG_ERR, signal(SIGUSR1, signal_handler));
+ ASSERT_NE(SIG_ERR, signal(SIGPIPE, SIG_IGN));
+ }
+
+ virtual void SetUp() {
+ fdevent_reset();
+ ASSERT_EQ(0u, fdevent_installed_count());
+ }
+};
+
struct ThreadArg {
int first_read_fd;
int last_write_fd;
@@ -102,8 +96,6 @@
};
static void FdEventThreadFunc(ThreadArg* arg) {
- SignalHandlerRegister signal_handler_register({SIGUSR1}, signal_handler);
-
std::vector<int> read_fds;
std::vector<int> write_fds;
@@ -124,7 +116,7 @@
fdevent_loop();
}
-TEST(fdevent, smoke) {
+TEST_F(FdeventTest, smoke) {
const size_t PIPE_COUNT = 10;
const size_t MESSAGE_LOOP_COUNT = 100;
const std::string MESSAGE = "fdevent_test";
@@ -154,6 +146,8 @@
ASSERT_EQ(0, pthread_kill(thread, SIGUSR1));
ASSERT_EQ(0, pthread_join(thread, nullptr));
+ ASSERT_EQ(0, close(writer));
+ ASSERT_EQ(0, close(reader));
}
struct InvalidFdArg {
@@ -171,7 +165,7 @@
}
}
-void InvalidFdThreadFunc(void*) {
+static void InvalidFdThreadFunc(void*) {
const int INVALID_READ_FD = std::numeric_limits<int>::max() - 1;
size_t happened_event_count = 0;
InvalidFdArg read_arg;
@@ -189,7 +183,7 @@
fdevent_loop();
}
-TEST(fdevent, invalid_fd) {
+TEST_F(FdeventTest, invalid_fd) {
pthread_t thread;
ASSERT_EQ(0, pthread_create(&thread, nullptr,
reinterpret_cast<void* (*)(void*)>(InvalidFdThreadFunc),
diff --git a/adb/socket.h b/adb/socket.h
new file mode 100644
index 0000000..4083036
--- /dev/null
+++ b/adb/socket.h
@@ -0,0 +1,117 @@
+/*
+ * Copyright (C) 2015 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 __ADB_SOCKET_H
+#define __ADB_SOCKET_H
+
+#include <stddef.h>
+
+#include "fdevent.h"
+
+struct apacket;
+class atransport;
+
+/* An asocket represents one half of a connection between a local and
+** remote entity. A local asocket is bound to a file descriptor. A
+** remote asocket is bound to the protocol engine.
+*/
+struct asocket {
+ /* chain pointers for the local/remote list of
+ ** asockets that this asocket lives in
+ */
+ asocket *next;
+ asocket *prev;
+
+ /* the unique identifier for this asocket
+ */
+ unsigned id;
+
+ /* flag: set when the socket's peer has closed
+ ** but packets are still queued for delivery
+ */
+ int closing;
+
+ // flag: set when the socket failed to write, so the socket will not wait to
+ // write packets and close directly.
+ bool has_write_error;
+
+ /* flag: quit adbd when both ends close the
+ ** local service socket
+ */
+ int exit_on_close;
+
+ /* the asocket we are connected to
+ */
+
+ asocket *peer;
+
+ /* For local asockets, the fde is used to bind
+ ** us to our fd event system. For remote asockets
+ ** these fields are not used.
+ */
+ fdevent fde;
+ int fd;
+
+ /* queue of apackets waiting to be written
+ */
+ apacket *pkt_first;
+ apacket *pkt_last;
+
+ /* enqueue is called by our peer when it has data
+ ** for us. It should return 0 if we can accept more
+ ** data or 1 if not. If we return 1, we must call
+ ** peer->ready() when we once again are ready to
+ ** receive data.
+ */
+ int (*enqueue)(asocket *s, apacket *pkt);
+
+ /* ready is called by the peer when it is ready for
+ ** us to send data via enqueue again
+ */
+ void (*ready)(asocket *s);
+
+ /* shutdown is called by the peer before it goes away.
+ ** the socket should not do any further calls on its peer.
+ ** Always followed by a call to close. Optional, i.e. can be NULL.
+ */
+ void (*shutdown)(asocket *s);
+
+ /* close is called by the peer when it has gone away.
+ ** we are not allowed to make any further calls on the
+ ** peer once our close method is called.
+ */
+ void (*close)(asocket *s);
+
+ /* A socket is bound to atransport */
+ atransport *transport;
+
+ size_t get_max_payload() const;
+};
+
+asocket *find_local_socket(unsigned local_id, unsigned remote_id);
+void install_local_socket(asocket *s);
+void remove_socket(asocket *s);
+void close_all_sockets(atransport *t);
+
+asocket *create_local_socket(int fd);
+asocket *create_local_service_socket(const char* destination,
+ const atransport* transport);
+
+asocket *create_remote_socket(unsigned id, atransport *t);
+void connect_to_remote(asocket *s, const char *destination);
+void connect_to_smartsocket(asocket *s);
+
+#endif // __ADB_SOCKET_H
diff --git a/adb/socket_test.cpp b/adb/socket_test.cpp
new file mode 100644
index 0000000..8f395d1
--- /dev/null
+++ b/adb/socket_test.cpp
@@ -0,0 +1,300 @@
+/*
+ * Copyright (C) 2015 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 "fdevent.h"
+
+#include <gtest/gtest.h>
+
+#include <limits>
+#include <queue>
+#include <string>
+#include <vector>
+
+#include <pthread.h>
+#include <signal.h>
+#include <unistd.h>
+
+#include "adb.h"
+#include "adb_io.h"
+#include "socket.h"
+#include "sysdeps.h"
+
+static void signal_handler(int) {
+ ASSERT_EQ(1u, fdevent_installed_count());
+ pthread_exit(nullptr);
+}
+
+// On host, register a dummy socket, so fdevet_loop() will not abort when previously
+// registered local sockets are all closed. On device, fdevent_subproc_setup() installs
+// one fdevent which can be considered as dummy socket.
+static void InstallDummySocket() {
+#if ADB_HOST
+ int dummy_fds[2];
+ ASSERT_EQ(0, pipe(dummy_fds));
+ asocket* dummy_socket = create_local_socket(dummy_fds[0]);
+ ASSERT_TRUE(dummy_socket != nullptr);
+ dummy_socket->ready(dummy_socket);
+#endif
+}
+
+struct ThreadArg {
+ int first_read_fd;
+ int last_write_fd;
+ size_t middle_pipe_count;
+};
+
+static void FdEventThreadFunc(ThreadArg* arg) {
+ std::vector<int> read_fds;
+ std::vector<int> write_fds;
+
+ read_fds.push_back(arg->first_read_fd);
+ for (size_t i = 0; i < arg->middle_pipe_count; ++i) {
+ int fds[2];
+ ASSERT_EQ(0, adb_socketpair(fds));
+ read_fds.push_back(fds[0]);
+ write_fds.push_back(fds[1]);
+ }
+ write_fds.push_back(arg->last_write_fd);
+
+ for (size_t i = 0; i < read_fds.size(); ++i) {
+ asocket* reader = create_local_socket(read_fds[i]);
+ ASSERT_TRUE(reader != nullptr);
+ asocket* writer = create_local_socket(write_fds[i]);
+ ASSERT_TRUE(writer != nullptr);
+ reader->peer = writer;
+ writer->peer = reader;
+ reader->ready(reader);
+ }
+
+ InstallDummySocket();
+ fdevent_loop();
+}
+
+class LocalSocketTest : public ::testing::Test {
+ protected:
+ static void SetUpTestCase() {
+ ASSERT_NE(SIG_ERR, signal(SIGUSR1, signal_handler));
+ ASSERT_NE(SIG_ERR, signal(SIGPIPE, SIG_IGN));
+ }
+
+ virtual void SetUp() {
+ fdevent_reset();
+ ASSERT_EQ(0u, fdevent_installed_count());
+ }
+};
+
+TEST_F(LocalSocketTest, smoke) {
+ const size_t PIPE_COUNT = 100;
+ const size_t MESSAGE_LOOP_COUNT = 100;
+ const std::string MESSAGE = "socket_test";
+ int fd_pair1[2];
+ int fd_pair2[2];
+ ASSERT_EQ(0, adb_socketpair(fd_pair1));
+ ASSERT_EQ(0, adb_socketpair(fd_pair2));
+ pthread_t thread;
+ ThreadArg thread_arg;
+ thread_arg.first_read_fd = fd_pair1[0];
+ thread_arg.last_write_fd = fd_pair2[1];
+ thread_arg.middle_pipe_count = PIPE_COUNT;
+ int writer = fd_pair1[1];
+ int reader = fd_pair2[0];
+
+ ASSERT_EQ(0, pthread_create(&thread, nullptr,
+ reinterpret_cast<void* (*)(void*)>(FdEventThreadFunc),
+ &thread_arg));
+
+ usleep(1000);
+ for (size_t i = 0; i < MESSAGE_LOOP_COUNT; ++i) {
+ std::string read_buffer = MESSAGE;
+ std::string write_buffer(MESSAGE.size(), 'a');
+ ASSERT_TRUE(WriteFdExactly(writer, read_buffer.c_str(), read_buffer.size()));
+ ASSERT_TRUE(ReadFdExactly(reader, &write_buffer[0], write_buffer.size()));
+ ASSERT_EQ(read_buffer, write_buffer);
+ }
+ ASSERT_EQ(0, adb_close(writer));
+ ASSERT_EQ(0, adb_close(reader));
+ // Wait until the local sockets are closed.
+ sleep(1);
+
+ ASSERT_EQ(0, pthread_kill(thread, SIGUSR1));
+ ASSERT_EQ(0, pthread_join(thread, nullptr));
+}
+
+struct CloseWithPacketArg {
+ int socket_fd;
+ size_t bytes_written;
+ int cause_close_fd;
+};
+
+static void CloseWithPacketThreadFunc(CloseWithPacketArg* arg) {
+ asocket* s = create_local_socket(arg->socket_fd);
+ ASSERT_TRUE(s != nullptr);
+ arg->bytes_written = 0;
+ while (true) {
+ apacket* p = get_apacket();
+ p->len = sizeof(p->data);
+ arg->bytes_written += p->len;
+ int ret = s->enqueue(s, p);
+ if (ret == 1) {
+ // The writer has one packet waiting to send.
+ break;
+ }
+ }
+
+ asocket* cause_close_s = create_local_socket(arg->cause_close_fd);
+ ASSERT_TRUE(cause_close_s != nullptr);
+ cause_close_s->peer = s;
+ s->peer = cause_close_s;
+ cause_close_s->ready(cause_close_s);
+
+ InstallDummySocket();
+ fdevent_loop();
+}
+
+// This test checks if we can close local socket in the following situation:
+// The socket is closing but having some packets, so it is not closed. Then
+// some write error happens in the socket's file handler, e.g., the file
+// handler is closed.
+TEST_F(LocalSocketTest, close_with_packet) {
+ int socket_fd[2];
+ ASSERT_EQ(0, adb_socketpair(socket_fd));
+ int cause_close_fd[2];
+ ASSERT_EQ(0, adb_socketpair(cause_close_fd));
+ CloseWithPacketArg arg;
+ arg.socket_fd = socket_fd[1];
+ arg.cause_close_fd = cause_close_fd[1];
+ pthread_t thread;
+ ASSERT_EQ(0, pthread_create(&thread, nullptr,
+ reinterpret_cast<void* (*)(void*)>(CloseWithPacketThreadFunc),
+ &arg));
+ // Wait until the fdevent_loop() starts.
+ sleep(1);
+ ASSERT_EQ(0, adb_close(cause_close_fd[0]));
+ sleep(1);
+ ASSERT_EQ(2u, fdevent_installed_count());
+ ASSERT_EQ(0, adb_close(socket_fd[0]));
+ // Wait until the socket is closed.
+ sleep(1);
+
+ ASSERT_EQ(0, pthread_kill(thread, SIGUSR1));
+ ASSERT_EQ(0, pthread_join(thread, nullptr));
+}
+
+#undef shutdown
+
+// This test checks if we can read packets from a closing local socket.
+// The socket's file handler may be non readable if the other side has
+// called shutdown(SHUT_WR). But we should always write packets
+// successfully to the other side.
+TEST_F(LocalSocketTest, half_close_with_packet) {
+ int socket_fd[2];
+ ASSERT_EQ(0, adb_socketpair(socket_fd));
+ int cause_close_fd[2];
+ ASSERT_EQ(0, adb_socketpair(cause_close_fd));
+ CloseWithPacketArg arg;
+ arg.socket_fd = socket_fd[1];
+ arg.cause_close_fd = cause_close_fd[1];
+
+ pthread_t thread;
+ ASSERT_EQ(0, pthread_create(&thread, nullptr,
+ reinterpret_cast<void* (*)(void*)>(CloseWithPacketThreadFunc),
+ &arg));
+ // Wait until the fdevent_loop() starts.
+ sleep(1);
+ ASSERT_EQ(0, adb_close(cause_close_fd[0]));
+ sleep(1);
+ ASSERT_EQ(2u, fdevent_installed_count());
+ ASSERT_EQ(0, shutdown(socket_fd[0], SHUT_WR));
+
+ // Verify if we can read successfully.
+ std::vector<char> buf(arg.bytes_written);
+ ASSERT_EQ(true, ReadFdExactly(socket_fd[0], buf.data(), buf.size()));
+ ASSERT_EQ(0, adb_close(socket_fd[0]));
+
+ // Wait until the socket is closed.
+ sleep(1);
+
+ ASSERT_EQ(0, pthread_kill(thread, SIGUSR1));
+ ASSERT_EQ(0, pthread_join(thread, nullptr));
+}
+
+// This test checks if we can close local socket in the following situation:
+// The socket is not closed and has some packets. When it fails to write to
+// the socket's file handler because the other end is closed, we check if the
+// socket is closed.
+TEST_F(LocalSocketTest, write_error_when_having_packets) {
+ int socket_fd[2];
+ ASSERT_EQ(0, adb_socketpair(socket_fd));
+ int cause_close_fd[2];
+ ASSERT_EQ(0, adb_socketpair(cause_close_fd));
+ CloseWithPacketArg arg;
+ arg.socket_fd = socket_fd[1];
+ arg.cause_close_fd = cause_close_fd[1];
+
+ pthread_t thread;
+ ASSERT_EQ(0, pthread_create(&thread, nullptr,
+ reinterpret_cast<void* (*)(void*)>(CloseWithPacketThreadFunc),
+ &arg));
+ // Wait until the fdevent_loop() starts.
+ sleep(1);
+ ASSERT_EQ(3u, fdevent_installed_count());
+ ASSERT_EQ(0, adb_close(socket_fd[0]));
+
+ // Wait until the socket is closed.
+ sleep(1);
+
+ ASSERT_EQ(0, pthread_kill(thread, SIGUSR1));
+ ASSERT_EQ(0, pthread_join(thread, nullptr));
+}
+
+struct CloseNoEventsArg {
+ int socket_fd;
+};
+
+static void CloseNoEventsThreadFunc(CloseNoEventsArg* arg) {
+ asocket* s = create_local_socket(arg->socket_fd);
+ ASSERT_TRUE(s != nullptr);
+
+ InstallDummySocket();
+ fdevent_loop();
+}
+
+// This test checks when a local socket doesn't enable FDE_READ/FDE_WRITE/FDE_ERROR, it
+// can still be closed when some error happens on its file handler.
+// This test successes on linux but fails on mac because of different implementation of
+// poll(). I think the function tested here is useful to make adb server more stable on
+// linux.
+TEST_F(LocalSocketTest, close_with_no_events_installed) {
+ int socket_fd[2];
+ ASSERT_EQ(0, adb_socketpair(socket_fd));
+
+ CloseNoEventsArg arg;
+ arg.socket_fd = socket_fd[1];
+ pthread_t thread;
+ ASSERT_EQ(0, pthread_create(&thread, nullptr,
+ reinterpret_cast<void* (*)(void*)>(CloseNoEventsThreadFunc),
+ &arg));
+ // Wait until the fdevent_loop() starts.
+ sleep(1);
+ ASSERT_EQ(2u, fdevent_installed_count());
+ ASSERT_EQ(0, adb_close(socket_fd[0]));
+
+ // Wait until the socket is closed.
+ sleep(1);
+
+ ASSERT_EQ(0, pthread_kill(thread, SIGUSR1));
+ ASSERT_EQ(0, pthread_join(thread, nullptr));
+}
diff --git a/adb/sockets.cpp b/adb/sockets.cpp
index 104ad6b..bd33d79 100644
--- a/adb/sockets.cpp
+++ b/adb/sockets.cpp
@@ -157,6 +157,8 @@
}
if((r == 0) || (errno != EAGAIN)) {
D( "LS(%d): not ready, errno=%d: %s", s->id, errno, strerror(errno) );
+ put_apacket(p);
+ s->has_write_error = true;
s->close(s);
return 1; /* not ready (error) */
} else {
@@ -252,7 +254,7 @@
/* If we are already closing, or if there are no
** pending packets, destroy immediately
*/
- if (s->closing || s->pkt_first == NULL) {
+ if (s->closing || s->has_write_error || s->pkt_first == NULL) {
int id = s->id;
local_socket_destroy(s);
D("LS(%d): closed", id);
@@ -267,6 +269,7 @@
remove_socket(s);
D("LS(%d): put on socket_closing_list fd=%d", s->id, s->fd);
insert_local_socket(s, &local_socket_closing_list);
+ CHECK_EQ(FDE_WRITE, s->fde.state & FDE_WRITE);
}
static void local_socket_event_func(int fd, unsigned ev, void* _s)
@@ -296,6 +299,7 @@
}
D(" closing after write because r=%d and errno is %d", r, errno);
+ s->has_write_error = true;
s->close(s);
return;
}
@@ -392,6 +396,7 @@
D(" closing because is_eof=%d r=%d s->fde.force_eof=%d",
is_eof, r, s->fde.force_eof);
s->close(s);
+ return;
}
}
@@ -401,7 +406,6 @@
** bytes of readable data.
*/
D("LS(%d): FDE_ERROR (fd=%d)", s->id, s->fd);
-
return;
}
}
diff --git a/adb/test_device.py b/adb/test_device.py
index 4452eed..d033a01 100644
--- a/adb/test_device.py
+++ b/adb/test_device.py
@@ -499,7 +499,8 @@
self.assertEqual(temp_file.checksum, dev_md5)
self.device.shell(['rm', '-rf', self.DEVICE_TEMP_DIR])
- shutil.rmtree(base_dir + self.DEVICE_TEMP_DIR)
+ if base_dir is not None:
+ shutil.rmtree(base_dir)
def test_unicode_paths(self):
"""Ensure that we can support non-ASCII paths, even on Windows."""
diff --git a/init/perfboot.py b/init/perfboot.py
index 2a17ab6..91e6c2b 100755
--- a/init/perfboot.py
+++ b/init/perfboot.py
@@ -92,7 +92,7 @@
self._interval = interval
self._device = device
self._temp_paths = device.shell(
- ['ls', '/sys/class/thermal/thermal_zone*/temp']).splitlines()
+ ['ls', '/sys/class/thermal/thermal_zone*/temp'])[0].splitlines()
self._product = device.get_prop('ro.build.product')
self._waited = False
@@ -109,7 +109,7 @@
def _get_cpu_temp(self, threshold):
max_temp = 0
for temp_path in self._temp_paths:
- temp = int(self._device.shell(['cat', temp_path]).rstrip())
+ temp = int(self._device.shell(['cat', temp_path])[0].rstrip())
max_temp = max(max_temp, temp)
if temp >= threshold:
return temp
@@ -173,7 +173,7 @@
device.wait()
device.shell(['rm', '-rf', '/system/data/dropbox'])
original_dropbox_max_files = device.shell(
- ['settings', 'get', 'global', 'dropbox_max_files']).rstrip()
+ ['settings', 'get', 'global', 'dropbox_max_files'])[0].rstrip()
device.shell(['settings', 'put', 'global', 'dropbox_max_files', '0'])
return original_dropbox_max_files
@@ -244,7 +244,8 @@
"""Drop unknown tags not listed in device's event-log-tags file."""
device.wait()
supported_tags = set()
- for l in device.shell(['cat', '/system/etc/event-log-tags']).splitlines():
+ for l in device.shell(
+ ['cat', '/system/etc/event-log-tags'])[0].splitlines():
tokens = l.split(' ')
if len(tokens) >= 2:
supported_tags.add(tokens[1])
diff --git a/metricsd/Android.mk b/metricsd/Android.mk
index c219ab1..8a0a8b4 100644
--- a/metricsd/Android.mk
+++ b/metricsd/Android.mk
@@ -23,7 +23,8 @@
c_metrics_library.cc \
metrics_library.cc \
serialization/metric_sample.cc \
- serialization/serialization_utils.cc
+ serialization/serialization_utils.cc \
+ timer.cc
metrics_client_sources := \
metrics_client.cc
diff --git a/metricsd/timer.h b/metricsd/include/metrics/timer.h
similarity index 100%
rename from metricsd/timer.h
rename to metricsd/include/metrics/timer.h
diff --git a/metricsd/metrics_daemon.cc b/metricsd/metrics_daemon.cc
index de7f2ea..b0e4b2f 100644
--- a/metricsd/metrics_daemon.cc
+++ b/metricsd/metrics_daemon.cc
@@ -241,7 +241,7 @@
daily_active_use_.reset(
new PersistentInteger("Platform.DailyUseTime"));
version_cumulative_active_use_.reset(
- new PersistentInteger("Platform.CumulativeDailyUseTime"));
+ new PersistentInteger("Platform.CumulativeUseTime"));
version_cumulative_cpu_use_.reset(
new PersistentInteger("Platform.CumulativeCpuTime"));
@@ -444,7 +444,7 @@
UpdateStats(TimeTicks::Now(), Time::Now());
// Reports the active use time since the last crash and resets it.
- SendCrashIntervalSample(user_crash_interval_);
+ SendAndResetCrashIntervalSample(user_crash_interval_);
any_crashes_daily_count_->Add(1);
any_crashes_weekly_count_->Add(1);
@@ -457,7 +457,7 @@
UpdateStats(TimeTicks::Now(), Time::Now());
// Reports the active use time since the last crash and resets it.
- SendCrashIntervalSample(kernel_crash_interval_);
+ SendAndResetCrashIntervalSample(kernel_crash_interval_);
any_crashes_daily_count_->Add(1);
any_crashes_weekly_count_->Add(1);
@@ -472,7 +472,7 @@
UpdateStats(TimeTicks::Now(), Time::Now());
// Reports the active use time since the last crash and resets it.
- SendCrashIntervalSample(unclean_shutdown_interval_);
+ SendAndResetCrashIntervalSample(unclean_shutdown_interval_);
unclean_shutdowns_daily_count_->Add(1);
unclean_shutdowns_weekly_count_->Add(1);
@@ -1033,7 +1033,7 @@
int64_t active_use_seconds = version_cumulative_active_use_->Get();
if (active_use_seconds > 0) {
SendSample(version_cumulative_active_use_->Name(),
- active_use_seconds / 1000, // stat is in seconds
+ active_use_seconds,
1, // device may be used very little...
8 * 1000 * 1000, // ... or a lot (about 90 days)
100);
@@ -1046,7 +1046,7 @@
}
}
-void MetricsDaemon::SendDailyUseSample(
+void MetricsDaemon::SendAndResetDailyUseSample(
const scoped_ptr<PersistentInteger>& use) {
SendSample(use->Name(),
use->GetAndClear(),
@@ -1055,7 +1055,7 @@
50); // number of buckets
}
-void MetricsDaemon::SendCrashIntervalSample(
+void MetricsDaemon::SendAndResetCrashIntervalSample(
const scoped_ptr<PersistentInteger>& interval) {
SendSample(interval->Name(),
interval->GetAndClear(),
@@ -1064,7 +1064,7 @@
50); // number of buckets
}
-void MetricsDaemon::SendCrashFrequencySample(
+void MetricsDaemon::SendAndResetCrashFrequencySample(
const scoped_ptr<PersistentInteger>& frequency) {
SendSample(frequency->Name(),
frequency->GetAndClear(),
@@ -1097,21 +1097,20 @@
if (daily_cycle_->Get() != day) {
daily_cycle_->Set(day);
- SendDailyUseSample(daily_active_use_);
- SendDailyUseSample(version_cumulative_active_use_);
- SendCrashFrequencySample(any_crashes_daily_count_);
- SendCrashFrequencySample(user_crashes_daily_count_);
- SendCrashFrequencySample(kernel_crashes_daily_count_);
- SendCrashFrequencySample(unclean_shutdowns_daily_count_);
+ SendAndResetDailyUseSample(daily_active_use_);
+ SendAndResetCrashFrequencySample(any_crashes_daily_count_);
+ SendAndResetCrashFrequencySample(user_crashes_daily_count_);
+ SendAndResetCrashFrequencySample(kernel_crashes_daily_count_);
+ SendAndResetCrashFrequencySample(unclean_shutdowns_daily_count_);
SendKernelCrashesCumulativeCountStats();
}
if (weekly_cycle_->Get() != week) {
weekly_cycle_->Set(week);
- SendCrashFrequencySample(any_crashes_weekly_count_);
- SendCrashFrequencySample(user_crashes_weekly_count_);
- SendCrashFrequencySample(kernel_crashes_weekly_count_);
- SendCrashFrequencySample(unclean_shutdowns_weekly_count_);
+ SendAndResetCrashFrequencySample(any_crashes_weekly_count_);
+ SendAndResetCrashFrequencySample(user_crashes_weekly_count_);
+ SendAndResetCrashFrequencySample(kernel_crashes_weekly_count_);
+ SendAndResetCrashFrequencySample(unclean_shutdowns_weekly_count_);
}
}
diff --git a/metricsd/metrics_daemon.h b/metricsd/metrics_daemon.h
index b363c5e..fbb871e 100644
--- a/metricsd/metrics_daemon.h
+++ b/metricsd/metrics_daemon.h
@@ -171,15 +171,19 @@
base::TimeDelta GetIncrementalCpuUse();
// Sends a sample representing the number of seconds of active use
- // for a 24-hour period.
- void SendDailyUseSample(const scoped_ptr<PersistentInteger>& use);
+ // for a 24-hour period and reset |use|.
+ void SendAndResetDailyUseSample(
+ const scoped_ptr<PersistentInteger>& use);
// Sends a sample representing a time interval between two crashes of the
- // same type.
- void SendCrashIntervalSample(const scoped_ptr<PersistentInteger>& interval);
+ // same type and reset |interval|.
+ void SendAndResetCrashIntervalSample(
+ const scoped_ptr<PersistentInteger>& interval);
- // Sends a sample representing a frequency of crashes of some type.
- void SendCrashFrequencySample(const scoped_ptr<PersistentInteger>& frequency);
+ // Sends a sample representing a frequency of crashes of some type and reset
+ // |frequency|.
+ void SendAndResetCrashFrequencySample(
+ const scoped_ptr<PersistentInteger>& frequency);
// Initializes vm and disk stats reporting.
void StatsReporterInit();
diff --git a/metricsd/timer.cc b/metricsd/timer.cc
index 7b00cc0..0c2c119 100644
--- a/metricsd/timer.cc
+++ b/metricsd/timer.cc
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-#include "timer.h"
+#include "metrics/timer.h"
#include <string>
diff --git a/metricsd/timer_mock.h b/metricsd/timer_mock.h
index 8c9e8d8..200ee9a 100644
--- a/metricsd/timer_mock.h
+++ b/metricsd/timer_mock.h
@@ -21,7 +21,7 @@
#include <gmock/gmock.h>
-#include "timer.h"
+#include "metrics/timer.h"
namespace chromeos_metrics {
diff --git a/metricsd/timer_test.cc b/metricsd/timer_test.cc
index ab027d4..432c3d2 100644
--- a/metricsd/timer_test.cc
+++ b/metricsd/timer_test.cc
@@ -20,8 +20,8 @@
#include <gmock/gmock.h>
#include <gtest/gtest.h>
+#include "metrics/timer.h"
#include "metrics_library_mock.h"
-#include "timer.h"
#include "timer_mock.h"
using ::testing::_;
diff --git a/trusty/libtrusty/Android.mk b/trusty/libtrusty/Android.mk
new file mode 100644
index 0000000..45fc079
--- /dev/null
+++ b/trusty/libtrusty/Android.mk
@@ -0,0 +1,36 @@
+# Copyright (C) 2015 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.
+
+LOCAL_PATH := $(call my-dir)
+
+# == libtrusty Static library ==
+include $(CLEAR_VARS)
+
+LOCAL_MODULE := libtrusty
+LOCAL_MODULE_TAGS := optional
+LOCAL_SRC_FILES := trusty.c
+LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)/include
+
+include $(BUILD_STATIC_LIBRARY)
+
+# == libtrusty shared library ==
+include $(CLEAR_VARS)
+
+LOCAL_MODULE := libtrusty
+LOCAL_MODULE_TAGS := optional
+LOCAL_SRC_FILES := trusty.c
+LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)/include
+LOCAL_SHARED_LIBRARIES := liblog
+
+include $(BUILD_SHARED_LIBRARY)
diff --git a/trusty/libtrusty/include/trusty/tipc.h b/trusty/libtrusty/include/trusty/tipc.h
new file mode 100644
index 0000000..a3f2a3f
--- /dev/null
+++ b/trusty/libtrusty/include/trusty/tipc.h
@@ -0,0 +1,31 @@
+/*
+ * Copyright (C) 2015 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 _LIB_TIPC_H
+#define _LIB_TIPC_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+int tipc_connect(const char *dev_name, const char *srv_name);
+int tipc_close(int fd);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/trusty/libtrusty/tipc-test/Android.mk b/trusty/libtrusty/tipc-test/Android.mk
new file mode 100644
index 0000000..80030fe
--- /dev/null
+++ b/trusty/libtrusty/tipc-test/Android.mk
@@ -0,0 +1,29 @@
+# Copyright (C) 2015 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.
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE := tipc-test
+LOCAL_FORCE_STATIC_EXECUTABLE := true
+LOCAL_MODULE_PATH := $(TARGET_OUT_OPTIONAL_EXECUTABLES)
+LOCAL_MODULE_TAGS := optional
+LOCAL_SRC_FILES := tipc_test.c
+LOCAL_STATIC_LIBRARIES := libc libtrusty liblog
+LOCAL_MULTILIB := both
+LOCAL_MODULE_STEM_32 := $(LOCAL_MODULE)32
+LOCAL_MODULE_STEM_64 := $(LOCAL_MODULE)64
+
+include $(BUILD_EXECUTABLE)
diff --git a/trusty/libtrusty/tipc-test/tipc_test.c b/trusty/libtrusty/tipc-test/tipc_test.c
new file mode 100644
index 0000000..55d5ee6
--- /dev/null
+++ b/trusty/libtrusty/tipc-test/tipc_test.c
@@ -0,0 +1,744 @@
+/*
+ * Copyright (C) 2015 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 <stdio.h>
+#include <errno.h>
+#include <stdbool.h>
+#include <string.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <getopt.h>
+
+#include <trusty/tipc.h>
+
+#define TIPC_DEFAULT_DEVNAME "/dev/trusty-ipc-dev0"
+
+static const char *dev_name = NULL;
+static const char *test_name = NULL;
+
+static const char *uuid_name = "com.android.ipc-unittest.srv.uuid";
+static const char *echo_name = "com.android.ipc-unittest.srv.echo";
+static const char *ta_only_name = "com.android.ipc-unittest.srv.ta_only";
+static const char *ns_only_name = "com.android.ipc-unittest.srv.ns_only";
+static const char *datasink_name = "com.android.ipc-unittest.srv.datasink";
+static const char *closer1_name = "com.android.ipc-unittest.srv.closer1";
+static const char *closer2_name = "com.android.ipc-unittest.srv.closer2";
+static const char *closer3_name = "com.android.ipc-unittest.srv.closer3";
+static const char *main_ctrl_name = "com.android.ipc-unittest.ctrl";
+
+static const char *_sopts = "hsvD:t:r:m:b:";
+static const struct option _lopts[] = {
+ {"help", no_argument, 0, 'h'},
+ {"silent", no_argument, 0, 's'},
+ {"variable",no_argument, 0, 'v'},
+ {"dev", required_argument, 0, 'D'},
+ {"repeat", required_argument, 0, 'r'},
+ {"burst", required_argument, 0, 'b'},
+ {"msgsize", required_argument, 0, 'm'},
+ {0, 0, 0, 0}
+};
+
+static const char *usage =
+"Usage: %s [options]\n"
+"\n"
+"options:\n"
+" -h, --help prints this message and exit\n"
+" -D, --dev name device name\n"
+" -t, --test name test to run\n"
+" -r, --repeat cnt repeat count\n"
+" -m, --msgsize size max message size\n"
+" -v, --variable variable message size\n"
+" -s, --silent silent\n"
+"\n"
+;
+
+static const char *usage_long =
+"\n"
+"The following tests are available:\n"
+" connect - connect to datasink service\n"
+" connect_foo - connect to non existing service\n"
+" burst_write - send messages to datasink service\n"
+" echo - send/receive messages to echo service\n"
+" select - test select call\n"
+" blocked_read - test blocked read\n"
+" closer1 - connection closed by remote (test1)\n"
+" closer2 - connection closed by remote (test2)\n"
+" closer3 - connection closed by remote (test3)\n"
+" ta2ta-ipc - execute TA to TA unittest\n"
+" dev-uuid - print device uuid\n"
+" ta-access - test ta-access flags\n"
+"\n"
+;
+
+static uint opt_repeat = 1;
+static uint opt_msgsize = 32;
+static uint opt_msgburst = 32;
+static bool opt_variable = false;
+static bool opt_silent = false;
+
+static void print_usage_and_exit(const char *prog, int code, bool verbose)
+{
+ fprintf (stderr, usage, prog);
+ if (verbose)
+ fprintf (stderr, usage_long);
+ exit(code);
+}
+
+static void parse_options(int argc, char **argv)
+{
+ int c;
+ int oidx = 0;
+
+ while (1)
+ {
+ c = getopt_long (argc, argv, _sopts, _lopts, &oidx);
+ if (c == -1)
+ break; /* done */
+
+ switch (c) {
+
+ case 'D':
+ dev_name = strdup(optarg);
+ break;
+
+ case 't':
+ test_name = strdup(optarg);
+ break;
+
+ case 'v':
+ opt_variable = true;
+ break;
+
+ case 'r':
+ opt_repeat = atoi(optarg);
+ break;
+
+ case 'm':
+ opt_msgsize = atoi(optarg);
+ break;
+
+ case 'b':
+ opt_msgburst = atoi(optarg);
+ break;
+
+ case 's':
+ opt_silent = true;
+ break;
+
+ case 'h':
+ print_usage_and_exit(argv[0], EXIT_SUCCESS, true);
+ break;
+
+ default:
+ print_usage_and_exit(argv[0], EXIT_FAILURE, false);
+ }
+ }
+}
+
+static int connect_test(uint repeat)
+{
+ uint i;
+ int echo_fd;
+ int dsink_fd;
+
+ if (!opt_silent) {
+ printf("%s: repeat = %u\n", __func__, repeat);
+ }
+
+ for (i = 0; i < repeat; i++) {
+ echo_fd = tipc_connect(dev_name, echo_name);
+ if (echo_fd < 0) {
+ fprintf(stderr, "Failed to connect to '%s' service\n",
+ "echo");
+ }
+ dsink_fd = tipc_connect(dev_name, datasink_name);
+ if (dsink_fd < 0) {
+ fprintf(stderr, "Failed to connect to '%s' service\n",
+ "datasink");
+ }
+
+ if (echo_fd >= 0) {
+ tipc_close(echo_fd);
+ }
+ if (dsink_fd >= 0) {
+ tipc_close(dsink_fd);
+ }
+ }
+
+ if (!opt_silent) {
+ printf("%s: done\n", __func__);
+ }
+
+ return 0;
+}
+
+static int connect_foo(uint repeat)
+{
+ uint i;
+ int fd;
+
+ if (!opt_silent) {
+ printf("%s: repeat = %u\n", __func__, repeat);
+ }
+
+ for (i = 0; i < repeat; i++) {
+ fd = tipc_connect(dev_name, "foo");
+ if (fd >= 0) {
+ fprintf(stderr, "succeeded to connect to '%s' service\n",
+ "foo");
+ tipc_close(fd);
+ }
+ }
+
+ if (!opt_silent) {
+ printf("%s: done\n", __func__);
+ }
+
+ return 0;
+}
+
+
+static int closer1_test(uint repeat)
+{
+ uint i;
+ int fd;
+
+ if (!opt_silent) {
+ printf("%s: repeat = %u\n", __func__, repeat);
+ }
+
+ for (i = 0; i < repeat; i++) {
+ fd = tipc_connect(dev_name, closer1_name);
+ if (fd < 0) {
+ fprintf(stderr, "Failed to connect to '%s' service\n",
+ "closer1");
+ continue;
+ }
+ if (!opt_silent) {
+ printf("%s: connected\n", __func__);
+ }
+ tipc_close(fd);
+ }
+
+ if (!opt_silent) {
+ printf("%s: done\n", __func__);
+ }
+
+ return 0;
+}
+
+static int closer2_test(uint repeat)
+{
+ uint i;
+ int fd;
+
+ if (!opt_silent) {
+ printf("%s: repeat = %u\n", __func__, repeat);
+ }
+
+ for (i = 0; i < repeat; i++) {
+ fd = tipc_connect(dev_name, closer2_name);
+ if (fd < 0) {
+ if (!opt_silent) {
+ printf("failed to connect to '%s' service\n", "closer2");
+ }
+ } else {
+ /* this should always fail */
+ fprintf(stderr, "connected to '%s' service\n", "closer2");
+ tipc_close(fd);
+ }
+ }
+
+ if (!opt_silent) {
+ printf("%s: done\n", __func__);
+ }
+
+ return 0;
+}
+
+static int closer3_test(uint repeat)
+{
+ uint i, j;
+ ssize_t rc;
+ int fd[4];
+ char buf[64];
+
+ if (!opt_silent) {
+ printf("%s: repeat = %u\n", __func__, repeat);
+ }
+
+ for (i = 0; i < repeat; i++) {
+
+ /* open 4 connections to closer3 service */
+ for (j = 0; j < 4; j++) {
+ fd[j] = tipc_connect(dev_name, closer3_name);
+ if (fd[j] < 0) {
+ fprintf(stderr, "fd[%d]: failed to connect to '%s' service\n", j, "closer3");
+ } else {
+ if (!opt_silent) {
+ printf("%s: fd[%d]=%d: connected\n", __func__, j, fd[j]);
+ }
+ memset(buf, i + j, sizeof(buf));
+ rc = write(fd[j], buf, sizeof(buf));
+ if (rc != sizeof(buf)) {
+ if (!opt_silent) {
+ printf("%s: fd[%d]=%d: write returned = %zd\n",
+ __func__, j, fd[j], rc);
+ }
+ perror("closer3_test: write");
+ }
+ }
+ }
+
+ /* sleep a bit */
+ sleep(1);
+
+ /* It is expected that they will be closed by remote */
+ for (j = 0; j < 4; j++) {
+ if (fd[j] < 0)
+ continue;
+ rc = write(fd[j], buf, sizeof(buf));
+ if (rc != sizeof(buf)) {
+ if (!opt_silent) {
+ printf("%s: fd[%d]=%d: write returned = %zd\n",
+ __func__, j, fd[j], rc);
+ }
+ perror("closer3_test: write");
+ }
+ }
+
+ /* then they have to be closed by remote */
+ for (j = 0; j < 4; j++) {
+ if (fd[j] >= 0) {
+ tipc_close(fd[j]);
+ }
+ }
+ }
+
+ if (!opt_silent) {
+ printf("%s: done\n", __func__);
+ }
+
+ return 0;
+}
+
+
+static int echo_test(uint repeat, uint msgsz, bool var)
+{
+ uint i;
+ ssize_t rc;
+ size_t msg_len;
+ int echo_fd =-1;
+ char tx_buf[msgsz];
+ char rx_buf[msgsz];
+
+ if (!opt_silent) {
+ printf("%s: repeat %u: msgsz %u: variable %s\n",
+ __func__, repeat, msgsz, var ? "true" : "false");
+ }
+
+ echo_fd = tipc_connect(dev_name, echo_name);
+ if (echo_fd < 0) {
+ fprintf(stderr, "Failed to connect to service\n");
+ return echo_fd;
+ }
+
+ for (i = 0; i < repeat; i++) {
+
+ msg_len = msgsz;
+ if (opt_variable && msgsz) {
+ msg_len = rand() % msgsz;
+ }
+
+ memset(tx_buf, i + 1, msg_len);
+
+ rc = write(echo_fd, tx_buf, msg_len);
+ if ((size_t)rc != msg_len) {
+ perror("echo_test: write");
+ break;
+ }
+
+ rc = read(echo_fd, rx_buf, msg_len);
+ if (rc < 0) {
+ perror("echo_test: read");
+ break;
+ }
+
+ if ((size_t)rc != msg_len) {
+ fprintf(stderr, "data truncated (%zu vs. %zu)\n",
+ rc, msg_len);
+ continue;
+ }
+
+ if (memcmp(tx_buf, rx_buf, (size_t) rc)) {
+ fprintf(stderr, "data mismatch\n");
+ continue;
+ }
+ }
+
+ tipc_close(echo_fd);
+
+ if (!opt_silent) {
+ printf("%s: done\n",__func__);
+ }
+
+ return 0;
+}
+
+static int burst_write_test(uint repeat, uint msgburst, uint msgsz, bool var)
+{
+ int fd;
+ uint i, j;
+ ssize_t rc;
+ size_t msg_len;
+ char tx_buf[msgsz];
+
+ if (!opt_silent) {
+ printf("%s: repeat %u: burst %u: msgsz %u: variable %s\n",
+ __func__, repeat, msgburst, msgsz,
+ var ? "true" : "false");
+ }
+
+ for (i = 0; i < repeat; i++) {
+
+ fd = tipc_connect(dev_name, datasink_name);
+ if (fd < 0) {
+ fprintf(stderr, "Failed to connect to '%s' service\n",
+ "datasink");
+ break;
+ }
+
+ for (j = 0; j < msgburst; j++) {
+ msg_len = msgsz;
+ if (var && msgsz) {
+ msg_len = rand() % msgsz;
+ }
+
+ memset(tx_buf, i + 1, msg_len);
+ rc = write(fd, tx_buf, msg_len);
+ if ((size_t)rc != msg_len) {
+ perror("burst_test: write");
+ break;
+ }
+ }
+
+ tipc_close(fd);
+ }
+
+ if (!opt_silent) {
+ printf("%s: done\n",__func__);
+ }
+
+ return 0;
+}
+
+
+static int _wait_for_msg(int fd, uint msgsz, int timeout)
+{
+ int rc;
+ fd_set rfds;
+ uint msgcnt = 0;
+ char rx_buf[msgsz];
+ struct timeval tv;
+
+ if (!opt_silent) {
+ printf("waiting (%d) for msg\n", timeout);
+ }
+
+ FD_ZERO(&rfds);
+ FD_SET(fd, &rfds);
+
+ tv.tv_sec = timeout;
+ tv.tv_usec = 0;
+
+ for(;;) {
+ rc = select(fd+1, &rfds, NULL, NULL, &tv);
+
+ if (rc == 0) {
+ if (!opt_silent) {
+ printf("select timedout\n");
+ }
+ break;
+ }
+
+ if (rc == -1) {
+ perror("select_test: select");
+ return rc;
+ }
+
+ rc = read(fd, rx_buf, sizeof(rx_buf));
+ if (rc < 0) {
+ perror("select_test: read");
+ return rc;
+ } else {
+ if (rc > 0) {
+ msgcnt++;
+ }
+ }
+ }
+
+ if (!opt_silent) {
+ printf("got %u messages\n", msgcnt);
+ }
+
+ return 0;
+}
+
+
+static int select_test(uint repeat, uint msgburst, uint msgsz)
+{
+ int fd;
+ uint i, j;
+ ssize_t rc;
+ char tx_buf[msgsz];
+
+ if (!opt_silent) {
+ printf("%s: repeat %u\n", __func__, repeat);
+ }
+
+ fd = tipc_connect(dev_name, echo_name);
+ if (fd < 0) {
+ fprintf(stderr, "Failed to connect to '%s' service\n",
+ "echo");
+ return fd;
+ }
+
+ for (i = 0; i < repeat; i++) {
+
+ _wait_for_msg(fd, msgsz, 1);
+
+ if (!opt_silent) {
+ printf("sending burst: %u msg\n", msgburst);
+ }
+
+ for (j = 0; j < msgburst; j++) {
+ memset(tx_buf, i + j, msgsz);
+ rc = write(fd, tx_buf, msgsz);
+ if ((size_t)rc != msgsz) {
+ perror("burst_test: write");
+ break;
+ }
+ }
+ }
+
+ tipc_close(fd);
+
+ if (!opt_silent) {
+ printf("%s: done\n",__func__);
+ }
+
+ return 0;
+}
+
+static int blocked_read_test(uint repeat)
+{
+ int fd;
+ uint i;
+ ssize_t rc;
+ char rx_buf[512];
+
+ if (!opt_silent) {
+ printf("%s: repeat %u\n", __func__, repeat);
+ }
+
+ fd = tipc_connect(dev_name, echo_name);
+ if (fd < 0) {
+ fprintf(stderr, "Failed to connect to '%s' service\n",
+ "echo");
+ return fd;
+ }
+
+ for (i = 0; i < repeat; i++) {
+ rc = read(fd, rx_buf, sizeof(rx_buf));
+ if (rc < 0) {
+ perror("select_test: read");
+ break;
+ } else {
+ if (!opt_silent) {
+ printf("got %zd bytes\n", rc);
+ }
+ }
+ }
+
+ tipc_close(fd);
+
+ if (!opt_silent) {
+ printf("%s: done\n",__func__);
+ }
+
+ return 0;
+}
+
+static int ta2ta_ipc_test(void)
+{
+ int fd;
+ char rx_buf[64];
+
+ if (!opt_silent) {
+ printf("%s:\n", __func__);
+ }
+
+ fd = tipc_connect(dev_name, main_ctrl_name);
+ if (fd < 0) {
+ fprintf(stderr, "Failed to connect to '%s' service\n",
+ "main_ctrl");
+ return fd;
+ }
+
+ /* wait for test to complete */
+ (void) read(fd, rx_buf, sizeof(rx_buf));
+
+ tipc_close(fd);
+
+ return 0;
+}
+
+typedef struct uuid
+{
+ uint32_t time_low;
+ uint16_t time_mid;
+ uint16_t time_hi_and_version;
+ uint8_t clock_seq_and_node[8];
+} uuid_t;
+
+static void print_uuid(const char *dev, uuid_t *uuid)
+{
+ printf("%s:", dev);
+ printf("uuid: %08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x\n",
+ uuid->time_low,
+ uuid->time_mid,
+ uuid->time_hi_and_version,
+ uuid->clock_seq_and_node[0],
+ uuid->clock_seq_and_node[1],
+ uuid->clock_seq_and_node[2],
+ uuid->clock_seq_and_node[3],
+ uuid->clock_seq_and_node[4],
+ uuid->clock_seq_and_node[5],
+ uuid->clock_seq_and_node[6],
+ uuid->clock_seq_and_node[7]
+ );
+}
+
+static int dev_uuid_test(void)
+{
+ int fd;
+ ssize_t rc;
+ uuid_t uuid;
+
+ fd = tipc_connect(dev_name, uuid_name);
+ if (fd < 0) {
+ fprintf(stderr, "Failed to connect to '%s' service\n",
+ "uuid");
+ return fd;
+ }
+
+ /* wait for test to complete */
+ rc = read(fd, &uuid, sizeof(uuid));
+ if (rc < 0) {
+ perror("dev_uuid_test: read");
+ } else if (rc != sizeof(uuid)) {
+ fprintf(stderr, "unexpected uuid size (%d vs. %d)\n",
+ (int)rc, (int)sizeof(uuid));
+ } else {
+ print_uuid(dev_name, &uuid);
+ }
+
+ tipc_close(fd);
+
+ return 0;
+}
+
+static int ta_access_test(void)
+{
+ int fd;
+
+ if (!opt_silent) {
+ printf("%s:\n", __func__);
+ }
+
+ fd = tipc_connect(dev_name, ta_only_name);
+ if (fd >= 0) {
+ fprintf(stderr, "Succeed to connect to '%s' service\n",
+ "ta_only");
+ tipc_close(fd);
+ }
+
+ fd = tipc_connect(dev_name, ns_only_name);
+ if (fd < 0) {
+ fprintf(stderr, "Failed to connect to '%s' service\n",
+ "ns_only");
+ return fd;
+ }
+ tipc_close(fd);
+
+ if (!opt_silent) {
+ printf("%s: done\n",__func__);
+ }
+
+ return 0;
+}
+
+
+int main(int argc, char **argv)
+{
+ int rc = 0;
+
+ if (argc <= 1) {
+ print_usage_and_exit(argv[0], EXIT_FAILURE, false);
+ }
+
+ parse_options(argc, argv);
+
+ if (!dev_name) {
+ dev_name = TIPC_DEFAULT_DEVNAME;
+ }
+
+ if (!test_name) {
+ fprintf(stderr, "need a Test to run\n");
+ print_usage_and_exit(argv[0], EXIT_FAILURE, true);
+ }
+
+ if (strcmp(test_name, "connect") == 0) {
+ rc = connect_test(opt_repeat);
+ } else if (strcmp(test_name, "connect_foo") == 0) {
+ rc = connect_foo(opt_repeat);
+ } else if (strcmp(test_name, "burst_write") == 0) {
+ rc = burst_write_test(opt_repeat, opt_msgburst, opt_msgsize, opt_variable);
+ } else if (strcmp(test_name, "select") == 0) {
+ rc = select_test(opt_repeat, opt_msgburst, opt_msgsize);
+ } else if (strcmp(test_name, "blocked_read") == 0) {
+ rc = blocked_read_test(opt_repeat);
+ } else if (strcmp(test_name, "closer1") == 0) {
+ rc = closer1_test(opt_repeat);
+ } else if (strcmp(test_name, "closer2") == 0) {
+ rc = closer2_test(opt_repeat);
+ } else if (strcmp(test_name, "closer3") == 0) {
+ rc = closer3_test(opt_repeat);
+ } else if (strcmp(test_name, "echo") == 0) {
+ rc = echo_test(opt_repeat, opt_msgsize, opt_variable);
+ } else if(strcmp(test_name, "ta2ta-ipc") == 0) {
+ rc = ta2ta_ipc_test();
+ } else if (strcmp(test_name, "dev-uuid") == 0) {
+ rc = dev_uuid_test();
+ } else if (strcmp(test_name, "ta-access") == 0) {
+ rc = ta_access_test();
+ } else {
+ fprintf(stderr, "Unrecognized test name '%s'\n", test_name);
+ print_usage_and_exit(argv[0], EXIT_FAILURE, true);
+ }
+
+ return rc == 0 ? EXIT_SUCCESS : EXIT_FAILURE;
+}
diff --git a/trusty/libtrusty/tipc_ioctl.h b/trusty/libtrusty/tipc_ioctl.h
new file mode 100644
index 0000000..27da56a
--- /dev/null
+++ b/trusty/libtrusty/tipc_ioctl.h
@@ -0,0 +1,26 @@
+/*
+ * Copyright (C) 2015 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 _TIPC_IOCTL_H
+#define _TIPC_IOCTL_H
+
+#include <linux/ioctl.h>
+#include <linux/types.h>
+
+#define TIPC_IOC_MAGIC 'r'
+#define TIPC_IOC_CONNECT _IOW(TIPC_IOC_MAGIC, 0x80, char *)
+
+#endif
diff --git a/trusty/libtrusty/trusty.c b/trusty/libtrusty/trusty.c
new file mode 100644
index 0000000..b6897ce
--- /dev/null
+++ b/trusty/libtrusty/trusty.c
@@ -0,0 +1,59 @@
+/*
+ * Copyright (C) 2015 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.
+ */
+
+#define LOG_TAG "libtrusty"
+
+#include <errno.h>
+#include <fcntl.h>
+#include <stdbool.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include <cutils/log.h>
+
+#include "tipc_ioctl.h"
+
+int tipc_connect(const char *dev_name, const char *srv_name)
+{
+ int fd;
+ int rc;
+
+ fd = open(dev_name, O_RDWR);
+ if (fd < 0) {
+ rc = -errno;
+ ALOGE("%s: cannot open tipc device \"%s\": %s\n",
+ __func__, dev_name, strerror(errno));
+ return rc < 0 ? rc : -1;
+ }
+
+ rc = ioctl(fd, TIPC_IOC_CONNECT, srv_name);
+ if (rc < 0) {
+ rc = -errno;
+ ALOGE("%s: can't connect to tipc service \"%s\" (err=%d)\n",
+ __func__, srv_name, errno);
+ close(fd);
+ return rc < 0 ? rc : -1;
+ }
+
+ ALOGV("%s: connected to \"%s\" fd %d\n", __func__, srv_name, fd);
+ return fd;
+}
+
+void tipc_close(int fd)
+{
+ close(fd);
+}