1 // Copyright 2017 The Chromium Authors
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 "partition_alloc/shim/malloc_zone_functions_apple.h"
6 
7 #include "testing/gtest/include/gtest/gtest.h"
8 
9 namespace allocator_shim {
10 
11 class MallocZoneFunctionsTest : public testing::Test {
12  protected:
TearDown()13   void TearDown() override { ClearAllMallocZonesForTesting(); }
14 };
15 
TEST_F(MallocZoneFunctionsTest,TestDefaultZoneMallocFree)16 TEST_F(MallocZoneFunctionsTest, TestDefaultZoneMallocFree) {
17   ChromeMallocZone* malloc_zone =
18       reinterpret_cast<ChromeMallocZone*>(malloc_default_zone());
19   StoreMallocZone(malloc_zone);
20   int* test = reinterpret_cast<int*>(
21       g_malloc_zones[0].malloc(malloc_default_zone(), 33));
22   test[0] = 1;
23   test[1] = 2;
24   g_malloc_zones[0].free(malloc_default_zone(), test);
25 }
26 
TEST_F(MallocZoneFunctionsTest,IsZoneAlreadyStored)27 TEST_F(MallocZoneFunctionsTest, IsZoneAlreadyStored) {
28   ChromeMallocZone* malloc_zone =
29       reinterpret_cast<ChromeMallocZone*>(malloc_default_zone());
30   EXPECT_FALSE(IsMallocZoneAlreadyStored(malloc_zone));
31   StoreMallocZone(malloc_zone);
32   EXPECT_TRUE(IsMallocZoneAlreadyStored(malloc_zone));
33 }
34 
TEST_F(MallocZoneFunctionsTest,CannotDoubleStoreZone)35 TEST_F(MallocZoneFunctionsTest, CannotDoubleStoreZone) {
36   ChromeMallocZone* malloc_zone =
37       reinterpret_cast<ChromeMallocZone*>(malloc_default_zone());
38   StoreMallocZone(malloc_zone);
39   StoreMallocZone(malloc_zone);
40   EXPECT_EQ(1, GetMallocZoneCountForTesting());
41 }
42 
TEST_F(MallocZoneFunctionsTest,CannotStoreMoreThanMaxZones)43 TEST_F(MallocZoneFunctionsTest, CannotStoreMoreThanMaxZones) {
44   std::vector<ChromeMallocZone> zones;
45   zones.resize(kMaxZoneCount * 2);
46   for (int i = 0; i < kMaxZoneCount * 2; ++i) {
47     ChromeMallocZone& zone = zones[i];
48     memcpy(&zone, malloc_default_zone(), sizeof(ChromeMallocZone));
49     StoreMallocZone(&zone);
50   }
51 
52   int max_zone_count = kMaxZoneCount;
53   EXPECT_EQ(max_zone_count, GetMallocZoneCountForTesting());
54 }
55 
56 }  // namespace allocator_shim
57