support_shared_allocate.c 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /* Allocate a memory region shared across processes.
  2. Copyright (C) 2017-2019 Free Software Foundation, Inc.
  3. This file is part of the GNU C Library.
  4. The GNU C Library is free software; you can redistribute it and/or
  5. modify it under the terms of the GNU Lesser General Public
  6. License as published by the Free Software Foundation; either
  7. version 2.1 of the License, or (at your option) any later version.
  8. The GNU C Library is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public
  13. License along with the GNU C Library; if not, see
  14. <http://www.gnu.org/licenses/>. */
  15. #include <errno.h>
  16. #include <stddef.h>
  17. #include <support/support.h>
  18. #include <support/xunistd.h>
  19. #include <sys/mman.h>
  20. /* Header for the allocation. It contains the size of the allocation
  21. for subsequent unmapping. */
  22. struct header
  23. {
  24. size_t total_size;
  25. char data[] __attribute__ ((aligned (__alignof__ (max_align_t))));
  26. };
  27. void *
  28. support_shared_allocate (size_t size)
  29. {
  30. size_t total_size = size + offsetof (struct header, data);
  31. if (total_size < size)
  32. {
  33. errno = ENOMEM;
  34. oom_error (__func__, size);
  35. return NULL;
  36. }
  37. else
  38. {
  39. struct header *result = xmmap (NULL, total_size, PROT_READ | PROT_WRITE,
  40. MAP_ANONYMOUS | MAP_SHARED, -1);
  41. result->total_size = total_size;
  42. return &result->data;
  43. }
  44. }
  45. void
  46. support_shared_free (void *data)
  47. {
  48. struct header *header = data - offsetof (struct header, data);
  49. xmunmap (header, header->total_size);
  50. }