Home | History | Annotate | Download | only in wtf
      1 /*
      2  * Copyright (C) 2003, 2006, 2007 Apple Inc.  All rights reserved.
      3  * Copyright (C) 2007-2009 Torch Mobile, Inc.
      4  * Copyright (C) 2011 University of Szeged. All rights reserved.
      5  *
      6  * Redistribution and use in source and binary forms, with or without
      7  * modification, are permitted provided that the following conditions
      8  * are met:
      9  * 1. Redistributions of source code must retain the above copyright
     10  *    notice, this list of conditions and the following disclaimer.
     11  * 2. Redistributions in binary form must reproduce the above copyright
     12  *    notice, this list of conditions and the following disclaimer in the
     13  *    documentation and/or other materials provided with the distribution.
     14  *
     15  * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
     16  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     18  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
     19  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
     20  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
     21  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
     22  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
     23  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
     24  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
     25  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     26  */
     27 
     28 // The vprintf_stderr_common function triggers this error in the Mac build.
     29 // Feel free to remove this pragma if this file builds on Mac.
     30 // According to http://gcc.gnu.org/onlinedocs/gcc-4.2.1/gcc/Diagnostic-Pragmas.html#Diagnostic-Pragmas
     31 // we need to place this directive before any data or functions are defined.
     32 #pragma GCC diagnostic ignored "-Wmissing-format-attribute"
     33 
     34 #include "config.h"
     35 #include "Assertions.h"
     36 
     37 #include "Compiler.h"
     38 #include "OwnPtr.h"
     39 #include "PassOwnPtr.h"
     40 
     41 #include <stdio.h>
     42 #include <stdarg.h>
     43 #include <stdlib.h>
     44 #include <string.h>
     45 
     46 #if HAVE(SIGNAL_H)
     47 #include <signal.h>
     48 #endif
     49 
     50 #if USE(CF)
     51 #include <AvailabilityMacros.h>
     52 #include <CoreFoundation/CFString.h>
     53 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1080
     54 #define WTF_USE_APPLE_SYSTEM_LOG 1
     55 #include <asl.h>
     56 #endif
     57 #endif // USE(CF)
     58 
     59 #if COMPILER(MSVC)
     60 #include <crtdbg.h>
     61 #endif
     62 
     63 #if OS(WIN)
     64 #include <windows.h>
     65 #define HAVE_ISDEBUGGERPRESENT 1
     66 #endif
     67 
     68 #if OS(MACOSX) || (OS(LINUX) && !defined(__UCLIBC__))
     69 #include <cxxabi.h>
     70 #include <dlfcn.h>
     71 #include <execinfo.h>
     72 #endif
     73 
     74 #if OS(ANDROID)
     75 #include <android/log.h>
     76 #endif
     77 
     78 extern "C" {
     79 
     80 WTF_ATTRIBUTE_PRINTF(1, 0)
     81 static void vprintf_stderr_common(const char* format, va_list args)
     82 {
     83 #if USE(CF) && !OS(WIN)
     84     if (strstr(format, "%@")) {
     85         CFStringRef cfFormat = CFStringCreateWithCString(NULL, format, kCFStringEncodingUTF8);
     86 
     87 #if COMPILER(CLANG)
     88 #pragma clang diagnostic push
     89 #pragma clang diagnostic ignored "-Wformat-nonliteral"
     90 #endif
     91         CFStringRef str = CFStringCreateWithFormatAndArguments(NULL, NULL, cfFormat, args);
     92 #if COMPILER(CLANG)
     93 #pragma clang diagnostic pop
     94 #endif
     95         CFIndex length = CFStringGetMaximumSizeForEncoding(CFStringGetLength(str), kCFStringEncodingUTF8);
     96         char* buffer = (char*)malloc(length + 1);
     97 
     98         CFStringGetCString(str, buffer, length, kCFStringEncodingUTF8);
     99 
    100 #if USE(APPLE_SYSTEM_LOG)
    101         asl_log(0, 0, ASL_LEVEL_NOTICE, "%s", buffer);
    102 #endif
    103         fputs(buffer, stderr);
    104 
    105         free(buffer);
    106         CFRelease(str);
    107         CFRelease(cfFormat);
    108         return;
    109     }
    110 
    111 #if USE(APPLE_SYSTEM_LOG)
    112     va_list copyOfArgs;
    113     va_copy(copyOfArgs, args);
    114     asl_vlog(0, 0, ASL_LEVEL_NOTICE, format, copyOfArgs);
    115     va_end(copyOfArgs);
    116 #endif
    117 
    118     // Fall through to write to stderr in the same manner as other platforms.
    119 
    120 #elif OS(ANDROID)
    121     __android_log_vprint(ANDROID_LOG_WARN, "WebKit", format, args);
    122 #elif HAVE(ISDEBUGGERPRESENT)
    123     if (IsDebuggerPresent()) {
    124         size_t size = 1024;
    125 
    126         do {
    127             char* buffer = (char*)malloc(size);
    128 
    129             if (buffer == NULL)
    130                 break;
    131 
    132             if (_vsnprintf(buffer, size, format, args) != -1) {
    133                 OutputDebugStringA(buffer);
    134                 free(buffer);
    135                 break;
    136             }
    137 
    138             free(buffer);
    139             size *= 2;
    140         } while (size > 1024);
    141     }
    142 #endif
    143     vfprintf(stderr, format, args);
    144 }
    145 
    146 #if COMPILER(CLANG) || (COMPILER(GCC) && GCC_VERSION_AT_LEAST(4, 6, 0))
    147 #pragma GCC diagnostic push
    148 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
    149 #endif
    150 
    151 static void vprintf_stderr_with_prefix(const char* prefix, const char* format, va_list args)
    152 {
    153     size_t prefixLength = strlen(prefix);
    154     size_t formatLength = strlen(format);
    155     OwnPtr<char[]> formatWithPrefix = adoptArrayPtr(new char[prefixLength + formatLength + 1]);
    156     memcpy(formatWithPrefix.get(), prefix, prefixLength);
    157     memcpy(formatWithPrefix.get() + prefixLength, format, formatLength);
    158     formatWithPrefix[prefixLength + formatLength] = 0;
    159 
    160     vprintf_stderr_common(formatWithPrefix.get(), args);
    161 }
    162 
    163 static void vprintf_stderr_with_trailing_newline(const char* format, va_list args)
    164 {
    165     size_t formatLength = strlen(format);
    166     if (formatLength && format[formatLength - 1] == '\n') {
    167         vprintf_stderr_common(format, args);
    168         return;
    169     }
    170 
    171     OwnPtr<char[]> formatWithNewline = adoptArrayPtr(new char[formatLength + 2]);
    172     memcpy(formatWithNewline.get(), format, formatLength);
    173     formatWithNewline[formatLength] = '\n';
    174     formatWithNewline[formatLength + 1] = 0;
    175 
    176     vprintf_stderr_common(formatWithNewline.get(), args);
    177 }
    178 
    179 #if COMPILER(CLANG) || (COMPILER(GCC) && GCC_VERSION_AT_LEAST(4, 6, 0))
    180 #pragma GCC diagnostic pop
    181 #endif
    182 
    183 WTF_ATTRIBUTE_PRINTF(1, 2)
    184 static void printf_stderr_common(const char* format, ...)
    185 {
    186     va_list args;
    187     va_start(args, format);
    188     vprintf_stderr_common(format, args);
    189     va_end(args);
    190 }
    191 
    192 static void printCallSite(const char* file, int line, const char* function)
    193 {
    194 #if OS(WIN) && defined(_DEBUG)
    195     _CrtDbgReport(_CRT_WARN, file, line, NULL, "%s\n", function);
    196 #else
    197     // By using this format, which matches the format used by MSVC for compiler errors, developers
    198     // using Visual Studio can double-click the file/line number in the Output Window to have the
    199     // editor navigate to that line of code. It seems fine for other developers, too.
    200     printf_stderr_common("%s(%d) : %s\n", file, line, function);
    201 #endif
    202 }
    203 
    204 void WTFReportAssertionFailure(const char* file, int line, const char* function, const char* assertion)
    205 {
    206     if (assertion)
    207         printf_stderr_common("ASSERTION FAILED: %s\n", assertion);
    208     else
    209         printf_stderr_common("SHOULD NEVER BE REACHED\n");
    210     printCallSite(file, line, function);
    211 }
    212 
    213 void WTFReportAssertionFailureWithMessage(const char* file, int line, const char* function, const char* assertion, const char* format, ...)
    214 {
    215     va_list args;
    216     va_start(args, format);
    217     vprintf_stderr_with_prefix("ASSERTION FAILED: ", format, args);
    218     va_end(args);
    219     printf_stderr_common("\n%s\n", assertion);
    220     printCallSite(file, line, function);
    221 }
    222 
    223 void WTFReportArgumentAssertionFailure(const char* file, int line, const char* function, const char* argName, const char* assertion)
    224 {
    225     printf_stderr_common("ARGUMENT BAD: %s, %s\n", argName, assertion);
    226     printCallSite(file, line, function);
    227 }
    228 
    229 void WTFGetBacktrace(void** stack, int* size)
    230 {
    231 #if OS(MACOSX) || (OS(LINUX) && !defined(__UCLIBC__))
    232     *size = backtrace(stack, *size);
    233 #elif OS(WIN)
    234     // The CaptureStackBackTrace function is available in XP, but it is not defined
    235     // in the Windows Server 2003 R2 Platform SDK. So, we'll grab the function
    236     // through GetProcAddress.
    237     typedef WORD (NTAPI* RtlCaptureStackBackTraceFunc)(DWORD, DWORD, PVOID*, PDWORD);
    238     HMODULE kernel32 = ::GetModuleHandleW(L"Kernel32.dll");
    239     if (!kernel32) {
    240         *size = 0;
    241         return;
    242     }
    243     RtlCaptureStackBackTraceFunc captureStackBackTraceFunc = reinterpret_cast<RtlCaptureStackBackTraceFunc>(
    244         ::GetProcAddress(kernel32, "RtlCaptureStackBackTrace"));
    245     if (captureStackBackTraceFunc)
    246         *size = captureStackBackTraceFunc(0, *size, stack, 0);
    247     else
    248         *size = 0;
    249 #else
    250     *size = 0;
    251 #endif
    252 }
    253 
    254 void WTFReportBacktrace(int framesToShow)
    255 {
    256     static const int framesToSkip = 2;
    257     // Use alloca to allocate on the stack since this function is used in OOM situations.
    258     void** samples = static_cast<void**>(alloca((framesToShow + framesToSkip) * sizeof(void *)));
    259     int frames = framesToShow + framesToSkip;
    260 
    261     WTFGetBacktrace(samples, &frames);
    262     WTFPrintBacktrace(samples + framesToSkip, frames - framesToSkip);
    263 }
    264 
    265 FrameToNameScope::FrameToNameScope(void* addr)
    266     : m_name(0)
    267     , m_cxaDemangled(0)
    268 {
    269 #if OS(MACOSX) || (OS(LINUX) && !defined(__UCLIBC__))
    270     Dl_info info;
    271     if (!dladdr(addr, &info) || !info.dli_sname)
    272         return;
    273     const char* mangledName = info.dli_sname;
    274     if ((m_cxaDemangled = abi::__cxa_demangle(mangledName, 0, 0, 0)))
    275         m_name = m_cxaDemangled;
    276     else
    277         m_name = mangledName;
    278 #else
    279     (void)addr;
    280 #endif
    281 }
    282 
    283 FrameToNameScope::~FrameToNameScope()
    284 {
    285     free(m_cxaDemangled);
    286 }
    287 
    288 void WTFPrintBacktrace(void** stack, int size)
    289 {
    290     for (int i = 0; i < size; ++i) {
    291         FrameToNameScope frameToName(stack[i]);
    292         const int frameNumber = i + 1;
    293         if (frameToName.nullableName())
    294             printf_stderr_common("%-3d %p %s\n", frameNumber, stack[i], frameToName.nullableName());
    295         else
    296             printf_stderr_common("%-3d %p\n", frameNumber, stack[i]);
    297     }
    298 }
    299 
    300 static WTFCrashHookFunction globalHook = 0;
    301 
    302 void WTFSetCrashHook(WTFCrashHookFunction function)
    303 {
    304     globalHook = function;
    305 }
    306 
    307 void WTFInvokeCrashHook()
    308 {
    309     if (globalHook)
    310         globalHook();
    311 }
    312 
    313 #if HAVE(SIGNAL_H)
    314 static NO_RETURN void dumpBacktraceSignalHandler(int sig)
    315 {
    316     WTFReportBacktrace();
    317     exit(128 + sig);
    318 }
    319 
    320 static void installSignalHandlersForFatalErrors(void (*handler)(int))
    321 {
    322     signal(SIGILL, handler); //    4: illegal instruction (not reset when caught).
    323     signal(SIGTRAP, handler); //   5: trace trap (not reset when caught).
    324     signal(SIGFPE, handler); //    8: floating point exception.
    325     signal(SIGBUS, handler); //   10: bus error.
    326     signal(SIGSEGV, handler); //  11: segmentation violation.
    327     signal(SIGSYS, handler); //   12: bad argument to system call.
    328     signal(SIGPIPE, handler); //  13: write on a pipe with no reader.
    329     signal(SIGXCPU, handler); //  24: exceeded CPU time limit.
    330     signal(SIGXFSZ, handler); //  25: exceeded file size limit.
    331 }
    332 
    333 static void resetSignalHandlersForFatalErrors()
    334 {
    335     installSignalHandlersForFatalErrors(SIG_DFL);
    336 }
    337 #endif
    338 
    339 void WTFInstallReportBacktraceOnCrashHook()
    340 {
    341 #if HAVE(SIGNAL_H)
    342     // Needed otherwise we are going to dump the stack trace twice
    343     // in case we hit an assertion.
    344     WTFSetCrashHook(&resetSignalHandlersForFatalErrors);
    345     installSignalHandlersForFatalErrors(&dumpBacktraceSignalHandler);
    346 #endif
    347 }
    348 
    349 void WTFReportFatalError(const char* file, int line, const char* function, const char* format, ...)
    350 {
    351     va_list args;
    352     va_start(args, format);
    353     vprintf_stderr_with_prefix("FATAL ERROR: ", format, args);
    354     va_end(args);
    355     printf_stderr_common("\n");
    356     printCallSite(file, line, function);
    357 }
    358 
    359 void WTFReportError(const char* file, int line, const char* function, const char* format, ...)
    360 {
    361     va_list args;
    362     va_start(args, format);
    363     vprintf_stderr_with_prefix("ERROR: ", format, args);
    364     va_end(args);
    365     printf_stderr_common("\n");
    366     printCallSite(file, line, function);
    367 }
    368 
    369 void WTFLog(WTFLogChannel* channel, const char* format, ...)
    370 {
    371     if (channel->state != WTFLogChannelOn)
    372         return;
    373 
    374     va_list args;
    375     va_start(args, format);
    376     vprintf_stderr_with_trailing_newline(format, args);
    377     va_end(args);
    378 }
    379 
    380 void WTFLogVerbose(const char* file, int line, const char* function, WTFLogChannel* channel, const char* format, ...)
    381 {
    382     if (channel->state != WTFLogChannelOn)
    383         return;
    384 
    385     va_list args;
    386     va_start(args, format);
    387     vprintf_stderr_with_trailing_newline(format, args);
    388     va_end(args);
    389 
    390     printCallSite(file, line, function);
    391 }
    392 
    393 void WTFLogAlways(const char* format, ...)
    394 {
    395     va_list args;
    396     va_start(args, format);
    397     vprintf_stderr_with_trailing_newline(format, args);
    398     va_end(args);
    399 }
    400 
    401 } // extern "C"
    402