address_space_randomization.cc 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. // Copyright 2014 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #include "base/allocator/partition_allocator/address_space_randomization.h"
  5. #include "base/allocator/partition_allocator/partition_alloc_check.h"
  6. #include "base/allocator/partition_allocator/random.h"
  7. #include "build/build_config.h"
  8. #if BUILDFLAG(IS_WIN)
  9. #include <windows.h> // Must be in front of other Windows header files.
  10. #include <versionhelpers.h>
  11. #endif
  12. namespace partition_alloc {
  13. uintptr_t GetRandomPageBase() {
  14. uintptr_t random = static_cast<uintptr_t>(internal::RandomValue());
  15. #if defined(ARCH_CPU_64_BITS)
  16. random <<= 32ULL;
  17. random |= static_cast<uintptr_t>(internal::RandomValue());
  18. // The ASLRMask() and ASLROffset() constants will be suitable for the
  19. // OS and build configuration.
  20. #if BUILDFLAG(IS_WIN) && !defined(MEMORY_TOOL_REPLACES_ALLOCATOR)
  21. // Windows >= 8.1 has the full 47 bits. Use them where available.
  22. static bool windows_81 = false;
  23. static bool windows_81_initialized = false;
  24. if (!windows_81_initialized) {
  25. windows_81 = IsWindows8Point1OrGreater();
  26. windows_81_initialized = true;
  27. }
  28. if (!windows_81) {
  29. random &= internal::ASLRMaskBefore8_10();
  30. } else {
  31. random &= internal::ASLRMask();
  32. }
  33. random += internal::ASLROffset();
  34. #else
  35. random &= internal::ASLRMask();
  36. random += internal::ASLROffset();
  37. #endif // BUILDFLAG(IS_WIN) && !defined(MEMORY_TOOL_REPLACES_ALLOCATOR)
  38. #else // defined(ARCH_CPU_32_BITS)
  39. #if BUILDFLAG(IS_WIN)
  40. // On win32 host systems the randomization plus huge alignment causes
  41. // excessive fragmentation. Plus most of these systems lack ASLR, so the
  42. // randomization isn't buying anything. In that case we just skip it.
  43. // TODO(palmer): Just dump the randomization when HE-ASLR is present.
  44. static BOOL is_wow64 = -1;
  45. if (is_wow64 == -1 && !IsWow64Process(GetCurrentProcess(), &is_wow64))
  46. is_wow64 = FALSE;
  47. if (!is_wow64)
  48. return 0;
  49. #endif // BUILDFLAG(IS_WIN)
  50. random &= internal::ASLRMask();
  51. random += internal::ASLROffset();
  52. #endif // defined(ARCH_CPU_32_BITS)
  53. PA_DCHECK(!(random & internal::PageAllocationGranularityOffsetMask()));
  54. return random;
  55. }
  56. } // namespace partition_alloc