binderfs_example.c 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. // SPDX-License-Identifier: GPL-2.0
  2. #define _GNU_SOURCE
  3. #include <errno.h>
  4. #include <fcntl.h>
  5. #include <sched.h>
  6. #include <stdio.h>
  7. #include <stdlib.h>
  8. #include <string.h>
  9. #include <sys/ioctl.h>
  10. #include <sys/mount.h>
  11. #include <sys/stat.h>
  12. #include <sys/types.h>
  13. #include <unistd.h>
  14. #include <linux/android/binder.h>
  15. #include <linux/android/binderfs.h>
  16. int main(int argc, char *argv[])
  17. {
  18. int fd, ret, saved_errno;
  19. struct binderfs_device device = { 0 };
  20. ret = unshare(CLONE_NEWNS);
  21. if (ret < 0) {
  22. fprintf(stderr, "%s - Failed to unshare mount namespace\n",
  23. strerror(errno));
  24. exit(EXIT_FAILURE);
  25. }
  26. ret = mount(NULL, "/", NULL, MS_REC | MS_PRIVATE, 0);
  27. if (ret < 0) {
  28. fprintf(stderr, "%s - Failed to mount / as private\n",
  29. strerror(errno));
  30. exit(EXIT_FAILURE);
  31. }
  32. ret = mkdir("/dev/binderfs", 0755);
  33. if (ret < 0 && errno != EEXIST) {
  34. fprintf(stderr, "%s - Failed to create binderfs mountpoint\n",
  35. strerror(errno));
  36. exit(EXIT_FAILURE);
  37. }
  38. ret = mount(NULL, "/dev/binderfs", "binder", 0, 0);
  39. if (ret < 0) {
  40. fprintf(stderr, "%s - Failed to mount binderfs\n",
  41. strerror(errno));
  42. exit(EXIT_FAILURE);
  43. }
  44. memcpy(device.name, "my-binder", strlen("my-binder"));
  45. fd = open("/dev/binderfs/binder-control", O_RDONLY | O_CLOEXEC);
  46. if (fd < 0) {
  47. fprintf(stderr, "%s - Failed to open binder-control device\n",
  48. strerror(errno));
  49. exit(EXIT_FAILURE);
  50. }
  51. ret = ioctl(fd, BINDER_CTL_ADD, &device);
  52. saved_errno = errno;
  53. close(fd);
  54. errno = saved_errno;
  55. if (ret < 0) {
  56. fprintf(stderr, "%s - Failed to allocate new binder device\n",
  57. strerror(errno));
  58. exit(EXIT_FAILURE);
  59. }
  60. printf("Allocated new binder device with major %d, minor %d, and name %s\n",
  61. device.major, device.minor, device.name);
  62. ret = unlink("/dev/binderfs/my-binder");
  63. if (ret < 0) {
  64. fprintf(stderr, "%s - Failed to delete binder device\n",
  65. strerror(errno));
  66. exit(EXIT_FAILURE);
  67. }
  68. /* Cleanup happens when the mount namespace dies. */
  69. exit(EXIT_SUCCESS);
  70. }