-
-
Notifications
You must be signed in to change notification settings - Fork 60
Expand file tree
/
Copy pathBuildPostProcess.cs
More file actions
281 lines (255 loc) · 11.4 KB
/
BuildPostProcess.cs
File metadata and controls
281 lines (255 loc) · 11.4 KB
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
using System;
using System.IO;
using Sentry.Extensibility;
using Sentry.Unity.Editor.ConfigurationWindow;
using System.Text.RegularExpressions;
using UnityEngine;
using UnityEditor;
using UnityEditor.Build;
using UnityEditor.Callbacks;
using System.Diagnostics;
namespace Sentry.Unity.Editor.Native;
public static class BuildPostProcess
{
[PostProcessBuild(1)]
public static void OnPostProcessBuild(BuildTarget target, string executablePath)
{
var targetGroup = BuildPipeline.GetBuildTargetGroup(target);
if (targetGroup is not BuildTargetGroup.Standalone
and not BuildTargetGroup.GameCoreXboxSeries
and not BuildTargetGroup.PS5)
{
return;
}
var cliOptions = SentryScriptableObject.LoadCliOptions();
var options = SentryScriptableObject.LoadOptions(isBuilding: true);
var logger = options?.DiagnosticLogger ?? new UnityLogger(options ?? new SentryUnityOptions());
if (options is null)
{
logger.LogWarning("Native support disabled because Sentry has not been configured. " +
"You can do that through the editor: {0}", SentryWindow.EditorMenuPath);
return;
}
if (!options.IsValid())
{
logger.LogDebug("Skipping native post build process.");
return;
}
#pragma warning disable CS0618
var isMono = PlayerSettings.GetScriptingBackend(targetGroup) == ScriptingImplementation.Mono2x;
#pragma warning restore CS0618
// The executable path resolves to the following when pointing Unity into a `build/platform/` directory:
// - Desktop: `./samples/unity-of-bugs/builds/windows/unityofbugs.exe`
// - Xbox: `./samples/unity-of-bugs/builds/xsx/`
// - PlayStation: `./samples/unity-of-bugs/builds/ps5/`
var buildOutputDir = targetGroup switch
{
BuildTargetGroup.Standalone => Path.GetDirectoryName(executablePath),
BuildTargetGroup.GameCoreXboxSeries => executablePath,
BuildTargetGroup.PS5 => executablePath,
_ => string.Empty
};
if (string.IsNullOrEmpty(buildOutputDir))
{
logger.LogError("Failed to find build output directory based on the executable path '{0}'." +
"\nSkipping adding crash-handler and uploading debug symbols.", executablePath);
return;
}
UploadDebugSymbols(logger, target, buildOutputDir, options, cliOptions, isMono);
if (!IsEnabledForPlatform(target, options))
{
logger.LogDebug("Skipping adding the crash-handler. Native support for the current platform is disabled in the configuration.");
return;
}
try
{
AddCrashHandler(logger, target, buildOutputDir);
}
catch (Exception e)
{
logger.LogError(e, "Failed to add the crash-handler to the built application.");
throw new BuildFailedException("Sentry Native BuildPostProcess failed");
}
}
private static bool IsEnabledForPlatform(BuildTarget target, SentryUnityOptions options) => target switch
{
BuildTarget.StandaloneWindows => options.WindowsNativeSupportEnabled,
BuildTarget.StandaloneWindows64 => options.WindowsNativeSupportEnabled,
BuildTarget.StandaloneOSX => options.MacosNativeSupportEnabled,
BuildTarget.StandaloneLinux64 => options.LinuxNativeSupportEnabled,
BuildTarget.GameCoreXboxSeries or BuildTarget.GameCoreXboxOne => options.XboxNativeSupportEnabled,
BuildTarget.PS5 => options.PlayStationNativeSupportEnabled,
_ => false,
};
private static void AddCrashHandler(IDiagnosticLogger logger, BuildTarget target, string buildOutputDir)
{
switch (target)
{
case BuildTarget.StandaloneWindows:
case BuildTarget.StandaloneWindows64:
logger.LogDebug("Adding crashpad.");
CopyHandler(logger, buildOutputDir, Path.Combine("Windows", "Sentry", "crashpad_handler.exe"));
CopyHandler(logger, buildOutputDir, Path.Combine("Windows", "Sentry", "crashpad_wer.dll"));
break;
case BuildTarget.StandaloneLinux64:
case BuildTarget.StandaloneOSX:
// No standalone crash handler for Linux/macOS - uses built-in handlers.
return;
case BuildTarget.GameCoreXboxSeries:
case BuildTarget.GameCoreXboxOne:
// No standalone crash handler for Xbox - comes with Breakpad
return;
case BuildTarget.PS5:
// No standalone crash handler for PlayStation
return;
default:
throw new ArgumentException($"Unsupported build target: {target}");
}
}
private static void CopyHandler(IDiagnosticLogger logger, string buildOutputDir, string handlerPath)
{
var fullHandlerPath = Path.GetFullPath(Path.Combine("Packages", SentryPackageInfo.GetName(), "Plugins", handlerPath));
var targetHandlerPath = Path.Combine(buildOutputDir, Path.GetFileName(fullHandlerPath));
logger.LogInfo("Copying handler '{0}' to {1}", Path.GetFileName(fullHandlerPath), targetHandlerPath);
File.Copy(fullHandlerPath, targetHandlerPath, true);
}
private static void UploadDebugSymbols(IDiagnosticLogger logger, BuildTarget target, string buildOutputDir, SentryUnityOptions options, SentryCliOptions? cliOptions, bool isMono)
{
var projectDir = Directory.GetParent(Application.dataPath).FullName;
if (cliOptions?.IsValid(logger, EditorUserBuildSettings.development) is not true)
{
if (options.Il2CppLineNumberSupportEnabled)
{
logger.LogWarning("The IL2CPP line number support requires the debug symbol upload to be enabled.");
}
return;
}
logger.LogInfo("Uploading debugging information using sentry-cli in {0}", buildOutputDir);
// Setting the `buildOutputDir` as the root for debug symbol upload. This will make sure we pick up
// `BurstDebugInformation` and`_DoNotShip` as well
var paths = $" \"{buildOutputDir}\"";
switch (target)
{
case BuildTarget.StandaloneWindows:
case BuildTarget.StandaloneWindows64:
var windowsSentryPdb = Path.GetFullPath($"Packages/{SentryPackageInfo.GetName()}/Plugins/Windows/Sentry/sentry.pdb");
if (File.Exists(windowsSentryPdb))
{
paths += $" \"{windowsSentryPdb}\"";
}
break;
case BuildTarget.GameCoreXboxSeries:
case BuildTarget.GameCoreXboxOne:
var xboxSentryPluginPath = Path.GetFullPath("Assets/Plugins/Sentry/");
if (Directory.Exists(xboxSentryPluginPath))
{
paths += $" \"{xboxSentryPluginPath}\"";
}
break;
case BuildTarget.PS5:
var playstationSentryPluginPath = Path.GetFullPath("Assets/Plugins/Sentry/");
if (Directory.Exists(playstationSentryPluginPath))
{
paths += $" \"{playstationSentryPluginPath}\"";
}
break;
case BuildTarget.StandaloneLinux64:
// Add debug symbols for both x86_64 and ARM64 - sentry-cli will match by debug ID
var linuxSentryDbgX64 = Path.GetFullPath($"Packages/{SentryPackageInfo.GetName()}/Plugins/Linux/Sentry/x86_64/libsentry.dbg.so");
if (File.Exists(linuxSentryDbgX64))
{
paths += $" \"{linuxSentryDbgX64}\"";
}
var linuxSentryDbgArm64 = Path.GetFullPath($"Packages/{SentryPackageInfo.GetName()}/Plugins/Linux/Sentry/arm64/libsentry.dbg.so");
if (File.Exists(linuxSentryDbgArm64))
{
paths += $" \"{linuxSentryDbgArm64}\"";
}
break;
case BuildTarget.StandaloneOSX:
var macOSSentryDsym = Path.GetFullPath($"Packages/{SentryPackageInfo.GetName()}/Plugins/macOS/Sentry/Sentry.dylib.dSYM");
if (Directory.Exists(macOSSentryDsym))
{
paths += $" \"{macOSSentryDsym}\"";
}
break;
default:
logger.LogError($"Symbol upload for '{target}' is currently not supported.");
return;
}
// Unity stores the .pdb files for script assemblies in `./Temp/ManagedSymbols/`
var managedSymbolsDirectory = $"{projectDir}/Temp/ManagedSymbols";
if (Directory.Exists(managedSymbolsDirectory))
{
paths += $" \"{managedSymbolsDirectory}\"";
}
var cliArgs = "debug-files upload ";
if (!isMono)
{
cliArgs += "--il2cpp-mapping ";
}
if (cliOptions.UploadSources)
{
cliArgs += "--include-sources ";
}
if (cliOptions.IgnoreCliErrors)
{
cliArgs += "--allow-failure";
}
cliArgs += paths;
// Configure the process using the StartInfo properties.
var process = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = SentryCli.SetupSentryCli(),
WorkingDirectory = buildOutputDir,
Arguments = cliArgs,
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true
}
};
var propertiesFile = SentryCli.CreateSentryProperties(buildOutputDir, cliOptions, options);
try
{
process.StartInfo.EnvironmentVariables["SENTRY_PROPERTIES"] = propertiesFile;
DataReceivedEventHandler logForwarder = (object sender, DataReceivedEventArgs e) =>
{
if (!string.IsNullOrEmpty(e.Data))
{
var msg = e.Data.Trim();
var msgLower = msg.ToLowerInvariant();
var level = SentryLevel.Debug;
if (msgLower.StartsWith("error"))
{
level = SentryLevel.Error;
}
else if (msgLower.StartsWith("warn"))
{
level = SentryLevel.Warning;
}
else if (msgLower.StartsWith("info"))
{
level = SentryLevel.Info;
}
// Remove the level and timestamp from the beginning of the message.
// INFO 2022-06-20 15:10:03.613794800 +02:00
msg = Regex.Replace(msg, "^[a-zA-Z]+ +[0-9\\-]{10} [0-9:]{8}\\.[0-9]+ \\+[0-9:]{5} +", "");
logger.Log(level, "sentry-cli: {0}", null, msg);
}
};
process.OutputDataReceived += logForwarder;
process.ErrorDataReceived += logForwarder;
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
process.WaitForExit();
}
finally
{
File.Delete(propertiesFile);
}
}
}