forked from Unity-Technologies/UnityCsReference
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAPIUpdaterHelper.cs
More file actions
374 lines (309 loc) · 14.5 KB
/
Copy pathAPIUpdaterHelper.cs
File metadata and controls
374 lines (309 loc) · 14.5 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
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
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using UnityEditor.Utils;
using UnityEngine;
using UnityEngine.Scripting.APIUpdating;
using System.Linq;
using System.Diagnostics;
using System.Text;
using System.Text.RegularExpressions;
using ICSharpCode.NRefactory;
using ICSharpCode.NRefactory.Ast;
using ICSharpCode.NRefactory.Visitors;
using Mono.Cecil;
using Unity.DataContract;
using UnityEditor.Modules;
using UnityEditor.Scripting.Compilers;
using Debug = UnityEngine.Debug;
using SupportedLanguage = ICSharpCode.NRefactory.SupportedLanguage;
using TypeReference = ICSharpCode.NRefactory.Ast.TypeReference;
namespace UnityEditor.Scripting
{
internal class APIUpdaterHelper
{
public static bool IsReferenceToMissingObsoleteMember(string namespaceName, string className)
{
try
{
var found = FindTypeInLoadedAssemblies(t => t.Name == className && t.Namespace == namespaceName && IsUpdateable(t));
return found != null;
}
catch (ReflectionTypeLoadException ex)
{
throw new Exception(ex.Message + ex.LoaderExceptions.Aggregate("", (acc, curr) => acc + "\r\n\t" + curr.Message));
}
}
public static bool IsReferenceToTypeWithChangedNamespace(string normalizedErrorMessage)
{
try
{
var lines = normalizedErrorMessage.Split('\n');
var simpleOrQualifiedName = GetValueFromNormalizedMessage(lines, "EntityName=");
var found = FindExactTypeMatchingMovedType(simpleOrQualifiedName) ?? FindTypeMatchingMovedTypeBasedOnNamespaceFromError(lines);
return found != null;
}
catch (ReflectionTypeLoadException ex)
{
throw new Exception(ex.Message + ex.LoaderExceptions.Aggregate("", (acc, curr) => acc + "\r\n\t" + curr.Message));
}
}
public static void Run(string commaSeparatedListOfAssemblies)
{
var assemblies = commaSeparatedListOfAssemblies.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries);
foreach (var assemblyPath in assemblies)
{
if ((File.GetAttributes(assemblyPath) & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
{
APIUpdaterLogger.WriteErrorToConsole("Error can't update assembly {0} the file is read-only", assemblyPath);
return;
}
}
APIUpdaterLogger.WriteToFile("Started to update {0} assemblie(s)", assemblies.Count());
var sw = new Stopwatch();
sw.Start();
foreach (var assemblyPath in assemblies)
{
if (!AssemblyHelper.IsManagedAssembly(assemblyPath))
continue;
string stdOut, stdErr;
var assemblyFullPath = ResolveAssemblyPath(assemblyPath);
var exitCode = RunUpdatingProgram("AssemblyUpdater.exe", "-u -a " + assemblyFullPath + APIVersionArgument() + AssemblySearchPathArgument() + ConfigurationProviderAssembliesPathArgument(), out stdOut, out stdErr);
if (stdOut.Length > 0)
APIUpdaterLogger.WriteToFile("Assembly update output ({0})\r\n{1}", assemblyFullPath, stdOut);
if (IsError(exitCode))
APIUpdaterLogger.WriteErrorToConsole("Error {0} running AssemblyUpdater. Its output is: `{1}`", exitCode, stdErr);
}
APIUpdaterLogger.WriteToFile("Update finished in {0}s", sw.Elapsed.TotalSeconds);
}
private static bool IsError(int exitCode)
{
return (exitCode & (1 << 7)) != 0;
}
private static string ResolveAssemblyPath(string assemblyPath)
{
return CommandLineFormatter.PrepareFileName(assemblyPath);
}
public static bool DoesAssemblyRequireUpgrade(string assemblyFullPath)
{
if (!File.Exists(assemblyFullPath))
return false;
if (!AssemblyHelper.IsManagedAssembly(assemblyFullPath))
return false;
if (!MayContainUpdatableReferences(assemblyFullPath))
return false;
string stdOut, stdErr;
var ret = RunUpdatingProgram("AssemblyUpdater.exe", TimeStampArgument() + APIVersionArgument() + "--check-update-required -a " + CommandLineFormatter.PrepareFileName(assemblyFullPath) + AssemblySearchPathArgument() + ConfigurationProviderAssembliesPathArgument(), out stdOut, out stdErr);
{
Console.WriteLine("{0}{1}", stdOut, stdErr);
switch (ret)
{
// See AssemblyUpdater/Program.cs
case 0:
case 1: return false;
case 2: return true;
default:
Debug.LogError(stdOut + Environment.NewLine + stdErr);
return false;
}
}
}
private static string AssemblySearchPathArgument()
{
var searchPath = Path.Combine(MonoInstallationFinder.GetFrameWorksFolder(), "Managed") + ","
+ "+" + Path.Combine(EditorApplication.applicationContentsPath, "UnityExtensions/Unity") + ","
+ "+" + Application.dataPath;
return " -s \"" + searchPath + "\"";
}
private static string ConfigurationProviderAssembliesPathArgument()
{
var paths = new StringBuilder();
foreach (var ext in ModuleManager.packageManager.unityExtensions)
{
foreach (var dllPath in ext.files.Where(f => f.Value.type == PackageFileType.Dll).Select(pi => pi.Key))
{
paths.AppendFormat(" {0}", CommandLineFormatter.PrepareFileName(Path.Combine(ext.basePath, dllPath)));
}
}
var editorManagedPath = GetUnityEditorManagedPath();
paths.AppendFormat(" {0}", CommandLineFormatter.PrepareFileName(Path.Combine(editorManagedPath, "UnityEngine.dll")));
paths.AppendFormat(" {0}", CommandLineFormatter.PrepareFileName(Path.Combine(editorManagedPath, "UnityEditor.dll")));
return paths.ToString();
}
private static string GetUnityEditorManagedPath()
{
return Path.Combine(MonoInstallationFinder.GetFrameWorksFolder(), "Managed");
}
private static int RunUpdatingProgram(string executable, string arguments, out string stdOut, out string stdErr)
{
var scriptUpdater = EditorApplication.applicationContentsPath + "/Tools/ScriptUpdater/" + executable;
var program = new ManagedProgram(MonoInstallationFinder.GetMonoInstallation("MonoBleedingEdge"), null, scriptUpdater, arguments, false, null);
program.LogProcessStartInfo();
program.Start();
program.WaitForExit();
stdOut = program.GetStandardOutputAsString();
stdErr = string.Join("\r\n", program.GetErrorOutput());
return program.ExitCode;
}
private static string APIVersionArgument()
{
return " --api-version " + Application.unityVersion + " ";
}
private static string TimeStampArgument()
{
return " --timestamp " + DateTime.Now.Ticks + " ";
}
private static bool IsUpdateable(Type type)
{
var attrs = type.GetCustomAttributes(typeof(ObsoleteAttribute), false);
if (attrs.Length != 1)
return false;
var oa = (ObsoleteAttribute)attrs[0];
return oa.Message.Contains("UnityUpgradable");
}
private static bool NamespaceHasChanged(Type type, string namespaceName)
{
var attrs = type.GetCustomAttributes(typeof(MovedFromAttribute), false);
if (attrs.Length != 1)
return false;
if (string.IsNullOrEmpty(namespaceName))
return true;
var from = (MovedFromAttribute)attrs[0];
return from.Namespace == namespaceName;
}
private static Type FindTypeInLoadedAssemblies(Func<Type, bool> predicate)
{
var found = AppDomain.CurrentDomain.GetAssemblies()
.Where(assembly => !IsIgnoredAssembly(assembly.GetName()))
.SelectMany<Assembly, Type>(a => GetValidTypesIn(a))
.FirstOrDefault(predicate);
return found;
}
private static IEnumerable<Type> GetValidTypesIn(Assembly a)
{
Type[] types;
try
{
types = a.GetTypes();
}
catch (ReflectionTypeLoadException e)
{
types = e.Types;
}
return types.Where(t => t != null);
}
private static bool IsIgnoredAssembly(AssemblyName assemblyName)
{
var name = assemblyName.Name;
return _ignoredAssemblies.Any(candidate => Regex.IsMatch(name, candidate));
}
internal static bool MayContainUpdatableReferences(string assemblyPath)
{
using (var assembly = AssemblyDefinition.ReadAssembly(assemblyPath))
{
if (assembly.Name.IsWindowsRuntime)
return false;
if (!IsTargetFrameworkValidOnCurrentOS(assembly))
return false;
}
return true;
}
private static bool IsTargetFrameworkValidOnCurrentOS(AssemblyDefinition assembly)
{
return Environment.OSVersion.Platform == PlatformID.Win32NT
|| !(assembly.HasCustomAttributes && assembly.CustomAttributes.Any(attr => TargetsWindowsSpecificFramework(attr)));
}
private static bool TargetsWindowsSpecificFramework(CustomAttribute targetFrameworkAttr)
{
if (!targetFrameworkAttr.AttributeType.FullName.Contains("System.Runtime.Versioning.TargetFrameworkAttribute"))
return false;
var regex = new Regex("\\.NETCore|\\.NETPortable");
var targetsNetCoreOrPCL = targetFrameworkAttr.ConstructorArguments.Any(arg => arg.Type.FullName == typeof(string).FullName && regex.IsMatch((string)arg.Value));
return targetsNetCoreOrPCL;
}
private static Type FindExactTypeMatchingMovedType(string simpleOrQualifiedName)
{
var match = Regex.Match(simpleOrQualifiedName, @"^(?:(?<namespace>.*)(?=\.)\.)?(?<typename>[a-zA-Z_0-9]+)$");
if (!match.Success)
return null;
var typename = match.Groups["typename"].Value;
var namespaceName = match.Groups["namespace"].Value;
return FindTypeInLoadedAssemblies(t => t.Name == typename && NamespaceHasChanged(t, namespaceName));
}
// C# compiler does not emmit the full qualified type name when it fails to resolve a 'theorically', fully qualified type reference
// for instance, if 'NSBar', a namespace gets renamed to 'NSBar2', a refernce to 'NSFoo.NSBar.TypeBaz' will emit an error
// with only NSBar and NSFoo in the message. In this case we use NRefactory to dive in to the code, looking for type references
// in the reported error line/column
private static Type FindTypeMatchingMovedTypeBasedOnNamespaceFromError(IEnumerable<string> lines)
{
var value = GetValueFromNormalizedMessage(lines, "Line=");
var line = (value != null) ? Int32.Parse(value) : -1;
value = GetValueFromNormalizedMessage(lines, "Column=");
var column = (value != null) ? Int32.Parse(value) : -1;
var script = GetValueFromNormalizedMessage(lines, "Script=");
if (line == -1 || column == -1 || script == null)
{
return null;
}
try
{
using (var scriptStream = File.Open(script, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
var parser = ParserFactory.CreateParser(SupportedLanguage.CSharp, new StreamReader(scriptStream));
parser.Lexer.EvaluateConditionalCompilation = false;
parser.Parse();
var typeNotFound = InvalidTypeOrNamespaceErrorTypeMapper.IsTypeMovedToNamespaceError(parser.CompilationUnit, line, column);
if (typeNotFound == null)
return null;
return FindExactTypeMatchingMovedType(typeNotFound);
}
}
catch (FileNotFoundException)
{
return null;
}
}
private static string GetValueFromNormalizedMessage(IEnumerable<string> lines, string marker)
{
string value = null;
var foundLine = lines.FirstOrDefault(l => l.StartsWith(marker));
if (foundLine != null)
{
value = foundLine.Substring(marker.Length).Trim();
}
return value;
}
private static string[] _ignoredAssemblies = { "^UnityScript$", "^System\\..*", "^mscorlib$" };
}
internal class InvalidTypeOrNamespaceErrorTypeMapper : AbstractAstVisitor
{
public static string IsTypeMovedToNamespaceError(CompilationUnit cu, int line, int column)
{
var self = new InvalidTypeOrNamespaceErrorTypeMapper(line, column);
cu.AcceptVisitor(self, null);
return self.Found;
}
public string Found { get; private set; }
private readonly int _line;
private readonly int _column;
public override object VisitTypeReference(TypeReference typeReference, object data)
{
var withinRange = _column >= typeReference.StartLocation.Column && _column < typeReference.StartLocation.Column + typeReference.Type.Length;
if (typeReference.StartLocation.Line == _line && withinRange)
{
Found = typeReference.Type;
return true;
}
return base.VisitTypeReference(typeReference, data);
}
private InvalidTypeOrNamespaceErrorTypeMapper(int line, int column)
{
_line = line;
_column = column;
}
}
}