winheap_stubs_win_unittest.cc 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. // Copyright 2018 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/winheap_stubs_win.h"
  5. #include "base/bits.h"
  6. #include "base/check.h"
  7. #include "testing/gtest/include/gtest/gtest.h"
  8. namespace base {
  9. namespace allocator {
  10. namespace {
  11. bool IsPtrAligned(void* ptr, size_t alignment) {
  12. CHECK(base::bits::IsPowerOfTwo(alignment));
  13. uintptr_t address = reinterpret_cast<uintptr_t>(ptr);
  14. return base::bits::AlignUp(address, alignment) == address;
  15. }
  16. } // namespace
  17. TEST(WinHeapStubs, AlignedAllocationAreAligned) {
  18. for (size_t alignment = 1; alignment < 65536; alignment *= 2) {
  19. SCOPED_TRACE(alignment);
  20. void* ptr = WinHeapAlignedMalloc(10, alignment);
  21. ASSERT_NE(ptr, nullptr);
  22. EXPECT_TRUE(IsPtrAligned(ptr, alignment));
  23. ptr = WinHeapAlignedRealloc(ptr, 1000, alignment);
  24. ASSERT_NE(ptr, nullptr);
  25. EXPECT_TRUE(IsPtrAligned(ptr, alignment));
  26. WinHeapAlignedFree(ptr);
  27. }
  28. }
  29. TEST(WinHeapStubs, AlignedReallocationsCorrectlyCopyData) {
  30. constexpr size_t kAlignment = 64;
  31. constexpr uint8_t kMagicByte = 0xab;
  32. size_t old_size = 8;
  33. void* ptr = WinHeapAlignedMalloc(old_size, kAlignment);
  34. ASSERT_NE(ptr, nullptr);
  35. // Cause allocations to grow and shrink and confirm allocation contents are
  36. // copied regardless.
  37. constexpr size_t kSizes[] = {10, 1000, 50, 3000, 30, 9000};
  38. for (size_t size : kSizes) {
  39. SCOPED_TRACE(size);
  40. memset(ptr, kMagicByte, old_size);
  41. ptr = WinHeapAlignedRealloc(ptr, size, kAlignment);
  42. ASSERT_NE(ptr, nullptr);
  43. for (size_t i = 0; i < std::min(size, old_size); i++) {
  44. SCOPED_TRACE(i);
  45. ASSERT_EQ(reinterpret_cast<uint8_t*>(ptr)[i], kMagicByte);
  46. }
  47. old_size = size;
  48. }
  49. WinHeapAlignedFree(ptr);
  50. }
  51. } // namespace allocator
  52. } // namespace base