michael@0: // Copyright (c) 2011, Google Inc. michael@0: // All rights reserved. michael@0: // michael@0: // Redistribution and use in source and binary forms, with or without michael@0: // modification, are permitted provided that the following conditions are michael@0: // met: michael@0: // michael@0: // * Redistributions of source code must retain the above copyright michael@0: // notice, this list of conditions and the following disclaimer. michael@0: // * Redistributions in binary form must reproduce the above michael@0: // copyright notice, this list of conditions and the following disclaimer michael@0: // in the documentation and/or other materials provided with the michael@0: // distribution. michael@0: // * Neither the name of Google Inc. nor the names of its michael@0: // contributors may be used to endorse or promote products derived from michael@0: // this software without specific prior written permission. michael@0: // michael@0: // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS michael@0: // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT michael@0: // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR michael@0: // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT michael@0: // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, michael@0: // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT michael@0: // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, michael@0: // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY michael@0: // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT michael@0: // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE michael@0: // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. michael@0: michael@0: #define VERBOSE 0 michael@0: michael@0: #if VERBOSE michael@0: static bool gDebugLog = true; michael@0: #else michael@0: static bool gDebugLog = false; michael@0: #endif michael@0: michael@0: #define DEBUGLOG if (gDebugLog) fprintf michael@0: #define IGNORE_DEBUGGER "BREAKPAD_IGNORE_DEBUGGER" michael@0: michael@0: #import "client/ios/Breakpad.h" michael@0: michael@0: #import michael@0: #include michael@0: #include michael@0: #include michael@0: michael@0: #import "client/mac/crash_generation/ConfigFile.h" michael@0: #import "client/mac/handler/exception_handler.h" michael@0: #import "client/mac/handler/minidump_generator.h" michael@0: #import "client/mac/sender/uploader.h" michael@0: #import "common/mac/SimpleStringDictionary.h" michael@0: #import "client/ios/handler/ios_exception_minidump_generator.h" michael@0: #import "client/mac/handler/protected_memory_allocator.h" michael@0: michael@0: #ifndef __EXCEPTIONS michael@0: // This file uses C++ try/catch (but shouldn't). Duplicate the macros from michael@0: // allowing this file to work properly with michael@0: // exceptions disabled even when other C++ libraries are used. #undef the try michael@0: // and catch macros first in case libstdc++ is in use and has already provided michael@0: // its own definitions. michael@0: #undef try michael@0: #define try if (true) michael@0: #undef catch michael@0: #define catch(X) if (false) michael@0: #endif // __EXCEPTIONS michael@0: michael@0: using google_breakpad::ConfigFile; michael@0: using google_breakpad::EnsureDirectoryPathExists; michael@0: using google_breakpad::KeyValueEntry; michael@0: using google_breakpad::SimpleStringDictionary; michael@0: using google_breakpad::SimpleStringDictionaryIterator; michael@0: michael@0: //============================================================================= michael@0: // We want any memory allocations which are used by breakpad during the michael@0: // exception handling process (after a crash has happened) to be read-only michael@0: // to prevent them from being smashed before a crash occurs. Unfortunately michael@0: // we cannot protect against smashes to our exception handling thread's michael@0: // stack. michael@0: // michael@0: // NOTE: Any memory allocations which are not used during the exception michael@0: // handling process may be allocated in the normal ways. michael@0: // michael@0: // The ProtectedMemoryAllocator class provides an Allocate() method which michael@0: // we'll using in conjunction with placement operator new() to control michael@0: // allocation of C++ objects. Note that we don't use operator delete() michael@0: // but instead call the objects destructor directly: object->~ClassName(); michael@0: // michael@0: ProtectedMemoryAllocator *gMasterAllocator = NULL; michael@0: ProtectedMemoryAllocator *gKeyValueAllocator = NULL; michael@0: ProtectedMemoryAllocator *gBreakpadAllocator = NULL; michael@0: michael@0: // Mutex for thread-safe access to the key/value dictionary used by breakpad. michael@0: // It's a global instead of an instance variable of Breakpad michael@0: // since it can't live in a protected memory area. michael@0: pthread_mutex_t gDictionaryMutex; michael@0: michael@0: //============================================================================= michael@0: // Stack-based object for thread-safe access to a memory-protected region. michael@0: // It's assumed that normally the memory block (allocated by the allocator) michael@0: // is protected (read-only). Creating a stack-based instance of michael@0: // ProtectedMemoryLocker will unprotect this block after taking the lock. michael@0: // Its destructor will first re-protect the memory then release the lock. michael@0: class ProtectedMemoryLocker { michael@0: public: michael@0: // allocator may be NULL, in which case no Protect() or Unprotect() calls michael@0: // will be made, but a lock will still be taken michael@0: ProtectedMemoryLocker(pthread_mutex_t *mutex, michael@0: ProtectedMemoryAllocator *allocator) michael@0: : mutex_(mutex), allocator_(allocator) { michael@0: // Lock the mutex michael@0: assert(pthread_mutex_lock(mutex_) == 0); michael@0: michael@0: // Unprotect the memory michael@0: if (allocator_ ) { michael@0: allocator_->Unprotect(); michael@0: } michael@0: } michael@0: michael@0: ~ProtectedMemoryLocker() { michael@0: // First protect the memory michael@0: if (allocator_) { michael@0: allocator_->Protect(); michael@0: } michael@0: michael@0: // Then unlock the mutex michael@0: assert(pthread_mutex_unlock(mutex_) == 0); michael@0: }; michael@0: michael@0: private: michael@0: // Keep anybody from ever creating one of these things not on the stack. michael@0: ProtectedMemoryLocker() { } michael@0: ProtectedMemoryLocker(const ProtectedMemoryLocker&); michael@0: ProtectedMemoryLocker & operator=(ProtectedMemoryLocker&); michael@0: michael@0: pthread_mutex_t *mutex_; michael@0: ProtectedMemoryAllocator *allocator_; michael@0: }; michael@0: michael@0: //============================================================================= michael@0: class Breakpad { michael@0: public: michael@0: // factory method michael@0: static Breakpad *Create(NSDictionary *parameters) { michael@0: // Allocate from our special allocation pool michael@0: Breakpad *breakpad = michael@0: new (gBreakpadAllocator->Allocate(sizeof(Breakpad))) michael@0: Breakpad(); michael@0: michael@0: if (!breakpad) michael@0: return NULL; michael@0: michael@0: if (!breakpad->Initialize(parameters)) { michael@0: // Don't use operator delete() here since we allocated from special pool michael@0: breakpad->~Breakpad(); michael@0: return NULL; michael@0: } michael@0: michael@0: return breakpad; michael@0: } michael@0: michael@0: ~Breakpad(); michael@0: michael@0: void SetKeyValue(NSString *key, NSString *value); michael@0: NSString *KeyValue(NSString *key); michael@0: void RemoveKeyValue(NSString *key); michael@0: NSString *NextCrashReportToUpload(); michael@0: void UploadNextReport(); michael@0: void UploadData(NSData *data, NSString *name, michael@0: NSDictionary *server_parameters); michael@0: NSDictionary *GenerateReport(NSDictionary *server_parameters); michael@0: michael@0: private: michael@0: Breakpad() michael@0: : handler_(NULL), michael@0: config_params_(NULL) {} michael@0: michael@0: bool Initialize(NSDictionary *parameters); michael@0: michael@0: bool ExtractParameters(NSDictionary *parameters); michael@0: michael@0: // Dispatches to HandleMinidump() michael@0: static bool HandleMinidumpCallback(const char *dump_dir, michael@0: const char *minidump_id, michael@0: void *context, bool succeeded); michael@0: michael@0: bool HandleMinidump(const char *dump_dir, michael@0: const char *minidump_id); michael@0: michael@0: // NSException handler michael@0: static void UncaughtExceptionHandler(NSException *exception); michael@0: michael@0: // Handle an uncaught NSException. michael@0: void HandleUncaughtException(NSException *exception); michael@0: michael@0: // Since ExceptionHandler (w/o namespace) is defined as typedef in OSX's michael@0: // MachineExceptions.h, we have to explicitly name the handler. michael@0: google_breakpad::ExceptionHandler *handler_; // The actual handler (STRONG) michael@0: michael@0: SimpleStringDictionary *config_params_; // Create parameters (STRONG) michael@0: michael@0: ConfigFile config_file_; michael@0: michael@0: // A static reference to the current Breakpad instance. Used for handling michael@0: // NSException. michael@0: static Breakpad *current_breakpad_; michael@0: }; michael@0: michael@0: Breakpad *Breakpad::current_breakpad_ = NULL; michael@0: michael@0: #pragma mark - michael@0: #pragma mark Helper functions michael@0: michael@0: //============================================================================= michael@0: // Helper functions michael@0: michael@0: //============================================================================= michael@0: static BOOL IsDebuggerActive() { michael@0: BOOL result = NO; michael@0: NSUserDefaults *stdDefaults = [NSUserDefaults standardUserDefaults]; michael@0: michael@0: // We check both defaults and the environment variable here michael@0: michael@0: BOOL ignoreDebugger = [stdDefaults boolForKey:@IGNORE_DEBUGGER]; michael@0: michael@0: if (!ignoreDebugger) { michael@0: char *ignoreDebuggerStr = getenv(IGNORE_DEBUGGER); michael@0: ignoreDebugger = michael@0: (ignoreDebuggerStr ? strtol(ignoreDebuggerStr, NULL, 10) : 0) != 0; michael@0: } michael@0: michael@0: if (!ignoreDebugger) { michael@0: pid_t pid = getpid(); michael@0: int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PID, pid}; michael@0: int mibSize = sizeof(mib) / sizeof(int); michael@0: size_t actualSize; michael@0: michael@0: if (sysctl(mib, mibSize, NULL, &actualSize, NULL, 0) == 0) { michael@0: struct kinfo_proc *info = (struct kinfo_proc *)malloc(actualSize); michael@0: michael@0: if (info) { michael@0: // This comes from looking at the Darwin xnu Kernel michael@0: if (sysctl(mib, mibSize, info, &actualSize, NULL, 0) == 0) michael@0: result = (info->kp_proc.p_flag & P_TRACED) ? YES : NO; michael@0: michael@0: free(info); michael@0: } michael@0: } michael@0: } michael@0: michael@0: return result; michael@0: } michael@0: michael@0: //============================================================================= michael@0: bool Breakpad::HandleMinidumpCallback(const char *dump_dir, michael@0: const char *minidump_id, michael@0: void *context, bool succeeded) { michael@0: Breakpad *breakpad = (Breakpad *)context; michael@0: michael@0: // If our context is damaged or something, just return false to indicate that michael@0: // the handler should continue without us. michael@0: if (!breakpad || !succeeded) michael@0: return false; michael@0: michael@0: return breakpad->HandleMinidump(dump_dir, minidump_id); michael@0: } michael@0: michael@0: //============================================================================= michael@0: void Breakpad::UncaughtExceptionHandler(NSException *exception) { michael@0: NSSetUncaughtExceptionHandler(NULL); michael@0: if (current_breakpad_) { michael@0: current_breakpad_->HandleUncaughtException(exception); michael@0: } michael@0: } michael@0: michael@0: //============================================================================= michael@0: #pragma mark - michael@0: michael@0: //============================================================================= michael@0: bool Breakpad::Initialize(NSDictionary *parameters) { michael@0: // Initialize michael@0: current_breakpad_ = this; michael@0: config_params_ = NULL; michael@0: handler_ = NULL; michael@0: michael@0: // Gather any user specified parameters michael@0: if (!ExtractParameters(parameters)) { michael@0: return false; michael@0: } michael@0: michael@0: // Check for debugger michael@0: if (IsDebuggerActive()) { michael@0: DEBUGLOG(stderr, "Debugger is active: Not installing handler\n"); michael@0: return true; michael@0: } michael@0: michael@0: // Create the handler (allocating it in our special protected pool) michael@0: handler_ = michael@0: new (gBreakpadAllocator->Allocate( michael@0: sizeof(google_breakpad::ExceptionHandler))) michael@0: google_breakpad::ExceptionHandler( michael@0: config_params_->GetValueForKey(BREAKPAD_DUMP_DIRECTORY), michael@0: 0, &HandleMinidumpCallback, this, true, 0); michael@0: NSSetUncaughtExceptionHandler(&Breakpad::UncaughtExceptionHandler); michael@0: return true; michael@0: } michael@0: michael@0: //============================================================================= michael@0: Breakpad::~Breakpad() { michael@0: NSSetUncaughtExceptionHandler(NULL); michael@0: current_breakpad_ = NULL; michael@0: // Note that we don't use operator delete() on these pointers, michael@0: // since they were allocated by ProtectedMemoryAllocator objects. michael@0: // michael@0: if (config_params_) { michael@0: config_params_->~SimpleStringDictionary(); michael@0: } michael@0: michael@0: if (handler_) michael@0: handler_->~ExceptionHandler(); michael@0: } michael@0: michael@0: //============================================================================= michael@0: bool Breakpad::ExtractParameters(NSDictionary *parameters) { michael@0: NSString *serverType = [parameters objectForKey:@BREAKPAD_SERVER_TYPE]; michael@0: NSString *display = [parameters objectForKey:@BREAKPAD_PRODUCT_DISPLAY]; michael@0: NSString *product = [parameters objectForKey:@BREAKPAD_PRODUCT]; michael@0: NSString *version = [parameters objectForKey:@BREAKPAD_VERSION]; michael@0: NSString *urlStr = [parameters objectForKey:@BREAKPAD_URL]; michael@0: NSString *vendor = michael@0: [parameters objectForKey:@BREAKPAD_VENDOR]; michael@0: NSString *dumpSubdirectory = michael@0: [parameters objectForKey:@BREAKPAD_DUMP_DIRECTORY]; michael@0: michael@0: NSDictionary *serverParameters = michael@0: [parameters objectForKey:@BREAKPAD_SERVER_PARAMETER_DICT]; michael@0: michael@0: if (!product) michael@0: product = [parameters objectForKey:@"CFBundleName"]; michael@0: michael@0: if (!display) { michael@0: display = [parameters objectForKey:@"CFBundleDisplayName"]; michael@0: if (!display) { michael@0: display = product; michael@0: } michael@0: } michael@0: michael@0: if (!version) michael@0: version = [parameters objectForKey:@"CFBundleVersion"]; michael@0: michael@0: if (!vendor) { michael@0: vendor = @"Vendor not specified"; michael@0: } michael@0: michael@0: if (!dumpSubdirectory) { michael@0: NSString *cachePath = michael@0: [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, michael@0: NSUserDomainMask, michael@0: YES) michael@0: objectAtIndex:0]; michael@0: dumpSubdirectory = michael@0: [cachePath stringByAppendingPathComponent:@kDefaultLibrarySubdirectory]; michael@0: michael@0: EnsureDirectoryPathExists(dumpSubdirectory); michael@0: } michael@0: michael@0: // The product, version, and URL are required values. michael@0: if (![product length]) { michael@0: DEBUGLOG(stderr, "Missing required product key.\n"); michael@0: return false; michael@0: } michael@0: michael@0: if (![version length]) { michael@0: DEBUGLOG(stderr, "Missing required version key.\n"); michael@0: return false; michael@0: } michael@0: michael@0: if (![urlStr length]) { michael@0: DEBUGLOG(stderr, "Missing required URL key.\n"); michael@0: return false; michael@0: } michael@0: michael@0: config_params_ = michael@0: new (gKeyValueAllocator->Allocate(sizeof(SimpleStringDictionary)) ) michael@0: SimpleStringDictionary(); michael@0: michael@0: SimpleStringDictionary &dictionary = *config_params_; michael@0: michael@0: dictionary.SetKeyValue(BREAKPAD_SERVER_TYPE, [serverType UTF8String]); michael@0: dictionary.SetKeyValue(BREAKPAD_PRODUCT_DISPLAY, [display UTF8String]); michael@0: dictionary.SetKeyValue(BREAKPAD_PRODUCT, [product UTF8String]); michael@0: dictionary.SetKeyValue(BREAKPAD_VERSION, [version UTF8String]); michael@0: dictionary.SetKeyValue(BREAKPAD_URL, [urlStr UTF8String]); michael@0: dictionary.SetKeyValue(BREAKPAD_VENDOR, [vendor UTF8String]); michael@0: dictionary.SetKeyValue(BREAKPAD_DUMP_DIRECTORY, michael@0: [dumpSubdirectory UTF8String]); michael@0: michael@0: struct timeval tv; michael@0: gettimeofday(&tv, NULL); michael@0: char timeStartedString[32]; michael@0: sprintf(timeStartedString, "%zd", tv.tv_sec); michael@0: dictionary.SetKeyValue(BREAKPAD_PROCESS_START_TIME, timeStartedString); michael@0: michael@0: if (serverParameters) { michael@0: // For each key-value pair, call BreakpadAddUploadParameter() michael@0: NSEnumerator *keyEnumerator = [serverParameters keyEnumerator]; michael@0: NSString *aParameter; michael@0: while ((aParameter = [keyEnumerator nextObject])) { michael@0: BreakpadAddUploadParameter(this, aParameter, michael@0: [serverParameters objectForKey:aParameter]); michael@0: } michael@0: } michael@0: return true; michael@0: } michael@0: michael@0: //============================================================================= michael@0: void Breakpad::SetKeyValue(NSString *key, NSString *value) { michael@0: // We allow nil values. This is the same as removing the keyvalue. michael@0: if (!config_params_ || !key) michael@0: return; michael@0: michael@0: config_params_->SetKeyValue([key UTF8String], [value UTF8String]); michael@0: } michael@0: michael@0: //============================================================================= michael@0: NSString *Breakpad::KeyValue(NSString *key) { michael@0: if (!config_params_ || !key) michael@0: return nil; michael@0: michael@0: const char *value = config_params_->GetValueForKey([key UTF8String]); michael@0: return value ? [NSString stringWithUTF8String:value] : nil; michael@0: } michael@0: michael@0: //============================================================================= michael@0: void Breakpad::RemoveKeyValue(NSString *key) { michael@0: if (!config_params_ || !key) return; michael@0: michael@0: config_params_->RemoveKey([key UTF8String]); michael@0: } michael@0: michael@0: //============================================================================= michael@0: NSString *Breakpad::NextCrashReportToUpload() { michael@0: NSString *directory = KeyValue(@BREAKPAD_DUMP_DIRECTORY); michael@0: if (!directory) michael@0: return nil; michael@0: NSArray *dirContents = [[NSFileManager defaultManager] michael@0: contentsOfDirectoryAtPath:directory error:nil]; michael@0: NSArray *configs = [dirContents filteredArrayUsingPredicate:[NSPredicate michael@0: predicateWithFormat:@"self BEGINSWITH 'Config-'"]]; michael@0: NSString *config = [configs lastObject]; michael@0: if (!config) michael@0: return nil; michael@0: return [NSString stringWithFormat:@"%@/%@", directory, config]; michael@0: } michael@0: michael@0: //============================================================================= michael@0: void Breakpad::UploadNextReport() { michael@0: NSString *configFile = NextCrashReportToUpload(); michael@0: if (configFile) { michael@0: Uploader *uploader = [[[Uploader alloc] michael@0: initWithConfigFile:[configFile UTF8String]] autorelease]; michael@0: if (uploader) michael@0: [uploader report]; michael@0: } michael@0: } michael@0: michael@0: //============================================================================= michael@0: void Breakpad::UploadData(NSData *data, NSString *name, michael@0: NSDictionary *server_parameters) { michael@0: NSMutableDictionary *config = [NSMutableDictionary dictionary]; michael@0: michael@0: SimpleStringDictionaryIterator it(*config_params_); michael@0: while (const KeyValueEntry *next = it.Next()) { michael@0: [config setValue:[NSString stringWithUTF8String:next->GetValue()] michael@0: forKey:[NSString stringWithUTF8String:next->GetKey()]]; michael@0: } michael@0: michael@0: Uploader *uploader = michael@0: [[[Uploader alloc] initWithConfig:config] autorelease]; michael@0: for (NSString *key in server_parameters) { michael@0: [uploader addServerParameter:[server_parameters objectForKey:key] michael@0: forKey:key]; michael@0: } michael@0: [uploader uploadData:data name:name]; michael@0: } michael@0: michael@0: //============================================================================= michael@0: NSDictionary *Breakpad::GenerateReport(NSDictionary *server_parameters) { michael@0: NSString *dumpDirAsNSString = KeyValue(@BREAKPAD_DUMP_DIRECTORY); michael@0: if (!dumpDirAsNSString) michael@0: return nil; michael@0: const char *dumpDir = [dumpDirAsNSString UTF8String]; michael@0: michael@0: google_breakpad::MinidumpGenerator generator(mach_task_self(), michael@0: MACH_PORT_NULL); michael@0: std::string dumpId; michael@0: std::string dumpFilename = generator.UniqueNameInDirectory(dumpDir, &dumpId); michael@0: bool success = generator.Write(dumpFilename.c_str()); michael@0: if (!success) michael@0: return nil; michael@0: michael@0: SimpleStringDictionary params = *config_params_; michael@0: for (NSString *key in server_parameters) { michael@0: params.SetKeyValue([key UTF8String], michael@0: [[server_parameters objectForKey:key] UTF8String]); michael@0: } michael@0: ConfigFile config_file; michael@0: config_file.WriteFile(dumpDir, ¶ms, dumpDir, dumpId.c_str()); michael@0: michael@0: // Handle results. michael@0: NSMutableDictionary *result = [NSMutableDictionary dictionary]; michael@0: NSString *dumpFullPath = [dumpDirAsNSString stringByAppendingPathComponent: michael@0: [NSString stringWithUTF8String:dumpFilename.c_str()]]; michael@0: [result setValue:dumpFullPath michael@0: forKey:@BREAKPAD_OUTPUT_DUMP_FILE]; michael@0: [result setValue:[NSString stringWithUTF8String:config_file.GetFilePath()] michael@0: forKey:@BREAKPAD_OUTPUT_CONFIG_FILE]; michael@0: return result; michael@0: } michael@0: michael@0: //============================================================================= michael@0: bool Breakpad::HandleMinidump(const char *dump_dir, michael@0: const char *minidump_id) { michael@0: DEBUGLOG(stderr, "Breakpad: a minidump has been created.\n"); michael@0: michael@0: config_file_.WriteFile(dump_dir, michael@0: config_params_, michael@0: dump_dir, michael@0: minidump_id); michael@0: michael@0: // Return true here to indicate that we've processed things as much as we michael@0: // want. michael@0: return true; michael@0: } michael@0: michael@0: //============================================================================= michael@0: void Breakpad::HandleUncaughtException(NSException *exception) { michael@0: // Generate the minidump. michael@0: google_breakpad::IosExceptionMinidumpGenerator generator(exception); michael@0: const char *minidump_path = michael@0: config_params_->GetValueForKey(BREAKPAD_DUMP_DIRECTORY); michael@0: std::string minidump_id; michael@0: std::string minidump_filename = generator.UniqueNameInDirectory(minidump_path, michael@0: &minidump_id); michael@0: generator.Write(minidump_filename.c_str()); michael@0: michael@0: // Copy the config params and our custom parameter. This is necessary for 2 michael@0: // reasons: michael@0: // 1- config_params_ is protected. michael@0: // 2- If the application crash while trying to handle this exception, a usual michael@0: // report will be generated. This report must not contain these special michael@0: // keys. michael@0: SimpleStringDictionary params = *config_params_; michael@0: params.SetKeyValue(BREAKPAD_SERVER_PARAMETER_PREFIX "type", "exception"); michael@0: params.SetKeyValue(BREAKPAD_SERVER_PARAMETER_PREFIX "exceptionName", michael@0: [[exception name] UTF8String]); michael@0: params.SetKeyValue(BREAKPAD_SERVER_PARAMETER_PREFIX "exceptionReason", michael@0: [[exception reason] UTF8String]); michael@0: michael@0: // And finally write the config file. michael@0: ConfigFile config_file; michael@0: config_file.WriteFile(minidump_path, michael@0: ¶ms, michael@0: minidump_path, michael@0: minidump_id.c_str()); michael@0: } michael@0: michael@0: //============================================================================= michael@0: michael@0: #pragma mark - michael@0: #pragma mark Public API michael@0: michael@0: //============================================================================= michael@0: BreakpadRef BreakpadCreate(NSDictionary *parameters) { michael@0: try { michael@0: // This is confusing. Our two main allocators for breakpad memory are: michael@0: // - gKeyValueAllocator for the key/value memory michael@0: // - gBreakpadAllocator for the Breakpad, ExceptionHandler, and other michael@0: // breakpad allocations which are accessed at exception handling time. michael@0: // michael@0: // But in order to avoid these two allocators themselves from being smashed, michael@0: // we'll protect them as well by allocating them with gMasterAllocator. michael@0: // michael@0: // gMasterAllocator itself will NOT be protected, but this doesn't matter, michael@0: // since once it does its allocations and locks the memory, smashes to michael@0: // itself don't affect anything we care about. michael@0: gMasterAllocator = michael@0: new ProtectedMemoryAllocator(sizeof(ProtectedMemoryAllocator) * 2); michael@0: michael@0: gKeyValueAllocator = michael@0: new (gMasterAllocator->Allocate(sizeof(ProtectedMemoryAllocator))) michael@0: ProtectedMemoryAllocator(sizeof(SimpleStringDictionary)); michael@0: michael@0: // Create a mutex for use in accessing the SimpleStringDictionary michael@0: int mutexResult = pthread_mutex_init(&gDictionaryMutex, NULL); michael@0: if (mutexResult == 0) { michael@0: michael@0: // With the current compiler, gBreakpadAllocator is allocating 1444 bytes. michael@0: // Let's round up to the nearest page size. michael@0: // michael@0: int breakpad_pool_size = 4096; michael@0: michael@0: /* michael@0: sizeof(Breakpad) michael@0: + sizeof(google_breakpad::ExceptionHandler) michael@0: + sizeof( STUFF ALLOCATED INSIDE ExceptionHandler ) michael@0: */ michael@0: michael@0: gBreakpadAllocator = michael@0: new (gMasterAllocator->Allocate(sizeof(ProtectedMemoryAllocator))) michael@0: ProtectedMemoryAllocator(breakpad_pool_size); michael@0: michael@0: // Stack-based autorelease pool for Breakpad::Create() obj-c code. michael@0: NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; michael@0: Breakpad *breakpad = Breakpad::Create(parameters); michael@0: michael@0: if (breakpad) { michael@0: // Make read-only to protect against memory smashers michael@0: gMasterAllocator->Protect(); michael@0: gKeyValueAllocator->Protect(); michael@0: gBreakpadAllocator->Protect(); michael@0: // Can uncomment this line to figure out how much space was actually michael@0: // allocated using this allocator michael@0: // printf("gBreakpadAllocator allocated size = %d\n", michael@0: // gBreakpadAllocator->GetAllocatedSize() ); michael@0: [pool release]; michael@0: return (BreakpadRef)breakpad; michael@0: } michael@0: michael@0: [pool release]; michael@0: } michael@0: } catch(...) { // don't let exceptions leave this C API michael@0: fprintf(stderr, "BreakpadCreate() : error\n"); michael@0: } michael@0: michael@0: if (gKeyValueAllocator) { michael@0: gKeyValueAllocator->~ProtectedMemoryAllocator(); michael@0: gKeyValueAllocator = NULL; michael@0: } michael@0: michael@0: if (gBreakpadAllocator) { michael@0: gBreakpadAllocator->~ProtectedMemoryAllocator(); michael@0: gBreakpadAllocator = NULL; michael@0: } michael@0: michael@0: delete gMasterAllocator; michael@0: gMasterAllocator = NULL; michael@0: michael@0: return NULL; michael@0: } michael@0: michael@0: //============================================================================= michael@0: void BreakpadRelease(BreakpadRef ref) { michael@0: try { michael@0: Breakpad *breakpad = (Breakpad *)ref; michael@0: michael@0: if (gMasterAllocator) { michael@0: gMasterAllocator->Unprotect(); michael@0: gKeyValueAllocator->Unprotect(); michael@0: gBreakpadAllocator->Unprotect(); michael@0: michael@0: breakpad->~Breakpad(); michael@0: michael@0: // Unfortunately, it's not possible to deallocate this stuff michael@0: // because the exception handling thread is still finishing up michael@0: // asynchronously at this point... OK, it could be done with michael@0: // locks, etc. But since BreakpadRelease() should usually only michael@0: // be called right before the process exits, it's not worth michael@0: // deallocating this stuff. michael@0: #if 0 michael@0: gKeyValueAllocator->~ProtectedMemoryAllocator(); michael@0: gBreakpadAllocator->~ProtectedMemoryAllocator(); michael@0: delete gMasterAllocator; michael@0: michael@0: gMasterAllocator = NULL; michael@0: gKeyValueAllocator = NULL; michael@0: gBreakpadAllocator = NULL; michael@0: #endif michael@0: michael@0: pthread_mutex_destroy(&gDictionaryMutex); michael@0: } michael@0: } catch(...) { // don't let exceptions leave this C API michael@0: fprintf(stderr, "BreakpadRelease() : error\n"); michael@0: } michael@0: } michael@0: michael@0: //============================================================================= michael@0: void BreakpadSetKeyValue(BreakpadRef ref, NSString *key, NSString *value) { michael@0: try { michael@0: // Not called at exception time michael@0: Breakpad *breakpad = (Breakpad *)ref; michael@0: michael@0: if (breakpad && key && gKeyValueAllocator) { michael@0: ProtectedMemoryLocker locker(&gDictionaryMutex, gKeyValueAllocator); michael@0: michael@0: breakpad->SetKeyValue(key, value); michael@0: } michael@0: } catch(...) { // don't let exceptions leave this C API michael@0: fprintf(stderr, "BreakpadSetKeyValue() : error\n"); michael@0: } michael@0: } michael@0: michael@0: void BreakpadAddUploadParameter(BreakpadRef ref, michael@0: NSString *key, michael@0: NSString *value) { michael@0: // The only difference, internally, between an upload parameter and michael@0: // a key value one that is set with BreakpadSetKeyValue is that we michael@0: // prepend the keyname with a special prefix. This informs the michael@0: // crash sender that the parameter should be sent along with the michael@0: // POST of the crash dump upload. michael@0: try { michael@0: Breakpad *breakpad = (Breakpad *)ref; michael@0: michael@0: if (breakpad && key && gKeyValueAllocator) { michael@0: ProtectedMemoryLocker locker(&gDictionaryMutex, gKeyValueAllocator); michael@0: michael@0: NSString *prefixedKey = [@BREAKPAD_SERVER_PARAMETER_PREFIX michael@0: stringByAppendingString:key]; michael@0: breakpad->SetKeyValue(prefixedKey, value); michael@0: } michael@0: } catch(...) { // don't let exceptions leave this C API michael@0: fprintf(stderr, "BreakpadSetKeyValue() : error\n"); michael@0: } michael@0: } michael@0: michael@0: void BreakpadRemoveUploadParameter(BreakpadRef ref, michael@0: NSString *key) { michael@0: try { michael@0: // Not called at exception time michael@0: Breakpad *breakpad = (Breakpad *)ref; michael@0: michael@0: if (breakpad && key && gKeyValueAllocator) { michael@0: ProtectedMemoryLocker locker(&gDictionaryMutex, gKeyValueAllocator); michael@0: michael@0: NSString *prefixedKey = [NSString stringWithFormat:@"%@%@", michael@0: @BREAKPAD_SERVER_PARAMETER_PREFIX, key]; michael@0: breakpad->RemoveKeyValue(prefixedKey); michael@0: } michael@0: } catch(...) { // don't let exceptions leave this C API michael@0: fprintf(stderr, "BreakpadRemoveKeyValue() : error\n"); michael@0: } michael@0: } michael@0: //============================================================================= michael@0: NSString *BreakpadKeyValue(BreakpadRef ref, NSString *key) { michael@0: NSString *value = nil; michael@0: michael@0: try { michael@0: // Not called at exception time michael@0: Breakpad *breakpad = (Breakpad *)ref; michael@0: michael@0: if (!breakpad || !key || !gKeyValueAllocator) michael@0: return nil; michael@0: michael@0: ProtectedMemoryLocker locker(&gDictionaryMutex, gKeyValueAllocator); michael@0: michael@0: value = breakpad->KeyValue(key); michael@0: } catch(...) { // don't let exceptions leave this C API michael@0: fprintf(stderr, "BreakpadKeyValue() : error\n"); michael@0: } michael@0: michael@0: return value; michael@0: } michael@0: michael@0: //============================================================================= michael@0: void BreakpadRemoveKeyValue(BreakpadRef ref, NSString *key) { michael@0: try { michael@0: // Not called at exception time michael@0: Breakpad *breakpad = (Breakpad *)ref; michael@0: michael@0: if (breakpad && key && gKeyValueAllocator) { michael@0: ProtectedMemoryLocker locker(&gDictionaryMutex, gKeyValueAllocator); michael@0: michael@0: breakpad->RemoveKeyValue(key); michael@0: } michael@0: } catch(...) { // don't let exceptions leave this C API michael@0: fprintf(stderr, "BreakpadRemoveKeyValue() : error\n"); michael@0: } michael@0: } michael@0: michael@0: //============================================================================= michael@0: bool BreakpadHasCrashReportToUpload(BreakpadRef ref) { michael@0: try { michael@0: // Not called at exception time michael@0: Breakpad *breakpad = (Breakpad *)ref; michael@0: michael@0: if (breakpad) { michael@0: return breakpad->NextCrashReportToUpload() != 0; michael@0: } michael@0: } catch(...) { // don't let exceptions leave this C API michael@0: fprintf(stderr, "BreakpadHasCrashReportToUpload() : error\n"); michael@0: } michael@0: return false; michael@0: } michael@0: michael@0: //============================================================================= michael@0: void BreakpadUploadNextReport(BreakpadRef ref) { michael@0: try { michael@0: // Not called at exception time michael@0: Breakpad *breakpad = (Breakpad *)ref; michael@0: michael@0: if (breakpad) { michael@0: breakpad->UploadNextReport(); michael@0: } michael@0: } catch(...) { // don't let exceptions leave this C API michael@0: fprintf(stderr, "BreakpadUploadNextReport() : error\n"); michael@0: } michael@0: } michael@0: michael@0: //============================================================================= michael@0: void BreakpadUploadData(BreakpadRef ref, NSData *data, NSString *name, michael@0: NSDictionary *server_parameters) { michael@0: try { michael@0: // Not called at exception time michael@0: Breakpad *breakpad = (Breakpad *)ref; michael@0: michael@0: if (breakpad) { michael@0: breakpad->UploadData(data, name, server_parameters); michael@0: } michael@0: } catch(...) { // don't let exceptions leave this C API michael@0: fprintf(stderr, "BreakpadUploadData() : error\n"); michael@0: } michael@0: } michael@0: michael@0: //============================================================================= michael@0: NSDictionary *BreakpadGenerateReport(BreakpadRef ref, michael@0: NSDictionary *server_parameters) { michael@0: try { michael@0: // Not called at exception time michael@0: Breakpad *breakpad = (Breakpad *)ref; michael@0: michael@0: if (breakpad) { michael@0: return breakpad->GenerateReport(server_parameters); michael@0: } else { michael@0: return nil; michael@0: } michael@0: } catch(...) { // don't let exceptions leave this C API michael@0: fprintf(stderr, "BreakpadGenerateReport() : error\n"); michael@0: return nil; michael@0: } michael@0: }