Add abhijeet.k@samsung.com to AUTHORS list.
[chromium-blink-merge.git] / components / crash / app / crashpad_mac.mm
blob962cce63e847e26ac56c14d68a8e6c8aefad3e32
1 // Copyright 2015 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "components/crash/app/crashpad_mac.h"
7 #include <string.h>
8 #include <unistd.h>
10 #include <algorithm>
11 #include <map>
12 #include <vector>
14 #include "base/auto_reset.h"
15 #include "base/debug/crash_logging.h"
16 #include "base/debug/dump_without_crashing.h"
17 #include "base/files/file_path.h"
18 #include "base/logging.h"
19 #include "base/mac/bundle_locations.h"
20 #include "base/mac/foundation_util.h"
21 #include "base/strings/string_piece.h"
22 #include "base/strings/stringprintf.h"
23 #include "base/strings/sys_string_conversions.h"
24 #include "components/crash/app/crash_reporter_client.h"
25 #include "third_party/crashpad/crashpad/client/crash_report_database.h"
26 #include "third_party/crashpad/crashpad/client/crashpad_client.h"
27 #include "third_party/crashpad/crashpad/client/crashpad_info.h"
28 #include "third_party/crashpad/crashpad/client/settings.h"
29 #include "third_party/crashpad/crashpad/client/simple_string_dictionary.h"
30 #include "third_party/crashpad/crashpad/client/simulate_crash.h"
32 namespace crash_reporter {
34 namespace {
36 crashpad::SimpleStringDictionary* g_simple_string_dictionary;
37 crashpad::CrashReportDatabase* g_database;
39 void SetCrashKeyValue(const base::StringPiece& key,
40                       const base::StringPiece& value) {
41   g_simple_string_dictionary->SetKeyValue(key.data(), value.data());
44 void ClearCrashKey(const base::StringPiece& key) {
45   g_simple_string_dictionary->RemoveKey(key.data());
48 bool LogMessageHandler(int severity,
49                        const char* file,
50                        int line,
51                        size_t message_start,
52                        const std::string& string) {
53   // Only handle FATAL.
54   if (severity != logging::LOG_FATAL) {
55     return false;
56   }
58   // In case of an out-of-memory condition, this code could be reentered when
59   // constructing and storing the key. Using a static is not thread-safe, but if
60   // multiple threads are in the process of a fatal crash at the same time, this
61   // should work.
62   static bool guarded = false;
63   if (guarded) {
64     return false;
65   }
66   base::AutoReset<bool> guard(&guarded, true);
68   // Only log last path component.  This matches logging.cc.
69   if (file) {
70     const char* slash = strrchr(file, '/');
71     if (slash) {
72       file = slash + 1;
73     }
74   }
76   std::string message = base::StringPrintf("%s:%d: %s", file, line,
77                                            string.c_str() + message_start);
78   SetCrashKeyValue("LOG_FATAL", message);
80   // Rather than including the code to force the crash here, allow the caller to
81   // do it.
82   return false;
85 void DumpWithoutCrashing() {
86   CRASHPAD_SIMULATE_CRASH();
89 }  // namespace
91 void InitializeCrashpad(const std::string& process_type) {
92   static bool initialized = false;
93   DCHECK(!initialized);
94   initialized = true;
96   const bool browser_process = process_type.empty();
97   CrashReporterClient* crash_reporter_client = GetCrashReporterClient();
99   base::FilePath database_path;  // Only valid in the browser process.
101   if (browser_process) {
102     @autoreleasepool {
103       base::FilePath framework_bundle_path = base::mac::FrameworkBundlePath();
104       base::FilePath handler_path =
105           framework_bundle_path.Append("Helpers").Append("crashpad_handler");
107       // Is there a way to recover if this fails?
108       crash_reporter_client->GetCrashDumpLocation(&database_path);
110       // TODO(mark): Reading the Breakpad keys is temporary and transitional. At
111       // the very least, they should be renamed to Crashpad. For the time being,
112       // this isn't the worst thing: Crashpad is still uploading to a
113       // Breakpad-type server, after all.
114       NSBundle* framework_bundle = base::mac::FrameworkBundle();
115       NSString* product = base::mac::ObjCCast<NSString>(
116           [framework_bundle objectForInfoDictionaryKey:@"BreakpadProduct"]);
117       NSString* version = base::mac::ObjCCast<NSString>(
118           [framework_bundle objectForInfoDictionaryKey:@"BreakpadVersion"]);
119       NSString* url_ns = base::mac::ObjCCast<NSString>(
120           [framework_bundle objectForInfoDictionaryKey:@"BreakpadURL"]);
122       std::string url = base::SysNSStringToUTF8(url_ns);
124       std::map<std::string, std::string> process_annotations;
125       process_annotations["prod"] = base::SysNSStringToUTF8(product);
126       process_annotations["ver"] = base::SysNSStringToUTF8(version);
127       process_annotations["plat"] = std::string("OS X");
129       crashpad::CrashpadClient crashpad_client;
130       if (crashpad_client.StartHandler(handler_path, database_path, url,
131                                        process_annotations,
132                                        std::vector<std::string>())) {
133         crashpad_client.UseHandler();
134       }
135     }  // @autoreleasepool
136   }
138   crashpad::CrashpadInfo* crashpad_info =
139       crashpad::CrashpadInfo::GetCrashpadInfo();
141 #if defined(NDEBUG)
142   const bool is_debug_build = false;
143 #else
144   const bool is_debug_build = true;
145 #endif
147   // Disable forwarding to the system's crash reporter in processes other than
148   // the browser process. For the browser, the system's crash reporter presents
149   // the crash UI to the user, so it's desirable there. Additionally, having
150   // crash reports appear in ~/Library/Logs/DiagnosticReports provides a
151   // fallback. Forwarding is turned off for debug-mode builds even for the
152   // browser process, because the system's crash reporter can take a very long
153   // time to chew on symbols.
154   if (!browser_process || is_debug_build) {
155     crashpad_info->set_system_crash_reporter_forwarding(
156         crashpad::TriState::kDisabled);
157   }
159   g_simple_string_dictionary = new crashpad::SimpleStringDictionary();
160   crashpad_info->set_simple_annotations(g_simple_string_dictionary);
162   base::debug::SetCrashKeyReportingFunctions(SetCrashKeyValue, ClearCrashKey);
163   crash_reporter_client->RegisterCrashKeys();
165   SetCrashKeyValue("ptype", browser_process ? base::StringPiece("browser")
166                                             : base::StringPiece(process_type));
167   SetCrashKeyValue("pid", base::StringPrintf("%d", getpid()));
169   logging::SetLogMessageHandler(LogMessageHandler);
171   // If clients called CRASHPAD_SIMULATE_CRASH() instead of
172   // base::debug::DumpWithoutCrashing(), these dumps would appear as crashes in
173   // the correct function, at the correct file and line. This would be
174   // preferable to having all occurrences show up in DumpWithoutCrashing() at
175   // the same file and line.
176   base::debug::SetDumpWithoutCrashingFunction(DumpWithoutCrashing);
178   if (browser_process) {
179     g_database =
180         crashpad::CrashReportDatabase::Initialize(database_path).release();
182     bool enable_uploads = false;
183     if (!crash_reporter_client->ReportingIsEnforcedByPolicy(&enable_uploads)) {
184       enable_uploads = crash_reporter_client->GetCollectStatsConsent() ||
185                        crash_reporter_client->IsRunningUnattended();
186       // Breakpad provided a --disable-breakpad switch here. Should this?
187     }
189     SetUploadsEnabled(enable_uploads);
190   }
193 void SetUploadsEnabled(bool enable_uploads) {
194   if (g_database) {
195     crashpad::Settings* settings = g_database->GetSettings();
196     settings->SetUploadsEnabled(enable_uploads);
197   }
200 bool GetUploadsEnabled() {
201   if (g_database) {
202     crashpad::Settings* settings = g_database->GetSettings();
203     bool enable_uploads;
204     if (settings->GetUploadsEnabled(&enable_uploads)) {
205       return enable_uploads;
206     }
207   }
209   return false;
212 void GetUploadedReports(std::vector<UploadedReport>* uploaded_reports) {
213   uploaded_reports->clear();
215   if (!g_database) {
216     return;
217   }
219   std::vector<crashpad::CrashReportDatabase::Report> completed_reports;
220   crashpad::CrashReportDatabase::OperationStatus status =
221       g_database->GetCompletedReports(&completed_reports);
222   if (status != crashpad::CrashReportDatabase::kNoError) {
223     return;
224   }
226   for (const crashpad::CrashReportDatabase::Report& completed_report :
227        completed_reports) {
228     if (completed_report.uploaded) {
229       UploadedReport uploaded_report;
230       uploaded_report.local_id = completed_report.uuid.ToString();
231       uploaded_report.remote_id = completed_report.id;
232       uploaded_report.creation_time = completed_report.creation_time;
234       uploaded_reports->push_back(uploaded_report);
235     }
236   }
238   struct {
239     bool operator()(const UploadedReport& a, const UploadedReport& b) {
240       return a.creation_time >= b.creation_time;
241     }
242   } sort_by_time;
243   std::sort(uploaded_reports->begin(), uploaded_reports->end(), sort_by_time);
246 }  // namespace crash_reporter