├── .gitattributes
├── .gitignore
├── BoxingDetector.sln
├── BoxingDetector
├── App.config
├── BoxingDetector.csproj
├── Detector.cs
├── Properties
│ └── AssemblyInfo.cs
└── Utils
│ └── TypeHelper.cs
└── README.md
/.gitattributes:
--------------------------------------------------------------------------------
1 | # Auto detect text files and perform LF normalization
2 | * text=auto
3 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 | ##
4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
5 |
6 | # User-specific files
7 | *.rsuser
8 | *.suo
9 | *.user
10 | *.userosscache
11 | *.sln.docstates
12 |
13 | # User-specific files (MonoDevelop/Xamarin Studio)
14 | *.userprefs
15 |
16 | # Mono auto generated files
17 | mono_crash.*
18 |
19 | # Build results
20 | [Dd]ebug/
21 | [Dd]ebugPublic/
22 | [Rr]elease/
23 | [Rr]eleases/
24 | x64/
25 | x86/
26 | [Aa][Rr][Mm]/
27 | [Aa][Rr][Mm]64/
28 | bld/
29 | [Bb]in/
30 | [Oo]bj/
31 | [Ll]og/
32 | [Ll]ogs/
33 |
34 | # Visual Studio 2015/2017 cache/options directory
35 | .vs/
36 | # Uncomment if you have tasks that create the project's static files in wwwroot
37 | #wwwroot/
38 |
39 | # Visual Studio 2017 auto generated files
40 | Generated\ Files/
41 |
42 | # MSTest test Results
43 | [Tt]est[Rr]esult*/
44 | [Bb]uild[Ll]og.*
45 |
46 | # NUnit
47 | *.VisualState.xml
48 | TestResult.xml
49 | nunit-*.xml
50 |
51 | # Build Results of an ATL Project
52 | [Dd]ebugPS/
53 | [Rr]eleasePS/
54 | dlldata.c
55 |
56 | # Benchmark Results
57 | BenchmarkDotNet.Artifacts/
58 |
59 | # .NET Core
60 | project.lock.json
61 | project.fragment.lock.json
62 | artifacts/
63 |
64 | # StyleCop
65 | StyleCopReport.xml
66 |
67 | # Files built by Visual Studio
68 | *_i.c
69 | *_p.c
70 | *_h.h
71 | *.ilk
72 | *.meta
73 | *.obj
74 | *.iobj
75 | *.pch
76 | *.pdb
77 | *.ipdb
78 | *.pgc
79 | *.pgd
80 | *.rsp
81 | *.sbr
82 | *.tlb
83 | *.tli
84 | *.tlh
85 | *.tmp
86 | *.tmp_proj
87 | *_wpftmp.csproj
88 | *.log
89 | *.vspscc
90 | *.vssscc
91 | .builds
92 | *.pidb
93 | *.svclog
94 | *.scc
95 |
96 | # Chutzpah Test files
97 | _Chutzpah*
98 |
99 | # Visual C++ cache files
100 | ipch/
101 | *.aps
102 | *.ncb
103 | *.opendb
104 | *.opensdf
105 | *.sdf
106 | *.cachefile
107 | *.VC.db
108 | *.VC.VC.opendb
109 |
110 | # Visual Studio profiler
111 | *.psess
112 | *.vsp
113 | *.vspx
114 | *.sap
115 |
116 | # Visual Studio Trace Files
117 | *.e2e
118 |
119 | # TFS 2012 Local Workspace
120 | $tf/
121 |
122 | # Guidance Automation Toolkit
123 | *.gpState
124 |
125 | # ReSharper is a .NET coding add-in
126 | _ReSharper*/
127 | *.[Rr]e[Ss]harper
128 | *.DotSettings.user
129 |
130 | # JustCode is a .NET coding add-in
131 | .JustCode
132 |
133 | # TeamCity is a build add-in
134 | _TeamCity*
135 |
136 | # DotCover is a Code Coverage Tool
137 | *.dotCover
138 |
139 | # AxoCover is a Code Coverage Tool
140 | .axoCover/*
141 | !.axoCover/settings.json
142 |
143 | # Visual Studio code coverage results
144 | *.coverage
145 | *.coveragexml
146 |
147 | # NCrunch
148 | _NCrunch_*
149 | .*crunch*.local.xml
150 | nCrunchTemp_*
151 |
152 | # MightyMoose
153 | *.mm.*
154 | AutoTest.Net/
155 |
156 | # Web workbench (sass)
157 | .sass-cache/
158 |
159 | # Installshield output folder
160 | [Ee]xpress/
161 |
162 | # DocProject is a documentation generator add-in
163 | DocProject/buildhelp/
164 | DocProject/Help/*.HxT
165 | DocProject/Help/*.HxC
166 | DocProject/Help/*.hhc
167 | DocProject/Help/*.hhk
168 | DocProject/Help/*.hhp
169 | DocProject/Help/Html2
170 | DocProject/Help/html
171 |
172 | # Click-Once directory
173 | publish/
174 |
175 | # Publish Web Output
176 | *.[Pp]ublish.xml
177 | *.azurePubxml
178 | # Note: Comment the next line if you want to checkin your web deploy settings,
179 | # but database connection strings (with potential passwords) will be unencrypted
180 | *.pubxml
181 | *.publishproj
182 |
183 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
184 | # checkin your Azure Web App publish settings, but sensitive information contained
185 | # in these scripts will be unencrypted
186 | PublishScripts/
187 |
188 | # NuGet Packages
189 | *.nupkg
190 | # NuGet Symbol Packages
191 | *.snupkg
192 | # The packages folder can be ignored because of Package Restore
193 | **/[Pp]ackages/*
194 | # except build/, which is used as an MSBuild target.
195 | !**/[Pp]ackages/build/
196 | # Uncomment if necessary however generally it will be regenerated when needed
197 | #!**/[Pp]ackages/repositories.config
198 | # NuGet v3's project.json files produces more ignorable files
199 | *.nuget.props
200 | *.nuget.targets
201 |
202 | # Microsoft Azure Build Output
203 | csx/
204 | *.build.csdef
205 |
206 | # Microsoft Azure Emulator
207 | ecf/
208 | rcf/
209 |
210 | # Windows Store app package directories and files
211 | AppPackages/
212 | BundleArtifacts/
213 | Package.StoreAssociation.xml
214 | _pkginfo.txt
215 | *.appx
216 | *.appxbundle
217 | *.appxupload
218 |
219 | # Visual Studio cache files
220 | # files ending in .cache can be ignored
221 | *.[Cc]ache
222 | # but keep track of directories ending in .cache
223 | !?*.[Cc]ache/
224 |
225 | # Others
226 | ClientBin/
227 | ~$*
228 | *~
229 | *.dbmdl
230 | *.dbproj.schemaview
231 | *.jfm
232 | *.pfx
233 | *.publishsettings
234 | orleans.codegen.cs
235 |
236 | # Including strong name files can present a security risk
237 | # (https://github.com/github/gitignore/pull/2483#issue-259490424)
238 | #*.snk
239 |
240 | # Since there are multiple workflows, uncomment next line to ignore bower_components
241 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
242 | #bower_components/
243 |
244 | # RIA/Silverlight projects
245 | Generated_Code/
246 |
247 | # Backup & report files from converting an old project file
248 | # to a newer Visual Studio version. Backup files are not needed,
249 | # because we have git ;-)
250 | _UpgradeReport_Files/
251 | Backup*/
252 | UpgradeLog*.XML
253 | UpgradeLog*.htm
254 | ServiceFabricBackup/
255 | *.rptproj.bak
256 |
257 | # SQL Server files
258 | *.mdf
259 | *.ldf
260 | *.ndf
261 |
262 | # Business Intelligence projects
263 | *.rdl.data
264 | *.bim.layout
265 | *.bim_*.settings
266 | *.rptproj.rsuser
267 | *- [Bb]ackup.rdl
268 | *- [Bb]ackup ([0-9]).rdl
269 | *- [Bb]ackup ([0-9][0-9]).rdl
270 |
271 | # Microsoft Fakes
272 | FakesAssemblies/
273 |
274 | # GhostDoc plugin setting file
275 | *.GhostDoc.xml
276 |
277 | # Node.js Tools for Visual Studio
278 | .ntvs_analysis.dat
279 | node_modules/
280 |
281 | # Visual Studio 6 build log
282 | *.plg
283 |
284 | # Visual Studio 6 workspace options file
285 | *.opt
286 |
287 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
288 | *.vbw
289 |
290 | # Visual Studio LightSwitch build output
291 | **/*.HTMLClient/GeneratedArtifacts
292 | **/*.DesktopClient/GeneratedArtifacts
293 | **/*.DesktopClient/ModelManifest.xml
294 | **/*.Server/GeneratedArtifacts
295 | **/*.Server/ModelManifest.xml
296 | _Pvt_Extensions
297 |
298 | # Paket dependency manager
299 | .paket/paket.exe
300 | paket-files/
301 |
302 | # FAKE - F# Make
303 | .fake/
304 |
305 | # CodeRush personal settings
306 | .cr/personal
307 |
308 | # Python Tools for Visual Studio (PTVS)
309 | __pycache__/
310 | *.pyc
311 |
312 | # Cake - Uncomment if you are using it
313 | # tools/**
314 | # !tools/packages.config
315 |
316 | # Tabs Studio
317 | *.tss
318 |
319 | # Telerik's JustMock configuration file
320 | *.jmconfig
321 |
322 | # BizTalk build output
323 | *.btp.cs
324 | *.btm.cs
325 | *.odx.cs
326 | *.xsd.cs
327 |
328 | # OpenCover UI analysis results
329 | OpenCover/
330 |
331 | # Azure Stream Analytics local run output
332 | ASALocalRun/
333 |
334 | # MSBuild Binary and Structured Log
335 | *.binlog
336 |
337 | # NVidia Nsight GPU debugger configuration file
338 | *.nvuser
339 |
340 | # MFractors (Xamarin productivity tool) working folder
341 | .mfractor/
342 |
343 | # Local History for Visual Studio
344 | .localhistory/
345 |
346 | # BeatPulse healthcheck temp database
347 | healthchecksdb
348 |
349 | # Backup folder for Package Reference Convert tool in Visual Studio 2017
350 | MigrationBackup/
351 |
352 | # Ionide (cross platform F# VS Code tools) working folder
353 | .ionide/
354 |
--------------------------------------------------------------------------------
/BoxingDetector.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio Version 16
4 | VisualStudioVersion = 16.0.29905.134
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BoxingDetector", "BoxingDetector\BoxingDetector.csproj", "{F5BA84D1-FE3E-4BD2-8319-99408BBBDBC0}"
7 | EndProject
8 | Global
9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
10 | Debug|Any CPU = Debug|Any CPU
11 | Release|Any CPU = Release|Any CPU
12 | EndGlobalSection
13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
14 | {F5BA84D1-FE3E-4BD2-8319-99408BBBDBC0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
15 | {F5BA84D1-FE3E-4BD2-8319-99408BBBDBC0}.Debug|Any CPU.Build.0 = Debug|Any CPU
16 | {F5BA84D1-FE3E-4BD2-8319-99408BBBDBC0}.Release|Any CPU.ActiveCfg = Release|Any CPU
17 | {F5BA84D1-FE3E-4BD2-8319-99408BBBDBC0}.Release|Any CPU.Build.0 = Release|Any CPU
18 | EndGlobalSection
19 | GlobalSection(SolutionProperties) = preSolution
20 | HideSolutionNode = FALSE
21 | EndGlobalSection
22 | GlobalSection(ExtensibilityGlobals) = postSolution
23 | SolutionGuid = {400FBF3B-E39C-45B7-ADC6-5884D88CFE98}
24 | EndGlobalSection
25 | EndGlobal
26 |
--------------------------------------------------------------------------------
/BoxingDetector/App.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/BoxingDetector/BoxingDetector.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Debug
6 | AnyCPU
7 | {F5BA84D1-FE3E-4BD2-8319-99408BBBDBC0}
8 | Exe
9 | BoxingDetector
10 | BoxingDetector
11 | v4.7.2
12 | 512
13 | true
14 | true
15 |
16 |
17 | AnyCPU
18 | true
19 | full
20 | false
21 | ..\bin\
22 | DEBUG;TRACE
23 | prompt
24 | 4
25 | true
26 |
27 |
28 | AnyCPU
29 | pdbonly
30 | true
31 | ..\bin\
32 | TRACE
33 | prompt
34 | 4
35 | true
36 |
37 |
38 |
39 | ..\..\..\..\..\GitHub\Lib\FastAccessors.dll
40 |
41 |
42 | ..\..\..\..\..\GitHub\Lib\ILReader.Analyzer.dll
43 |
44 |
45 | ..\..\..\..\..\GitHub\Lib\ILReader.Core.dll
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
--------------------------------------------------------------------------------
/BoxingDetector/Detector.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.IO;
4 | using System.Reflection;
5 | using ILReader.Analyzer;
6 | using BF = System.Reflection.BindingFlags;
7 |
8 | namespace BoxingDetector {
9 | class Program {
10 | static HashSet KnownAssemblies = new HashSet(StringComparer.OrdinalIgnoreCase);
11 | static Program() {
12 | KnownAssemblies.Add(typeof(FastAccessors.Field).Assembly.GetName().Name);
13 | KnownAssemblies.Add(typeof(ILReader.Configuration).Assembly.GetName().Name);
14 | KnownAssemblies.Add(typeof(ILPattern).Assembly.GetName().Name);
15 | }
16 | static void Main() {
17 | var args = Environment.GetCommandLineArgs();
18 | string localPath = Path.GetDirectoryName(args[0]);
19 | if(args.Length > 1) {
20 | for(int i = 1; i < args.Length; i++)
21 | ProcessAssembly(localPath, args[i]);
22 | }
23 | else {
24 | var localFiles = Directory.GetFiles(localPath, "*.dll");
25 | for(int i = 0; i < localFiles.Length; i++)
26 | ProcessAssembly(localPath, localFiles[i], true);
27 | }
28 | }
29 | //
30 | static ILPattern[] boxingPatterns = new ILPattern[] {
31 | StringFormatBoxing.Instance,
32 | StringConcatBoxing.Instance,
33 | EnumMethodBoxing.Instance,
34 | EnumToStringBoxing.Instance,
35 | };
36 | static void ProcessAssembly(string localPath, string asmPath, bool skipKnownAssemblies = false) {
37 | if(!File.Exists(asmPath))
38 | asmPath = Path.Combine(localPath, asmPath);
39 | if(File.Exists(asmPath)) {
40 | Assembly assembly = Assembly.LoadFrom(asmPath);
41 | if(assembly == null)
42 | return;
43 | var asmName = assembly.GetName().Name;
44 | if(skipKnownAssemblies && KnownAssemblies.Contains(asmName))
45 | return;
46 | var cfg = ILReader.Configuration.Standard;
47 | ProcessMethods(assembly, x => {
48 | var reader = cfg.GetReader(x);
49 | for(int i = 0; i < boxingPatterns.Length; i++) {
50 | var pattern = boxingPatterns[i];
51 | if(pattern.Match(reader))
52 | return pattern;
53 | }
54 | return null;
55 | }, asmName.ToUpperInvariant());
56 | }
57 | }
58 | static void ProcessMethods(Assembly assembly, Func detectBoxing, string asmName) {
59 | bool asmMatch = false;
60 | var types = TypeHelper.GetTypes(assembly);
61 | for(int i = 0; i < types.Length; i++) {
62 | var type = types[i];
63 | if(type.IsInterface || type.IsAnonymousType())
64 | continue;
65 | var methods = type.GetMethods(BF.DeclaredOnly | BF.Public | BF.NonPublic | BF.Static | BF.Instance);
66 | if(methods.Length == 0)
67 | continue;
68 | bool typeMatch = false;
69 | for(int j = 0; j < methods.Length; j++) {
70 | var method = methods[j];
71 | var boxingPattern = detectBoxing(method);
72 | if(boxingPattern == null)
73 | continue;
74 | if(!typeMatch) {
75 | if(!asmMatch) {
76 | Console.WriteLine(asmName);
77 | Console.WriteLine(new string('-', asmName.Length + 4));
78 | asmMatch = true;
79 | }
80 | Console.WriteLine();
81 | Console.WriteLine(TypeHelper.GetTypeName(type));
82 | typeMatch = true;
83 | }
84 | Console.Write("->" + boxingPattern.ToString());
85 | }
86 | }
87 | if(asmMatch) Console.WriteLine();
88 | }
89 | }
90 | }
--------------------------------------------------------------------------------
/BoxingDetector/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Reflection;
3 | using System.Runtime.CompilerServices;
4 | using System.Runtime.InteropServices;
5 |
6 | [assembly: AssemblyVersion("1.0.0.0")]
7 | [assembly: CLSCompliant(true)]
8 | [assembly: AssemblyTitle("MSIL Boxing Detector")]
9 | [assembly: AssemblyDescription("MSIL-level boxing detector tool for .Net (powered by ILReader)")]
10 | [assembly: AssemblyCompany("Dmitry Garavsky(https://github.com/DmitryGaravsky)")]
11 | [assembly: AssemblyProduct("Microsoft® .NET Framework Extension")]
12 | [assembly: AssemblyCopyright("Dmitry Garavsky, ©2020")]
13 | [assembly: AssemblyFileVersion("1.0.0.0")]
14 | [assembly: StringFreezing]
15 | [assembly: ComVisible(false)]
--------------------------------------------------------------------------------
/BoxingDetector/Utils/TypeHelper.cs:
--------------------------------------------------------------------------------
1 | namespace BoxingDetector {
2 | using System;
3 | using System.Linq;
4 | using System.Reflection;
5 | //
6 | static class TypeHelper {
7 | public static Type[] GetTypes(Assembly assembly) {
8 | try {
9 | return assembly.GetTypes();
10 | }
11 | catch(ReflectionTypeLoadException e) {
12 | return e.Types;
13 | }
14 | }
15 | readonly static Type CompilerGenerated = typeof(System.Runtime.CompilerServices.CompilerGeneratedAttribute);
16 | public static bool IsAnonymousType(this Type type) {
17 | return type.GetCustomAttributesData().Any(d => d.AttributeType == CompilerGenerated) && type.Name.Contains("AnonymousType");
18 | }
19 | public static string GetTypeName(Type type) {
20 | var typeName = GetTypeNameCore(type);
21 | if(!type.IsGenericType)
22 | return typeName;
23 | var sb = new System.Text.StringBuilder(typeName);
24 | int argumentsPos = typeName.IndexOf('`');
25 | sb.Remove(argumentsPos, typeName.Length - argumentsPos);
26 | sb.Append("<");
27 | var genericArgs = type.GetGenericArguments();
28 | for(int i = 0; i < genericArgs.Length; i++) {
29 | sb.Append(GetTypeName(genericArgs[i]));
30 | if(i > 0) sb.Append(",");
31 | }
32 | sb.Append(">");
33 | return sb.ToString();
34 | }
35 | static string GetTypeNameCore(Type type) {
36 | if(!string.IsNullOrEmpty(type.Namespace)) {
37 | var sb = new System.Text.StringBuilder(type.Namespace);
38 | if(type.IsNested) {
39 | Type parent = type.DeclaringType;
40 | while(parent != null) {
41 | sb.Append(".");
42 | sb.Append(parent.Name);
43 | if(parent.IsNested)
44 | parent = parent.DeclaringType;
45 | else parent = null;
46 | }
47 | }
48 | sb.Append(".");
49 | sb.Append(type.Name);
50 | return sb.ToString();
51 | }
52 | return type.Name;
53 | }
54 | }
55 | }
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # MSIL Boxing Detector
2 |
3 | MSIL-level boxing detector tool for .Net (powered by [ILReader](https://github.com/DmitryGaravsky/ILReader))
4 |
5 |
6 | ### Boxing patterns detected:
7 |
8 | 1) Typical errors in string operations:
9 |
10 | ```cs
11 | int a = 42;
12 | string answer = string.Format("{0}", a); // boxing here
13 | ```
14 |
15 | ```cs
16 | int a = 2; int b = 3;
17 | string question = string.Concat(a," + ", b); // boxing here
18 | ```
19 |
20 | 2) Boxing with the `Enum.HasValue` method call:
21 |
22 | ```cs
23 | [Flags]
24 | enum State { One, Two }
25 | //...
26 | var state = State.One | State.Two;
27 | bool isOne = state.HasFlag(State.One); // boxing here
28 | ```
29 |
30 |
31 | ### Usage scenarios:
32 |
33 | 1) To process all the assemblies within the MSIL Boxing Detector **current folder**
34 | add all the specific assemblies into this folder and run the `BoxingDetector.exe` without arguments.
35 |
36 | 2) To process the specific assemblies use the following snippet:
37 |
38 | ```cmd
39 | BoxingDetector.exe AssemblyXXX.dll AssemblyYYY.dll AssemblyZZZ.dll
40 | ```
41 |
42 | **Output:**
43 |
44 | ```cmd
45 | ILREADER.ANALYZER
46 | ---------------------
47 |
48 | ILReader.Analyzer.Tests.Boxing_Patterns_Tests.Format
49 | ->Stub2:
50 | IL_0007: box System.Int32
51 | IL_0012: call System.String Format(System.String, System.Object, System.Object)
52 |
53 | ILReader.Analyzer.Tests.Boxing_Patterns_Tests.Concat
54 | ->Stub2:
55 | IL_0002: box System.Int32
56 | IL_000D: call System.String Concat(System.Object, System.Object)
57 |
58 | ILReader.Analyzer.Tests.Boxing_Patterns_Tests.EnumHasFlag
59 | ->Stub2:
60 | IL_0002: box ILReader.Analyzer.Tests.Boxing_Patterns_Tests+EnumHasFlag+State
61 | IL_000D: call Boolean HasFlag(System.Enum)
62 | ->Stub4:
63 | IL_0003: constrained. ILReader.Analyzer.Tests.Boxing_Patterns_Tests+EnumHasFlag+State
64 | IL_0009: callvirt System.String ToString()
65 | ```
66 |
--------------------------------------------------------------------------------