asan_premap_shadow.cpp 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. //===-- asan_premap_shadow.cpp --------------------------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file is a part of AddressSanitizer, an address sanity checker.
  10. //
  11. // Reserve shadow memory with an ifunc resolver.
  12. //===----------------------------------------------------------------------===//
  13. #include "asan_mapping.h"
  14. #if ASAN_PREMAP_SHADOW
  15. #include "asan_premap_shadow.h"
  16. #include "sanitizer_common/sanitizer_posix.h"
  17. namespace __asan {
  18. // The code in this file needs to run in an unrelocated binary. It may not
  19. // access any external symbol, including its own non-hidden globals.
  20. // Conservative upper limit.
  21. uptr PremapShadowSize() {
  22. uptr granularity = GetMmapGranularity();
  23. return RoundUpTo(GetMaxVirtualAddress() >> ASAN_SHADOW_SCALE, granularity);
  24. }
  25. // Returns an address aligned to 8 pages, such that one page on the left and
  26. // PremapShadowSize() bytes on the right of it are mapped r/o.
  27. uptr PremapShadow() {
  28. return MapDynamicShadow(PremapShadowSize(), /*mmap_alignment_scale*/ 3,
  29. /*min_shadow_base_alignment*/ 0, kHighMemEnd);
  30. }
  31. bool PremapShadowFailed() {
  32. uptr shadow = reinterpret_cast<uptr>(&__asan_shadow);
  33. uptr resolver = reinterpret_cast<uptr>(&__asan_premap_shadow);
  34. // shadow == resolver is how Android KitKat and older handles ifunc.
  35. // shadow == 0 just in case.
  36. if (shadow == 0 || shadow == resolver)
  37. return true;
  38. return false;
  39. }
  40. } // namespace __asan
  41. extern "C" {
  42. decltype(__asan_shadow)* __asan_premap_shadow() {
  43. // The resolver may be called multiple times. Map the shadow just once.
  44. static uptr premapped_shadow = 0;
  45. if (!premapped_shadow) premapped_shadow = __asan::PremapShadow();
  46. return reinterpret_cast<decltype(__asan_shadow)*>(premapped_shadow);
  47. }
  48. // __asan_shadow is a "function" that has the same address as the first byte of
  49. // the shadow mapping.
  50. INTERFACE_ATTRIBUTE __attribute__((ifunc("__asan_premap_shadow"))) void
  51. __asan_shadow();
  52. }
  53. #endif // ASAN_PREMAP_SHADOW