debug-test.c++ 12.9 KB
Newer Older
Kenton Varda's avatar
Kenton Varda committed
1 2
// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors
// Licensed under the MIT License:
3
//
Kenton Varda's avatar
Kenton Varda committed
4 5 6 7 8 9
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
10
//
Kenton Varda's avatar
Kenton Varda committed
11 12
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
13
//
Kenton Varda's avatar
Kenton Varda committed
14 15 16 17 18 19 20
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
21

Kenton Varda's avatar
Kenton Varda committed
22
#include "debug.h"
23
#include "exception.h"
24
#include <kj/compat/gtest.h>
25 26
#include <string>
#include <stdio.h>
27
#include <signal.h>
28 29
#include <errno.h>
#include <string.h>
30
#include <exception>
31
#include <stdlib.h>
32

33 34
#include "miniposix.h"

35
#if !_WIN32
36
#include <sys/wait.h>
37
#endif
38

39 40 41 42 43
#if _MSC_VER
#pragma warning(disable: 4996)
// Warns that sprintf() is buffer-overrunny. Yeah, I know, it's cool.
#endif

44
namespace kj {
45
namespace _ {  // private
46 47 48 49 50 51 52 53 54 55
namespace {

class MockException {};

class MockExceptionCallback: public ExceptionCallback {
public:
  ~MockExceptionCallback() {}

  std::string text;

56 57 58 59 60 61
  int outputPipe = -1;

  bool forkForDeathTest() {
    // This is called when exceptions are disabled.  We fork the process instead and then expect
    // the child to die.

62 63 64 65 66
#if _WIN32
    // Windows doesn't support fork() or anything like it. Just skip the test.
    return false;

#else
67
    int pipeFds[2];
Kenton Varda's avatar
Kenton Varda committed
68
    KJ_SYSCALL(pipe(pipeFds));
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
    pid_t child = fork();
    if (child == 0) {
      // This is the child!
      close(pipeFds[0]);
      outputPipe = pipeFds[1];
      return true;
    } else {
      close(pipeFds[1]);

      // Read child error messages into our local buffer.
      char buf[1024];
      for (;;) {
        ssize_t n = read(pipeFds[0], buf, sizeof(buf));
        if (n < 0) {
          if (errno == EINTR) {
            continue;
          } else {
            break;
          }
        } else if (n == 0) {
          break;
        } else {
          text.append(buf, n);
        }
      }

      close(pipeFds[0]);

      // Get exit status.
      int status;
99
      KJ_SYSCALL(waitpid(child, &status, 0));
100 101 102 103 104 105

      EXPECT_TRUE(WIFEXITED(status));
      EXPECT_EQ(74, WEXITSTATUS(status));

      return false;
    }
106
#endif  // _WIN32, else
107 108 109 110 111 112 113 114
  }

  void flush() {
    if (outputPipe != -1) {
      const char* pos = &*text.begin();
      const char* end = pos + text.size();

      while (pos < end) {
115
        miniposix::ssize_t n = miniposix::write(outputPipe, pos, end - pos);
116 117 118 119 120 121 122 123 124 125 126 127 128 129
        if (n < 0) {
          if (errno == EINTR) {
            continue;
          } else {
            break;  // Give up on error.
          }
        }
        pos += n;
      }

      text.clear();
    }
  }

130 131
  void onRecoverableException(Exception&& exception) override {
    text += "recoverable exception: ";
132
    auto what = str(exception);
133 134
    // Discard the stack trace.
    const char* end = strstr(what.cStr(), "\nstack: ");
135
    if (end == nullptr) {
136
      text += what.cStr();
137
    } else {
138
      text.append(what.cStr(), end);
139
    }
140
    text += '\n';
141
    flush();
142 143 144 145
  }

  void onFatalException(Exception&& exception) override {
    text += "fatal exception: ";
146
    auto what = str(exception);
147 148
    // Discard the stack trace.
    const char* end = strstr(what.cStr(), "\nstack: ");
149
    if (end == nullptr) {
150
      text += what.cStr();
151
    } else {
152
      text.append(what.cStr(), end);
153
    }
154
    text += '\n';
155 156 157 158 159 160 161 162 163
    flush();
#if KJ_NO_EXCEPTIONS
    if (outputPipe >= 0) {
      // This is a child process.  We got what we want, now exit quickly without writing any
      // additional messages, with a status code that the parent will interpret as "exited in the
      // way we expected".
      _exit(74);
    }
#else
164
    throw MockException();
165
#endif
166 167
  }

168 169
  void logMessage(LogSeverity severity, const char* file, int line, int contextDepth,
                  String&& text) override {
170
    this->text += "log message: ";
171
    text = str(file, ":", line, ":+", contextDepth, ": ", severity, ": ", mv(text));
172 173 174 175
    this->text.append(text.begin(), text.end());
  }
};

176 177 178
#if KJ_NO_EXCEPTIONS
#define EXPECT_FATAL(code) if (mockCallback.forkForDeathTest()) { code; abort(); }
#else
179 180 181 182
#define EXPECT_FATAL(code) \
  try { code; KJ_FAIL_EXPECT("expected exception"); } \
  catch (MockException e) {} \
  catch (...) { KJ_FAIL_EXPECT("wrong exception"); }
183 184
#endif

185
std::string fileLine(std::string file, int line) {
186 187
  file = trimSourceFilename(file.c_str()).cStr();

188 189 190 191 192 193 194
  file += ':';
  char buffer[32];
  sprintf(buffer, "%d", line);
  file += buffer;
  return file;
}

195
TEST(Debug, Log) {
196 197 198
  MockExceptionCallback mockCallback;
  int line;

199
  KJ_LOG(WARNING, "Hello world!"); line = __LINE__;
200
  EXPECT_EQ("log message: " + fileLine(__FILE__, line) + ":+0: warning: Hello world!\n",
201 202 203 204 205 206
            mockCallback.text);
  mockCallback.text.clear();

  int i = 123;
  const char* str = "foo";

207
  KJ_LOG(ERROR, i, str); line = __LINE__;
208
  EXPECT_EQ("log message: " + fileLine(__FILE__, line) + ":+0: error: i = 123; str = foo\n",
209 210 211
            mockCallback.text);
  mockCallback.text.clear();

212
  KJ_DBG("Some debug text."); line = __LINE__;
213
  EXPECT_EQ("log message: " + fileLine(__FILE__, line) + ":+0: debug: Some debug text.\n",
214 215 216 217 218 219 220 221 222
            mockCallback.text);
  mockCallback.text.clear();

  // INFO logging is disabled by default.
  KJ_LOG(INFO, "Info."); line = __LINE__;
  EXPECT_EQ("", mockCallback.text);
  mockCallback.text.clear();

  // Enable it.
Kenton Varda's avatar
Kenton Varda committed
223
  Debug::setLogLevel(Debug::Severity::INFO);
224
  KJ_LOG(INFO, "Some text."); line = __LINE__;
225
  EXPECT_EQ("log message: " + fileLine(__FILE__, line) + ":+0: info: Some text.\n",
226 227 228 229
            mockCallback.text);
  mockCallback.text.clear();

  // Back to default.
Kenton Varda's avatar
Kenton Varda committed
230
  Debug::setLogLevel(Debug::Severity::WARNING);
231

232
  KJ_ASSERT(1 == 1);
233
  EXPECT_FATAL(KJ_ASSERT(1 == 2)); line = __LINE__;
234
  EXPECT_EQ("fatal exception: " + fileLine(__FILE__, line) + ": failed: expected "
235 236 237
            "1 == 2\n", mockCallback.text);
  mockCallback.text.clear();

238
  KJ_ASSERT(1 == 1) {
239
    ADD_FAILURE() << "Shouldn't call recovery code when check passes.";
240
    break;
241 242 243
  };

  bool recovered = false;
244
  KJ_ASSERT(1 == 2, "1 is not 2") { recovered = true; break; } line = __LINE__;
245
  EXPECT_EQ("recoverable exception: " + fileLine(__FILE__, line) + ": failed: expected "
246 247 248 249
            "1 == 2; 1 is not 2\n", mockCallback.text);
  EXPECT_TRUE(recovered);
  mockCallback.text.clear();

250
  EXPECT_FATAL(KJ_ASSERT(1 == 2, i, "hi", str)); line = __LINE__;
251
  EXPECT_EQ("fatal exception: " + fileLine(__FILE__, line) + ": failed: expected "
252 253 254
            "1 == 2; i = 123; hi; str = foo\n", mockCallback.text);
  mockCallback.text.clear();

255
  EXPECT_FATAL(KJ_REQUIRE(1 == 2, i, "hi", str)); line = __LINE__;
256
  EXPECT_EQ("fatal exception: " + fileLine(__FILE__, line) + ": failed: expected "
257 258
            "1 == 2; i = 123; hi; str = foo\n", mockCallback.text);
  mockCallback.text.clear();
259

260
  EXPECT_FATAL(KJ_FAIL_ASSERT("foo")); line = __LINE__;
261
  EXPECT_EQ("fatal exception: " + fileLine(__FILE__, line) + ": failed: foo\n",
262 263 264 265
            mockCallback.text);
  mockCallback.text.clear();
}

266 267 268 269 270 271
TEST(Debug, Exception) {
  int i = 123;

  int line = __LINE__; Exception exception = KJ_EXCEPTION(DISCONNECTED, "foo", i);

  EXPECT_EQ(Exception::Type::DISCONNECTED, exception.getType());
272
  EXPECT_TRUE(kj::StringPtr(__FILE__).endsWith(exception.getFile()));
273 274 275 276
  EXPECT_EQ(line, exception.getLine());
  EXPECT_EQ("foo; i = 123", exception.getDescription());
}

277
TEST(Debug, Catch) {
278 279
  int line;

280 281 282 283 284 285 286 287
  {
    // Catch recoverable as kj::Exception.
    Maybe<Exception> exception = kj::runCatchingExceptions([&](){
      line = __LINE__; KJ_FAIL_ASSERT("foo") { break; }
    });

    KJ_IF_MAYBE(e, exception) {
      String what = str(*e);
288 289 290 291
      KJ_IF_MAYBE(eol, what.findFirst('\n')) {
        what = kj::str(what.slice(0, *eol));
      }
      std::string text(what.cStr());
292
      EXPECT_EQ(fileLine(__FILE__, line) + ": failed: foo", text);
293 294 295
    } else {
      ADD_FAILURE() << "Expected exception.";
    }
296 297
  }

298
#if !KJ_NO_EXCEPTIONS
299 300 301 302 303 304 305 306
  {
    // Catch fatal as kj::Exception.
    Maybe<Exception> exception = kj::runCatchingExceptions([&](){
      line = __LINE__; KJ_FAIL_ASSERT("foo");
    });

    KJ_IF_MAYBE(e, exception) {
      String what = str(*e);
307 308 309 310
      KJ_IF_MAYBE(eol, what.findFirst('\n')) {
        what = kj::str(what.slice(0, *eol));
      }
      std::string text(what.cStr());
311
      EXPECT_EQ(fileLine(__FILE__, line) + ": failed: foo", text);
312 313 314 315 316 317 318 319 320 321 322
    } else {
      ADD_FAILURE() << "Expected exception.";
    }
  }

  {
    // Catch as std::exception.
    try {
      line = __LINE__; KJ_FAIL_ASSERT("foo");
      ADD_FAILURE() << "Expected exception.";
    } catch (const std::exception& e) {
323
      kj::StringPtr what = e.what();
Kenton Varda's avatar
Kenton Varda committed
324
      std::string text;
325 326 327 328 329
      KJ_IF_MAYBE(eol, what.findFirst('\n')) {
        text.assign(what.cStr(), *eol);
      } else {
        text.assign(what.cStr());
      }
330
      EXPECT_EQ(fileLine(__FILE__, line) + ": failed: foo", text);
331
    }
332
  }
333
#endif
334 335
}

336 337 338 339 340
int mockSyscall(int i, int error = 0) {
  errno = error;
  return i;
}

341
TEST(Debug, Syscall) {
342 343 344 345 346 347
  MockExceptionCallback mockCallback;
  int line;

  int i = 123;
  const char* str = "foo";

348 349 350 351 352
  KJ_SYSCALL(mockSyscall(0));
  KJ_SYSCALL(mockSyscall(1));

  EXPECT_FATAL(KJ_SYSCALL(mockSyscall(-1, EBADF), i, "bar", str)); line = __LINE__;
  EXPECT_EQ("fatal exception: " + fileLine(__FILE__, line) +
353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371
            ": failed: mockSyscall(-1, EBADF): " + strerror(EBADF) +
            "; i = 123; bar; str = foo\n", mockCallback.text);
  mockCallback.text.clear();

  EXPECT_FATAL(KJ_SYSCALL(mockSyscall(-1, ECONNRESET), i, "bar", str)); line = __LINE__;
  EXPECT_EQ("fatal exception: " + fileLine(__FILE__, line) +
            ": disconnected: mockSyscall(-1, ECONNRESET): " + strerror(ECONNRESET) +
            "; i = 123; bar; str = foo\n", mockCallback.text);
  mockCallback.text.clear();

  EXPECT_FATAL(KJ_SYSCALL(mockSyscall(-1, ENOMEM), i, "bar", str)); line = __LINE__;
  EXPECT_EQ("fatal exception: " + fileLine(__FILE__, line) +
            ": overloaded: mockSyscall(-1, ENOMEM): " + strerror(ENOMEM) +
            "; i = 123; bar; str = foo\n", mockCallback.text);
  mockCallback.text.clear();

  EXPECT_FATAL(KJ_SYSCALL(mockSyscall(-1, ENOSYS), i, "bar", str)); line = __LINE__;
  EXPECT_EQ("fatal exception: " + fileLine(__FILE__, line) +
            ": unimplemented: mockSyscall(-1, ENOSYS): " + strerror(ENOSYS) +
372
            "; i = 123; bar; str = foo\n", mockCallback.text);
373 374 375 376
  mockCallback.text.clear();

  int result = 0;
  bool recovered = false;
377 378
  KJ_SYSCALL(result = mockSyscall(-2, EBADF), i, "bar", str) { recovered = true; break; } line = __LINE__;
  EXPECT_EQ("recoverable exception: " + fileLine(__FILE__, line) +
379
            ": failed: mockSyscall(-2, EBADF): " + strerror(EBADF) +
380
            "; i = 123; bar; str = foo\n", mockCallback.text);
381
  EXPECT_EQ(-2, result);
382
  EXPECT_TRUE(recovered);
383 384
}

385
TEST(Debug, Context) {
386 387 388
  MockExceptionCallback mockCallback;

  {
389
    KJ_CONTEXT("foo"); int cline = __LINE__;
390

391 392 393 394 395 396
    KJ_LOG(WARNING, "blah"); int line = __LINE__;
    EXPECT_EQ("log message: " + fileLine(__FILE__, cline) + ":+0: context: foo\n"
              "log message: " + fileLine(__FILE__, line) + ":+1: warning: blah\n",
              mockCallback.text);
    mockCallback.text.clear();

397
    EXPECT_FATAL(KJ_FAIL_ASSERT("bar")); line = __LINE__;
398
    EXPECT_EQ("fatal exception: " + fileLine(__FILE__, cline) + ": context: foo\n"
399
              + fileLine(__FILE__, line) + ": failed: bar\n",
400 401 402 403 404 405
              mockCallback.text);
    mockCallback.text.clear();

    {
      int i = 123;
      const char* str = "qux";
406
      KJ_CONTEXT("baz", i, "corge", str); int cline2 = __LINE__;
407
      EXPECT_FATAL(KJ_FAIL_ASSERT("bar")); line = __LINE__;
408 409 410

      EXPECT_EQ("fatal exception: " + fileLine(__FILE__, cline) + ": context: foo\n"
                + fileLine(__FILE__, cline2) + ": context: baz; i = 123; corge; str = qux\n"
411
                + fileLine(__FILE__, line) + ": failed: bar\n",
412 413 414 415 416
                mockCallback.text);
      mockCallback.text.clear();
    }

    {
417
      KJ_CONTEXT("grault"); int cline2 = __LINE__;
418
      EXPECT_FATAL(KJ_FAIL_ASSERT("bar")); line = __LINE__;
419 420 421

      EXPECT_EQ("fatal exception: " + fileLine(__FILE__, cline) + ": context: foo\n"
                + fileLine(__FILE__, cline2) + ": context: grault\n"
422
                + fileLine(__FILE__, line) + ": failed: bar\n",
423 424 425 426 427 428
                mockCallback.text);
      mockCallback.text.clear();
    }
  }
}

429
}  // namespace
430
}  // namespace _ (private)
431
}  // namespace kj