1 // Copyright (c) 2012 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 5 #include "base/memory/aligned_memory.h" 6 #include "base/memory/scoped_ptr.h" 7 #include "testing/gtest/include/gtest/gtest.h" 8 9 #define EXPECT_ALIGNED(ptr, align) \ 10 EXPECT_EQ(0u, reinterpret_cast<uintptr_t>(ptr) & (align - 1)) 11 12 namespace { 13 14 using base::AlignedMemory; 15 16 TEST(AlignedMemoryTest, StaticAlignment) { 17 static AlignedMemory<8, 8> raw8; 18 static AlignedMemory<8, 16> raw16; 19 static AlignedMemory<8, 256> raw256; 20 static AlignedMemory<8, 4096> raw4096; 21 22 EXPECT_EQ(8u, ALIGNOF(raw8)); 23 EXPECT_EQ(16u, ALIGNOF(raw16)); 24 EXPECT_EQ(256u, ALIGNOF(raw256)); 25 EXPECT_EQ(4096u, ALIGNOF(raw4096)); 26 27 EXPECT_ALIGNED(raw8.void_data(), 8); 28 EXPECT_ALIGNED(raw16.void_data(), 16); 29 EXPECT_ALIGNED(raw256.void_data(), 256); 30 EXPECT_ALIGNED(raw4096.void_data(), 4096); 31 } 32 33 TEST(AlignedMemoryTest, StackAlignment) { 34 AlignedMemory<8, 8> raw8; 35 AlignedMemory<8, 16> raw16; 36 AlignedMemory<8, 128> raw128; 37 38 EXPECT_EQ(8u, ALIGNOF(raw8)); 39 EXPECT_EQ(16u, ALIGNOF(raw16)); 40 EXPECT_EQ(128u, ALIGNOF(raw128)); 41 42 EXPECT_ALIGNED(raw8.void_data(), 8); 43 EXPECT_ALIGNED(raw16.void_data(), 16); 44 EXPECT_ALIGNED(raw128.void_data(), 128); 45 46 // NaCl x86-64 compiler emits non-validating instructions for >128 47 // bytes alignment. 48 // http://www.chromium.org/nativeclient/design-documents/nacl-sfi-model-on-x86-64-systems 49 // TODO(hamaji): Ideally, NaCl compiler for x86-64 should workaround 50 // this limitation and this #if should be removed. 51 // https://code.google.com/p/nativeclient/issues/detail?id=3463 52 #if !(defined(OS_NACL) && defined(ARCH_CPU_X86_64)) 53 AlignedMemory<8, 256> raw256; 54 EXPECT_EQ(256u, ALIGNOF(raw256)); 55 EXPECT_ALIGNED(raw256.void_data(), 256); 56 57 // TODO(ios): This test hits an armv7 bug in clang. crbug.com/138066 58 #if !(defined(OS_IOS) && defined(ARCH_CPU_ARM_FAMILY)) 59 AlignedMemory<8, 4096> raw4096; 60 EXPECT_EQ(4096u, ALIGNOF(raw4096)); 61 EXPECT_ALIGNED(raw4096.void_data(), 4096); 62 #endif // !(defined(OS_IOS) && defined(ARCH_CPU_ARM_FAMILY)) 63 #endif 64 } 65 66 TEST(AlignedMemoryTest, DynamicAllocation) { 67 void* p = base::AlignedAlloc(8, 8); 68 EXPECT_TRUE(p); 69 EXPECT_ALIGNED(p, 8); 70 base::AlignedFree(p); 71 72 p = base::AlignedAlloc(8, 16); 73 EXPECT_TRUE(p); 74 EXPECT_ALIGNED(p, 16); 75 base::AlignedFree(p); 76 77 p = base::AlignedAlloc(8, 256); 78 EXPECT_TRUE(p); 79 EXPECT_ALIGNED(p, 256); 80 base::AlignedFree(p); 81 82 p = base::AlignedAlloc(8, 4096); 83 EXPECT_TRUE(p); 84 EXPECT_ALIGNED(p, 4096); 85 base::AlignedFree(p); 86 } 87 88 TEST(AlignedMemoryTest, ScopedDynamicAllocation) { 89 scoped_ptr_malloc<float, base::ScopedPtrAlignedFree> p( 90 static_cast<float*>(base::AlignedAlloc(8, 8))); 91 EXPECT_TRUE(p.get()); 92 EXPECT_ALIGNED(p.get(), 8); 93 } 94 95 } // namespace 96