Merge changes from topic 'adb_shell'
* changes:
adb: add client side shell protocol and enable.
adb: implement shell protocol.
diff --git a/adb/Android.mk b/adb/Android.mk
index 60673e6..6d68bec 100644
--- a/adb/Android.mk
+++ b/adb/Android.mk
@@ -78,6 +78,9 @@
LIBADB_TEST_darwin_SRCS := \
fdevent_test.cpp \
+LIBADB_TEST_windows_SRCS := \
+ sysdeps_win32_test.cpp \
+
include $(CLEAR_VARS)
LOCAL_CLANG := true
LOCAL_MODULE := libadbd
@@ -144,6 +147,7 @@
include $(CLEAR_VARS)
LOCAL_MODULE := adb_test
+LOCAL_MODULE_HOST_OS := darwin linux windows
LOCAL_CFLAGS := -DADB_HOST=1 $(LIBADB_CFLAGS)
LOCAL_CFLAGS_windows := $(LIBADB_windows_CFLAGS)
LOCAL_CFLAGS_linux := $(LIBADB_linux_CFLAGS)
@@ -155,6 +159,7 @@
LOCAL_SRC_FILES_linux := $(LIBADB_TEST_linux_SRCS)
LOCAL_SRC_FILES_darwin := $(LIBADB_TEST_darwin_SRCS)
+LOCAL_SRC_FILES_windows := $(LIBADB_TEST_windows_SRCS)
LOCAL_SANITIZE := $(adb_host_sanitize)
LOCAL_SHARED_LIBRARIES := libbase
LOCAL_STATIC_LIBRARIES := \
@@ -162,6 +167,8 @@
libcrypto_static \
libcutils \
+# Set entrypoint to wmain from sysdeps_win32.cpp instead of main
+LOCAL_LDFLAGS_windows := -municode
LOCAL_LDLIBS_linux := -lrt -ldl -lpthread
LOCAL_LDLIBS_darwin := -framework CoreFoundation -framework IOKit
LOCAL_LDLIBS_windows := -lws2_32 -luserenv
diff --git a/adb/client/main.cpp b/adb/client/main.cpp
index 6e27c0f..47234ee 100644
--- a/adb/client/main.cpp
+++ b/adb/client/main.cpp
@@ -169,34 +169,8 @@
return 0;
}
-#ifdef _WIN32
-static bool _argv_is_utf8 = false;
-#endif
-
int main(int argc, char** argv) {
-#ifdef _WIN32
- if (!_argv_is_utf8) {
- fatal("_argv_is_utf8 is not set, suggesting that wmain was not "
- "called. Did you forget to link with -municode?");
- }
-#endif
-
adb_sysdeps_init();
adb_trace_init(argv);
return adb_commandline(argc - 1, const_cast<const char**>(argv + 1));
}
-
-#ifdef _WIN32
-
-extern "C"
-int wmain(int argc, wchar_t **argv) {
- // Set diagnostic flag to try to detect if the build system was not
- // configured to call wmain.
- _argv_is_utf8 = true;
-
- // Convert args from UTF-16 to UTF-8 and pass that to main().
- NarrowArgs narrow_args(argc, argv);
- return main(argc, narrow_args.data());
-}
-
-#endif
diff --git a/adb/shell_service_protocol_test.cpp b/adb/shell_service_protocol_test.cpp
index 85b2f91..a826035 100644
--- a/adb/shell_service_protocol_test.cpp
+++ b/adb/shell_service_protocol_test.cpp
@@ -72,13 +72,17 @@
read_protocol_->buffer_end_ = read_protocol_->data() + size;
}
+#if !defined(_WIN32)
static sig_t saved_sigpipe_handler_;
+#endif
int read_fd_ = -1, write_fd_ = -1;
ShellProtocol *read_protocol_ = nullptr, *write_protocol_ = nullptr;
};
+#if !defined(_WIN32)
sig_t ShellProtocolTest::saved_sigpipe_handler_ = nullptr;
+#endif
namespace {
diff --git a/adb/sysdeps_win32.cpp b/adb/sysdeps_win32.cpp
index b53cd77..5b23c79 100644
--- a/adb/sysdeps_win32.cpp
+++ b/adb/sysdeps_win32.cpp
@@ -25,6 +25,7 @@
#include <stdio.h>
#include <stdlib.h>
+#include <algorithm>
#include <memory>
#include <string>
#include <unordered_map>
@@ -1120,6 +1121,11 @@
BIPD(( "bip_buffer_write: enter %d->%d len %d", bip->fdin, bip->fdout, len ));
BIPDUMP( src, len );
+ if (bip->closed) {
+ errno = EPIPE;
+ return -1;
+ }
+
EnterCriticalSection( &bip->lock );
while (!bip->can_write) {
@@ -3776,6 +3782,29 @@
return _wfopen(widen(f).c_str(), widen(m).c_str());
}
+// Return a lowercase version of the argument. Uses C Runtime tolower() on
+// each byte which is not UTF-8 aware, and theoretically uses the current C
+// Runtime locale (which in practice is not changed, so this becomes a ASCII
+// conversion).
+static std::string ToLower(const std::string& anycase) {
+ // copy string
+ std::string str(anycase);
+ // transform the copy
+ std::transform(str.begin(), str.end(), str.begin(), tolower);
+ return str;
+}
+
+extern "C" int main(int argc, char** argv);
+
+// Link with -municode to cause this wmain() to be used as the program
+// entrypoint. It will convert the args from UTF-16 to UTF-8 and call the
+// regular main() with UTF-8 args.
+extern "C" int wmain(int argc, wchar_t **argv) {
+ // Convert args from UTF-16 to UTF-8 and pass that to main().
+ NarrowArgs narrow_args(argc, argv);
+ return main(argc, narrow_args.data());
+}
+
// Shadow UTF-8 environment variable name/value pairs that are created from
// _wenviron the first time that adb_getenv() is called. Note that this is not
// currently updated if putenv, setenv, unsetenv are called. Note that no
@@ -3790,6 +3819,13 @@
return;
}
+ if (_wenviron == nullptr) {
+ // If _wenviron is null, then -municode probably wasn't used. That
+ // linker flag will cause the entry point to setup _wenviron. It will
+ // also require an implementation of wmain() (which we provide above).
+ fatal("_wenviron is not set, did you link with -municode?");
+ }
+
// Read name/value pairs from UTF-16 _wenviron and write new name/value
// pairs to UTF-8 g_environ_utf8. Note that it probably does not make sense
// to use the D() macro here because that tracing only works if the
@@ -3803,21 +3839,26 @@
continue;
}
- const std::string name_utf8(narrow(std::wstring(*env, equal - *env)));
+ // Store lowercase name so that we can do case-insensitive searches.
+ const std::string name_utf8(ToLower(narrow(
+ std::wstring(*env, equal - *env))));
char* const value_utf8 = strdup(narrow(equal + 1).c_str());
- // Overwrite any duplicate name, but there shouldn't be a dup in the
- // first place.
- g_environ_utf8[name_utf8] = value_utf8;
+ // Don't overwrite a previus env var with the same name. In reality,
+ // the system probably won't let two env vars with the same name exist
+ // in _wenviron.
+ g_environ_utf8.insert({name_utf8, value_utf8});
}
}
// Version of getenv() that takes a UTF-8 environment variable name and
-// retrieves a UTF-8 value.
+// retrieves a UTF-8 value. Case-insensitive to match getenv() on Windows.
char* adb_getenv(const char* name) {
_ensure_env_setup();
- const auto it = g_environ_utf8.find(std::string(name));
+ // Case-insensitive search by searching for lowercase name in a map of
+ // lowercase names.
+ const auto it = g_environ_utf8.find(ToLower(std::string(name)));
if (it == g_environ_utf8.end()) {
return nullptr;
}
diff --git a/adb/sysdeps_win32_test.cpp b/adb/sysdeps_win32_test.cpp
new file mode 100755
index 0000000..cc3ac5c
--- /dev/null
+++ b/adb/sysdeps_win32_test.cpp
@@ -0,0 +1,69 @@
+/*
+ * 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 <gtest/gtest.h>
+
+#include "sysdeps.h"
+
+TEST(sysdeps_win32, adb_getenv) {
+ // Insert all test env vars before first call to adb_getenv() which will
+ // read the env var block only once.
+ ASSERT_EQ(0, _putenv("SYSDEPS_WIN32_TEST_UPPERCASE=1"));
+ ASSERT_EQ(0, _putenv("sysdeps_win32_test_lowercase=2"));
+ ASSERT_EQ(0, _putenv("Sysdeps_Win32_Test_MixedCase=3"));
+
+ // UTF-16 value
+ ASSERT_EQ(0, _wputenv(L"SYSDEPS_WIN32_TEST_UNICODE=\u00a1\u0048\u006f\u006c"
+ L"\u0061\u0021\u03b1\u03b2\u03b3\u0061\u006d\u0062"
+ L"\u0075\u006c\u014d\u043f\u0440\u0438\u0432\u0435"
+ L"\u0442"));
+
+ // Search for non-existant env vars.
+ EXPECT_STREQ(nullptr, adb_getenv("SYSDEPS_WIN32_TEST_NONEXISTANT"));
+
+ // Search for existing env vars.
+
+ // There is no test for an env var with a value of a zero-length string
+ // because _putenv() does not support inserting such an env var.
+
+ // Search for env var that is uppercase.
+ EXPECT_STREQ("1", adb_getenv("SYSDEPS_WIN32_TEST_UPPERCASE"));
+ EXPECT_STREQ("1", adb_getenv("sysdeps_win32_test_uppercase"));
+ EXPECT_STREQ("1", adb_getenv("Sysdeps_Win32_Test_Uppercase"));
+
+ // Search for env var that is lowercase.
+ EXPECT_STREQ("2", adb_getenv("SYSDEPS_WIN32_TEST_LOWERCASE"));
+ EXPECT_STREQ("2", adb_getenv("sysdeps_win32_test_lowercase"));
+ EXPECT_STREQ("2", adb_getenv("Sysdeps_Win32_Test_Lowercase"));
+
+ // Search for env var that is mixed-case.
+ EXPECT_STREQ("3", adb_getenv("SYSDEPS_WIN32_TEST_MIXEDCASE"));
+ EXPECT_STREQ("3", adb_getenv("sysdeps_win32_test_mixedcase"));
+ EXPECT_STREQ("3", adb_getenv("Sysdeps_Win32_Test_MixedCase"));
+
+ // Check that UTF-16 was converted to UTF-8.
+ EXPECT_STREQ("\xc2\xa1\x48\x6f\x6c\x61\x21\xce\xb1\xce\xb2\xce\xb3\x61\x6d"
+ "\x62\x75\x6c\xc5\x8d\xd0\xbf\xd1\x80\xd0\xb8\xd0\xb2\xd0\xb5"
+ "\xd1\x82",
+ adb_getenv("SYSDEPS_WIN32_TEST_UNICODE"));
+
+ // Check an env var that should always be set.
+ const char* path_val = adb_getenv("PATH");
+ EXPECT_NE(nullptr, path_val);
+ if (path_val != nullptr) {
+ EXPECT_GT(strlen(path_val), 0);
+ }
+}
diff --git a/base/Android.mk b/base/Android.mk
index a09a747..613636b 100644
--- a/base/Android.mk
+++ b/base/Android.mk
@@ -79,6 +79,7 @@
LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)/include
LOCAL_STATIC_LIBRARIES := libcutils
LOCAL_MULTILIB := both
+LOCAL_MODULE_HOST_OS := darwin linux windows
include $(BUILD_HOST_SHARED_LIBRARY)
# Tests
@@ -97,6 +98,7 @@
include $(CLEAR_VARS)
LOCAL_MODULE := libbase_test
+LOCAL_MODULE_HOST_OS := darwin linux windows
LOCAL_SRC_FILES := $(libbase_test_src_files)
LOCAL_C_INCLUDES := $(LOCAL_PATH)
LOCAL_CPPFLAGS := $(libbase_cppflags)
diff --git a/base/parseint_test.cpp b/base/parseint_test.cpp
index 6a109f4..e19c6e3 100644
--- a/base/parseint_test.cpp
+++ b/base/parseint_test.cpp
@@ -20,49 +20,49 @@
TEST(parseint, signed_smoke) {
int i;
- ASSERT_EQ(false, android::base::ParseInt("x", &i));
- ASSERT_EQ(false, android::base::ParseInt("123x", &i));
+ ASSERT_FALSE(android::base::ParseInt("x", &i));
+ ASSERT_FALSE(android::base::ParseInt("123x", &i));
- ASSERT_EQ(true, android::base::ParseInt("123", &i));
+ ASSERT_TRUE(android::base::ParseInt("123", &i));
ASSERT_EQ(123, i);
- ASSERT_EQ(true, android::base::ParseInt("-123", &i));
+ ASSERT_TRUE(android::base::ParseInt("-123", &i));
ASSERT_EQ(-123, i);
short s;
- ASSERT_EQ(true, android::base::ParseInt("1234", &s));
+ ASSERT_TRUE(android::base::ParseInt("1234", &s));
ASSERT_EQ(1234, s);
- ASSERT_EQ(true, android::base::ParseInt("12", &i, 0, 15));
+ ASSERT_TRUE(android::base::ParseInt("12", &i, 0, 15));
ASSERT_EQ(12, i);
- ASSERT_EQ(false, android::base::ParseInt("-12", &i, 0, 15));
- ASSERT_EQ(false, android::base::ParseInt("16", &i, 0, 15));
+ ASSERT_FALSE(android::base::ParseInt("-12", &i, 0, 15));
+ ASSERT_FALSE(android::base::ParseInt("16", &i, 0, 15));
}
TEST(parseint, unsigned_smoke) {
unsigned int i;
- ASSERT_EQ(false, android::base::ParseUint("x", &i));
- ASSERT_EQ(false, android::base::ParseUint("123x", &i));
+ ASSERT_FALSE(android::base::ParseUint("x", &i));
+ ASSERT_FALSE(android::base::ParseUint("123x", &i));
- ASSERT_EQ(true, android::base::ParseUint("123", &i));
+ ASSERT_TRUE(android::base::ParseUint("123", &i));
ASSERT_EQ(123u, i);
- ASSERT_EQ(false, android::base::ParseUint("-123", &i));
+ ASSERT_FALSE(android::base::ParseUint("-123", &i));
unsigned short s;
- ASSERT_EQ(true, android::base::ParseUint("1234", &s));
+ ASSERT_TRUE(android::base::ParseUint("1234", &s));
ASSERT_EQ(1234u, s);
- ASSERT_EQ(true, android::base::ParseUint("12", &i, 15u));
+ ASSERT_TRUE(android::base::ParseUint("12", &i, 15u));
ASSERT_EQ(12u, i);
- ASSERT_EQ(false, android::base::ParseUint("-12", &i, 15u));
- ASSERT_EQ(false, android::base::ParseUint("16", &i, 15u));
+ ASSERT_FALSE(android::base::ParseUint("-12", &i, 15u));
+ ASSERT_FALSE(android::base::ParseUint("16", &i, 15u));
}
TEST(parseint, no_implicit_octal) {
int i;
- ASSERT_EQ(true, android::base::ParseInt("0123", &i));
+ ASSERT_TRUE(android::base::ParseInt("0123", &i));
ASSERT_EQ(123, i);
unsigned int u;
- ASSERT_EQ(true, android::base::ParseUint("0123", &u));
+ ASSERT_TRUE(android::base::ParseUint("0123", &u));
ASSERT_EQ(123u, u);
}
diff --git a/fs_mgr/fs_mgr_slotselect.c b/fs_mgr/fs_mgr_slotselect.c
index 99dcd0e..ca07b18 100644
--- a/fs_mgr/fs_mgr_slotselect.c
+++ b/fs_mgr/fs_mgr_slotselect.c
@@ -78,10 +78,11 @@
return 0;
}
-// Gets slot_suffix from either the kernel cmdline / firmware, the
-// misc partition or built-in fallback.
-static void get_active_slot_suffix(struct fstab *fstab, char *out_suffix,
- size_t suffix_len)
+// Gets slot_suffix from either the kernel cmdline / firmware or the
+// misc partition. Sets |out_suffix| on success and returns 0. Returns
+// -1 if slot_suffix could not be determined.
+static int get_active_slot_suffix(struct fstab *fstab, char *out_suffix,
+ size_t suffix_len)
{
char propbuf[PROPERTY_VALUE_MAX];
@@ -91,30 +92,19 @@
property_get("ro.boot.slot_suffix", propbuf, "");
if (propbuf[0] != '\0') {
strncpy(out_suffix, propbuf, suffix_len);
- return;
+ return 0;
}
// If we couldn't get the suffix from the kernel cmdline, try the
// the misc partition.
if (get_active_slot_suffix_from_misc(fstab, out_suffix, suffix_len) == 0) {
INFO("Using slot suffix \"%s\" from misc\n", out_suffix);
- return;
+ return 0;
}
- // If that didn't work, fall back to _a. The reasoning here is
- // that since the fstab has the slotselect option set (otherwise
- // we wouldn't end up here) we must assume that partitions are
- // indeed set up for A/B. This corner-case is important because we
- // may be on this codepath on newly provisioned A/B devices where
- // misc isn't set up properly (it's just zeroes) and the
- // bootloader does not (yet) natively support A/B.
- //
- // Why '_a'? Because that's what system/extras/boot_control_copy
- // is using and since the bootloader isn't A/B aware we assume
- // slots are set up this way.
- WARNING("Could not determine slot suffix, falling back to \"_a\"\n");
- strncpy(out_suffix, "_a", suffix_len);
- return;
+ ERROR("Error determining slot_suffix\n");
+
+ return -1;
}
// Updates |fstab| for slot_suffix. Returns 0 on success, -1 on error.
@@ -130,7 +120,10 @@
if (!got_suffix) {
memset(suffix, '\0', sizeof(suffix));
- get_active_slot_suffix(fstab, suffix, sizeof(suffix) - 1);
+ if (get_active_slot_suffix(fstab, suffix,
+ sizeof(suffix) - 1) != 0) {
+ return -1;
+ }
got_suffix = 1;
}
diff --git a/include/binderwrapper/binder_test_base.h b/include/binderwrapper/binder_test_base.h
new file mode 100644
index 0000000..06543de
--- /dev/null
+++ b/include/binderwrapper/binder_test_base.h
@@ -0,0 +1,45 @@
+/*
+ * 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 SYSTEM_CORE_INCLUDE_BINDERWRAPPER_BINDER_TEST_BASE_H_
+#define SYSTEM_CORE_INCLUDE_BINDERWRAPPER_BINDER_TEST_BASE_H_
+
+#include <base/macros.h>
+#include <gtest/gtest.h>
+
+namespace android {
+
+class StubBinderWrapper;
+
+// Class that can be inherited from (or aliased via typedef/using) when writing
+// tests that use StubBinderManager.
+class BinderTestBase : public ::testing::Test {
+ public:
+ BinderTestBase();
+ ~BinderTestBase() override;
+
+ StubBinderWrapper* binder_wrapper() { return binder_wrapper_; }
+
+ protected:
+ StubBinderWrapper* binder_wrapper_; // Not owned.
+
+ private:
+ DISALLOW_COPY_AND_ASSIGN(BinderTestBase);
+};
+
+} // namespace android
+
+#endif // SYSTEM_CORE_INCLUDE_BINDERWRAPPER_BINDER_TEST_BASE_H_
diff --git a/include/binderwrapper/binder_wrapper.h b/include/binderwrapper/binder_wrapper.h
new file mode 100644
index 0000000..e57cf83
--- /dev/null
+++ b/include/binderwrapper/binder_wrapper.h
@@ -0,0 +1,77 @@
+/*
+ * 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 SYSTEM_CORE_INCLUDE_BINDERWRAPPER_BINDER_WRAPPER_H_
+#define SYSTEM_CORE_INCLUDE_BINDERWRAPPER_BINDER_WRAPPER_H_
+
+#include <string>
+
+#include <base/callback.h>
+#include <utils/StrongPointer.h>
+
+namespace android {
+
+class BBinder;
+class IBinder;
+
+// Wraps libbinder to make it testable.
+class BinderWrapper {
+ public:
+ virtual ~BinderWrapper() {}
+
+ // Creates and initializes the singleton (using a wrapper that communicates
+ // with the real binder system).
+ static void Create();
+
+ // Initializes |wrapper| as the singleton, taking ownership of it. Tests that
+ // want to inject their own wrappers should call this instead of Create().
+ static void InitForTesting(BinderWrapper* wrapper);
+
+ // Destroys the singleton. Must be called before calling Create() or
+ // InitForTesting() a second time.
+ static void Destroy();
+
+ // Returns the singleton instance previously created by Create() or set by
+ // InitForTesting().
+ static BinderWrapper* Get();
+
+ // Gets the binder for communicating with the service identified by
+ // |service_name|, returning null immediately if it doesn't exist.
+ virtual sp<IBinder> GetService(const std::string& service_name) = 0;
+
+ // Registers |binder| as |service_name| with the service manager.
+ virtual bool RegisterService(const std::string& service_name,
+ const sp<IBinder>& binder) = 0;
+
+ // Creates a local binder object.
+ virtual sp<BBinder> CreateLocalBinder() = 0;
+
+ // Registers |callback| to be invoked when |binder| dies. If another callback
+ // is currently registered for |binder|, it will be replaced.
+ virtual bool RegisterForDeathNotifications(
+ const sp<IBinder>& binder,
+ const base::Closure& callback) = 0;
+
+ // Unregisters the callback, if any, for |binder|.
+ virtual bool UnregisterForDeathNotifications(const sp<IBinder>& binder) = 0;
+
+ private:
+ static BinderWrapper* instance_;
+};
+
+} // namespace android
+
+#endif // SYSTEM_CORE_INCLUDE_BINDERWRAPPER_BINDER_WRAPPER_H_
diff --git a/include/binderwrapper/stub_binder_wrapper.h b/include/binderwrapper/stub_binder_wrapper.h
new file mode 100644
index 0000000..6e198ae
--- /dev/null
+++ b/include/binderwrapper/stub_binder_wrapper.h
@@ -0,0 +1,124 @@
+/*
+ * 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 SYSTEM_CORE_INCLUDE_BINDERWRAPPER_STUB_BINDER_WRAPPER_H_
+#define SYSTEM_CORE_INCLUDE_BINDERWRAPPER_STUB_BINDER_WRAPPER_H_
+
+#include <map>
+#include <string>
+#include <vector>
+
+#include <base/macros.h>
+#include <binder/Binder.h>
+#include <binder/IBinder.h>
+#include <binderwrapper/binder_wrapper.h>
+
+namespace android {
+
+// Stub implementation of BinderWrapper for testing.
+//
+// Example usage:
+//
+// First, assuming a base IFoo binder interface, create a stub class that
+// derives from BnFoo to implement the receiver side of the communication:
+//
+// class StubFoo : public BnFoo {
+// public:
+// ...
+// status_t doSomething(int arg) override {
+// // e.g. save passed-in value for later inspection by tests.
+// return OK;
+// }
+// };
+//
+// Next, from your test code, inject a StubBinderManager either directly or by
+// inheriting from the BinderTestBase class:
+//
+// StubBinderWrapper* wrapper = new StubBinderWrapper();
+// BinderWrapper::InitForTesting(wrapper); // Takes ownership.
+//
+// Also from your test, create a StubFoo and register it with the wrapper:
+//
+// StubFoo* foo = new StubFoo();
+// sp<IBinder> binder(foo);
+// wrapper->SetBinderForService("foo", binder);
+//
+// The code being tested can now use the wrapper to get the stub and call it:
+//
+// sp<IBinder> binder = BinderWrapper::Get()->GetService("foo");
+// CHECK(binder.get());
+// sp<IFoo> foo = interface_cast<IFoo>(binder);
+// CHECK_EQ(foo->doSomething(3), OK);
+//
+// To create a local BBinder object, production code can call
+// CreateLocalBinder(). Then, a test can get the BBinder's address via
+// local_binders() to check that they're passed as expected in binder calls.
+//
+class StubBinderWrapper : public BinderWrapper {
+ public:
+ StubBinderWrapper();
+ ~StubBinderWrapper() override;
+
+ const std::vector<sp<BBinder>>& local_binders() const {
+ return local_binders_;
+ }
+ void clear_local_binders() { local_binders_.clear(); }
+
+ // Sets the binder to return when |service_name| is passed to GetService() or
+ // WaitForService().
+ void SetBinderForService(const std::string& service_name,
+ const sp<IBinder>& binder);
+
+ // Returns the binder previously registered for |service_name| via
+ // RegisterService(), or null if the service hasn't been registered.
+ sp<IBinder> GetRegisteredService(const std::string& service_name) const;
+
+ // Run the calback in |death_callbacks_| corresponding to |binder|.
+ void NotifyAboutBinderDeath(const sp<IBinder>& binder);
+
+ // BinderWrapper:
+ sp<IBinder> GetService(const std::string& service_name) override;
+ bool RegisterService(const std::string& service_name,
+ const sp<IBinder>& binder) override;
+ sp<BBinder> CreateLocalBinder() override;
+ bool RegisterForDeathNotifications(const sp<IBinder>& binder,
+ const base::Closure& callback) override;
+ bool UnregisterForDeathNotifications(const sp<IBinder>& binder) override;
+
+ private:
+ using ServiceMap = std::map<std::string, sp<IBinder>>;
+
+ // Map from service name to associated binder handle. Used by GetService() and
+ // WaitForService().
+ ServiceMap services_to_return_;
+
+ // Map from service name to associated binder handle. Updated by
+ // RegisterService().
+ ServiceMap registered_services_;
+
+ // Local binders returned by CreateLocalBinder().
+ std::vector<sp<BBinder>> local_binders_;
+
+ // Map from binder handle to the callback that should be invoked on binder
+ // death.
+ std::map<sp<IBinder>, base::Closure> death_callbacks_;
+
+ DISALLOW_COPY_AND_ASSIGN(StubBinderWrapper);
+};
+
+} // namespace android
+
+#endif // SYSTEM_CORE_INCLUDE_BINDERWRAPPER_STUB_BINDER_WRAPPER_H_
diff --git a/libbinderwrapper/Android.mk b/libbinderwrapper/Android.mk
new file mode 100644
index 0000000..23c2246
--- /dev/null
+++ b/libbinderwrapper/Android.mk
@@ -0,0 +1,62 @@
+#
+# 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)
+
+binderwrapperCommonCFlags := -Wall -Werror -Wno-unused-parameter
+binderwrapperCommonCFlags += -Wno-sign-promo # for libchrome
+binderwrapperCommonExportCIncludeDirs := $(LOCAL_PATH)/../include
+binderwrapperCommonCIncludes := $(LOCAL_PATH)/../include
+binderwrapperCommonSharedLibraries := \
+ libbinder \
+ libchrome \
+ libutils \
+
+# libbinderwrapper shared library
+# ========================================================
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := libbinderwrapper
+LOCAL_CPP_EXTENSION := .cc
+LOCAL_CFLAGS := $(binderwrapperCommonCFlags)
+LOCAL_EXPORT_C_INCLUDE_DIRS := $(binderwrapperCommonExportCIncludeDirs)
+LOCAL_C_INCLUDES := $(binderwrapperCommonCIncludes)
+LOCAL_SHARED_LIBRARIES := $(binderwrapperCommonSharedLibraries)
+LOCAL_SRC_FILES := \
+ binder_wrapper.cc \
+ real_binder_wrapper.cc \
+
+include $(BUILD_SHARED_LIBRARY)
+
+# libbinderwrapper_test_support shared library
+# ========================================================
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := libbinderwrapper_test_support
+LOCAL_CPP_EXTENSION := .cc
+LOCAL_CFLAGS := $(binderwrapperCommonCFlags)
+LOCAL_EXPORT_C_INCLUDE_DIRS := $(binderwrapperCommonExportCIncludeDirs)
+LOCAL_C_INCLUDES := $(binderwrapperCommonCIncludes)
+LOCAL_STATIC_LIBRARIES := libgtest
+LOCAL_SHARED_LIBRARIES := \
+ $(binderwrapperCommonSharedLibraries) \
+ libbinderwrapper \
+
+LOCAL_SRC_FILES := \
+ binder_test_base.cc \
+ stub_binder_wrapper.cc \
+
+include $(BUILD_SHARED_LIBRARY)
diff --git a/libbinderwrapper/binder_test_base.cc b/libbinderwrapper/binder_test_base.cc
new file mode 100644
index 0000000..af93a04
--- /dev/null
+++ b/libbinderwrapper/binder_test_base.cc
@@ -0,0 +1,33 @@
+/*
+ * 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 <binderwrapper/binder_test_base.h>
+
+#include <binderwrapper/binder_wrapper.h>
+#include <binderwrapper/stub_binder_wrapper.h>
+
+namespace android {
+
+BinderTestBase::BinderTestBase() : binder_wrapper_(new StubBinderWrapper()) {
+ // Pass ownership.
+ BinderWrapper::InitForTesting(binder_wrapper_);
+}
+
+BinderTestBase::~BinderTestBase() {
+ BinderWrapper::Destroy();
+}
+
+} // namespace android
diff --git a/libbinderwrapper/binder_wrapper.cc b/libbinderwrapper/binder_wrapper.cc
new file mode 100644
index 0000000..0b5ff96
--- /dev/null
+++ b/libbinderwrapper/binder_wrapper.cc
@@ -0,0 +1,53 @@
+/*
+ * 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 <binderwrapper/binder_wrapper.h>
+
+#include <base/logging.h>
+
+#include "real_binder_wrapper.h"
+
+namespace android {
+
+// Singleton instance.
+BinderWrapper* BinderWrapper::instance_ = nullptr;
+
+// static
+void BinderWrapper::Create() {
+ CHECK(!instance_) << "Already initialized; missing call to Destroy()?";
+ instance_ = new RealBinderWrapper();
+}
+
+// static
+void BinderWrapper::InitForTesting(BinderWrapper* wrapper) {
+ CHECK(!instance_) << "Already initialized; missing call to Destroy()?";
+ instance_ = wrapper;
+}
+
+// static
+void BinderWrapper::Destroy() {
+ CHECK(instance_) << "Not initialized; missing call to Create()?";
+ delete instance_;
+ instance_ = nullptr;
+}
+
+// static
+BinderWrapper* BinderWrapper::Get() {
+ CHECK(instance_) << "Not initialized; missing call to Create()?";
+ return instance_;
+}
+
+} // namespace android
diff --git a/libbinderwrapper/real_binder_wrapper.cc b/libbinderwrapper/real_binder_wrapper.cc
new file mode 100644
index 0000000..adff19b
--- /dev/null
+++ b/libbinderwrapper/real_binder_wrapper.cc
@@ -0,0 +1,114 @@
+/*
+ * 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 "real_binder_wrapper.h"
+
+#include <base/logging.h>
+#include <binder/Binder.h>
+#include <binder/IBinder.h>
+#include <binder/IServiceManager.h>
+
+namespace android {
+
+// Class that handles binder death notifications. libbinder wants the recipient
+// to be wrapped in sp<>, so registering RealBinderWrapper as a recipient would
+// be awkward.
+class RealBinderWrapper::DeathRecipient : public IBinder::DeathRecipient {
+ public:
+ explicit DeathRecipient(const base::Closure& callback)
+ : callback_(callback) {}
+ ~DeathRecipient() = default;
+
+ // IBinder::DeathRecipient:
+ void binderDied(const wp<IBinder>& who) override {
+ callback_.Run();
+ }
+
+ private:
+ // Callback to run in response to binder death.
+ base::Closure callback_;
+
+ DISALLOW_COPY_AND_ASSIGN(DeathRecipient);
+};
+
+RealBinderWrapper::RealBinderWrapper() = default;
+
+RealBinderWrapper::~RealBinderWrapper() = default;
+
+sp<IBinder> RealBinderWrapper::GetService(const std::string& service_name) {
+ sp<IServiceManager> service_manager = defaultServiceManager();
+ if (!service_manager.get()) {
+ LOG(ERROR) << "Unable to get service manager";
+ return sp<IBinder>();
+ }
+ sp<IBinder> binder =
+ service_manager->checkService(String16(service_name.c_str()));
+ if (!binder.get())
+ LOG(ERROR) << "Unable to get \"" << service_name << "\" service";
+ return binder;
+}
+
+bool RealBinderWrapper::RegisterService(const std::string& service_name,
+ const sp<IBinder>& binder) {
+ sp<IServiceManager> service_manager = defaultServiceManager();
+ if (!service_manager.get()) {
+ LOG(ERROR) << "Unable to get service manager";
+ return false;
+ }
+ status_t status = defaultServiceManager()->addService(
+ String16(service_name.c_str()), binder);
+ if (status != OK) {
+ LOG(ERROR) << "Failed to register \"" << service_name << "\" with service "
+ << "manager";
+ return false;
+ }
+ return true;
+}
+
+sp<BBinder> RealBinderWrapper::CreateLocalBinder() {
+ return sp<BBinder>(new BBinder());
+}
+
+bool RealBinderWrapper::RegisterForDeathNotifications(
+ const sp<IBinder>& binder,
+ const base::Closure& callback) {
+ sp<DeathRecipient> recipient(new DeathRecipient(callback));
+ if (binder->linkToDeath(recipient) != OK) {
+ LOG(ERROR) << "Failed to register for death notifications on "
+ << binder.get();
+ return false;
+ }
+ death_recipients_[binder] = recipient;
+ return true;
+}
+
+bool RealBinderWrapper::UnregisterForDeathNotifications(
+ const sp<IBinder>& binder) {
+ auto it = death_recipients_.find(binder);
+ if (it == death_recipients_.end()) {
+ LOG(ERROR) << "Not registered for death notifications on " << binder.get();
+ return false;
+ }
+ if (binder->unlinkToDeath(it->second) != OK) {
+ LOG(ERROR) << "Failed to unregister for death notifications on "
+ << binder.get();
+ return false;
+ }
+ death_recipients_.erase(it);
+ return true;
+}
+
+} // namespace android
diff --git a/libbinderwrapper/real_binder_wrapper.h b/libbinderwrapper/real_binder_wrapper.h
new file mode 100644
index 0000000..8e281f2
--- /dev/null
+++ b/libbinderwrapper/real_binder_wrapper.h
@@ -0,0 +1,54 @@
+/*
+ * 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 SYSTEM_CORE_LIBBINDERWRAPPER_REAL_BINDER_WRAPPER_H_
+#define SYSTEM_CORE_LIBBINDERWRAPPER_REAL_BINDER_WRAPPER_H_
+
+#include <base/macros.h>
+#include <binderwrapper/binder_wrapper.h>
+
+namespace android {
+
+class IBinder;
+
+// Real implementation of BinderWrapper.
+class RealBinderWrapper : public BinderWrapper {
+ public:
+ RealBinderWrapper();
+ ~RealBinderWrapper() override;
+
+ // BinderWrapper:
+ sp<IBinder> GetService(const std::string& service_name) override;
+ bool RegisterService(const std::string& service_name,
+ const sp<IBinder>& binder) override;
+ sp<BBinder> CreateLocalBinder() override;
+ bool RegisterForDeathNotifications(const sp<IBinder>& binder,
+ const base::Closure& callback) override;
+ bool UnregisterForDeathNotifications(const sp<IBinder>& binder) override;
+
+ private:
+ class DeathRecipient;
+
+ // Map from binder handle to object that should be notified of the binder's
+ // death.
+ std::map<sp<IBinder>, sp<DeathRecipient>> death_recipients_;
+
+ DISALLOW_COPY_AND_ASSIGN(RealBinderWrapper);
+};
+
+} // namespace android
+
+#endif // SYSTEM_CORE_LIBBINDER_WRAPPER_REAL_BINDER_WRAPPER_H_
diff --git a/libbinderwrapper/stub_binder_wrapper.cc b/libbinderwrapper/stub_binder_wrapper.cc
new file mode 100644
index 0000000..1d24681
--- /dev/null
+++ b/libbinderwrapper/stub_binder_wrapper.cc
@@ -0,0 +1,76 @@
+/*
+ * 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 <binderwrapper/stub_binder_wrapper.h>
+
+#include <base/logging.h>
+#include <binder/Binder.h>
+#include <binder/IBinder.h>
+
+namespace android {
+
+StubBinderWrapper::StubBinderWrapper() = default;
+
+StubBinderWrapper::~StubBinderWrapper() = default;
+
+void StubBinderWrapper::SetBinderForService(const std::string& service_name,
+ const sp<IBinder>& binder) {
+ services_to_return_[service_name] = binder;
+}
+
+sp<IBinder> StubBinderWrapper::GetRegisteredService(
+ const std::string& service_name) const {
+ const auto it = registered_services_.find(service_name);
+ return it != registered_services_.end() ? it->second : sp<IBinder>();
+}
+
+void StubBinderWrapper::NotifyAboutBinderDeath(const sp<IBinder>& binder) {
+ const auto it = death_callbacks_.find(binder);
+ if (it != death_callbacks_.end())
+ it->second.Run();
+}
+
+sp<IBinder> StubBinderWrapper::GetService(const std::string& service_name) {
+ const auto it = services_to_return_.find(service_name);
+ return it != services_to_return_.end() ? it->second : sp<IBinder>();
+}
+
+bool StubBinderWrapper::RegisterService(const std::string& service_name,
+ const sp<IBinder>& binder) {
+ registered_services_[service_name] = binder;
+ return true;
+}
+
+sp<BBinder> StubBinderWrapper::CreateLocalBinder() {
+ sp<BBinder> binder(new BBinder());
+ local_binders_.push_back(binder);
+ return binder;
+}
+
+bool StubBinderWrapper::RegisterForDeathNotifications(
+ const sp<IBinder>& binder,
+ const base::Closure& callback) {
+ death_callbacks_[binder] = callback;
+ return true;
+}
+
+bool StubBinderWrapper::UnregisterForDeathNotifications(
+ const sp<IBinder>& binder) {
+ death_callbacks_.erase(binder);
+ return true;
+}
+
+} // namespace android
diff --git a/liblog/Android.mk b/liblog/Android.mk
index 3a1a9db..271c6f9 100644
--- a/liblog/Android.mk
+++ b/liblog/Android.mk
@@ -50,6 +50,7 @@
LOCAL_LDLIBS_linux := -lrt
LOCAL_MULTILIB := both
LOCAL_CXX_STL := none
+LOCAL_MODULE_HOST_OS := darwin linux windows
include $(BUILD_HOST_SHARED_LIBRARY)
diff --git a/toolbox/Android.mk b/toolbox/Android.mk
index 1d3605e..579d26e 100644
--- a/toolbox/Android.mk
+++ b/toolbox/Android.mk
@@ -24,18 +24,11 @@
LOCAL_MODULE := libtoolbox_dd
include $(BUILD_STATIC_LIBRARY)
-include $(CLEAR_VARS)
-LOCAL_SRC_FILES := upstream-netbsd/usr.bin/du/du.c
-LOCAL_CFLAGS += $(common_cflags) -Dmain=du_main
-LOCAL_MODULE := libtoolbox_du
-include $(BUILD_STATIC_LIBRARY)
-
include $(CLEAR_VARS)
BSD_TOOLS := \
dd \
- du \
OUR_TOOLS := \
df \
@@ -43,7 +36,6 @@
iftop \
ioctl \
log \
- lsof \
nandread \
newfs_msdos \
ps \
diff --git a/toolbox/lsof.c b/toolbox/lsof.c
deleted file mode 100644
index 198ca52..0000000
--- a/toolbox/lsof.c
+++ /dev/null
@@ -1,296 +0,0 @@
-/*
- * Copyright (c) 2010, The Android Open Source Project
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in
- * the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google, Inc. nor the names of its contributors
- * may be used to endorse or promote products derived from this
- * software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
- * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
- * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
- * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
- * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
- * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- */
-
-#include <ctype.h>
-#include <dirent.h>
-#include <errno.h>
-#include <fcntl.h>
-#include <libgen.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <unistd.h>
-
-#include <pwd.h>
-#include <sys/stat.h>
-
-#define BUF_MAX 1024
-#define CMD_DISPLAY_MAX (9 + 1)
-#define USER_DISPLAY_MAX (10 + 1)
-
-struct pid_info_t {
- pid_t pid;
- char user[USER_DISPLAY_MAX];
-
- char cmdline[CMD_DISPLAY_MAX];
-
- char path[PATH_MAX];
- ssize_t parent_length;
-};
-
-static void print_header()
-{
- printf("%-9s %5s %10s %4s %9s %18s %9s %10s %s\n",
- "COMMAND",
- "PID",
- "USER",
- "FD",
- "TYPE",
- "DEVICE",
- "SIZE/OFF",
- "NODE",
- "NAME");
-}
-
-static void print_symlink(const char* name, const char* path, struct pid_info_t* info)
-{
- static ssize_t link_dest_size;
- static char link_dest[PATH_MAX];
-
- strlcat(info->path, path, sizeof(info->path));
- if ((link_dest_size = readlink(info->path, link_dest, sizeof(link_dest)-1)) < 0) {
- if (errno == ENOENT)
- goto out;
-
- snprintf(link_dest, sizeof(link_dest), "%s (readlink: %s)", info->path, strerror(errno));
- } else {
- link_dest[link_dest_size] = '\0';
- }
-
- // Things that are just the root filesystem are uninteresting (we already know)
- if (!strcmp(link_dest, "/"))
- goto out;
-
- const char* fd = name;
- char rw = ' ';
- char locks = ' '; // TODO: read /proc/locks
-
- const char* type = "unknown";
- char device[32] = "?";
- char size_off[32] = "?";
- char node[32] = "?";
-
- struct stat sb;
- if (lstat(link_dest, &sb) != -1) {
- switch ((sb.st_mode & S_IFMT)) {
- case S_IFSOCK: type = "sock"; break; // TODO: what domain?
- case S_IFLNK: type = "LINK"; break;
- case S_IFREG: type = "REG"; break;
- case S_IFBLK: type = "BLK"; break;
- case S_IFDIR: type = "DIR"; break;
- case S_IFCHR: type = "CHR"; break;
- case S_IFIFO: type = "FIFO"; break;
- }
- snprintf(device, sizeof(device), "%d,%d", (int) sb.st_dev, (int) sb.st_rdev);
- snprintf(node, sizeof(node), "%d", (int) sb.st_ino);
- snprintf(size_off, sizeof(size_off), "%d", (int) sb.st_size);
- }
-
- if (!name) {
- // We're looking at an fd, so read its flags.
- fd = path;
- char fdinfo_path[PATH_MAX];
- snprintf(fdinfo_path, sizeof(fdinfo_path), "/proc/%d/fdinfo/%s", info->pid, path);
- FILE* fp = fopen(fdinfo_path, "r");
- if (fp != NULL) {
- int pos;
- unsigned flags;
-
- if (fscanf(fp, "pos: %d flags: %o", &pos, &flags) == 2) {
- flags &= O_ACCMODE;
- if (flags == O_RDONLY) rw = 'r';
- else if (flags == O_WRONLY) rw = 'w';
- else rw = 'u';
- }
- fclose(fp);
- }
- }
-
- printf("%-9s %5d %10s %4s%c%c %9s %18s %9s %10s %s\n",
- info->cmdline, info->pid, info->user, fd, rw, locks, type, device, size_off, node, link_dest);
-
-out:
- info->path[info->parent_length] = '\0';
-}
-
-// Prints out all file that have been memory mapped
-static void print_maps(struct pid_info_t* info)
-{
- FILE *maps;
- size_t offset;
- char device[10];
- long int inode;
- char file[PATH_MAX];
-
- strlcat(info->path, "maps", sizeof(info->path));
-
- maps = fopen(info->path, "r");
- if (!maps)
- goto out;
-
- while (fscanf(maps, "%*x-%*x %*s %zx %s %ld %s\n", &offset, device, &inode, file) == 4) {
- // We don't care about non-file maps
- if (inode == 0 || !strcmp(device, "00:00"))
- continue;
-
- printf("%-9s %5d %10s %4s %9s %18s %9zd %10ld %s\n",
- info->cmdline, info->pid, info->user, "mem",
- "REG", device, offset, inode, file);
- }
-
- fclose(maps);
-
-out:
- info->path[info->parent_length] = '\0';
-}
-
-// Prints out all open file descriptors
-static void print_fds(struct pid_info_t* info)
-{
- static char* fd_path = "fd/";
- strlcat(info->path, fd_path, sizeof(info->path));
-
- int previous_length = info->parent_length;
- info->parent_length += strlen(fd_path);
-
- DIR *dir = opendir(info->path);
- if (dir == NULL) {
- char msg[BUF_MAX];
- snprintf(msg, sizeof(msg), "%s (opendir: %s)", info->path, strerror(errno));
- printf("%-9s %5d %10s %4s %9s %18s %9s %10s %s\n",
- info->cmdline, info->pid, info->user, "FDS",
- "", "", "", "", msg);
- goto out;
- }
-
- struct dirent* de;
- while ((de = readdir(dir))) {
- if (!strcmp(de->d_name, ".") || !strcmp(de->d_name, ".."))
- continue;
-
- print_symlink(NULL, de->d_name, info);
- }
- closedir(dir);
-
-out:
- info->parent_length = previous_length;
- info->path[info->parent_length] = '\0';
-}
-
-static void lsof_dumpinfo(pid_t pid)
-{
- int fd;
- struct pid_info_t info;
- struct stat pidstat;
- struct passwd *pw;
-
- info.pid = pid;
- snprintf(info.path, sizeof(info.path), "/proc/%d/", pid);
- info.parent_length = strlen(info.path);
-
- // Get the UID by calling stat on the proc/pid directory.
- if (!stat(info.path, &pidstat)) {
- pw = getpwuid(pidstat.st_uid);
- if (pw) {
- strlcpy(info.user, pw->pw_name, sizeof(info.user));
- } else {
- snprintf(info.user, USER_DISPLAY_MAX, "%d", (int)pidstat.st_uid);
- }
- } else {
- strcpy(info.user, "???");
- }
-
- // Read the command line information; each argument is terminated with NULL.
- strlcat(info.path, "cmdline", sizeof(info.path));
- fd = open(info.path, O_RDONLY);
- if (fd < 0) {
- fprintf(stderr, "Couldn't read %s\n", info.path);
- return;
- }
-
- char cmdline[PATH_MAX];
- int numRead = read(fd, cmdline, sizeof(cmdline) - 1);
- close(fd);
-
- if (numRead < 0) {
- fprintf(stderr, "Error reading cmdline: %s: %s\n", info.path, strerror(errno));
- return;
- }
-
- cmdline[numRead] = '\0';
-
- // We only want the basename of the cmdline
- strlcpy(info.cmdline, basename(cmdline), sizeof(info.cmdline));
-
- // Read each of these symlinks
- print_symlink("cwd", "cwd", &info);
- print_symlink("txt", "exe", &info);
- print_symlink("rtd", "root", &info);
- print_fds(&info);
- print_maps(&info);
-}
-
-int lsof_main(int argc, char *argv[])
-{
- long int pid = 0;
- char* endptr;
- if (argc == 2) {
- pid = strtol(argv[1], &endptr, 10);
- }
-
- print_header();
-
- if (pid) {
- lsof_dumpinfo(pid);
- } else {
- DIR *dir = opendir("/proc");
- if (dir == NULL) {
- fprintf(stderr, "Couldn't open /proc\n");
- return -1;
- }
-
- struct dirent* de;
- while ((de = readdir(dir))) {
- if (!strcmp(de->d_name, ".") || !strcmp(de->d_name, ".."))
- continue;
-
- // Only inspect directories that are PID numbers
- pid = strtol(de->d_name, &endptr, 10);
- if (*endptr != '\0')
- continue;
-
- lsof_dumpinfo(pid);
- }
- closedir(dir);
- }
-
- return 0;
-}
diff --git a/toolbox/upstream-netbsd/usr.bin/du/du.c b/toolbox/upstream-netbsd/usr.bin/du/du.c
deleted file mode 100644
index 086ac4a..0000000
--- a/toolbox/upstream-netbsd/usr.bin/du/du.c
+++ /dev/null
@@ -1,364 +0,0 @@
-/* $NetBSD: du.c,v 1.36 2012/03/11 11:23:20 shattered Exp $ */
-
-/*
- * Copyright (c) 1989, 1993, 1994
- * The Regents of the University of California. All rights reserved.
- *
- * This code is derived from software contributed to Berkeley by
- * Chris Newcomb.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of the University nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- */
-
-#include <sys/cdefs.h>
-#ifndef lint
-__COPYRIGHT("@(#) Copyright (c) 1989, 1993, 1994\
- The Regents of the University of California. All rights reserved.");
-#endif /* not lint */
-
-#ifndef lint
-#if 0
-static char sccsid[] = "@(#)du.c 8.5 (Berkeley) 5/4/95";
-#else
-__RCSID("$NetBSD: du.c,v 1.36 2012/03/11 11:23:20 shattered Exp $");
-#endif
-#endif /* not lint */
-
-#include <sys/param.h>
-#include <sys/types.h>
-#include <sys/stat.h>
-
-#include <dirent.h>
-#include <err.h>
-#include <errno.h>
-#include <fts.h>
-#include <inttypes.h>
-#include <util.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <unistd.h>
-#include <limits.h>
-
-/* Count inodes or file size */
-#define COUNT (iflag ? 1 : p->fts_statp->st_blocks)
-
-static int linkchk(dev_t, ino_t);
-static void prstat(const char *, int64_t);
-__dead static void usage(void);
-
-static int hflag, iflag;
-static long blocksize;
-
-int
-main(int argc, char *argv[])
-{
- FTS *fts;
- FTSENT *p;
- int64_t totalblocks;
- int ftsoptions, listfiles;
- int depth;
- int Hflag, Lflag, aflag, ch, cflag, dflag, gkmflag, nflag, rval, sflag;
- const char *noargv[2];
-
- Hflag = Lflag = aflag = cflag = dflag = gkmflag = nflag = sflag = 0;
- totalblocks = 0;
- ftsoptions = FTS_PHYSICAL;
- depth = INT_MAX;
- while ((ch = getopt(argc, argv, "HLPacd:ghikmnrsx")) != -1)
- switch (ch) {
- case 'H':
- Hflag = 1;
- Lflag = 0;
- break;
- case 'L':
- Lflag = 1;
- Hflag = 0;
- break;
- case 'P':
- Hflag = Lflag = 0;
- break;
- case 'a':
- aflag = 1;
- break;
- case 'c':
- cflag = 1;
- break;
- case 'd':
- dflag = 1;
- depth = atoi(optarg);
- if (depth < 0 || depth > SHRT_MAX) {
- warnx("invalid argument to option d: %s",
- optarg);
- usage();
- }
- break;
- case 'g':
- blocksize = 1024 * 1024 * 1024;
- gkmflag = 1;
- break;
- case 'h':
- hflag = 1;
- break;
- case 'i':
- iflag = 1;
- break;
- case 'k':
- blocksize = 1024;
- gkmflag = 1;
- break;
- case 'm':
- blocksize = 1024 * 1024;
- gkmflag = 1;
- break;
- case 'n':
- nflag = 1;
- break;
- case 'r':
- break;
- case 's':
- sflag = 1;
- break;
- case 'x':
- ftsoptions |= FTS_XDEV;
- break;
- case '?':
- default:
- usage();
- }
- argc -= optind;
- argv += optind;
-
- /*
- * XXX
- * Because of the way that fts(3) works, logical walks will not count
- * the blocks actually used by symbolic links. We rationalize this by
- * noting that users computing logical sizes are likely to do logical
- * copies, so not counting the links is correct. The real reason is
- * that we'd have to re-implement the kernel's symbolic link traversing
- * algorithm to get this right. If, for example, you have relative
- * symbolic links referencing other relative symbolic links, it gets
- * very nasty, very fast. The bottom line is that it's documented in
- * the man page, so it's a feature.
- */
- if (Hflag)
- ftsoptions |= FTS_COMFOLLOW;
- if (Lflag) {
- ftsoptions &= ~FTS_PHYSICAL;
- ftsoptions |= FTS_LOGICAL;
- }
-
- listfiles = 0;
- if (aflag) {
- if (sflag || dflag)
- usage();
- listfiles = 1;
- } else if (sflag) {
- if (dflag)
- usage();
- depth = 0;
- }
-
- if (!*argv) {
- noargv[0] = ".";
- noargv[1] = NULL;
- argv = __UNCONST(noargv);
- }
-
- if (!gkmflag)
- (void)getbsize(NULL, &blocksize);
- blocksize /= 512;
-
- if ((fts = fts_open(argv, ftsoptions, NULL)) == NULL)
- err(1, "fts_open `%s'", *argv);
-
- for (rval = 0; (p = fts_read(fts)) != NULL;) {
-#ifndef __ANDROID__
- if (nflag) {
- switch (p->fts_info) {
- case FTS_NS:
- case FTS_SLNONE:
- /* nothing */
- break;
- default:
- if (p->fts_statp->st_flags & UF_NODUMP) {
- fts_set(fts, p, FTS_SKIP);
- continue;
- }
- }
- }
-#endif
- switch (p->fts_info) {
- case FTS_D: /* Ignore. */
- break;
- case FTS_DP:
- p->fts_parent->fts_number +=
- p->fts_number += COUNT;
- if (cflag)
- totalblocks += COUNT;
- /*
- * If listing each directory, or not listing files
- * or directories and this is post-order of the
- * root of a traversal, display the total.
- */
- if (p->fts_level <= depth
- || (!listfiles && !p->fts_level))
- prstat(p->fts_path, p->fts_number);
- break;
- case FTS_DC: /* Ignore. */
- break;
- case FTS_DNR: /* Warn, continue. */
- case FTS_ERR:
- case FTS_NS:
- warnx("%s: %s", p->fts_path, strerror(p->fts_errno));
- rval = 1;
- break;
- default:
- if (p->fts_statp->st_nlink > 1 &&
- linkchk(p->fts_statp->st_dev, p->fts_statp->st_ino))
- break;
- /*
- * If listing each file, or a non-directory file was
- * the root of a traversal, display the total.
- */
- if (listfiles || !p->fts_level)
- prstat(p->fts_path, COUNT);
- p->fts_parent->fts_number += COUNT;
- if (cflag)
- totalblocks += COUNT;
- }
- }
- if (errno)
- err(1, "fts_read");
- if (cflag)
- prstat("total", totalblocks);
- exit(rval);
-}
-
-static void
-prstat(const char *fname, int64_t blocks)
-{
- if (iflag) {
- (void)printf("%" PRId64 "\t%s\n", blocks, fname);
- return;
- }
-
- if (hflag) {
- char buf[5];
- int64_t sz = blocks * 512;
-
- humanize_number(buf, sizeof(buf), sz, "", HN_AUTOSCALE,
- HN_B | HN_NOSPACE | HN_DECIMAL);
-
- (void)printf("%s\t%s\n", buf, fname);
- } else
- (void)printf("%" PRId64 "\t%s\n",
- howmany(blocks, (int64_t)blocksize),
- fname);
-}
-
-static int
-linkchk(dev_t dev, ino_t ino)
-{
- static struct entry {
- dev_t dev;
- ino_t ino;
- } *htable;
- static int htshift; /* log(allocated size) */
- static int htmask; /* allocated size - 1 */
- static int htused; /* 2*number of insertions */
- static int sawzero; /* Whether zero is in table or not */
- int h, h2;
- uint64_t tmp;
- /* this constant is (1<<64)/((1+sqrt(5))/2)
- * aka (word size)/(golden ratio)
- */
- const uint64_t HTCONST = 11400714819323198485ULL;
- const int HTBITS = CHAR_BIT * sizeof(tmp);
-
- /* Never store zero in hashtable */
- if (dev == 0 && ino == 0) {
- h = sawzero;
- sawzero = 1;
- return h;
- }
-
- /* Extend hash table if necessary, keep load under 0.5 */
- if (htused<<1 >= htmask) {
- struct entry *ohtable;
-
- if (!htable)
- htshift = 10; /* starting hashtable size */
- else
- htshift++; /* exponential hashtable growth */
-
- htmask = (1 << htshift) - 1;
- htused = 0;
-
- ohtable = htable;
- htable = calloc(htmask+1, sizeof(*htable));
- if (!htable)
- err(1, "calloc");
-
- /* populate newly allocated hashtable */
- if (ohtable) {
- int i;
- for (i = 0; i <= htmask>>1; i++)
- if (ohtable[i].ino || ohtable[i].dev)
- linkchk(ohtable[i].dev, ohtable[i].ino);
- free(ohtable);
- }
- }
-
- /* multiplicative hashing */
- tmp = dev;
- tmp <<= HTBITS>>1;
- tmp |= ino;
- tmp *= HTCONST;
- h = tmp >> (HTBITS - htshift);
- h2 = 1 | ( tmp >> (HTBITS - (htshift<<1) - 1)); /* must be odd */
-
- /* open address hashtable search with double hash probing */
- while (htable[h].ino || htable[h].dev) {
- if ((htable[h].ino == ino) && (htable[h].dev == dev))
- return 1;
- h = (h + h2) & htmask;
- }
-
- /* Insert the current entry into hashtable */
- htable[h].dev = dev;
- htable[h].ino = ino;
- htused++;
- return 0;
-}
-
-static void
-usage(void)
-{
-
- (void)fprintf(stderr,
- "usage: du [-H | -L | -P] [-a | -d depth | -s] [-cghikmnrx] [file ...]\n");
- exit(1);
-}