summaryrefslogtreecommitdiffstats
path: root/toolkit/xre/dllservices/tests/TestMMPolicy.cpp
blob: 1ae93a4ed142329453bd910ec2f75c3dd899f20a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "nsWindowsDllInterceptor.h"

#include <functional>

mozilla::interceptor::MMPolicyInProcess gPolicy;

void DepleteVirtualAddress(
    uint8_t* aStart, size_t aSize,
    const std::function<void(void*)>& aPostAllocCallback) {
  const DWORD granularity = gPolicy.GetAllocGranularity();
  if (aStart == 0 || aSize < granularity) {
    return;
  }

  uint8_t* alignedStart = reinterpret_cast<uint8_t*>(
      (((reinterpret_cast<uintptr_t>(aStart) - 1) / granularity) + 1) *
      granularity);
  aSize -= (alignedStart - aStart);
  if (auto p = VirtualAlloc(alignedStart, aSize, MEM_RESERVE, PAGE_NOACCESS)) {
    aPostAllocCallback(p);
    return;
  }

  uintptr_t mask = ~(static_cast<uintptr_t>(granularity) - 1);
  size_t halfSize = (aSize >> 1) & mask;
  if (halfSize == 0) {
    return;
  }

  DepleteVirtualAddress(aStart, halfSize, aPostAllocCallback);
  DepleteVirtualAddress(aStart + halfSize, aSize - halfSize,
                        aPostAllocCallback);
}

bool ValidateFreeRegion(LPVOID aRegion, size_t aDesiredLen) {
  MEMORY_BASIC_INFORMATION mbi;
  if (VirtualQuery(aRegion, &mbi, sizeof(mbi)) != sizeof(mbi)) {
    printf(
        "TEST-FAILED | TestMMPolicy | "
        "VirtualQuery(%p) failed - %08lx\n",
        aRegion, GetLastError());
    return false;
  }

  if (mbi.State != MEM_FREE) {
    printf(
        "TEST-FAILED | TestMMPolicy | "
        "%p is not within a free region\n",
        aRegion);
    return false;
  }

  if (aRegion != mbi.BaseAddress ||
      reinterpret_cast<uintptr_t>(mbi.BaseAddress) %
          gPolicy.GetAllocGranularity()) {
    printf(
        "TEST-FAILED | TestMMPolicy | "
        "%p is not a region's start address\n",
        aRegion);
    return false;
  }

  LPVOID allocated = VirtualAlloc(aRegion, aDesiredLen,
                                  MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
  if (!allocated) {
    printf(
        "TEST-FAILED | TestMMPolicy | "
        "VirtualAlloc(%p) failed - %08lx\n",
        aRegion, GetLastError());
    return false;
  }

  if (!VirtualFree(allocated, 0, MEM_RELEASE)) {
    printf(
        "TEST-FAILED | TestMMPolicy | "
        "VirtualFree(%p) failed - %08lx\n",
        allocated, GetLastError());
    return false;
  }

  return true;
}

bool TestFindRegion() {
  // Skip the near-null addresses
  uint8_t* minAddr = reinterpret_cast<uint8_t*>(
      std::max(gPolicy.GetAllocGranularity(), 0x1000000ul));
  // 64bit address space is too large to deplete.  32bit space is enough.
  uint8_t* maxAddr = reinterpret_cast<uint8_t*>(std::min(
      gPolicy.GetMaxUserModeAddress(), static_cast<uintptr_t>(0xffffffff)));

  // Keep one of the regions we allocate so that we can release it later.
  void* lastResort = nullptr;

  // Reserve all free regions in the range [minAddr, maxAddr]
  for (uint8_t* address = minAddr; address <= maxAddr;) {
    MEMORY_BASIC_INFORMATION mbi;
    if (VirtualQuery(address, &mbi, sizeof(mbi)) != sizeof(mbi)) {
      printf(
          "TEST-FAILED | TestMMPolicy | "
          "VirtualQuery(%p) failed - %08lx\n",
          address, GetLastError());
      break;
    }

    address = reinterpret_cast<uint8_t*>(mbi.BaseAddress);
    if (mbi.State == MEM_FREE) {
      DepleteVirtualAddress(address, mbi.RegionSize,
                            [&lastResort](void* aAllocated) {
                              // Pick the first address we allocate to make sure
                              // FindRegion scans the full range.
                              if (!lastResort) {
                                lastResort = aAllocated;
                              }
                            });
    }

    address += mbi.RegionSize;
  }

  if (!lastResort) {
    printf(
        "TEST-SKIPPED | TestMMPolicy | "
        "No free region in [%p - %p].  Skipping the testcase.\n",
        minAddr, maxAddr);
    return true;
  }

  // Make sure there are no free regions
  PVOID freeRegion =
      gPolicy.FindRegion(GetCurrentProcess(), 1, minAddr, maxAddr);
  if (freeRegion) {
    if (reinterpret_cast<uintptr_t>(freeRegion) %
        gPolicy.GetAllocGranularity()) {
      printf(
          "TEST-FAILED | TestMMPolicy | "
          "MMPolicyBase::FindRegion returned an unaligned address %p.\n",
          freeRegion);
      return false;
    }

    printf(
        "TEST-SKIPPED | TestMMPolicy | "
        "%p was freed after depletion.  Skipping the testcase.\n",
        freeRegion);
    return true;
  }

  // Free one region, and thus we can expect FindRegion finds this region
  if (!VirtualFree(lastResort, 0, MEM_RELEASE)) {
    printf(
        "TEST-FAILED | TestMMPolicy | "
        "VirtualFree(%p) failed - %08lx\n",
        lastResort, GetLastError());
    return false;
  }
  printf("The region starting from %p has been freed.\n", lastResort);

  // Run the function several times because it uses a randon number inside
  // and its result is nondeterministic.
  for (int i = 0; i < 50; ++i) {
    // Because one region was freed, a desire up to one region
    // should be fulfilled.
    const size_t desiredLengths[] = {1, gPolicy.GetAllocGranularity()};

    for (auto desiredLen : desiredLengths) {
      freeRegion =
          gPolicy.FindRegion(GetCurrentProcess(), desiredLen, minAddr, maxAddr);
      if (!freeRegion) {
        printf(
            "TEST-FAILED | TestMMPolicy | "
            "Failed to find a free region.\n");
        return false;
      }

      if (!ValidateFreeRegion(freeRegion, desiredLen)) {
        return false;
      }
    }
  }

  return true;
}

extern "C" int wmain(int argc, wchar_t* argv[]) {
  // Preload delayload modules (e.g. advapi32.dll, bcryptPrimitives.dll, etc.)
  // by calling rand_s(), which is used in MMPolicy::FindRegion, before
  // depleting the process memory during the test.
  unsigned int rnd = 0;
  rand_s(&rnd);

  if (!TestFindRegion()) {
    return 1;
  }

  printf("TEST-PASS | TestMMPolicy | All tests passed.\n");
  return 0;
}