-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAssemblyTranslator.cs
More file actions
3256 lines (2599 loc) · 127 KB
/
Copy pathAssemblyTranslator.cs
File metadata and controls
3256 lines (2599 loc) · 127 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
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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using ICSharpCode.Decompiler.Ast;
using ICSharpCode.Decompiler.ILAst;
using JSIL.Ast;
using JSIL.Internal;
using JSIL.Transforms;
using JSIL.Translator;
using Mono.Cecil;
using ICSharpCode.Decompiler;
using GenericParameterAttributes = Mono.Cecil.GenericParameterAttributes;
using MethodInfo = JSIL.Internal.MethodInfo;
using TypeInfo = JSIL.Internal.TypeInfo;
namespace JSIL {
public delegate void AssemblyLoadedHandler (string assemblyName, string classification);
public delegate void ProgressHandler (ProgressReporter pr);
public delegate void DecompilingMethodHandler (string methodName, ProgressReporter pr);
public delegate void LoadErrorHandler (string name, Exception error);
public class AssemblyTranslator : IDisposable {
public struct Cachers {
public readonly TypeExpressionCacher Type;
public readonly SignatureCacher Signature;
public readonly BaseMethodCacher BaseMethod;
public Cachers (TypeExpressionCacher type, SignatureCacher signature, BaseMethodCacher baseMethod) {
if (type == null)
throw new ArgumentNullException("type");
else if (signature == null)
throw new ArgumentNullException("signature");
else if (baseMethod == null)
throw new ArgumentNullException("baseMethod");
Type = type;
Signature = signature;
BaseMethod = baseMethod;
}
}
struct MethodToAnalyze {
public readonly MethodDefinition MD;
public readonly MethodInfo MI;
public MethodToAnalyze (MethodDefinition md) {
MD = md;
MI = null;
}
public MethodToAnalyze (MethodInfo mi) {
MD = mi.Member;
MI = mi;
}
}
public const int LargeMethodThreshold = 20 * 1024;
public const int DefaultStreamCapacity = 4 * (1024 * 1024);
public readonly Configuration Configuration;
public readonly SymbolProvider SymbolProvider = new SymbolProvider();
public readonly AssemblyCache AssemblyCache;
public readonly FunctionCache FunctionCache;
public readonly AssemblyManifest Manifest;
public readonly List<Exception> Failures = new List<Exception>();
public event AssemblyLoadedHandler AssemblyLoaded;
public event AssemblyLoadedHandler AssemblyNotLoaded;
public event AssemblyLoadedHandler ProxyAssemblyLoaded;
public event ProgressHandler Decompiling;
public event ProgressHandler RunningTransforms;
public event ProgressHandler Writing;
public event DecompilingMethodHandler DecompilingMethod;
public event LoadErrorHandler CouldNotLoadSymbols;
public event LoadErrorHandler CouldNotResolveAssembly;
public event LoadErrorHandler CouldNotDecompileMethod;
public event Action<string> Warning;
public event Action<string, string[]> IgnoredMethod;
public event Action<TypeIdentifier> ProxyNotMatched;
public event Action<QualifiedMemberIdentifier> ProxyMemberNotMatched;
public event Action<AssemblyDefinition[]> AssembliesLoaded;
public event Action AnalyzeStarted;
public event Func<MemberReference, bool> MemberCanBeSkipped;
public readonly TypeInfoProvider _TypeInfoProvider;
protected bool OwnsAssemblyCache;
protected bool OwnsTypeInfoProvider;
protected readonly static HashSet<string> TypeDeclarationsToSuppress = new HashSet<string> {
"System.Object", "System.ValueType", "System.Type", "System.RuntimeType",
"System.Reflection.MemberInfo", "System.Reflection.MethodBase",
"System.Reflection.MethodInfo", "System.Reflection.FieldInfo",
"System.Reflection.ConstructorInfo", "System.Reflection.PropertyInfo",
"System.Array", "System.Delegate", "System.MulticastDelegate",
"System.Byte", "System.SByte",
"System.UInt16", "System.Int16",
"System.UInt32", "System.Int32",
"System.UInt64", "System.Int64",
"System.Single", "System.Double",
"System.Boolean", "System.Char",
"System.Reflection.Assembly", "System.Reflection.RuntimeAssembly",
"System.Attribute", "System.Decimal",
"System.IntPtr", "System.UIntPtr"
};
public AssemblyTranslator (
Configuration configuration,
TypeInfoProvider typeInfoProvider = null,
AssemblyManifest manifest = null,
AssemblyCache assemblyCache = null,
AssemblyLoadedHandler onProxyAssemblyLoaded = null
) {
ProxyAssemblyLoaded = onProxyAssemblyLoaded;
Warning = (s) =>
Console.Error.WriteLine("// {0}", s);
Configuration = configuration;
bool useDefaultProxies = configuration.UseDefaultProxies.GetValueOrDefault(true);
Manifest = manifest ?? new AssemblyManifest();
if (typeInfoProvider != null) {
_TypeInfoProvider = typeInfoProvider;
OwnsTypeInfoProvider = false;
if (configuration.Assemblies.Proxies.Count > 0)
throw new InvalidOperationException("Cannot reuse an existing type provider if explicitly loading proxies");
} else {
_TypeInfoProvider = new JSIL.TypeInfoProvider();
OwnsTypeInfoProvider = true;
if (useDefaultProxies) {
var defaultProxyAssembly =
GetDefaultProxyAssembly(configuration.FrameworkVersion.GetValueOrDefault(4.0));
if (defaultProxyAssembly == null)
throw new InvalidOperationException("No default proxy assembly was loaded.");
AddProxyAssembly(defaultProxyAssembly);
}
foreach (var fn in configuration.Assemblies.Proxies.Distinct())
AddProxyAssembly(fn);
}
OwnsAssemblyCache = (assemblyCache == null);
AssemblyCache = assemblyCache ?? new AssemblyCache();
FunctionCache = new FunctionCache(_TypeInfoProvider);
}
public static Assembly GetDefaultProxyAssembly (double frameworkVersion) {
var myAssemblyPath = Util.GetPathOfAssembly(Assembly.GetExecutingAssembly());
var proxyFolder = Path.GetDirectoryName(myAssemblyPath);
string proxyPath = null;
try {
if (frameworkVersion == 4.0) {
proxyPath = Path.Combine(proxyFolder, "JSIL.Proxies.4.0.dll");
} else {
throw new ArgumentOutOfRangeException(
"frameworkVersion",
String.Format("Framework version '{0}' not supported", frameworkVersion)
);
}
return Assembly.LoadFile(proxyPath);
} catch (FileNotFoundException fnf) {
throw new FileNotFoundException(
String.Format("Could not load the .NET proxies assembly from '{0}'.", proxyPath),
fnf
);
}
}
internal void WarningFormatFunction (string functionName, string format, params object[] args) {
Warning(String.Format("{0}: {1}", functionName, String.Format(format, args)));
}
internal void WarningFormat (string format, params object[] args) {
Warning(String.Format(format, args));
}
protected virtual ReaderParameters GetReaderParameters (bool useSymbols, string mainAssemblyPath = null) {
var readerParameters = new ReaderParameters {
ReadingMode = ReadingMode.Deferred,
ReadSymbols = useSymbols
};
if (mainAssemblyPath != null) {
readerParameters.AssemblyResolver = new AssemblyResolver(new string[] {
Path.GetDirectoryName(mainAssemblyPath),
Path.GetDirectoryName(Util.GetPathOfAssembly(Assembly.GetExecutingAssembly()))
}, Configuration, AssemblyCache);
readerParameters.MetadataResolver = new CachingMetadataResolver(readerParameters.AssemblyResolver);
}
if (useSymbols)
readerParameters.SymbolReaderProvider = SymbolProvider;
return readerParameters;
}
private void OnProxiesFoundHandler (AssemblyDefinition asm) {
if (ProxyAssemblyLoaded != null)
ProxyAssemblyLoaded(asm.Name.Name, "proxy");
}
public void AddProxyAssembly (string path) {
var assemblies = LoadAssembly(path, Configuration.UseSymbols.GetValueOrDefault(true), false);
_TypeInfoProvider.AddProxyAssemblies(OnProxiesFoundHandler, assemblies);
}
public void AddProxyAssembly (Assembly assembly) {
var path = Util.GetPathOfAssembly(assembly);
AddProxyAssembly(path);
}
public AssemblyDefinition[] LoadAssembly (string path) {
return LoadAssembly(
path,
Configuration.UseSymbols.GetValueOrDefault(true),
Configuration.IncludeDependencies.GetValueOrDefault(true)
);
}
protected AssemblyDefinition AssemblyLoadErrorWrapper<T> (
Func<T, ReaderParameters, AssemblyDefinition> loader,
T assemblyName, ReaderParameters readerParameters,
bool useSymbols, string mainAssemblyPath
) {
AssemblyDefinition result = null;
try {
result = loader(assemblyName, readerParameters);
} catch (Exception ex) {
if (useSymbols) {
try {
result = loader(assemblyName, GetReaderParameters(false, mainAssemblyPath));
if (CouldNotLoadSymbols != null)
CouldNotLoadSymbols(assemblyName.ToString(), ex);
} catch (Exception ex2) {
if (CouldNotResolveAssembly != null)
CouldNotResolveAssembly(assemblyName.ToString(), ex2);
}
} else {
if (CouldNotResolveAssembly != null)
CouldNotResolveAssembly(assemblyName.ToString(), ex);
}
}
return result;
}
protected ParallelOptions GetParallelOptions () {
return new ParallelOptions {
MaxDegreeOfParallelism = Configuration.UseThreads.GetValueOrDefault(true)
? (Environment.ProcessorCount + 2)
: 1
};
}
protected bool IsIgnored (string assemblyName) {
foreach (var ia in Configuration.Assemblies.Ignored) {
if (Regex.IsMatch(assemblyName, ia, RegexOptions.IgnoreCase))
return true;
}
return false;
}
protected bool IsRedirected (string assemblyName) {
foreach (var ra in Configuration.Assemblies.Redirects.Keys) {
if (Regex.IsMatch(assemblyName, ra, RegexOptions.IgnoreCase))
return true;
}
return false;
}
public string ClassifyAssembly (AssemblyDefinition asm) {
if (IsIgnored(asm.FullName))
return "ignored";
else if (IsStubbed(asm))
return "stubbed";
else
return "translate";
}
protected AssemblyDefinition[] LoadAssembly (string path, bool useSymbols, bool includeDependencies) {
if (String.IsNullOrWhiteSpace(path))
throw new InvalidDataException("Assembly path was empty.");
var readerParameters = GetReaderParameters(useSymbols, path);
var assembly = AssemblyLoadErrorWrapper(
AssemblyDefinition.ReadAssembly,
path, readerParameters,
useSymbols, path
);
if (assembly == null)
throw new FileNotFoundException("Could not load the assembly '" + path + "'");
var result = new List<AssemblyDefinition> {
assembly
};
if (AssemblyLoaded != null)
AssemblyLoaded(path, ClassifyAssembly(assembly));
if (includeDependencies) {
var parallelOptions = GetParallelOptions();
var modulesToVisit = new List<ModuleDefinition>(assembly.Modules);
var assembliesToLoad = new List<AssemblyNameReference>();
var visitedModules = new HashSet<string>();
var assemblyNames = new HashSet<string>();
while ((modulesToVisit.Count > 0) || (assembliesToLoad.Count > 0)) {
foreach (var module in modulesToVisit) {
if (visitedModules.Contains(module.FullyQualifiedName))
continue;
visitedModules.Add(module.FullyQualifiedName);
foreach (var reference in module.AssemblyReferences) {
bool ignored = IsIgnored(reference.FullName);
if (ignored) {
if (AssemblyNotLoaded != null)
AssemblyNotLoaded(reference.FullName, "ignored");
continue;
}
if (assemblyNames.Contains(reference.FullName))
continue;
assemblyNames.Add(reference.FullName);
assembliesToLoad.Add(reference);
}
}
modulesToVisit.Clear();
Parallel.For(
0, assembliesToLoad.Count, parallelOptions, (i) => {
var anr = assembliesToLoad[i];
var refAssembly = AssemblyLoadErrorWrapper(
readerParameters.AssemblyResolver.Resolve,
anr, readerParameters,
useSymbols, path
);
if (refAssembly != null) {
if (AssemblyLoaded != null)
AssemblyLoaded(refAssembly.MainModule.FullyQualifiedName, ClassifyAssembly(refAssembly));
lock (result)
result.Add(refAssembly);
lock (modulesToVisit)
modulesToVisit.AddRange(refAssembly.Modules);
} else {
Warning(String.Format(
"Failed to load assembly '{0}'", anr.FullName
));
}
}
);
assembliesToLoad.Clear();
}
}
// HACK: If an assembly we loaded has indirect references to multiple versions of BCL assemblies,
// Cecil will resolve them all to the same version. As a result, we'll end up with multiple copies
// of the same assembly in result. We need to filter those out so we only return each assembly once.
return result.Distinct(new FullNameAssemblyComparer()).ToArray();
}
protected DecompilerContext MakeDecompilerContext (ModuleDefinition module) {
return new DecompilerContext(module) {
Settings = {
AsyncAwait = false,
YieldReturn = false,
AnonymousMethods = true,
QueryExpressions = false,
LockStatement = false,
FullyQualifyAmbiguousTypeNames = true,
ForEachStatement = false,
ExpressionTrees = false,
ObjectOrCollectionInitializers = false
}
};
}
protected virtual string FormatOutputFilename (AssemblyNameDefinition assemblyName) {
var result = assemblyName.ToString();
if (Configuration.FilenameEscapeRegex != null)
return Regex.Replace(result, Configuration.FilenameEscapeRegex, "_");
else
return result;
}
public TranslationResult Translate (
string assemblyPath, bool scanForProxies = true
) {
var originalLatencyMode = System.Runtime.GCSettings.LatencyMode;
try {
#if TARGETTING_FX_4_5
if (Configuration.TuneGarbageCollection.GetValueOrDefault(true))
System.Runtime.GCSettings.LatencyMode = System.Runtime.GCLatencyMode.SustainedLowLatency;
#endif
var sw = Stopwatch.StartNew();
if (Configuration.RunBugChecks.GetValueOrDefault(true))
BugChecks.RunBugChecks();
else
Console.Error.WriteLine("// WARNING: Bug checks have been suppressed. You may be running JSIL on a broken/unsupported .NET runtime.");
var result = TranslateInternal(assemblyPath, scanForProxies);
sw.Stop();
result.Elapsed = sw.Elapsed;
return result;
} finally {
System.Runtime.GCSettings.LatencyMode = originalLatencyMode;
}
}
private TranslationResult TranslateInternal (
string assemblyPath, bool scanForProxies = true
) {
var result = new TranslationResult(this.Configuration, assemblyPath, Manifest);
var assemblies = new [] {assemblyPath}.Union(this.Configuration.Assemblies.TranslateAdditional).Distinct()
.SelectMany(LoadAssembly).Distinct(new FullNameAssemblyComparer()).ToArray();
var parallelOptions = GetParallelOptions();
if (AssembliesLoaded != null)
AssembliesLoaded(assemblies);
if (AnalyzeStarted != null) {
AnalyzeStarted();
}
if (scanForProxies)
_TypeInfoProvider.AddProxyAssemblies(OnProxiesFoundHandler, assemblies);
var pr = new ProgressReporter();
if (Decompiling != null)
Decompiling(pr);
var methodsToAnalyze = new ConcurrentBag<MethodToAnalyze>();
for (int i = 0; i < assemblies.Length; i++) {
pr.OnProgressChanged(i, assemblies.Length * 2);
GetMethodsToAnalyze(assemblies[i], methodsToAnalyze);
}
AnalyzeFunctions(
parallelOptions, assemblies,
methodsToAnalyze, pr
);
TriggerAutomaticGC();
pr.OnFinished();
pr = new ProgressReporter();
if (RunningTransforms != null)
RunningTransforms(pr);
RunTransformsOnAllFunctions(parallelOptions, pr, result.Log);
pr.OnFinished();
TriggerAutomaticGC();
pr = new ProgressReporter();
if (Writing != null)
Writing(pr);
// Assign a unique identifier for all participating assemblies up front
foreach (var assembly in assemblies) {
if (IsRedirected(assembly.FullName))
continue;
Manifest.GetPrivateToken(assembly);
}
Manifest.AssignIdentifiers();
Action<int> writeAssembly = (i) => {
var assembly = assemblies[i];
var outputPath = FormatOutputFilename(assembly.Name) + ".js";
long existingSize;
if (!Manifest.GetExistingSize(assembly, out existingSize)) {
using (var outputStream = new MemoryStream(DefaultStreamCapacity)) {
var context = MakeDecompilerContext(assembly.MainModule);
try {
TranslateSingleAssemblyInternal(context, assembly, outputStream);
} catch (Exception exc) {
throw new Exception("Error occurred while generating javascript for assembly '" + assembly.FullName + "'.", exc);
}
var segment = new ArraySegment<byte>(
outputStream.GetBuffer(), 0, (int)outputStream.Length
);
result.AddFile("Script", outputPath, segment);
Manifest.SetAlreadyTranslated(assembly, outputStream.Length);
}
lock (result.Assemblies)
result.Assemblies.Add(assembly);
} else {
Console.WriteLine(String.Format("Skipping '{0}' because it is already translated...", assembly.Name));
result.AddExistingFile("Script", outputPath, existingSize);
}
pr.OnProgressChanged(result.Assemblies.Count, assemblies.Length);
};
if (Configuration.UseThreads.GetValueOrDefault(true)) {
Parallel.For(
0, assemblies.Length, parallelOptions, writeAssembly
);
} else {
for (var i = 0; i < assemblies.Length; i++)
writeAssembly(i);
}
TriggerAutomaticGC();
pr.OnFinished();
DoProxyDiagnostics();
return result;
}
private void DoProxyDiagnostics () {
if ((ProxyNotMatched == null) && (ProxyMemberNotMatched == null))
return;
var methodsToSkip = new HashSet<MemberIdentifier>(new MemberIdentifier.Comparer(_TypeInfoProvider));
foreach (var p in _TypeInfoProvider.Proxies) {
var ti = new TypeIdentifier(p.Definition);
if ((p.UsageCount == 0) && (ProxyNotMatched != null)) {
ProxyNotMatched(ti);
continue;
}
// If they explicitly disabled replacement for the type, none of the members got replaced
if (p.MemberPolicy == Proxy.JSProxyMemberPolicy.ReplaceNone)
continue;
if (ProxyMemberNotMatched != null) {
methodsToSkip.Clear();
foreach (var kvp in p.Properties) {
if (kvp.Value.CustomAttributes.Any(ca => ca.AttributeType.FullName == "JSIL.Proxy.JSNeverReplace")) {
var mi = kvp.Key;
if (kvp.Value.GetMethod != null)
methodsToSkip.Add(mi.Getter);
if (kvp.Value.SetMethod != null)
methodsToSkip.Add(mi.Setter);
continue;
}
}
foreach (var kvp in p.Methods) {
if (methodsToSkip.Contains(kvp.Key))
continue;
var identifier = kvp.Key;
// Don't log warnings on failed 0-arg default ctor replacement.
// Very often this just means the 0-arg ctor the compiler synthesized for the proxy didn't replace anything.
if (
(identifier.Name == ".ctor") &&
(
(identifier.ParameterTypes == null) || (identifier.ParameterTypes.Length == 0)
)
)
continue;
bool used;
p.MemberReplacedTable.TryGetValue(identifier, out used);
if (!used) {
// Member was explicitly marked as neverreplace, so of course it didn't replace anything
if (kvp.Value.CustomAttributes.Any(ca => ca.AttributeType.FullName == "JSIL.Proxy.JSNeverReplace"))
continue;
ProxyMemberNotMatched(new QualifiedMemberIdentifier(ti, identifier));
}
}
}
}
}
private void TriggerAutomaticGC () {
if (Configuration.TuneGarbageCollection.GetValueOrDefault(true))
#if TARGETTING_FX_4_5
GC.Collect(2, GCCollectionMode.Optimized, false);
#else
GC.Collect(2, GCCollectionMode.Optimized);
#endif
}
public static void GenerateManifest (AssemblyManifest manifest, string assemblyPath, TranslationResult result) {
using (var ms = new MemoryStream())
using (var tw = new StreamWriter(ms, new UTF8Encoding(false))) {
tw.WriteLine("// {0} {1}", GetHeaderText(), Environment.NewLine);
tw.WriteLine("'use strict';");
foreach (var kvp in manifest.Entries) {
tw.WriteLine(
"var {0} = JSIL.GetAssembly({1});",
kvp.Key, Util.EscapeString(kvp.Value, '\"')
);
}
if (result.Configuration.GenerateContentManifest.GetValueOrDefault(true)) {
tw.WriteLine();
tw.WriteLine("if (typeof (contentManifest) !== \"object\") { JSIL.GlobalNamespace.contentManifest = {}; };");
tw.WriteLine("contentManifest[\"" + Path.GetFileName(assemblyPath).Replace("\\", "\\\\") + "\"] = [");
foreach (var fe in result.OrderedFiles) {
var propertiesObject = FormatFileProperties(fe);
tw.WriteLine(String.Format(
" [{0}, {1}, {2}],",
Util.EscapeString(fe.Type),
Util.EscapeString(fe.Filename.Replace("\\", "/")),
propertiesObject
));
}
tw.WriteLine("];");
}
tw.Flush();
result.Manifest = new ArraySegment<byte>(
ms.GetBuffer(), 0, (int)ms.Length
);
}
}
private static string FormatFileProperties (TranslationResult.ResultFile fe) {
var result = "{ ";
result += "\"sizeBytes\": ";
result += fe.Size;
if (fe.Properties != null)
foreach (var kvp in fe.Properties) {
result += ", \"" + kvp.Key + "\": ";
if (kvp.Value is string)
result += Util.EscapeString((string)kvp.Value, forJson: true);
else
throw new NotImplementedException("File property of type '" + kvp.Value.GetType().Name);
}
result += " }";
return result;
}
private void AnalyzeFunctions (
ParallelOptions parallelOptions, AssemblyDefinition[] assemblies,
ConcurrentBag<MethodToAnalyze> methodsToAnalyze, ProgressReporter pr
) {
int i = 0, mc = methodsToAnalyze.Count;
Func<int, ParallelLoopState, DecompilerContext, DecompilerContext> analyzeAMethod = (_, loopState, ctx) => {
MethodToAnalyze m;
if (!methodsToAnalyze.TryTake(out m))
throw new InvalidDataException("Method collection mutated during analysis. Try setting UseThreads=false (and report an issue!)");
ctx.CurrentModule = m.MD.Module;
ctx.CurrentType = m.MD.DeclaringType;
ctx.CurrentMethod = m.MD;
try {
TranslateMethodExpression(ctx, m.MD, m.MD, m.MI);
} catch (Exception exc) {
throw new Exception("Error occurred while translating method '" + m.MD.FullName + "'.", exc);
}
var j = Interlocked.Increment(ref i);
pr.OnProgressChanged(mc + j, mc * 2);
return ctx;
};
if (Configuration.UseThreads.GetValueOrDefault(true)) {
Parallel.For(
0, methodsToAnalyze.Count, parallelOptions,
() => MakeDecompilerContext(assemblies[0].MainModule),
analyzeAMethod,
(ctx) => { }
);
} else {
var ctx = MakeDecompilerContext(assemblies[0].MainModule);
while (methodsToAnalyze.Count > 0)
analyzeAMethod(0, default(ParallelLoopState), ctx);
}
}
protected void RunTransformsOnAllFunctions (ParallelOptions parallelOptions, ProgressReporter pr, StringBuilder log) {
int i = 0;
const int autoGcInterval = 256;
Action<QualifiedMemberIdentifier> itemHandler = (id) => {
var e = FunctionCache.GetCacheEntry(id);
// We can end up with multiple copies of a function in the pipeline, so we should just early out if we hit a duplicate
if (e.TransformPipelineHasCompleted)
return;
var _i = Interlocked.Increment(ref i);
if ((_i % autoGcInterval) == 0)
TriggerAutomaticGC();
if (e.Expression == null)
return;
pr.OnProgressChanged(_i, _i + FunctionCache.PendingTransformsQueue.Count);
if (RunTransformsOnFunction(id, e.Expression, e.SpecialIdentifiers, log)) {
// Release our SpecialIdentifiers instance so it doesn't leak indefinitely.
// e.SpecialIdentifiers = null;
}
};
while (FunctionCache.PendingTransformsQueue.Count > 0) {
// FIXME: Disabled right now because there is a race condition where the optimizer can be
// altering the static analysis information for a function while another function
// that depends on it is being optimized.
if (Configuration.CodeGenerator.EnableThreadedTransforms.GetValueOrDefault(true)) {
Parallel.ForEach(
FunctionCache.PendingTransformsQueue.TryDequeueAll,
parallelOptions, itemHandler
);
} else {
QualifiedMemberIdentifier _id;
while (FunctionCache.PendingTransformsQueue.TryDequeue(out _id))
itemHandler(_id);
}
}
}
// Invoking this function populates the type information graph, and builds a list
// of functions to analyze/optimize/translate (omitting ignored functions, etc).
private void GetMethodsToAnalyze (AssemblyDefinition assembly, ConcurrentBag<MethodToAnalyze> allMethods) {
bool isStubbed = IsStubbed(assembly);
var parallelOptions = GetParallelOptions();
var allTypes = new List<TypeDefinition>();
foreach (var module in assembly.Modules) {
var moduleInfo = _TypeInfoProvider.GetModuleInformation(module);
if (moduleInfo.IsIgnored)
continue;
allTypes.AddRange(module.Types);
}
while (allTypes.Count > 0) {
var types = new HashSet<TypeDefinition>(allTypes).ToList();
allTypes.Clear();
Parallel.For(
0, types.Count, parallelOptions,
() => new List<TypeDefinition>(),
(i, loopState, typeList) => {
var type = types[i];
typeList.AddRange(type.NestedTypes);
if (!ShouldTranslateMethods(type))
return typeList;
IEnumerable<MethodDefinition> methods = type.Methods;
var typeInfo = _TypeInfoProvider.GetExisting(type);
if (typeInfo != null) {
if (typeInfo.StaticConstructor != null) {
methods = methods.Concat(new[] { typeInfo.StaticConstructor });
}
foreach (var esc in typeInfo.ExtraStaticConstructors) {
allMethods.Add(new MethodToAnalyze(esc));
}
}
foreach (var m in methods) {
var mi = _TypeInfoProvider.GetMethod(m);
if ((mi == null) || (mi.IsIgnored))
continue;
// A pinvoke method with no body can be replaced by a proxy method body
if (!m.HasBody && !mi.IsFromProxy)
continue;
if (isStubbed && !mi.IsUnstubbable) {
var isProperty = mi.DeclaringProperty != null;
if (!(isProperty && m.IsCompilerGenerated()))
continue;
}
allMethods.Add(new MethodToAnalyze(m));
}
return typeList;
},
(typeList) => {
lock (allTypes)
allTypes.AddRange(typeList);
}
);
}
}
protected bool IsStubbed (AssemblyDefinition assembly) {
foreach (var sa in Configuration.Assemblies.Stubbed) {
if (Regex.IsMatch(assembly.FullName, sa, RegexOptions.IgnoreCase)) {
return true;
}
}
return false;
}
public static string GetHeaderText () {
var version = Assembly.GetExecutingAssembly().GetName().Version;
return String.Format(
"Generated by JSIL v{0}.{1}.{2} build {3}. See http://jsil.org/ for more information.",
version.Major, version.Minor, version.Build, version.Revision
);
}
protected void TranslateSingleAssemblyInternal (DecompilerContext context, AssemblyDefinition assembly, Stream outputStream) {
bool stubbed = IsStubbed(assembly);
var tw = new StreamWriter(outputStream, Encoding.ASCII);
var formatter = new JavascriptFormatter(
tw, this._TypeInfoProvider, Manifest, assembly, Configuration, stubbed
);
formatter.Comment(GetHeaderText());
formatter.NewLine();
formatter.WriteRaw("'use strict';");
formatter.NewLine();
if (stubbed) {
if (Configuration.GenerateSkeletonsForStubbedAssemblies.GetValueOrDefault(false)) {
formatter.Comment("Generating type skeletons");
} else {
formatter.Comment("Generating type stubs only");
}
formatter.NewLine();
}
formatter.DeclareAssembly();
formatter.NewLine();
if (assembly.EntryPoint != null) {
TranslateEntryPoint(assembly, formatter);
}
var sealedTypes = new HashSet<TypeDefinition>();
var declaredTypes = new HashSet<TypeDefinition>();
foreach (var module in assembly.Modules) {
if (module.Assembly != assembly) {
WarningFormat("Warning: Mono.Cecil failed to correctly load the module '{0}'. Skipping it.", module);
continue;
}
TranslateModule(context, formatter, module, sealedTypes, declaredTypes, stubbed);
}
tw.Flush();
}
protected void TranslateEntryPoint (
AssemblyDefinition assembly,
JavascriptFormatter output
) {
var entryMethod = assembly.EntryPoint;
output.WriteRaw("JSIL.SetEntryPoint");
output.LPar();
output.AssemblyReference(assembly);
output.Comma();
var context = new TypeReferenceContext();
output.TypeReference(entryMethod.DeclaringType, context);
output.Comma();
output.Value(entryMethod.Name);
output.Comma();
output.MethodSignature(
entryMethod,
new MethodSignature(
_TypeInfoProvider,
entryMethod.ReturnType,
(from p in entryMethod.Parameters select p.ParameterType).ToArray(),
null
),
context
);
output.RPar();
output.Semicolon(true);
output.NewLine();
}
protected void TranslateModule (
DecompilerContext context, JavascriptFormatter output, ModuleDefinition module,
HashSet<TypeDefinition> sealedTypes, HashSet<TypeDefinition> declaredTypes, bool stubbed
) {
var moduleInfo = _TypeInfoProvider.GetModuleInformation(module);
if (moduleInfo.IsIgnored)
return;
context.CurrentModule = module;
var js = new JSSpecialIdentifiers(FunctionCache.MethodTypes, context.CurrentModule.TypeSystem);
var jsil = new JSILIdentifier(FunctionCache.MethodTypes, context.CurrentModule.TypeSystem, this._TypeInfoProvider, js);
var astEmitter = new JavascriptAstEmitter(
output, jsil,
context.CurrentModule.TypeSystem, this._TypeInfoProvider,
Configuration
);
foreach (var typedef in module.Types)
DeclareType(context, typedef, astEmitter, output, declaredTypes, stubbed);
}
protected void TranslateInterface (
DecompilerContext context, JavascriptAstEmitter astEmitter,
JavascriptFormatter output, TypeDefinition iface
) {
output.Identifier("JSIL.MakeInterface", EscapingMode.None);
output.LPar();
output.NewLine();
output.Value(Util.DemangleCecilTypeName(iface.FullName));
output.Comma();
output.Value(iface.IsPublic);