cool#10610 Ensure the parent-child relations of comments.
[LibreOffice.git] / desktop / source / app / crashreport.cxx
blob18db12d07b38f116e7b788c1465299d54bbbcc22
1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2 /*
3 * This file is part of the LibreOffice project.
5 * This Source Code Form is subject to the terms of the Mozilla Public
6 * License, v. 2.0. If a copy of the MPL was not distributed with this
7 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
8 */
10 #include <desktop/crashreport.hxx>
11 #include <rtl/bootstrap.hxx>
12 #include <osl/file.hxx>
13 #include <comphelper/processfactory.hxx>
14 #include <ucbhelper/proxydecider.hxx>
15 #include <unotools/bootstrap.hxx>
16 #include <o3tl/char16_t2wchar_t.hxx>
17 #include <desktop/minidump.hxx>
18 #include <rtl/ustrbuf.hxx>
20 #include <config_version.h>
21 #include <config_folders.h>
23 #include <string>
24 #include <regex>
27 #if HAVE_FEATURE_BREAKPAD
29 #include <fstream>
30 #if defined( UNX ) && !defined MACOSX && !defined IOS && !defined ANDROID
31 #include <client/linux/handler/exception_handler.h>
32 #elif defined _WIN32
33 #if defined __clang__
34 #pragma clang diagnostic push
35 #pragma clang diagnostic ignored "-Wmicrosoft-enum-value"
36 #endif
37 #include <client/windows/handler/exception_handler.h>
38 #if defined __clang__
39 #pragma clang diagnostic pop
40 #endif
41 #include <locale>
42 #include <codecvt>
43 #endif
45 osl::Mutex CrashReporter::maMutex;
46 osl::Mutex CrashReporter::maActiveSfxObjectNameMutex;
47 osl::Mutex CrashReporter::maUnoLogCmdMutex;
48 std::unique_ptr<google_breakpad::ExceptionHandler> CrashReporter::mpExceptionHandler;
49 bool CrashReporter::mbInit = false;
50 CrashReporter::vmaKeyValues CrashReporter::maKeyValues;
51 CrashReporter::vmaloggedUnoCommands CrashReporter::maloggedUnoCommands;
52 OUString CrashReporter::msActiveSfxObjectName;
55 #if defined( UNX ) && !defined MACOSX && !defined IOS && !defined ANDROID
56 static bool dumpCallback(const google_breakpad::MinidumpDescriptor& descriptor, void* /*context*/, bool succeeded)
58 CrashReporter::addKeyValue("Active-SfxObject",CrashReporter::getActiveSfxObjectName(),CrashReporter::AddItem);
59 CrashReporter::addKeyValue("Last-4-Uno-Commands",CrashReporter::getLoggedUnoCommands(),CrashReporter::AddItem);
60 CrashReporter::addKeyValue("DumpFile", OStringToOUString(descriptor.path(), RTL_TEXTENCODING_UTF8), CrashReporter::Write);
61 SAL_WARN("desktop", "minidump generated: " << descriptor.path());
63 return succeeded;
65 #elif defined _WIN32
66 static bool dumpCallback(const wchar_t* path, const wchar_t* id,
67 void* /*context*/, EXCEPTION_POINTERS* /*exinfo*/,
68 MDRawAssertionInfo* /*assertion*/,
69 bool succeeded)
71 OUString aPath(OUString::Concat(o3tl::toU(path)) + o3tl::toU(id) + ".dmp");
72 CrashReporter::addKeyValue("Active-SfxObject",CrashReporter::getActiveSfxObjectName(),CrashReporter::AddItem);
73 CrashReporter::addKeyValue("Last-4-Uno-Commands",CrashReporter::getLoggedUnoCommands(),CrashReporter::AddItem);
74 CrashReporter::addKeyValue("DumpFile", aPath, CrashReporter::AddItem);
75 CrashReporter::addKeyValue("GDIHandles", OUString::number(::GetGuiResources(::GetCurrentProcess(), GR_GDIOBJECTS)), CrashReporter::Write);
76 SAL_WARN("desktop", "minidump generated: " << aPath);
77 return succeeded;
79 #endif
82 void CrashReporter::writeToFile(std::ios_base::openmode Openmode)
84 #if defined _WIN32
85 const std::string iniPath = getIniFileName();
86 std::wstring iniPathW;
87 const int nChars = MultiByteToWideChar(CP_UTF8, 0, iniPath.c_str(), -1, nullptr, 0);
88 auto buf = std::make_unique<wchar_t[]>(nChars);
89 if (MultiByteToWideChar(CP_UTF8, 0, iniPath.c_str(), -1, buf.get(), nChars) != 0)
90 iniPathW = buf.get();
92 std::ofstream ini_file
93 = iniPathW.empty() ? std::ofstream(iniPath, Openmode) : std::ofstream(iniPathW, Openmode);
94 #else
95 std::ofstream ini_file(getIniFileName(), Openmode);
96 #endif
98 for (auto& keyValue : maKeyValues)
100 ini_file << OUStringToOString(keyValue.first, RTL_TEXTENCODING_UTF8) << "=";
101 ini_file << OUStringToOString(keyValue.second, RTL_TEXTENCODING_UTF8) << "\n";
104 maKeyValues.clear();
105 ini_file.close();
108 void CrashReporter::addKeyValue(const OUString& rKey, const OUString& rValue, tAddKeyHandling AddKeyHandling)
110 osl::MutexGuard aGuard(maMutex);
112 if (IsDumpEnable())
114 if (!rKey.isEmpty())
115 maKeyValues.push_back(mpair(rKey, rValue));
117 if (AddKeyHandling != AddItem)
119 if (mbInit)
120 writeToFile(std::ios_base::app);
121 else if (AddKeyHandling == Create)
122 writeCommonInfo();
127 void CrashReporter::writeCommonInfo()
129 writeSystemInfo();
131 ucbhelper::InternetProxyDecider proxy_decider(::comphelper::getProcessComponentContext());
133 static constexpr OUString protocol = u"https"_ustr;
134 static constexpr OUString url = u"crashreport.libreoffice.org"_ustr;
135 const sal_Int32 port = 443;
137 const OUString proxy_server = proxy_decider.getProxy(protocol, url, port);
139 // save the new Keys
140 vmaKeyValues atlast = maKeyValues;
141 // clear the keys, the following Keys should be at the begin
142 maKeyValues.clear();
144 // limit the amount of code that needs to be executed before the crash reporting
145 addKeyValue("ProductName", "LibreOffice", AddItem);
146 addKeyValue("Version", LIBO_VERSION_DOTTED, AddItem);
147 addKeyValue("BuildID", utl::Bootstrap::getBuildIdData(""), AddItem);
148 addKeyValue("URL", protocol + "://" + url + "/submit/", AddItem);
150 if (!proxy_server.isEmpty())
152 addKeyValue("Proxy", proxy_server, AddItem);
155 // write the new keys at the end
156 maKeyValues.insert(maKeyValues.end(), atlast.begin(), atlast.end());
158 mbInit = true;
160 writeToFile(std::ios_base::trunc);
162 updateMinidumpLocation();
165 void CrashReporter::setActiveSfxObjectName(const OUString& rActiveSfxObjectName)
167 osl::MutexGuard aGuard(maActiveSfxObjectNameMutex);
168 msActiveSfxObjectName = rActiveSfxObjectName;
171 OUString CrashReporter::getActiveSfxObjectName()
173 osl::MutexGuard aGuard(maActiveSfxObjectNameMutex);
174 return msActiveSfxObjectName;
177 void CrashReporter::logUnoCommand(const OUString& rUnoCommand)
179 osl::MutexGuard aGuard(maUnoLogCmdMutex);
181 if( maloggedUnoCommands.size() == 4 )
182 maloggedUnoCommands.pop_front();
184 maloggedUnoCommands.push_back(rUnoCommand);
187 OUString CrashReporter::getLoggedUnoCommands()
189 osl::MutexGuard aGuard(maUnoLogCmdMutex);
191 OUString aCommandSeperator="";
192 OUStringBuffer aUnoCommandBuffer;
194 for( auto& unocommand: maloggedUnoCommands)
196 aUnoCommandBuffer.append(aCommandSeperator + unocommand);
197 aCommandSeperator=",";
199 return aUnoCommandBuffer.makeStringAndClear();
202 namespace {
204 OUString getCrashDirectory()
206 OUString aCrashURL;
207 rtl::Bootstrap::get("CrashDirectory", aCrashURL);
208 // Need to convert to URL in case of user-defined path
209 osl::FileBase::getFileURLFromSystemPath(aCrashURL, aCrashURL);
211 if (aCrashURL.isEmpty()) { // Fall back to user profile
212 aCrashURL = "${$BRAND_BASE_DIR/" LIBO_ETC_FOLDER "/" SAL_CONFIGFILE("bootstrap") ":UserInstallation}/crash/";
213 rtl::Bootstrap::expandMacros(aCrashURL);
216 if (!aCrashURL.endsWith("/"))
217 aCrashURL += "/";
219 osl::Directory::create(aCrashURL);
220 OUString aCrashPath;
221 osl::FileBase::getSystemPathFromFileURL(aCrashURL, aCrashPath);
222 return aCrashPath;
227 void CrashReporter::updateMinidumpLocation()
229 #if defined( UNX ) && !defined MACOSX && !defined IOS && !defined ANDROID
230 OUString aURL = getCrashDirectory();
231 OString aOStringUrl = OUStringToOString(aURL, RTL_TEXTENCODING_UTF8);
232 google_breakpad::MinidumpDescriptor descriptor(std::string{aOStringUrl});
233 mpExceptionHandler->set_minidump_descriptor(descriptor);
234 #elif defined _WIN32
235 OUString aURL = getCrashDirectory();
236 mpExceptionHandler->set_dump_path(std::wstring(o3tl::toW(aURL)));
237 #endif
240 bool CrashReporter::crashReportInfoExists()
242 static const bool InfoExist = crashreport::readConfig(CrashReporter::getIniFileName(), nullptr);
243 return InfoExist;
246 bool CrashReporter::readSendConfig(std::string& response)
248 return crashreport::readConfig(CrashReporter::getIniFileName(), &response);
251 void CrashReporter::installExceptionHandler()
253 if (!IsDumpEnable())
254 return;
255 #if defined( UNX ) && !defined MACOSX && !defined IOS && !defined ANDROID
256 google_breakpad::MinidumpDescriptor descriptor("/tmp");
257 mpExceptionHandler = std::make_unique<google_breakpad::ExceptionHandler>(descriptor, nullptr, dumpCallback, nullptr, true, -1);
258 #elif defined _WIN32
259 mpExceptionHandler = std::make_unique<google_breakpad::ExceptionHandler>(L".", nullptr, dumpCallback, nullptr, google_breakpad::ExceptionHandler::HANDLER_ALL);
260 #endif
263 void CrashReporter::removeExceptionHandler()
265 mpExceptionHandler.reset();
270 bool CrashReporter::IsDumpEnable()
272 auto const env = std::getenv("CRASH_DUMP_ENABLE");
273 if (env != nullptr && env[0] != '\0') {
274 return true;
276 // read configuration item 'CrashDumpEnable' -> bool on/off
277 OUString sToken;
278 if (rtl::Bootstrap::get("CrashDumpEnable", sToken))
280 return sToken.toBoolean();
282 return true; // default, always on
286 std::string CrashReporter::getIniFileName()
288 OUString url = getCrashDirectory() + "dump.ini";
289 OString aUrl = OUStringToOString(url, RTL_TEXTENCODING_UTF8);
290 std::string aRet(aUrl);
291 return aRet;
294 // Write system-specific information such as the CPU name and features.
295 // This may allow us to get some statistics for decisions (such as when
296 // deciding whether SSE2 can be made a hard-requirement for Windows).
297 // Breakpad provides this information poorly or not at all.
298 #if defined( UNX ) && !defined MACOSX && !defined IOS && !defined ANDROID
299 void CrashReporter::writeSystemInfo()
301 // Get 'model name' and 'flags' from /proc/cpuinfo.
302 if( std::ifstream cpuinfo( "/proc/cpuinfo" ); cpuinfo )
304 bool haveModel = false;
305 bool haveFlags = false;
306 std::regex modelRegex( "^model name[ \t]*:[ \t]*(.*)$" );
307 std::regex flagsRegex( "^flags[ \t]*:[ \t]*(.*)$" );
308 for( std::string line; std::getline( cpuinfo, line ); )
310 std::smatch match;
311 if( !haveModel && std::regex_match( line, match, modelRegex ) && match.size() == 2)
313 addKeyValue("CPUModelName", OUString::fromUtf8( match[ 1 ].str()), AddItem);
314 haveModel = true;
316 if( !haveFlags && std::regex_match( line, match, flagsRegex ) && match.size() == 2)
318 addKeyValue("CPUFlags", OUString::fromUtf8( match[ 1 ].str()), AddItem);
319 haveFlags = true;
321 if( haveModel && haveFlags )
322 break;
325 // Get 'MemTotal' from /proc/meminfo.
326 if( std::ifstream meminfo( "/proc/meminfo" ); meminfo )
328 std::regex memTotalRegex( "^MemTotal[ \t]*:[ \t]*(.*)$" );
329 for( std::string line; std::getline( meminfo, line ); )
331 std::smatch match;
332 if( std::regex_match( line, match, memTotalRegex ) && match.size() == 2)
334 addKeyValue("MemoryTotal", OUString::fromUtf8( match[ 1 ].str()), AddItem);
335 break;
340 #elif defined _WIN32
341 void CrashReporter::writeSystemInfo()
343 #if !defined(_ARM64_)
344 // Get CPU model name and flags.
345 // See https://docs.microsoft.com/en-us/cpp/intrinsics/cpuid-cpuidex
346 // and https://en.wikipedia.org/wiki/CPUID .
347 int cpui[ 4 ];
348 __cpuid( cpui, 0x80000000 ); // Get the highest extended ID.
349 unsigned int exIds = cpui[ 0 ];
350 if( exIds >= 0x80000004 )
352 int brand[ 16 ];
353 __cpuidex( brand, 0x80000002, 0 );
354 __cpuidex( brand + 4, 0x80000003, 0 );
355 __cpuidex( brand + 8, 0x80000004, 0 );
356 brand[ 12 ] = 0;;
357 addKeyValue( "CPUModelName", OUString::fromUtf8( reinterpret_cast< const char* >( brand )),
358 AddItem );
360 __cpuid( cpui, 0 ); // Get the highest ID.
361 int ids = cpui[ 0 ];
362 unsigned int ecx1 = 0, edx1 = 0, ebx7 = 0, ecx7 = 0, ecx81 = 0, edx81 = 0;
363 if( ids >= 0x1 )
365 __cpuidex( cpui, 0x1, 0 );
366 ecx1 = cpui[ 2 ];
367 edx1 = cpui[ 3 ];
369 if( ids >= 0x7 )
371 __cpuidex( cpui, 0x7, 0 );
372 ebx7 = cpui[ 1 ];
373 ecx7 = cpui[ 2 ];
375 if( exIds >= 0x80000001 )
377 __cpuidex( cpui, 0x80000001, 0 );
378 ecx81 = cpui[ 2 ];
379 edx81 = cpui[ 3 ];
381 struct FlagItem
383 unsigned int* reg;
384 int bit;
385 const char* name;
387 const FlagItem flagItems[] =
389 { &ecx1, 0, "sse3" },
390 { &ecx1, 1, "pclmulqdq" },
391 { &ecx1, 3, "monitor" },
392 { &ecx1, 9, "ssse3" },
393 { &ecx1, 12, "fma" },
394 { &ecx1, 13, "cpmxch16b" },
395 { &ecx1, 19, "sse41" },
396 { &ecx1, 20, "sse42" },
397 { &ecx1, 22, "movbe" },
398 { &ecx1, 23, "popcnt" },
399 { &ecx1, 25, "aes" },
400 { &ecx1, 26, "xsave" },
401 { &ecx1, 27, "osxsave" },
402 { &ecx1, 28, "avx" },
403 { &ecx1, 29, "f16c" },
404 { &ecx1, 30, "rdrand" },
405 { &edx1, 5, "msr" },
406 { &edx1, 8, "cx8" },
407 { &edx1, 11, "sep" },
408 { &edx1, 15, "cmov" },
409 { &edx1, 19, "clfsh" },
410 { &edx1, 23, "mmx" },
411 { &edx1, 24, "fxsr" },
412 { &edx1, 25, "sse" },
413 { &edx1, 26, "sse2" },
414 { &edx1, 28, "ht" },
415 { &ebx7, 0, "fsgsbase" },
416 { &ebx7, 3, "bmi1" },
417 { &ebx7, 4, "hle" },
418 { &ebx7, 5, "avx2" },
419 { &ebx7, 8, "bmi2" },
420 { &ebx7, 9, "erms" },
421 { &ebx7, 10, "invpcid" },
422 { &ebx7, 11, "rtm" },
423 { &ebx7, 16, "avx512f" },
424 { &ebx7, 18, "rdseed" },
425 { &ebx7, 19, "adx" },
426 { &ebx7, 26, "avx512pf" },
427 { &ebx7, 27, "avx512er" },
428 { &ebx7, 28, "avx512cd" },
429 { &ebx7, 29, "sha" },
430 { &ecx7, 0, "prefetchwt1" },
431 { &ecx81, 0, "lahf" },
432 { &ecx81, 5, "abm" },
433 { &ecx81, 6, "sse4a" },
434 { &ecx81, 11, "xop" },
435 { &ecx81, 21, "tbm" },
436 { &edx81, 11, "syscall" },
437 { &edx81, 22, "mmxext" },
438 { &edx81, 27, "rdtscp" },
439 { &edx81, 30, "3dnowext" },
440 { &edx81, 31, "3dnow" }
442 OUStringBuffer flags;
443 for( const FlagItem& item : flagItems )
445 if( *item.reg & ( 1U << item.bit ))
447 if( !flags.isEmpty())
448 flags.append( " " );
449 flags.appendAscii( item.name );
452 if( !flags.isEmpty())
453 addKeyValue( "CPUFlags", flags.makeStringAndClear(), AddItem );
454 #endif
455 // Get total memory.
456 MEMORYSTATUSEX memoryStatus;
457 memoryStatus.dwLength = sizeof( memoryStatus );
458 if( GlobalMemoryStatusEx( &memoryStatus ))
460 addKeyValue( "MemoryTotal", OUString::number( int( memoryStatus.ullTotalPhys / 1024 ))
461 + " kB", AddItem );
464 #else
465 void CrashReporter::writeSystemInfo()
468 #endif
470 #endif //HAVE_FEATURE_BREAKPAD
472 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */