libbinder_ndk: private SharedRefBase construction
SharedRefBase, like sp, has a weakref within it. This allows us to
promote to a strong ref when we only have a pointer to an object (for
instance when we're getting a binder from a binder transaction).
However, it means that the objects have an implicit ownership model.
So, this code is problematic:
std::shared_ptr<IFoo> foo = std::make_shared<MyFoo>();
...
// what other code will do when getting the binder from another
// process, creating double ownership w/ shared_ptrs
std::shared_ptr<IFoo> foo = foo->ref();
Here, we're hiding the use of the 'new' operator so that the initial
make_shared is impossible. If people always use 'SharedRefBase::make'
and 'SharedRefBase::ref' to get strong ownership of the object, then we
avoid this possibility.
Since we hide the 'new' operator, all heap allocation will be blocked.
So other possibilities of double-ownership (e.g. using std::shared_ptr)
will also fail.
One problem with this approach is that it still allows these objects to
be declared on the stack. This is an opportunity for improvement.
Bug: 149249948
Test: TH
Change-Id: I300008f1413474c9e78dd57217f57338a3528db0
diff --git a/libs/binder/ndk/include_ndk/android/binder_interface_utils.h b/libs/binder/ndk/include_ndk/android/binder_interface_utils.h
index 7331ba2..e6b743b 100644
--- a/libs/binder/ndk/include_ndk/android/binder_interface_utils.h
+++ b/libs/binder/ndk/include_ndk/android/binder_interface_utils.h
@@ -86,9 +86,15 @@
return t->template ref<T>();
}
+ static void operator delete(void* p) { std::free(p); }
+
private:
std::once_flag mFlagThis;
std::weak_ptr<SharedRefBase> mThis;
+
+ // Use 'SharedRefBase::make<T>(...)' to make. SharedRefBase has implicit
+ // ownership. Making this operator private to avoid double-ownership.
+ static void* operator new(size_t s) { return std::malloc(s); }
};
/**