ashmemd_client.cpp 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /*
  2. * Copyright (C) 2019 The Android Open Source Project
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #include <android-base/logging.h>
  17. #include <android/ashmemd/IAshmemDeviceService.h>
  18. #include <binder/IServiceManager.h>
  19. #include <cutils/android_filesystem_config.h>
  20. using android::IBinder;
  21. using android::IServiceManager;
  22. using android::String16;
  23. using android::ashmemd::IAshmemDeviceService;
  24. using android::os::ParcelFileDescriptor;
  25. namespace android {
  26. namespace ashmemd {
  27. static bool checkBinderAccess() {
  28. // Isolated apps are potentially subject to seccomp policy that restricts use of access()
  29. // (b/129483782). However, apps always have access to binder, so return true.
  30. auto uid = getuid() % AID_USER;
  31. if (AID_ISOLATED_START <= uid && uid <= AID_ISOLATED_END) {
  32. return true;
  33. }
  34. if (access("/dev/binder", R_OK | W_OK) == 0) {
  35. return true;
  36. }
  37. return false;
  38. }
  39. sp<IAshmemDeviceService> getAshmemService() {
  40. // Calls to defaultServiceManager() crash the process if it doesn't have appropriate
  41. // binder permissions. Check these permissions proactively.
  42. if (!checkBinderAccess()) {
  43. return nullptr;
  44. }
  45. sp<IServiceManager> sm = android::defaultServiceManager();
  46. sp<IBinder> binder = sm->checkService(String16("ashmem_device_service"));
  47. return interface_cast<IAshmemDeviceService>(binder);
  48. }
  49. extern "C" int openAshmemdFd() {
  50. static sp<IAshmemDeviceService> ashmemService = getAshmemService();
  51. if (!ashmemService) {
  52. LOG(ERROR) << "Failed to get IAshmemDeviceService.";
  53. return -1;
  54. }
  55. ParcelFileDescriptor fd;
  56. auto status = ashmemService->open(&fd);
  57. if (!status.isOk()) {
  58. LOG(ERROR) << "Failed IAshmemDeviceService::open()";
  59. return -1;
  60. }
  61. // unique_fd is the underlying type of ParcelFileDescriptor, i.e. fd is
  62. // closed when it falls out of scope, so we make a dup.
  63. return dup(fd.get());
  64. }
  65. } // namespace ashmemd
  66. } // namespace android