poison.cc 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. // Copyright 2024 The Abseil Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // https://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #include "absl/base/internal/poison.h"
  15. #include <cstdlib>
  16. #include "absl/base/config.h"
  17. #include "absl/base/internal/direct_mmap.h"
  18. #ifndef _WIN32
  19. #include <unistd.h>
  20. #endif
  21. #if defined(ABSL_HAVE_ADDRESS_SANITIZER)
  22. #include <sanitizer/asan_interface.h>
  23. #elif defined(ABSL_HAVE_MEMORY_SANITIZER)
  24. #include <sanitizer/msan_interface.h>
  25. #elif defined(ABSL_HAVE_MMAP)
  26. #include <sys/mman.h>
  27. #endif
  28. #if defined(_WIN32)
  29. #include <windows.h>
  30. #endif
  31. namespace absl {
  32. ABSL_NAMESPACE_BEGIN
  33. namespace base_internal {
  34. namespace {
  35. size_t GetPageSize() {
  36. #ifdef _WIN32
  37. SYSTEM_INFO system_info;
  38. GetSystemInfo(&system_info);
  39. return system_info.dwPageSize;
  40. #elif defined(__wasm__) || defined(__asmjs__) || defined(__hexagon__)
  41. return getpagesize();
  42. #else
  43. return static_cast<size_t>(sysconf(_SC_PAGESIZE));
  44. #endif
  45. }
  46. } // namespace
  47. void* InitializePoisonedPointerInternal() {
  48. const size_t block_size = GetPageSize();
  49. #if defined(ABSL_HAVE_ADDRESS_SANITIZER)
  50. void* data = malloc(block_size);
  51. ASAN_POISON_MEMORY_REGION(data, block_size);
  52. #elif defined(ABSL_HAVE_MEMORY_SANITIZER)
  53. void* data = malloc(block_size);
  54. __msan_poison(data, block_size);
  55. #elif defined(ABSL_HAVE_MMAP)
  56. void* data = DirectMmap(nullptr, block_size, PROT_NONE,
  57. MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
  58. if (data == MAP_FAILED) return GetBadPointerInternal();
  59. #elif defined(_WIN32)
  60. void* data = VirtualAlloc(nullptr, block_size, MEM_RESERVE | MEM_COMMIT,
  61. PAGE_NOACCESS);
  62. if (data == nullptr) return GetBadPointerInternal();
  63. #else
  64. return GetBadPointerInternal();
  65. #endif
  66. // Return the middle of the block so that dereferences before and after the
  67. // pointer will both crash.
  68. return static_cast<char*>(data) + block_size / 2;
  69. }
  70. } // namespace base_internal
  71. ABSL_NAMESPACE_END
  72. } // namespace absl