summaryrefslogtreecommitdiffstats
path: root/chrome_frame/test/exception_barrier_unittest.cc
blob: 3274318cdd7e5b0aabb05118ace372f26479b6d9 (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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "gtest/gtest.h"
#include "chrome_frame/exception_barrier.h"

namespace {

// retrieves the top SEH registration record
__declspec(naked) EXCEPTION_REGISTRATION* GetTopRegistration() {
  __asm {
    mov eax, FS:0
    ret
  }
}

// This function walks the SEH chain and attempts to ascertain whether it's
// sane, or rather tests it for any obvious signs of insanity.
// The signs it's capable of looking for are:
//   # Is each exception registration in bounds of our stack
//   # Is the registration DWORD aligned
//   # Does each exception handler point to a module, as opposed to
//      e.g. into the stack or never-never land.
//   # Do successive entries in the exception chain increase
//      monotonically in address
void TestSEHChainSane() {
  // get the skinny on our stack segment
  MEMORY_BASIC_INFORMATION info = { 0 };
  // Note that we pass the address of the info struct just as a handy
  // moniker to anything at all inside our stack allocation
  ASSERT_NE(0u, ::VirtualQuery(&info, &info, sizeof(info)));

  // The lower bound of our stack.
  // We use the address of info as a lower bound, this assumes that if this
  // function has an SEH handler, it'll be higher up in our invocation
  // record.
  EXCEPTION_REGISTRATION* limit =
          reinterpret_cast<EXCEPTION_REGISTRATION*>(&info);
  // the very top of our stack segment
  EXCEPTION_REGISTRATION* top =
          reinterpret_cast<EXCEPTION_REGISTRATION*>(
              reinterpret_cast<char*>(info.BaseAddress) + info.RegionSize);

  EXCEPTION_REGISTRATION* curr = GetTopRegistration();
  // there MUST be at least one registration
  ASSERT_TRUE(NULL != curr);

  EXCEPTION_REGISTRATION* prev = NULL;
  const EXCEPTION_REGISTRATION* kSentinel =
          reinterpret_cast<EXCEPTION_REGISTRATION*>(0xFFFFFFFF);
  for (; kSentinel != curr; prev = curr, curr = curr->prev) {
    // registrations must increase monotonically
    ASSERT_TRUE(curr > prev);
    // Check it's in bounds
    ASSERT_GE(top, curr);
    ASSERT_LT(limit, curr);

    // check for DWORD alignment
    ASSERT_EQ(0, (reinterpret_cast<UINT_PTR>(prev) & 0x00000003));

    // find the module hosting the handler
    ASSERT_NE(0u, ::VirtualQuery(curr->handler, &info, sizeof(info)));
    wchar_t module_filename[MAX_PATH];
    ASSERT_NE(0u, ::GetModuleFileName(
                    reinterpret_cast<HMODULE>(info.AllocationBase),
                    module_filename, ARRAYSIZE(module_filename)));
  }
}

void AccessViolationCrash() {
  volatile char* null = NULL;
  *null = '\0';
}

// A simple crash over the exception barrier
void CrashOverExceptionBarrier() {
  ExceptionBarrierCustomHandler barrier;

  TestSEHChainSane();

  AccessViolationCrash();

  TestSEHChainSane();
}

#pragma warning(push)
// Inline asm assigning to 'FS:0' : handler not registered as safe handler
// This warning is in error (the compiler can't know that we register the
// handler as a safe SEH handler in an .asm file)
#pragma warning(disable:4733)
// Hand-generate an SEH frame implicating the ExceptionBarrierCallCustomHandler,
// then crash to invoke it.
__declspec(naked) void CrashOnManualSEHBarrierHandler() {
  __asm {
    push  ExceptionBarrierCallCustomHandler
    push  FS:0
    mov   FS:0, esp
    call  AccessViolationCrash
    ret
  }
}
#pragma warning(pop)


class ExceptionBarrierTest: public testing::Test {
 public:
  ExceptionBarrierTest() {
  }

  // Install an exception handler for the ExceptionBarrier, and
  // set the handled flag to false. This allows us to see whether
  // the ExceptionBarrier gets to handle the exception
  virtual void SetUp() {
    ExceptionBarrierConfig::set_enabled(true);
    ExceptionBarrierCustomHandler::set_custom_handler(&ExceptionHandler);
    s_handled_ = false;

    TestSEHChainSane();
  }

  virtual void TearDown() {
    TestSEHChainSane();
    ExceptionBarrierCustomHandler::set_custom_handler(NULL);
    ExceptionBarrierConfig::set_enabled(false);
  }

  // The exception notification callback, sets the handled flag.
  static void CALLBACK ExceptionHandler(EXCEPTION_POINTERS* ptrs) {
    TestSEHChainSane();
    s_handled_ = true;
  }

  // Flag is set by handler
  static bool s_handled_;
};

bool ExceptionBarrierTest::s_handled_ = false;

bool TestExceptionExceptionBarrierHandler() {
  TestSEHChainSane();
  __try {
    CrashOnManualSEHBarrierHandler();
    return false;  // not reached
  } __except(EXCEPTION_ACCESS_VIOLATION == GetExceptionCode() ?
                      EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) {
    TestSEHChainSane();
    return true;
  }

  return false;  // not reached
}

typedef EXCEPTION_DISPOSITION
(__cdecl* ExceptionBarrierHandlerFunc)(
    struct _EXCEPTION_RECORD* exception_record,
    void* establisher_frame,
    struct _CONTEXT* context,
    void* reserved);

TEST_F(ExceptionBarrierTest, RegisterUnregister) {
  // Assert that registration modifies the chain
  // and the registered record as expected
  EXCEPTION_REGISTRATION* top = GetTopRegistration();
  ExceptionBarrierHandlerFunc handler = top->handler;
  EXCEPTION_REGISTRATION* prev = top->prev;

  EXCEPTION_REGISTRATION registration;
  ::RegisterExceptionRecord(&registration, ExceptionBarrierHandler);
  EXPECT_EQ(GetTopRegistration(), &registration);
  EXPECT_EQ(&ExceptionBarrierHandler, registration.handler);
  EXPECT_EQ(top, registration.prev);

  // test the whole chain for good measure
  TestSEHChainSane();

  // Assert that unregistration restores
  // everything as expected
  ::UnregisterExceptionRecord(&registration);
  EXPECT_EQ(top, GetTopRegistration());
  EXPECT_EQ(handler, top->handler);
  EXPECT_EQ(prev, top->prev);

  // and again test the whole chain for good measure
  TestSEHChainSane();
}


TEST_F(ExceptionBarrierTest, ExceptionBarrierHandler) {
  EXPECT_TRUE(TestExceptionExceptionBarrierHandler());
  EXPECT_TRUE(s_handled_);
}

bool TestExceptionBarrier() {
  __try {
    CrashOverExceptionBarrier();
  } __except(EXCEPTION_ACCESS_VIOLATION == GetExceptionCode() ?
                      EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) {
    TestSEHChainSane();
    return true;
  }

  return false;
}

TEST_F(ExceptionBarrierTest, HandlesAccessViolationException) {
  TestExceptionBarrier();
  EXPECT_TRUE(s_handled_);
}

void RecurseAndCrash(int depth) {
  __try {
    __try {
      if (0 == depth)
        AccessViolationCrash();
      else
        RecurseAndCrash(depth - 1);

      TestSEHChainSane();
    } __except(EXCEPTION_CONTINUE_SEARCH) {
      TestSEHChainSane();
    }
  } __finally {
    TestSEHChainSane();
  }
}

// This test exists only for comparison with TestExceptionBarrierChaining, and
// to "document" how the SEH chain is manipulated under our compiler.
// The two tests are expected to both fail if the particulars of the compiler's
// SEH implementation happens to change.
bool TestRegularChaining(EXCEPTION_REGISTRATION* top) {
  // This test relies on compiler-dependent details, notably we rely on the
  // compiler to generate a single SEH frame for the entire function, as
  // opposed to e.g. generating a separate SEH frame for each __try __except
  // statement.
  EXCEPTION_REGISTRATION* my_top = GetTopRegistration();
  if (my_top == top)
    return false;

  __try {
    // we should have the new entry in effect here still
    if (GetTopRegistration() != my_top)
      return false;
  } __except(EXCEPTION_EXECUTE_HANDLER) {
    return false;
  }

  __try {
    AccessViolationCrash();
    return false;  // not reached
  } __except(EXCEPTION_EXECUTE_HANDLER) {
    // and here
    if (GetTopRegistration() != my_top)
      return false;
  }

  __try {
    RecurseAndCrash(10);
    return false;  // not reached
  } __except(EXCEPTION_EXECUTE_HANDLER) {
    // we should have unrolled to our frame by now
    if (GetTopRegistration() != my_top)
      return false;
  }

  return true;
}

void RecurseAndCrashOverBarrier(int depth, bool crash) {
  ExceptionBarrierCustomHandler barrier;

  if (0 == depth) {
    if (crash)
      AccessViolationCrash();
  } else {
    RecurseAndCrashOverBarrier(depth - 1, crash);
  }
}

// Test that ExceptionBarrier doesn't molest the SEH chain, neither
// for regular unwinding, nor on exception unwinding cases.
//
// Note that while this test shows the ExceptionBarrier leaves the chain
// sane on both those cases, it's not clear that it does the right thing
// during first-chance exception handling. I can't think of a way to test
// that though, because first-chance exception handling is very difficult
// to hook into and to observe.
static bool TestExceptionBarrierChaining(EXCEPTION_REGISTRATION* top) {
  TestSEHChainSane();

  // This test relies on compiler-dependent details, notably we rely on the
  // compiler to generate a single SEH frame for the entire function, as
  // opposed to e.g. generating a separate SEH frame for each __try __except
  // statement.
  // Unfortunately we can't use ASSERT macros here, because they create
  // temporary objects and the compiler doesn't grok non POD objects
  // intermingled with __try and other SEH constructs.
  EXCEPTION_REGISTRATION* my_top = GetTopRegistration();
  if (my_top == top)
    return false;

  __try {
    // we should have the new entry in effect here still
    if (GetTopRegistration() != my_top)
      return false;
  } __except(EXCEPTION_EXECUTE_HANDLER) {
    return false;  // Not reached
  }

  __try {
    CrashOverExceptionBarrier();
    return false;  // Not reached
  } __except(EXCEPTION_EXECUTE_HANDLER) {
    // and here
    if (GetTopRegistration() != my_top)
      return false;
  }
  TestSEHChainSane();

  __try {
    RecurseAndCrashOverBarrier(10, true);
    return false;  // not reached
  } __except(EXCEPTION_EXECUTE_HANDLER) {
    // we should have unrolled to our frame by now
    if (GetTopRegistration() != my_top)
      return false;
  }
  TestSEHChainSane();

  __try {
    RecurseAndCrashOverBarrier(10, false);

    // we should have unrolled to our frame by now
    if (GetTopRegistration() != my_top)
      return false;
  } __except(EXCEPTION_EXECUTE_HANDLER) {
    return false;  // not reached
  }
  TestSEHChainSane();

  // success.
  return true;
}

static bool TestChaining() {
  EXCEPTION_REGISTRATION* top = GetTopRegistration();

  return TestRegularChaining(top) && TestExceptionBarrierChaining(top);
}

// Test that the SEH chain is unmolested by exception barrier, both under
// regular unroll, and under exception unroll.
TEST_F(ExceptionBarrierTest, SEHChainIsSaneAfterException) {
  EXPECT_TRUE(TestChaining());
}

}  // namespace