CSharpLanguage.cs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827
  1. // Copyright (c) 2011 AlphaSierraPapa for the SharpDevelop Team
  2. //
  3. // Permission is hereby granted, free of charge, to any person obtaining a copy of this
  4. // software and associated documentation files (the "Software"), to deal in the Software
  5. // without restriction, including without limitation the rights to use, copy, modify, merge,
  6. // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
  7. // to whom the Software is furnished to do so, subject to the following conditions:
  8. //
  9. // The above copyright notice and this permission notice shall be included in all copies or
  10. // substantial portions of the Software.
  11. //
  12. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
  13. // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
  14. // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
  15. // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  16. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  17. // DEALINGS IN THE SOFTWARE.
  18. using System;
  19. using System.Collections;
  20. using System.Collections.Generic;
  21. using System.ComponentModel.Composition;
  22. using System.IO;
  23. using System.Linq;
  24. using System.Resources;
  25. using System.Text.RegularExpressions;
  26. using System.Threading.Tasks;
  27. using System.Xml;
  28. using System.Xml.Linq;
  29. using System.Data.Linq;
  30. using ICSharpCode.Decompiler;
  31. using ICSharpCode.Decompiler.Ast;
  32. using ICSharpCode.Decompiler.Ast.Transforms;
  33. //using ICSharpCode.ILSpy.Options;
  34. using ICSharpCode.ILSpy.XmlDoc;
  35. using ICSharpCode.NRefactory.CSharp;
  36. using Mono.Cecil;
  37. namespace ICSharpCode.ILSpy
  38. {
  39. /// <summary>
  40. /// Decompiler logic for C#.
  41. /// </summary>
  42. [Export(typeof(Language))]
  43. public class CSharpLanguage : Language
  44. {
  45. string name = "C#";
  46. bool showAllMembers = false;
  47. Predicate<IAstTransform> transformAbortCondition = null;
  48. public CSharpLanguage()
  49. {
  50. }
  51. #if DEBUG
  52. internal static IEnumerable<CSharpLanguage> GetDebugLanguages()
  53. {
  54. DecompilerContext context = new DecompilerContext(ModuleDefinition.CreateModule("dummy", ModuleKind.Dll));
  55. string lastTransformName = "no transforms";
  56. foreach (Type _transformType in TransformationPipeline.CreatePipeline(context).Select(v => v.GetType()).Distinct()) {
  57. Type transformType = _transformType; // copy for lambda
  58. yield return new CSharpLanguage {
  59. transformAbortCondition = v => transformType.IsInstanceOfType(v),
  60. name = "C# - " + lastTransformName,
  61. showAllMembers = true
  62. };
  63. lastTransformName = "after " + transformType.Name;
  64. }
  65. yield return new CSharpLanguage {
  66. name = "C# - " + lastTransformName,
  67. showAllMembers = true
  68. };
  69. }
  70. #endif
  71. public override string Name
  72. {
  73. get { return name; }
  74. }
  75. public override string FileExtension
  76. {
  77. get { return ".cs"; }
  78. }
  79. public override string ProjectFileExtension
  80. {
  81. get { return ".csproj"; }
  82. }
  83. public override void DecompileMethod(MethodDefinition method, ITextOutput output, DecompilationOptions options)
  84. {
  85. WriteCommentLine(output, TypeToString(method.DeclaringType, includeNamespace: true));
  86. AstBuilder codeDomBuilder = CreateAstBuilder(options, currentType: method.DeclaringType, isSingleMember: true);
  87. if (method.IsConstructor && !method.IsStatic && !method.DeclaringType.IsValueType) {
  88. // also fields and other ctors so that the field initializers can be shown as such
  89. AddFieldsAndCtors(codeDomBuilder, method.DeclaringType, method.IsStatic);
  90. RunTransformsAndGenerateCode(codeDomBuilder, output, options, new SelectCtorTransform(method));
  91. } else {
  92. codeDomBuilder.AddMethod(method);
  93. RunTransformsAndGenerateCode(codeDomBuilder, output, options);
  94. }
  95. }
  96. class SelectCtorTransform : IAstTransform
  97. {
  98. readonly MethodDefinition ctorDef;
  99. public SelectCtorTransform(MethodDefinition ctorDef)
  100. {
  101. this.ctorDef = ctorDef;
  102. }
  103. public void Run(AstNode compilationUnit)
  104. {
  105. ConstructorDeclaration ctorDecl = null;
  106. foreach (var node in compilationUnit.Children) {
  107. ConstructorDeclaration ctor = node as ConstructorDeclaration;
  108. if (ctor != null) {
  109. if (ctor.Annotation<MethodDefinition>() == ctorDef) {
  110. ctorDecl = ctor;
  111. } else {
  112. // remove other ctors
  113. ctor.Remove();
  114. }
  115. }
  116. // Remove any fields without initializers
  117. FieldDeclaration fd = node as FieldDeclaration;
  118. if (fd != null && fd.Variables.All(v => v.Initializer.IsNull))
  119. fd.Remove();
  120. }
  121. if (ctorDecl.Initializer.ConstructorInitializerType == ConstructorInitializerType.This) {
  122. // remove all fields
  123. foreach (var node in compilationUnit.Children)
  124. if (node is FieldDeclaration)
  125. node.Remove();
  126. }
  127. }
  128. }
  129. public override void DecompileProperty(PropertyDefinition property, ITextOutput output, DecompilationOptions options)
  130. {
  131. WriteCommentLine(output, TypeToString(property.DeclaringType, includeNamespace: true));
  132. AstBuilder codeDomBuilder = CreateAstBuilder(options, currentType: property.DeclaringType, isSingleMember: true);
  133. codeDomBuilder.AddProperty(property);
  134. RunTransformsAndGenerateCode(codeDomBuilder, output, options);
  135. }
  136. public override void DecompileField(FieldDefinition field, ITextOutput output, DecompilationOptions options)
  137. {
  138. WriteCommentLine(output, TypeToString(field.DeclaringType, includeNamespace: true));
  139. AstBuilder codeDomBuilder = CreateAstBuilder(options, currentType: field.DeclaringType, isSingleMember: true);
  140. if (field.IsLiteral) {
  141. codeDomBuilder.AddField(field);
  142. } else {
  143. // also decompile ctors so that the field initializer can be shown
  144. AddFieldsAndCtors(codeDomBuilder, field.DeclaringType, field.IsStatic);
  145. }
  146. RunTransformsAndGenerateCode(codeDomBuilder, output, options, new SelectFieldTransform(field));
  147. }
  148. /// <summary>
  149. /// Removes all top-level members except for the specified fields.
  150. /// </summary>
  151. sealed class SelectFieldTransform : IAstTransform
  152. {
  153. readonly FieldDefinition field;
  154. public SelectFieldTransform(FieldDefinition field)
  155. {
  156. this.field = field;
  157. }
  158. public void Run(AstNode compilationUnit)
  159. {
  160. foreach (var child in compilationUnit.Children) {
  161. if (child is EntityDeclaration) {
  162. if (child.Annotation<FieldDefinition>() != field)
  163. child.Remove();
  164. }
  165. }
  166. }
  167. }
  168. void AddFieldsAndCtors(AstBuilder codeDomBuilder, TypeDefinition declaringType, bool isStatic)
  169. {
  170. foreach (var field in declaringType.Fields) {
  171. if (field.IsStatic == isStatic)
  172. codeDomBuilder.AddField(field);
  173. }
  174. foreach (var ctor in declaringType.Methods) {
  175. if (ctor.IsConstructor && ctor.IsStatic == isStatic)
  176. codeDomBuilder.AddMethod(ctor);
  177. }
  178. }
  179. public override void DecompileEvent(EventDefinition ev, ITextOutput output, DecompilationOptions options)
  180. {
  181. WriteCommentLine(output, TypeToString(ev.DeclaringType, includeNamespace: true));
  182. AstBuilder codeDomBuilder = CreateAstBuilder(options, currentType: ev.DeclaringType, isSingleMember: true);
  183. codeDomBuilder.AddEvent(ev);
  184. RunTransformsAndGenerateCode(codeDomBuilder, output, options);
  185. }
  186. public override void DecompileType(TypeDefinition type, ITextOutput output, DecompilationOptions options)
  187. {
  188. AstBuilder codeDomBuilder = CreateAstBuilder(options, currentType: type);
  189. codeDomBuilder.AddType(type);
  190. RunTransformsAndGenerateCode(codeDomBuilder, output, options);
  191. }
  192. void RunTransformsAndGenerateCode(AstBuilder astBuilder, ITextOutput output, DecompilationOptions options, IAstTransform additionalTransform = null)
  193. {
  194. astBuilder.RunTransformations(transformAbortCondition);
  195. if (additionalTransform != null) {
  196. additionalTransform.Run(astBuilder.SyntaxTree);
  197. }
  198. if (options.DecompilerSettings.ShowXmlDocumentation) {
  199. try {
  200. AddXmlDocTransform.Run(astBuilder.SyntaxTree);
  201. } catch (XmlException ex) {
  202. string[] msg = (" Exception while reading XmlDoc: " + ex.ToString()).Split(new[]{'\r', '\n'}, StringSplitOptions.RemoveEmptyEntries);
  203. var insertionPoint = astBuilder.SyntaxTree.FirstChild;
  204. for (int i = 0; i < msg.Length; i++)
  205. astBuilder.SyntaxTree.InsertChildBefore(insertionPoint, new Comment(msg[i], CommentType.Documentation), Roles.Comment);
  206. }
  207. }
  208. astBuilder.GenerateCode(output);
  209. }
  210. public static string GetPlatformDisplayName(ModuleDefinition module)
  211. {
  212. switch (module.Architecture) {
  213. case TargetArchitecture.I386:
  214. if ((module.Attributes & ModuleAttributes.Preferred32Bit) == ModuleAttributes.Preferred32Bit)
  215. return "AnyCPU (32-bit preferred)";
  216. else if ((module.Attributes & ModuleAttributes.Required32Bit) == ModuleAttributes.Required32Bit)
  217. return "x86";
  218. else
  219. return "AnyCPU (64-bit preferred)";
  220. case TargetArchitecture.AMD64:
  221. return "x64";
  222. case TargetArchitecture.IA64:
  223. return "Itanium";
  224. default:
  225. return module.Architecture.ToString();
  226. }
  227. }
  228. public static string GetPlatformName(ModuleDefinition module)
  229. {
  230. switch (module.Architecture) {
  231. case TargetArchitecture.I386:
  232. if ((module.Attributes & ModuleAttributes.Preferred32Bit) == ModuleAttributes.Preferred32Bit)
  233. return "AnyCPU";
  234. else if ((module.Attributes & ModuleAttributes.Required32Bit) == ModuleAttributes.Required32Bit)
  235. return "x86";
  236. else
  237. return "AnyCPU";
  238. case TargetArchitecture.AMD64:
  239. return "x64";
  240. case TargetArchitecture.IA64:
  241. return "Itanium";
  242. default:
  243. return module.Architecture.ToString();
  244. }
  245. }
  246. public static string GetRuntimeDisplayName(ModuleDefinition module)
  247. {
  248. switch (module.Runtime) {
  249. case TargetRuntime.Net_1_0:
  250. return ".NET 1.0";
  251. case TargetRuntime.Net_1_1:
  252. return ".NET 1.1";
  253. case TargetRuntime.Net_2_0:
  254. return ".NET 2.0";
  255. case TargetRuntime.Net_4_0:
  256. return ".NET 4.0";
  257. }
  258. return null;
  259. }
  260. public override void DecompileAssembly(LoadedAssembly assembly, ITextOutput output, DecompilationOptions options)
  261. {
  262. if (options.FullDecompilation && options.SaveAsProjectDirectory != null) {
  263. HashSet<string> directories = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
  264. var files = WriteCodeFilesInProject(assembly.ModuleDefinition, options, directories).ToList();
  265. files.AddRange(WriteResourceFilesInProject(assembly, options, directories));
  266. WriteProjectFile(new TextOutputWriter(output), files, assembly.ModuleDefinition,options,assembly.ProjectGuid);
  267. }
  268. else
  269. {
  270. base.DecompileAssembly(assembly, output, options);
  271. output.WriteLine();
  272. ModuleDefinition mainModule = assembly.ModuleDefinition;
  273. if (mainModule.Types.Count > 0) {
  274. output.Write("// Global type: ");
  275. output.WriteReference(mainModule.Types[0].FullName, mainModule.Types[0]);
  276. output.WriteLine();
  277. }
  278. if (mainModule.EntryPoint != null) {
  279. output.Write("// Entry point: ");
  280. output.WriteReference(mainModule.EntryPoint.DeclaringType.FullName + "." + mainModule.EntryPoint.Name, mainModule.EntryPoint);
  281. output.WriteLine();
  282. }
  283. output.WriteLine("// Architecture: " + GetPlatformDisplayName(mainModule));
  284. if ((mainModule.Attributes & ModuleAttributes.ILOnly) == 0) {
  285. output.WriteLine("// This assembly contains unmanaged code.");
  286. }
  287. string runtimeName = GetRuntimeDisplayName(mainModule);
  288. if (runtimeName != null) {
  289. output.WriteLine("// Runtime: " + runtimeName);
  290. }
  291. output.WriteLine();
  292. // don't automatically load additional assemblies when an assembly node is selected in the tree view
  293. using (options.FullDecompilation ? null : LoadedAssembly.DisableAssemblyLoad()) {
  294. AstBuilder codeDomBuilder = CreateAstBuilder(options, currentModule: assembly.ModuleDefinition);
  295. codeDomBuilder.AddAssembly(assembly.ModuleDefinition, onlyAssemblyLevel: !options.FullDecompilation);
  296. codeDomBuilder.RunTransformations(transformAbortCondition);
  297. codeDomBuilder.GenerateCode(output);
  298. }
  299. }
  300. }
  301. AstBuilder CreateAstBuilder(DecompilationOptions options, ModuleDefinition currentModule = null, TypeDefinition currentType = null, bool isSingleMember = false)
  302. {
  303. if (currentModule == null)
  304. currentModule = currentType.Module;
  305. DecompilerSettings settings = options.DecompilerSettings;
  306. if (isSingleMember) {
  307. settings = settings.Clone();
  308. settings.UsingDeclarations = false;
  309. }
  310. return new AstBuilder(
  311. new DecompilerContext(currentModule) {
  312. CancellationToken = options.CancellationToken,
  313. CurrentType = currentType,
  314. Settings = settings
  315. });
  316. }
  317. public override string TypeToString(TypeReference type, bool includeNamespace, ICustomAttributeProvider typeAttributes = null)
  318. {
  319. ConvertTypeOptions options = ConvertTypeOptions.IncludeTypeParameterDefinitions;
  320. if (includeNamespace)
  321. options |= ConvertTypeOptions.IncludeNamespace;
  322. return TypeToString(options, type, typeAttributes);
  323. }
  324. string TypeToString(ConvertTypeOptions options, TypeReference type, ICustomAttributeProvider typeAttributes = null)
  325. {
  326. AstType astType = AstBuilder.ConvertType(type, typeAttributes, options);
  327. StringWriter w = new StringWriter();
  328. if (type.IsByReference) {
  329. ParameterDefinition pd = typeAttributes as ParameterDefinition;
  330. if (pd != null && (!pd.IsIn && pd.IsOut))
  331. w.Write("out ");
  332. else
  333. w.Write("ref ");
  334. if (astType is ComposedType && ((ComposedType)astType).PointerRank > 0)
  335. ((ComposedType)astType).PointerRank--;
  336. }
  337. astType.AcceptVisitor(new CSharpOutputVisitor(w, FormattingOptionsFactory.CreateAllman()));
  338. return w.ToString();
  339. }
  340. public override string FormatPropertyName(PropertyDefinition property, bool? isIndexer)
  341. {
  342. if (property == null)
  343. throw new ArgumentNullException("property");
  344. if (!isIndexer.HasValue) {
  345. isIndexer = property.IsIndexer();
  346. }
  347. if (isIndexer.Value) {
  348. var buffer = new System.Text.StringBuilder();
  349. var accessor = property.GetMethod ?? property.SetMethod;
  350. if (accessor.HasOverrides) {
  351. var declaringType = accessor.Overrides.First().DeclaringType;
  352. buffer.Append(TypeToString(declaringType, includeNamespace: true));
  353. buffer.Append(@".");
  354. }
  355. buffer.Append(@"this[");
  356. bool addSeparator = false;
  357. foreach (var p in property.Parameters) {
  358. if (addSeparator)
  359. buffer.Append(@", ");
  360. else
  361. addSeparator = true;
  362. buffer.Append(TypeToString(p.ParameterType, includeNamespace: true));
  363. }
  364. buffer.Append(@"]");
  365. return buffer.ToString();
  366. } else
  367. return property.Name;
  368. }
  369. public override string FormatTypeName(TypeDefinition type)
  370. {
  371. if (type == null)
  372. throw new ArgumentNullException("type");
  373. return TypeToString(ConvertTypeOptions.DoNotUsePrimitiveTypeNames | ConvertTypeOptions.IncludeTypeParameterDefinitions, type);
  374. }
  375. public override bool ShowMember(MemberReference member)
  376. {
  377. return showAllMembers || !AstBuilder.MemberIsHidden(member, new DecompilationOptions().DecompilerSettings);
  378. }
  379. // public override MemberReference GetOriginalCodeLocation(MemberReference member)
  380. // {
  381. // if (showAllMembers || !DecompilerSettingsPanel.CurrentDecompilerSettings.AnonymousMethods)
  382. // return member;
  383. // else
  384. // return TreeNodes.Analyzer.Helpers.GetOriginalCodeLocation(member);
  385. // }
  386. public override string GetTooltip(MemberReference member)
  387. {
  388. MethodDefinition md = member as MethodDefinition;
  389. PropertyDefinition pd = member as PropertyDefinition;
  390. EventDefinition ed = member as EventDefinition;
  391. FieldDefinition fd = member as FieldDefinition;
  392. if (md != null || pd != null || ed != null || fd != null) {
  393. AstBuilder b = new AstBuilder(new DecompilerContext(member.Module) { Settings = new DecompilerSettings { UsingDeclarations = false } });
  394. b.DecompileMethodBodies = false;
  395. if (md != null)
  396. b.AddMethod(md);
  397. else if (pd != null)
  398. b.AddProperty(pd);
  399. else if (ed != null)
  400. b.AddEvent(ed);
  401. else
  402. b.AddField(fd);
  403. b.RunTransformations();
  404. foreach (var attribute in b.SyntaxTree.Descendants.OfType<AttributeSection>())
  405. attribute.Remove();
  406. StringWriter w = new StringWriter();
  407. b.GenerateCode(new PlainTextOutput(w));
  408. return Regex.Replace(w.ToString(), @"\s+", " ").TrimEnd();
  409. }
  410. return base.GetTooltip(member);
  411. }
  412. #region WriteProjectFile
  413. void WriteProjectFile(TextWriter writer, IEnumerable<Tuple<string, string>> files, ModuleDefinition module,DecompilationOptions options, Guid projGuid)
  414. {
  415. const string ns = "http://schemas.microsoft.com/developer/msbuild/2003";
  416. string platformName = GetPlatformName(module);
  417. Guid guid = projGuid == null ? Guid.NewGuid () : projGuid;
  418. using (XmlTextWriter w = new XmlTextWriter(writer)) {
  419. w.Formatting = Formatting.Indented;
  420. w.WriteStartDocument();
  421. w.WriteStartElement("Project", ns);
  422. w.WriteAttributeString("ToolsVersion", "4.0");
  423. w.WriteAttributeString("DefaultTargets", "Build");
  424. w.WriteStartElement("PropertyGroup");
  425. w.WriteElementString("ProjectGuid", guid.ToString("B").ToUpperInvariant());
  426. w.WriteStartElement("Configuration");
  427. w.WriteAttributeString("Condition", " '$(Configuration)' == '' ");
  428. w.WriteValue("Debug");
  429. w.WriteEndElement(); // </Configuration>
  430. w.WriteStartElement("Platform");
  431. w.WriteAttributeString("Condition", " '$(Platform)' == '' ");
  432. w.WriteValue(platformName);
  433. w.WriteEndElement(); // </Platform>
  434. switch (module.Kind) {
  435. case ModuleKind.Windows:
  436. w.WriteElementString("OutputType", "WinExe");
  437. break;
  438. case ModuleKind.Console:
  439. w.WriteElementString("OutputType", "Exe");
  440. break;
  441. default:
  442. w.WriteElementString("OutputType", "Library");
  443. break;
  444. }
  445. w.WriteElementString("AssemblyName", module.Assembly.Name.Name);
  446. bool useTargetFrameworkAttribute = false;
  447. var targetFrameworkAttribute = module.Assembly.CustomAttributes.FirstOrDefault(a => a.AttributeType.FullName == "System.Runtime.Versioning.TargetFrameworkAttribute");
  448. if (targetFrameworkAttribute != null && targetFrameworkAttribute.ConstructorArguments.Any()) {
  449. string frameworkName = (string)targetFrameworkAttribute.ConstructorArguments[0].Value;
  450. string[] frameworkParts = frameworkName.Split(',');
  451. string frameworkVersion = frameworkParts.FirstOrDefault(a => a.StartsWith("Version="));
  452. if (frameworkVersion != null) {
  453. w.WriteElementString("TargetFrameworkVersion", frameworkVersion.Substring("Version=".Length));
  454. useTargetFrameworkAttribute = true;
  455. }
  456. string frameworkProfile = frameworkParts.FirstOrDefault(a => a.StartsWith("Profile="));
  457. if (frameworkProfile != null)
  458. w.WriteElementString("TargetFrameworkProfile", frameworkProfile.Substring("Profile=".Length));
  459. }
  460. if (!useTargetFrameworkAttribute) {
  461. switch (module.Runtime) {
  462. case TargetRuntime.Net_1_0:
  463. w.WriteElementString("TargetFrameworkVersion", "v1.0");
  464. break;
  465. case TargetRuntime.Net_1_1:
  466. w.WriteElementString("TargetFrameworkVersion", "v1.1");
  467. break;
  468. case TargetRuntime.Net_2_0:
  469. w.WriteElementString("TargetFrameworkVersion", "v2.0");
  470. // TODO: Detect when .NET 3.0/3.5 is required
  471. break;
  472. default:
  473. w.WriteElementString("TargetFrameworkVersion", "v4.0");
  474. break;
  475. }
  476. }
  477. w.WriteElementString("WarningLevel", "4");
  478. w.WriteEndElement(); // </PropertyGroup>
  479. w.WriteStartElement("PropertyGroup"); // platform-specific
  480. w.WriteAttributeString("Condition", " '$(Platform)' == '" + platformName + "' ");
  481. w.WriteElementString("PlatformTarget", platformName);
  482. w.WriteEndElement(); // </PropertyGroup> (platform-specific)
  483. w.WriteStartElement("PropertyGroup"); // Debug
  484. w.WriteAttributeString("Condition", " '$(Configuration)' == 'Debug' ");
  485. w.WriteElementString("OutputPath", "bin\\Debug\\");
  486. w.WriteElementString("DebugSymbols", "true");
  487. w.WriteElementString("DebugType", "full");
  488. w.WriteElementString("Optimize", "false");
  489. w.WriteEndElement(); // </PropertyGroup> (Debug)
  490. w.WriteStartElement("PropertyGroup"); // Release
  491. w.WriteAttributeString("Condition", " '$(Configuration)' == 'Release' ");
  492. w.WriteElementString("OutputPath", "bin\\Release\\");
  493. w.WriteElementString("DebugSymbols", "true");
  494. w.WriteElementString("DebugType", "pdbonly");
  495. w.WriteElementString("Optimize", "true");
  496. w.WriteEndElement(); // </PropertyGroup> (Release)
  497. w.WriteStartElement("ItemGroup"); // References
  498. foreach (AssemblyNameReference r in module.AssemblyReferences) {
  499. if (r.Name != "mscorlib") {
  500. LoadedAssembly tmp = options.assenmlyList.findAssemblyByShortName (r.Name);
  501. if(tmp != null && tmp.ProjectGuid!=null)
  502. {
  503. //should use project reference
  504. continue;
  505. }
  506. w.WriteStartElement("Reference");
  507. w.WriteAttributeString("Include", r.Name);
  508. if (tmp != null) {
  509. w.WriteElementString ("HintPath", tmp.FileName);
  510. }
  511. w.WriteEndElement();
  512. }
  513. }
  514. w.WriteEndElement(); // </ItemGroup> (References)
  515. w.WriteStartElement("ItemGroup"); // References
  516. foreach (AssemblyNameReference r in module.AssemblyReferences) {
  517. if (r.Name != "mscorlib") {
  518. LoadedAssembly tmp = options.assenmlyList.findAssemblyByShortName (r.Name);
  519. if(tmp != null && tmp.ProjectGuid!=null && tmp.ProjectFileName!=null)
  520. {
  521. // <ItemGroup>
  522. // <ProjectReference Include="..\Assembly-CSharp-firstpass\Assembly-CSharp-firstpass.csproj">
  523. // <Project>{BCB77C12-CC46-4B68-AB67-963EC2F72E44}</Project>
  524. // <Name>Assembly-CSharp-firstpass</Name>
  525. // </ProjectReference>
  526. // </ItemGroup>
  527. w.WriteStartElement("ProjectReference");
  528. w.WriteAttributeString("Include", tmp.ProjectFileName);
  529. w.WriteElementString ("Project", tmp.ProjectGuid.ToString());
  530. w.WriteElementString ("Name", tmp.ShortName);
  531. w.WriteEndElement();
  532. continue;
  533. }
  534. w.WriteStartElement("Reference");
  535. w.WriteAttributeString("Include", r.Name);
  536. if (tmp != null) {
  537. w.WriteElementString ("HintPath", tmp.FileName);
  538. }
  539. w.WriteEndElement();
  540. }
  541. }
  542. w.WriteEndElement(); // </ItemGroup> (References)
  543. foreach (IGrouping<string, string> gr in (from f in files group f.Item2 by f.Item1 into g orderby g.Key select g)) {
  544. w.WriteStartElement("ItemGroup");
  545. foreach (string file in gr.OrderBy(f => f, StringComparer.OrdinalIgnoreCase)) {
  546. w.WriteStartElement(gr.Key);
  547. w.WriteAttributeString("Include", file);
  548. w.WriteEndElement();
  549. }
  550. w.WriteEndElement();
  551. }
  552. w.WriteStartElement("Import");
  553. w.WriteAttributeString("Project", "$(MSBuildToolsPath)\\Microsoft.CSharp.targets");
  554. w.WriteEndElement();
  555. w.WriteEndDocument();
  556. }
  557. }
  558. #endregion
  559. #region WriteCodeFilesInProject
  560. bool IncludeTypeWhenDecompilingProject(TypeDefinition type, DecompilationOptions options)
  561. {
  562. if (options.IncludedClassName != null ) {
  563. if ( type.Name == options.IncludedClassName) {
  564. // Console.WriteLine (file.Key);
  565. return true;
  566. }
  567. return false;
  568. }
  569. if (type.Name == "<Module>" || AstBuilder.MemberIsHidden(type, options.DecompilerSettings)
  570. )
  571. return false;
  572. if (type.Namespace == "XamlGeneratedNamespace" && type.Name == "GeneratedInternalTypeHelper")
  573. return false;
  574. return true;
  575. }
  576. public static void CreateDirSafely(string szdir)
  577. {
  578. if(!Directory.Exists(szdir))
  579. Directory.CreateDirectory(szdir);
  580. }
  581. IEnumerable<Tuple<string, string>> WriteAssemblyInfo(ModuleDefinition module, DecompilationOptions options, HashSet<string> directories)
  582. {
  583. // don't automatically load additional assemblies when an assembly node is selected in the tree view
  584. using (LoadedAssembly.DisableAssemblyLoad())
  585. {
  586. AstBuilder codeDomBuilder = CreateAstBuilder(options, currentModule: module);
  587. codeDomBuilder.AddAssembly(module, onlyAssemblyLevel: true);
  588. codeDomBuilder.RunTransformations(transformAbortCondition);
  589. string prop = "Properties";
  590. if (directories.Add("Properties"))
  591. {
  592. CreateDirSafely(Path.Combine(options.SaveAsProjectDirectory, prop));
  593. }
  594. string assemblyInfo = Path.Combine(prop, "AssemblyInfo" + this.FileExtension);
  595. using (StreamWriter w = new StreamWriter(Path.Combine(options.SaveAsProjectDirectory, assemblyInfo)))
  596. codeDomBuilder.GenerateCode(new PlainTextOutput(w));
  597. return new Tuple<string, string>[] { Tuple.Create("Compile", assemblyInfo) };
  598. }
  599. }
  600. string cleanupName(string text)
  601. {
  602. int pos = text.IndexOf(':');
  603. if (pos > 0)
  604. text = text.Substring(0, pos);
  605. pos = text.IndexOf('`');
  606. if (pos > 0)
  607. text = text.Substring(0, pos);
  608. text = text.Trim();
  609. foreach (char c in Path.GetInvalidFileNameChars())
  610. text = text.Replace(c, '-');
  611. return text;
  612. }
  613. IEnumerable<Tuple<string, string>> WriteCodeFilesInProject(ModuleDefinition module, DecompilationOptions options, HashSet<string> directories)
  614. {
  615. var files = module.Types.Where(t => IncludeTypeWhenDecompilingProject(t, options)).GroupBy(
  616. delegate(TypeDefinition type) {
  617. string file = cleanupName(type.Name) + this.FileExtension;
  618. if (string.IsNullOrEmpty(type.Namespace)) {
  619. return file;
  620. } else {
  621. string dir = cleanupName(type.Namespace);
  622. if (directories.Add(dir))
  623. {
  624. CreateDirSafely(Path.Combine(options.SaveAsProjectDirectory, dir));
  625. }
  626. return Path.Combine(dir, file);
  627. }
  628. }, StringComparer.OrdinalIgnoreCase).ToList();
  629. AstMethodBodyBuilder.ClearUnhandledOpcodes();
  630. // Parallel.ForEach(
  631. // files,
  632. // new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount },
  633. // delegate(IGrouping<string, TypeDefinition> file)
  634. foreach(IGrouping<string, TypeDefinition> file in files)
  635. {
  636. using (StreamWriter w = new StreamWriter(Path.Combine(options.SaveAsProjectDirectory, file.Key))) {
  637. AstBuilder codeDomBuilder = CreateAstBuilder(options, currentModule: module);
  638. foreach (TypeDefinition type in file) {
  639. codeDomBuilder.AddType(type);
  640. }
  641. codeDomBuilder.RunTransformations(transformAbortCondition);
  642. codeDomBuilder.GenerateCode(new PlainTextOutput(w));
  643. }
  644. }
  645. //);
  646. AstMethodBodyBuilder.PrintNumberOfUnhandledOpcodes();
  647. return files.Select(f => Tuple.Create("Compile", f.Key)).Concat(WriteAssemblyInfo(module, options, directories));
  648. }
  649. #endregion
  650. #region WriteResourceFilesInProject
  651. IEnumerable<Tuple<string, string>> WriteResourceFilesInProject(LoadedAssembly assembly, DecompilationOptions options, HashSet<string> directories)
  652. {
  653. //AppDomain bamlDecompilerAppDomain = null;
  654. //try {
  655. foreach (EmbeddedResource r in assembly.ModuleDefinition.Resources.OfType<EmbeddedResource>()) {
  656. string fileName;
  657. Stream s = r.GetResourceStream();
  658. s.Position = 0;
  659. if (r.Name.EndsWith(".g.resources", StringComparison.OrdinalIgnoreCase)) {
  660. IEnumerable<DictionaryEntry> rs = null;
  661. try {
  662. rs = new ResourceSet(s).Cast<DictionaryEntry>();
  663. }
  664. catch (ArgumentException) {
  665. }
  666. if (rs != null && rs.All(e => e.Value is Stream)) {
  667. foreach (var pair in rs) {
  668. fileName = Path.Combine(((string)pair.Key).Split('/').Select(p => cleanupName(p)).ToArray());
  669. string dirName = Path.GetDirectoryName(fileName);
  670. if (!string.IsNullOrEmpty(dirName) && directories.Add(dirName)) {
  671. CreateDirSafely(Path.Combine(options.SaveAsProjectDirectory, dirName));
  672. }
  673. Stream entryStream = (Stream)pair.Value;
  674. entryStream.Position = 0;
  675. if (fileName.EndsWith(".baml", StringComparison.OrdinalIgnoreCase)) {
  676. // MemoryStream ms = new MemoryStream();
  677. // entryStream.CopyTo(ms);
  678. // TODO implement extension point
  679. // var decompiler = Baml.BamlResourceEntryNode.CreateBamlDecompilerInAppDomain(ref bamlDecompilerAppDomain, assembly.FileName);
  680. // string xaml = null;
  681. // try {
  682. // xaml = decompiler.DecompileBaml(ms, assembly.FileName, new ConnectMethodDecompiler(assembly), new AssemblyResolver(assembly));
  683. // }
  684. // catch (XamlXmlWriterException) { } // ignore XAML writer exceptions
  685. // if (xaml != null) {
  686. // File.WriteAllText(Path.Combine(options.SaveAsProjectDirectory, Path.ChangeExtension(fileName, ".xaml")), xaml);
  687. // yield return Tuple.Create("Page", Path.ChangeExtension(fileName, ".xaml"));
  688. // continue;
  689. // }
  690. }
  691. using (FileStream fs = new FileStream(Path.Combine(options.SaveAsProjectDirectory, fileName), FileMode.Create, FileAccess.Write)) {
  692. entryStream.CopyTo(fs);
  693. }
  694. yield return Tuple.Create("Resource", fileName);
  695. }
  696. continue;
  697. }
  698. }
  699. fileName = GetFileNameForResource(r.Name, directories);
  700. using (FileStream fs = new FileStream(Path.Combine(options.SaveAsProjectDirectory, fileName), FileMode.Create, FileAccess.Write)) {
  701. s.CopyTo(fs);
  702. }
  703. yield return Tuple.Create("EmbeddedResource", fileName);
  704. }
  705. //}
  706. //finally {
  707. // if (bamlDecompilerAppDomain != null)
  708. // AppDomain.Unload(bamlDecompilerAppDomain);
  709. //}
  710. }
  711. string GetFileNameForResource(string fullName, HashSet<string> directories)
  712. {
  713. string[] splitName = fullName.Split('.');
  714. string fileName = cleanupName(fullName);
  715. for (int i = splitName.Length - 1; i > 0; i--) {
  716. string ns = string.Join(".", splitName, 0, i);
  717. if (directories.Contains(ns)) {
  718. string name = string.Join(".", splitName, i, splitName.Length - i);
  719. fileName = Path.Combine(ns, cleanupName(name));
  720. break;
  721. }
  722. }
  723. return fileName;
  724. }
  725. #endregion
  726. }
  727. }