-
-
Notifications
You must be signed in to change notification settings - Fork 492
/
Copy pathWatchDog.cs
418 lines (350 loc) · 14.4 KB
/
WatchDog.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
using Microsoft.AppCenter;
using Microsoft.AppCenter.Analytics;
using Microsoft.AppCenter.Crashes;
using Microsoft.AppCenter.Utils;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
using System.Security;
using System.Threading.Tasks;
using Telegram.Common;
using Telegram.Controls;
using Telegram.Converters;
using Telegram.Native;
using Telegram.Navigation;
using Telegram.Services;
using Telegram.Td;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
using Windows.Storage;
using Windows.System;
using Windows.System.Profile;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Automation.Peers;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;
using File = System.IO.File;
namespace Telegram
{
/*
* How does this work?
*
* We use a fork of the AppCenter SDK to get more accurate error reports.
* The end goal is to distinguish handled and unhandled exceptions,
* as well to get some insights about unmanaged crashes that
* would be otherwise invisible to us.
*
* When the framework reports a managed unhandled exception via UnhandledException,
* AppCenter SDK will raise CreatingErrorReport, providing a report id to associate
* the exception data with the additional logs that should be sent alongside the report.
* When this happens, crash.log is updated using the report id.
*
* If the process terminates smoothly, we delete crash.log.
* This happens in Application.Suspending.
*
* On the subsequent app launch, we check if crash.log exist and contains a report id.
* If this is the case, we will mark the report as a crash by returning true in
* ShouldProcessErrorReport.
*
* We're also monitoring unmanaged exceptions by registering
* SetUnhandledExceptionFilter on DLL_THREAD_ATTACH from Telegram.Native/dllmain.cpp.
* Whenever an unmanaged exception is thrown, we're going to wrap it
* into an UnmanagedException object, and pass it to Crashes.TrackCrash.
*
* Symbolification of unmanaged exceptions is done manually by using CDB.exe as follows:
* cdb -lines -z "{path to dll}" -y "{path to symbols}"
*
* 0.000> u 0x{base + address}; q
*
* base is 0x180000000 for x64 and 0x10000000 for x86
*
*/
public partial class Properties : Dictionary<string, object>
{
}
public partial class WatchDog
{
private static readonly bool _disabled = Constants.DEBUG;
private static readonly string _crashLog;
private static readonly string _reports;
private static string _lastSessionErrorReportId;
private static bool _lastSessionTerminatedUnexpectedly;
private static DateTime _launchTime;
static WatchDog()
{
_crashLog = Path.Combine(ApplicationData.Current.LocalFolder.Path, "crash.log");
_reports = Path.Combine(ApplicationData.Current.LocalFolder.Path, "Reports");
}
public static bool HasCrashedInLastSession { get; private set; }
public static void Initialize()
{
NativeUtils.SetFatalErrorCallback(FatalErrorCallback);
Client.SetLogMessageCallback(0, FatalErrorCallback);
BootStrapper.Current.UnhandledException += OnUnhandledException;
if (_disabled)
{
return;
}
_launchTime = DateTime.UtcNow;
Read();
TaskScheduler.UnobservedTaskException += (s, args) =>
{
Crashes.TrackCrash(args.Exception);
args.SetObserved();
};
//Crashes.UnhandledExceptionOccurring += (s, args) =>
//{
// args.Frames = NativeUtils.GetStowedException()
// .Select(x => new NativeStackFrame(x.NativeIP, x.NativeImageBase))
// .ToList();
//};
Crashes.CreatingErrorReport += (s, args) =>
{
Track(args.ReportId, args.Exception);
};
Crashes.SentErrorReport += (s, args) =>
{
if (File.Exists(GetErrorReportPath(args.Report.Id)))
{
try
{
File.Delete(GetErrorReportPath(args.Report.Id));
}
catch
{
// Somehow AppCenter messes up and the file might still be open
}
}
};
Crashes.ShouldProcessErrorReport = report =>
{
return report.Id == _lastSessionErrorReportId;
};
Crashes.GetErrorAttachments = report =>
{
var path = GetErrorReportPath(report.Id);
if (path.Length > 0 && File.Exists(path))
{
var data = File.ReadAllText(path);
return new[] { ErrorAttachmentLog.AttachmentWithText(data, "crash.txt") };
}
return Array.Empty<ErrorAttachmentLog>();
};
AppCenter.Start(Constants.AppCenterId, typeof(Analytics), typeof(Crashes));
Analytics.TrackEvent("Windows",
new Dictionary<string, string>
{
{ "DeviceFamily", AnalyticsInfo.VersionInfo.DeviceFamily },
{ "Architecture", Package.Current.Id.Architecture.ToString() },
{ "Processor", OSArchitecture().ToString() }
});
}
[HandleProcessCorruptedStateExceptions, SecurityCritical]
private static void OnUnhandledException(object sender, Windows.UI.Xaml.UnhandledExceptionEventArgs args)
{
args.Handled = args.Exception is not LayoutCycleException;
if (args.Exception is NotSupportedException)
{
var popups = VisualTreeHelper.GetOpenPopups(Window.Current);
foreach (var popup in popups)
{
if (popup.Child is ToolTip tooltip)
{
tooltip.IsOpen = false;
tooltip.IsOpen = true;
tooltip.IsOpen = false;
}
}
return;
}
else if (args.Exception is COMException { ErrorCode: -2147467259 })
{
return;
}
if (SettingsService.Current.Diagnostics.ShowMemoryUsage && Window.Current != null)
{
_ = MessagePopup.ShowAsync(Window.Current.Content.XamlRoot, args.Exception.ToString(), "Unhandled exception", "OK");
}
}
public static Architecture OSArchitecture()
{
var handle = new IntPtr(-1);
var wow64 = IsWow64Process2(handle, out var _, out var nativeMachine);
if (wow64)
{
return nativeMachine == 0xaa64
? Architecture.Arm64
: Architecture.X64;
}
return Architecture.X86;
}
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool IsWow64Process2(IntPtr process, out ushort processMachine, out ushort nativeMachine);
public static void TrackEvent(string name, Properties properties = null)
{
if (_disabled)
{
return;
}
Analytics.TrackEvent(name, properties?.ToDictionary(x => x.Key, y => y.Value.ToString()));
}
private static void Read()
{
if (File.Exists(_crashLog))
{
_lastSessionTerminatedUnexpectedly = true;
var data = File.ReadAllText(_crashLog);
if (Guid.TryParse(data, out Guid guid))
{
_lastSessionErrorReportId = guid.ToString();
}
File.Delete(_crashLog);
}
}
public static void FatalErrorCallback(FatalError error)
{
var exception = ToException(error);
var frames = error.Frames
.Select(x => new NativeStackFrame(x.NativeIP, x.NativeImageBase))
.ToList();
Crashes.TrackCrash(exception, frames);
}
private static Exception ToException(FatalError error)
{
if (error == null)
{
return null;
}
if (error.StackTrace.Contains("libvlc.dll") || error.StackTrace.Contains("libvlccore.dll"))
{
return new VLCException(error.Message + Environment.NewLine + error.StackTrace, error.StackTrace);
}
return new NativeException(error.Message + Environment.NewLine + error.StackTrace, error.StackTrace);
}
private static void FatalErrorCallback(int verbosityLevel, string message)
{
if (verbosityLevel != 0)
{
return;
}
var exception = TdException.FromMessage(message);
if (exception.IsUnhandled)
{
Crashes.TrackCrash(exception);
}
}
public static void Launch(ApplicationExecutionState previousExecutionState)
{
// NotRunning: An app could be in this state because it hasn't been launched
// since the last time the user rebooted or logged in. It can also be in this
// state if it was running but then crashed, or because the user closed it earlier.
HasCrashedInLastSession =
_lastSessionErrorReportId != null
&& previousExecutionState == ApplicationExecutionState.NotRunning;
}
private static void Track(string reportId, Exception exception)
{
var report = BuildReport(exception);
File.WriteAllText(_crashLog, reportId);
File.WriteAllText(GetErrorReportPath(reportId), report);
}
[StructLayout(LayoutKind.Sequential)]
private class MEMORYSTATUSEX
{
public uint dwLength;
public uint dwMemoryLoad;
public ulong ullTotalPhys;
public ulong ullAvailPhys;
public ulong ullTotalPageFile;
public ulong ullAvailPageFile;
public ulong ullTotalVirtual;
public ulong ullAvailVirtual;
public ulong ullAvailExtendedVirtual;
public MEMORYSTATUSEX()
{
dwLength = (uint)Marshal.SizeOf<MEMORYSTATUSEX>();
}
}
[DllImport("kernelbase.dll", ExactSpelling = true, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool GlobalMemoryStatusEx([In, Out] MEMORYSTATUSEX lpBuffer);
public static void MemoryStatus()
{
var status = new MEMORYSTATUSEX();
GlobalMemoryStatusEx(status);
var memoryUsage = FileSizeConverter.Convert((long)MemoryManager.AppMemoryUsage);
var memoryUsageAvailable = FileSizeConverter.Convert((long)status.ullAvailPhys);
var memoryUsageTotal = FileSizeConverter.Convert((long)status.ullTotalPhys);
Logger.Debug(string.Format("Usage: {0}, available: {1}, total: {2}", memoryUsage, memoryUsageAvailable, memoryUsageTotal));
}
public static string BuildReport(Exception exception)
{
var version = VersionLabel.GetVersion();
var language = LocaleService.Current.Id;
var next = DateTime.UtcNow - _launchTime;
var diff = next.ToDuration();
var count = SettingsService.Current.Diagnostics.UpdateCount;
var status = new MEMORYSTATUSEX();
GlobalMemoryStatusEx(status);
var memoryUsage = FileSizeConverter.Convert((long)MemoryManager.AppMemoryUsage);
var memoryUsageAvailable = FileSizeConverter.Convert((long)status.ullAvailPhys);
var memoryUsageTotal = FileSizeConverter.Convert((long)status.ullTotalPhys);
var info =
$"Current version: {version}\n" +
$"Current language: {language}\n" +
$"Current duration: {diff}\n" +
$"Memory usage: {memoryUsage}\n" +
$"Memory available: {memoryUsageAvailable}\n" +
$"Memory total: {memoryUsageTotal}\n" +
$"Update count: {count}\n";
if (WindowContext.Current != null)
{
var reader = AutomationPeer.ListenerExists(AutomationEvents.LiveRegionChanged);
var scaling = (WindowContext.Current.RasterizationScale * 100).ToString("N0");
var text = (BootStrapper.Current.TextScaleFactor * 100).ToString("N0");
var size = Window.Current.Bounds;
var ratio = SettingsService.Current.DialogsWidthRatio;
var width = MasterDetailPanel.CountDialogsWidthFromRatio(size.Width, ratio);
info += $"Screen reader: {reader}\n" +
$"Screen scaling: {scaling}%\n" +
$"Text scaling: {text}%\n" +
$"Window size: {size.Width}x{size.Height}\n" +
$"Column width: {ratio} ({width})\n";
}
info += $"Active call(s): {WindowContext.All.Count(x => x.IsCallInProgress)}\n";
info += $"HRESULT: 0x{exception.HResult:X4}\n" + "\n";
info += Environment.StackTrace + "\n\n";
var dump = Logger.Dump();
return info + dump;
}
private static string GetErrorReportPath(string reportId)
{
Directory.CreateDirectory(_reports);
return Path.Combine(ApplicationData.Current.LocalFolder.Path, _reports, reportId + ".appcenter");
}
public static void Suspend()
{
if (File.Exists(_crashLog))
{
File.Delete(_crashLog);
}
}
}
public partial class VLCException : Exception
{
public VLCException(string message, string stackTrace)
: base(message + "\n" + stackTrace)
{
}
}
public partial class NativeException : Exception
{
public NativeException(string message, string stackTrace)
: base(message + "\n" + stackTrace)
{
}
}
}