michael@0: // Copyright (c) 2006, 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: 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/mac/Framework/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/Inspector.h" michael@0: #import "client/mac/handler/exception_handler.h" michael@0: #import "client/mac/Framework/Breakpad.h" michael@0: #import "client/mac/Framework/OnDemandServer.h" michael@0: #import "client/mac/handler/protected_memory_allocator.h" michael@0: #import "common/mac/MachIPC.h" michael@0: #import "common/mac/SimpleStringDictionary.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::KeyValueEntry; michael@0: using google_breakpad::MachPortSender; michael@0: using google_breakpad::MachReceiveMessage; michael@0: using google_breakpad::MachSendMessage; michael@0: using google_breakpad::ReceivePort; 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: michael@0: void GenerateAndSendReport(); michael@0: michael@0: void SetFilterCallback(BreakpadFilterCallback callback, void *context) { michael@0: filter_callback_ = callback; michael@0: filter_callback_context_ = context; michael@0: } michael@0: michael@0: private: michael@0: Breakpad() michael@0: : handler_(NULL), michael@0: config_params_(NULL), michael@0: send_and_exit_(true), michael@0: filter_callback_(NULL), michael@0: filter_callback_context_(NULL) { michael@0: inspector_path_[0] = 0; michael@0: } michael@0: michael@0: bool Initialize(NSDictionary *parameters); michael@0: michael@0: bool ExtractParameters(NSDictionary *parameters); michael@0: michael@0: // Dispatches to HandleException() michael@0: static bool ExceptionHandlerDirectCallback(void *context, michael@0: int exception_type, michael@0: int exception_code, michael@0: int exception_subcode, michael@0: mach_port_t crashing_thread); michael@0: michael@0: bool HandleException(int exception_type, michael@0: int exception_code, michael@0: int exception_subcode, michael@0: mach_port_t crashing_thread); 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: char inspector_path_[PATH_MAX]; // Path to inspector tool michael@0: michael@0: SimpleStringDictionary *config_params_; // Create parameters (STRONG) michael@0: michael@0: OnDemandServer inspector_; michael@0: michael@0: bool send_and_exit_; // Exit after sending, if true michael@0: michael@0: BreakpadFilterCallback filter_callback_; michael@0: void *filter_callback_context_; michael@0: }; 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 = (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::ExceptionHandlerDirectCallback(void *context, michael@0: int exception_type, michael@0: int exception_code, michael@0: int exception_subcode, michael@0: mach_port_t crashing_thread) { 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) michael@0: return false; michael@0: michael@0: return breakpad->HandleException( exception_type, michael@0: exception_code, michael@0: exception_subcode, michael@0: crashing_thread); michael@0: } michael@0: michael@0: //============================================================================= michael@0: #pragma mark - michael@0: michael@0: #include michael@0: michael@0: //============================================================================= michael@0: // Returns the pathname to the Resources directory for this version of michael@0: // Breakpad which we are now running. michael@0: // michael@0: // Don't make the function static, since _dyld_lookup_and_bind_fully needs a michael@0: // simple non-static C name michael@0: // michael@0: extern "C" { michael@0: NSString * GetResourcePath(); michael@0: NSString * GetResourcePath() { michael@0: NSString *resourcePath = nil; michael@0: michael@0: // If there are multiple breakpads installed then calling bundleWithIdentifier michael@0: // will not work properly, so only use that as a backup plan. michael@0: // We want to find the bundle containing the code where this function lives michael@0: // and work from there michael@0: // michael@0: michael@0: // Get the pathname to the code which contains this function michael@0: Dl_info info; michael@0: if (dladdr((const void*)GetResourcePath, &info) != 0) { michael@0: NSFileManager *filemgr = [NSFileManager defaultManager]; michael@0: NSString *filePath = michael@0: [filemgr stringWithFileSystemRepresentation:info.dli_fname michael@0: length:strlen(info.dli_fname)]; michael@0: NSString *bundlePath = [filePath stringByDeletingLastPathComponent]; michael@0: // The "Resources" directory should be in the same directory as the michael@0: // executable code, since that's how the Breakpad framework is built. michael@0: resourcePath = [bundlePath stringByAppendingPathComponent:@"Resources/"]; michael@0: } else { michael@0: DEBUGLOG(stderr, "Could not find GetResourcePath\n"); michael@0: // fallback plan michael@0: NSBundle *bundle = michael@0: [NSBundle bundleWithIdentifier:@"com.Google.BreakpadFramework"]; michael@0: resourcePath = [bundle resourcePath]; michael@0: } michael@0: michael@0: return resourcePath; michael@0: } michael@0: } // extern "C" michael@0: michael@0: //============================================================================= michael@0: bool Breakpad::Initialize(NSDictionary *parameters) { michael@0: // Initialize michael@0: config_params_ = NULL; michael@0: handler_ = NULL; 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: // Gather any user specified parameters michael@0: if (!ExtractParameters(parameters)) { michael@0: return false; michael@0: } michael@0: michael@0: // Get path to Inspector executable. michael@0: NSString *inspectorPathString = KeyValue(@BREAKPAD_INSPECTOR_LOCATION); michael@0: michael@0: // Standardize path (resolve symlinkes, etc.) and escape spaces michael@0: inspectorPathString = [inspectorPathString stringByStandardizingPath]; michael@0: inspectorPathString = [[inspectorPathString componentsSeparatedByString:@" "] michael@0: componentsJoinedByString:@"\\ "]; michael@0: michael@0: // Create an on-demand server object representing the Inspector. michael@0: // In case of a crash, we simply need to call the LaunchOnDemand() michael@0: // method on it, then send a mach message to its service port. michael@0: // It will then launch and perform a process inspection of our crashed state. michael@0: // See the HandleException() method for the details. michael@0: #define RECEIVE_PORT_NAME "com.Breakpad.Inspector" michael@0: michael@0: name_t portName; michael@0: snprintf(portName, sizeof(name_t), "%s%d", RECEIVE_PORT_NAME, getpid()); michael@0: michael@0: // Save the location of the Inspector michael@0: strlcpy(inspector_path_, [inspectorPathString fileSystemRepresentation], michael@0: sizeof(inspector_path_)); michael@0: michael@0: // Append a single command-line argument to the Inspector path michael@0: // representing the bootstrap name of the launch-on-demand receive port. michael@0: // When the Inspector is launched, it can use this to lookup the port michael@0: // by calling bootstrap_check_in(). michael@0: strlcat(inspector_path_, " ", sizeof(inspector_path_)); michael@0: strlcat(inspector_path_, portName, sizeof(inspector_path_)); michael@0: michael@0: kern_return_t kr = inspector_.Initialize(inspector_path_, michael@0: portName, michael@0: true); // shutdown on exit michael@0: michael@0: if (kr != KERN_SUCCESS) { michael@0: return false; 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: Breakpad::ExceptionHandlerDirectCallback, this, true); michael@0: return true; michael@0: } michael@0: michael@0: //============================================================================= michael@0: Breakpad::~Breakpad() { 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: NSUserDefaults *stdDefaults = [NSUserDefaults standardUserDefaults]; michael@0: NSString *skipConfirm = [stdDefaults stringForKey:@BREAKPAD_SKIP_CONFIRM]; michael@0: NSString *sendAndExit = [stdDefaults stringForKey:@BREAKPAD_SEND_AND_EXIT]; michael@0: 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 *interval = [parameters objectForKey:@BREAKPAD_REPORT_INTERVAL]; michael@0: NSString *inspectorPathString = michael@0: [parameters objectForKey:@BREAKPAD_INSPECTOR_LOCATION]; michael@0: NSString *reporterPathString = michael@0: [parameters objectForKey:@BREAKPAD_REPORTER_EXE_LOCATION]; michael@0: NSString *timeout = [parameters objectForKey:@BREAKPAD_CONFIRM_TIMEOUT]; michael@0: NSArray *logFilePaths = [parameters objectForKey:@BREAKPAD_LOGFILES]; michael@0: NSString *logFileTailSize = michael@0: [parameters objectForKey:@BREAKPAD_LOGFILE_UPLOAD_SIZE]; michael@0: NSString *requestUserText = michael@0: [parameters objectForKey:@BREAKPAD_REQUEST_COMMENTS]; michael@0: NSString *requestEmail = [parameters objectForKey:@BREAKPAD_REQUEST_EMAIL]; 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: // These may have been set above as user prefs, which take priority. michael@0: if (!skipConfirm) { michael@0: skipConfirm = [parameters objectForKey:@BREAKPAD_SKIP_CONFIRM]; michael@0: } michael@0: if (!sendAndExit) { michael@0: sendAndExit = [parameters objectForKey:@BREAKPAD_SEND_AND_EXIT]; michael@0: } 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 (!interval) michael@0: interval = @"3600"; michael@0: michael@0: if (!timeout) michael@0: timeout = @"300"; michael@0: michael@0: if (!logFileTailSize) michael@0: logFileTailSize = @"200000"; michael@0: michael@0: if (!vendor) { michael@0: vendor = @"Vendor not specified"; michael@0: } michael@0: michael@0: // Normalize the values. michael@0: if (skipConfirm) { michael@0: skipConfirm = [skipConfirm uppercaseString]; michael@0: michael@0: if ([skipConfirm isEqualToString:@"YES"] || michael@0: [skipConfirm isEqualToString:@"TRUE"] || michael@0: [skipConfirm isEqualToString:@"1"]) michael@0: skipConfirm = @"YES"; michael@0: else michael@0: skipConfirm = @"NO"; michael@0: } else { michael@0: skipConfirm = @"NO"; michael@0: } michael@0: michael@0: send_and_exit_ = true; michael@0: if (sendAndExit) { michael@0: sendAndExit = [sendAndExit uppercaseString]; michael@0: michael@0: if ([sendAndExit isEqualToString:@"NO"] || michael@0: [sendAndExit isEqualToString:@"FALSE"] || michael@0: [sendAndExit isEqualToString:@"0"]) michael@0: send_and_exit_ = false; michael@0: } michael@0: michael@0: if (requestUserText) { michael@0: requestUserText = [requestUserText uppercaseString]; michael@0: michael@0: if ([requestUserText isEqualToString:@"YES"] || michael@0: [requestUserText isEqualToString:@"TRUE"] || michael@0: [requestUserText isEqualToString:@"1"]) michael@0: requestUserText = @"YES"; michael@0: else michael@0: requestUserText = @"NO"; michael@0: } else { michael@0: requestUserText = @"NO"; michael@0: } michael@0: michael@0: // Find the helper applications if not specified in user config. michael@0: NSString *resourcePath = nil; michael@0: if (!inspectorPathString || !reporterPathString) { michael@0: resourcePath = GetResourcePath(); michael@0: if (!resourcePath) { michael@0: DEBUGLOG(stderr, "Could not get resource path\n"); michael@0: return false; michael@0: } michael@0: } michael@0: michael@0: // Find Inspector. michael@0: if (!inspectorPathString) { michael@0: inspectorPathString = michael@0: [resourcePath stringByAppendingPathComponent:@"Inspector"]; michael@0: } michael@0: michael@0: // Verify that there is an Inspector tool. michael@0: if (![[NSFileManager defaultManager] fileExistsAtPath:inspectorPathString]) { michael@0: DEBUGLOG(stderr, "Cannot find Inspector tool\n"); michael@0: return false; michael@0: } michael@0: michael@0: // Find Reporter. michael@0: if (!reporterPathString) { michael@0: reporterPathString = michael@0: [resourcePath michael@0: stringByAppendingPathComponent:@"crash_report_sender.app"]; michael@0: reporterPathString = michael@0: [[NSBundle bundleWithPath:reporterPathString] executablePath]; michael@0: } michael@0: michael@0: // Verify that there is a Reporter application. michael@0: if (![[NSFileManager defaultManager] michael@0: fileExistsAtPath:reporterPathString]) { michael@0: DEBUGLOG(stderr, "Cannot find Reporter tool\n"); michael@0: return false; michael@0: } michael@0: michael@0: if (!dumpSubdirectory) { michael@0: 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_REPORT_INTERVAL, [interval UTF8String]); michael@0: dictionary.SetKeyValue(BREAKPAD_SKIP_CONFIRM, [skipConfirm UTF8String]); michael@0: dictionary.SetKeyValue(BREAKPAD_CONFIRM_TIMEOUT, [timeout UTF8String]); michael@0: dictionary.SetKeyValue(BREAKPAD_INSPECTOR_LOCATION, michael@0: [inspectorPathString fileSystemRepresentation]); michael@0: dictionary.SetKeyValue(BREAKPAD_REPORTER_EXE_LOCATION, michael@0: [reporterPathString fileSystemRepresentation]); michael@0: dictionary.SetKeyValue(BREAKPAD_LOGFILE_UPLOAD_SIZE, michael@0: [logFileTailSize UTF8String]); michael@0: dictionary.SetKeyValue(BREAKPAD_REQUEST_COMMENTS, michael@0: [requestUserText UTF8String]); michael@0: dictionary.SetKeyValue(BREAKPAD_REQUEST_EMAIL, [requestEmail 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, michael@0: timeStartedString); michael@0: michael@0: if (logFilePaths) { michael@0: char logFileKey[255]; michael@0: for(unsigned int i = 0; i < [logFilePaths count]; i++) { michael@0: sprintf(logFileKey,"%s%d", BREAKPAD_LOGFILE_KEY_PREFIX, i); michael@0: dictionary.SetKeyValue(logFileKey, michael@0: [[logFilePaths objectAtIndex:i] michael@0: fileSystemRepresentation]); michael@0: } michael@0: } 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: void Breakpad::GenerateAndSendReport() { michael@0: config_params_->SetKeyValue(BREAKPAD_ON_DEMAND, "YES"); michael@0: HandleException(0, 0, 0, mach_thread_self()); michael@0: config_params_->SetKeyValue(BREAKPAD_ON_DEMAND, "NO"); michael@0: } michael@0: michael@0: //============================================================================= michael@0: bool Breakpad::HandleException(int exception_type, michael@0: int exception_code, michael@0: int exception_subcode, michael@0: mach_port_t crashing_thread) { michael@0: DEBUGLOG(stderr, "Breakpad: an exception occurred\n"); michael@0: michael@0: if (filter_callback_) { michael@0: bool should_handle = filter_callback_(exception_type, michael@0: exception_code, michael@0: crashing_thread, michael@0: filter_callback_context_); michael@0: if (!should_handle) return false; michael@0: } michael@0: michael@0: // We need to reset the memory protections to be read/write, michael@0: // since LaunchOnDemand() requires changing state. michael@0: gBreakpadAllocator->Unprotect(); michael@0: // Configure the server to launch when we message the service port. michael@0: // The reason we do this here, rather than at startup, is that we michael@0: // can leak a bootstrap service entry if this method is called and michael@0: // there never ends up being a crash. michael@0: inspector_.LaunchOnDemand(); michael@0: gBreakpadAllocator->Protect(); michael@0: michael@0: // The Inspector should send a message to this port to verify it michael@0: // received our information and has finished the inspection. michael@0: ReceivePort acknowledge_port; michael@0: michael@0: // Send initial information to the Inspector. michael@0: MachSendMessage message(kMsgType_InspectorInitialInfo); michael@0: message.AddDescriptor(mach_task_self()); // our task michael@0: message.AddDescriptor(crashing_thread); // crashing thread michael@0: message.AddDescriptor(mach_thread_self()); // exception-handling thread michael@0: message.AddDescriptor(acknowledge_port.GetPort());// message receive port michael@0: michael@0: InspectorInfo info; michael@0: info.exception_type = exception_type; michael@0: info.exception_code = exception_code; michael@0: info.exception_subcode = exception_subcode; michael@0: info.parameter_count = config_params_->GetCount(); michael@0: message.SetData(&info, sizeof(info)); michael@0: michael@0: MachPortSender sender(inspector_.GetServicePort()); michael@0: michael@0: kern_return_t result = sender.SendMessage(message, 2000); michael@0: michael@0: if (result == KERN_SUCCESS) { michael@0: // Now, send a series of key-value pairs to the Inspector. michael@0: const KeyValueEntry *entry = NULL; michael@0: SimpleStringDictionaryIterator iter(*config_params_); michael@0: michael@0: while ( (entry = iter.Next()) ) { michael@0: KeyValueMessageData keyvalue_data(*entry); michael@0: michael@0: MachSendMessage keyvalue_message(kMsgType_InspectorKeyValuePair); michael@0: keyvalue_message.SetData(&keyvalue_data, sizeof(keyvalue_data)); michael@0: michael@0: result = sender.SendMessage(keyvalue_message, 2000); michael@0: michael@0: if (result != KERN_SUCCESS) { michael@0: break; michael@0: } michael@0: } michael@0: michael@0: if (result == KERN_SUCCESS) { michael@0: // Wait for acknowledgement that the inspection has finished. michael@0: MachReceiveMessage acknowledge_messsage; michael@0: result = acknowledge_port.WaitForMessage(&acknowledge_messsage, 5000); michael@0: } michael@0: } michael@0: michael@0: #if VERBOSE michael@0: PRINT_MACH_RESULT(result, "Breakpad: SendMessage "); michael@0: printf("Breakpad: Inspector service port = %#x\n", michael@0: inspector_.GetServicePort()); michael@0: #endif michael@0: michael@0: // If we don't want any forwarding, return true here to indicate that we've michael@0: // processed things as much as we want. michael@0: if (send_and_exit_) return true; michael@0: michael@0: return false; michael@0: } 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 itself michael@0: // 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: void BreakpadGenerateAndSendReport(BreakpadRef ref) { michael@0: try { michael@0: Breakpad *breakpad = (Breakpad *)ref; michael@0: michael@0: if (breakpad && gKeyValueAllocator) { michael@0: ProtectedMemoryLocker locker(&gDictionaryMutex, gKeyValueAllocator); michael@0: michael@0: gBreakpadAllocator->Unprotect(); michael@0: breakpad->GenerateAndSendReport(); michael@0: gBreakpadAllocator->Protect(); michael@0: } michael@0: } catch(...) { // don't let exceptions leave this C API michael@0: fprintf(stderr, "BreakpadGenerateAndSendReport() : error\n"); michael@0: } michael@0: } michael@0: michael@0: //============================================================================= michael@0: void BreakpadSetFilterCallback(BreakpadRef ref, michael@0: BreakpadFilterCallback callback, michael@0: void *context) { michael@0: michael@0: try { michael@0: Breakpad *breakpad = (Breakpad *)ref; michael@0: michael@0: if (breakpad && gBreakpadAllocator) { michael@0: // share the dictionary mutex here (we really don't need a mutex) michael@0: ProtectedMemoryLocker locker(&gDictionaryMutex, gBreakpadAllocator); michael@0: michael@0: breakpad->SetFilterCallback(callback, context); michael@0: } michael@0: } catch(...) { // don't let exceptions leave this C API michael@0: fprintf(stderr, "BreakpadSetFilterCallback() : error\n"); michael@0: } michael@0: } michael@0: michael@0: //============================================================================ michael@0: void BreakpadAddLogFile(BreakpadRef ref, NSString *logPathname) { michael@0: int logFileCounter = 0; michael@0: michael@0: NSString *logFileKey = [NSString stringWithFormat:@"%@%d", michael@0: @BREAKPAD_LOGFILE_KEY_PREFIX, michael@0: logFileCounter]; michael@0: michael@0: NSString *existingLogFilename = nil; michael@0: existingLogFilename = BreakpadKeyValue(ref, logFileKey); michael@0: // Find the first log file key that we can use by testing for existence michael@0: while (existingLogFilename) { michael@0: if ([existingLogFilename isEqualToString:logPathname]) { michael@0: return; michael@0: } michael@0: logFileCounter++; michael@0: logFileKey = [NSString stringWithFormat:@"%@%d", michael@0: @BREAKPAD_LOGFILE_KEY_PREFIX, michael@0: logFileCounter]; michael@0: existingLogFilename = BreakpadKeyValue(ref, logFileKey); michael@0: } michael@0: michael@0: BreakpadSetKeyValue(ref, logFileKey, logPathname); michael@0: }