-
Notifications
You must be signed in to change notification settings - Fork 1
/
Program.cs
414 lines (387 loc) · 15.5 KB
/
Program.cs
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
//
// Import Checker; simple program to show what 1 or more dlls import
//
// Authors:
// Carlo Kok <[email protected]>
//
// Copyright (C) 2010 RemObjects Software
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Mono.Cecil;
using Mono.Cecil.Metadata;
using Mono.Options;
using System.IO;
using System.Xml.Serialization;
using System.Text.RegularExpressions;
namespace ImportChecker
{
class Program
{
enum Mode { None, Create, Check }
static List<string> input = new List<string>();
static List<string> excludedLibraries = new List<string>();
static List<string> includedLibraries = new List<string>();
static string output = null;
static List<string> searchPath = new List<string>();
static DefaultAssemblyResolver resolver = new DefaultAssemblyResolver();
internal static bool IsFiltered(TypeReference tref) // true = skip this one
{
if (includedLibraries.Count != 0)
{
bool gotmatch= false;
for (int i= 0 ;i < includedLibraries.Count; i++)
{
if (Match(tref.Scope.Name, includedLibraries[i]))
{
gotmatch = true;
break;
}
}
if (!gotmatch) return true;
}
for (int i = 0; i < excludedLibraries.Count; i++)
if (Match(tref.Scope.Name, excludedLibraries[i]))
return true;
return false;
}
private static bool Match(string p, string match)
{
p = p.ToLowerInvariant();
match = match.ToLowerInvariant();
return Regex.IsMatch(p, Regex.Escape(match).Replace(@"\*", ".*").Replace(@"\?", "."), RegexOptions.Singleline);
}
static int Main(string[] args)
{
resolver.ResolveFailure += new AssemblyResolveEventHandler(ResolveFailure);
Mode lMode = Mode.None;
bool lHelp = false;
OptionSet opt = new OptionSet();
opt.Add("e|excludelibrary=", "Exclude an assembly name (accepts standard path filters * and ?), just the name part", v => excludedLibraries.Add(v));
opt.Add("i|includelibrary=", "Include an assembly name (accepts standard path filters * and ?), just the name part", v => includedLibraries.Add(v));
opt.Add("o|output=", "Output to a file", v => output = v);
opt.Add("s|searchpath=", "Add a search path", v=> searchPath.Add(v));
opt.Add("help", "Show help", v => lHelp = v != null);
opt.Add("create", "Create an xml file (-o, and 1 or more dlls as input)", v =>
{
if (lMode != Mode.None) throw new OptionException("mode cannot be set twice", "create");
lMode = Mode.Create;
});
opt.Add("check", "Compare an xml file against the existing dlls (1 or more xml files as input)", v =>
{
if (lMode != Mode.None) throw new OptionException("mode cannot be set twice", "check");
lMode = Mode.Check;
});
try
{
foreach (string file in opt.Parse(args))
{
if (file.StartsWith("@")) // allow parameter input from a file
{
input.AddRange(ArgumentStringSplit(File.ReadAllText(file.Substring(1))));
}
else
input.Add(file);
}
if (lHelp)
{
Console.Error.WriteLine("Usage: ImportChecker [Options] files");
Console.Error.WriteLine();
Console.Error.WriteLine("Options: ");
opt.WriteOptionDescriptions(Console.Error);
return 1;
}
if (lMode == Mode.None)
throw new OptionException("No mode selected. --check or --create required", "mode");
foreach (var el in input)
{
if (!File.Exists(el))
throw new OptionException("File " + el + " does not exist", "file");
}
if (lMode == Mode.Check)
return Check();
else
return Generate();
}
catch (OptionException e)
{
Console.Error.WriteLine("Error: " + e.Message);
Console.Error.WriteLine("Use --help for help");
return 1;
}
catch (Exception e)
{
Console.Error.WriteLine("Error: " + e.ToString());
Console.Error.WriteLine("Use --help for help");
return 1;
}
/*
List<string> lInput = new List<string>();
List<string> lExcludedLibraries = new List<string>();
List<string> lIncludedLibraries = new List<string>();
string lOutput = null;
List<string> lSearchPath = new List<string>();
Mode lMode = Mode.None;
*/
}
private static int Check()
{
XmlSerializer ser = new XmlSerializer(typeof(importchecker));
bool ok = true;
foreach (var el in input)
{
using (StreamReader sr = new StreamReader(el))
{
importchecker check = ser.Deserialize(sr) as importchecker;
if (!CheckImports(check))
ok = false;
}
}
if (ok)
return 0;
return 2;
}
private static bool CheckImports(importchecker check)
{
bool ok = true;
foreach (var el in check.library)
{
AssemblyDefinition ad = Program.resolver.Resolve(el.fullname);
foreach (var type in el.type) {
if (!CheckType(ad, type))
ok = false;
}
}
return ok;
}
private static bool CheckType(AssemblyDefinition ad, ImportedType type)
{
TypeDefinition td = null;
string name = type.name;
if (name.Contains("/"))
{
name = name.Substring(0, name.IndexOf("/"));
td = ad.Modules.SelectMany(a => a.Types).FirstOrDefault(a => a.FullName == name);
foreach (var el in type.name.Substring(type.name.IndexOf("/") + 1).Split('/'))
{
if (td == null) break;
td = td.NestedTypes.FirstOrDefault(a => a.Name == el);
}
} else
td = ad.Modules.SelectMany(a => a.Types).FirstOrDefault(a => a.FullName == name);
if (td == null) {
Log("Missing type: {0}", type.name);
return false;
}
bool ok = true;
if (td.IsInterface && type.implementedByTypeSpecified && type.implementedByType)
{
for (int i = 0; i < td.Methods.Count; i++)
{
if (!type.implemented.Any(a => a.signature == td.Methods[i].FullName))
{
Log("Interface {0} has new interface member that did not exist before: {1}", type.name, td.Methods[i].FullName);
ok = false;
}
}
}
else if (type.implemented.Count > 0) // overrides
{
if (td.IsSealed || ! td.IsPublic)
{
ok = false;
Log("Type is sealed or private while it should not be: {0}", type.name);
}
for (int i = 0; i < type.implemented.Count; i++)
{
if (!td.Methods.Any(a => a.FullName == type.implemented[i].signature))
{
Log("Type {0} has a method that was overriden in a subclass but no longer exists: {1}", type.name, type.implemented[i].signature);
ok = false;
}
}
}
for (int i = 0; i < type.members.Count; i++)
{
switch (type.members[i].kind)
{
case ElementType.field:
if (!td.Fields.Any(a => a.FullName == type.members[i].signature))
{
ok = false;
Log("Type {0} has a missing field: {1}", type.name, type.members[i].signature);
}
break;
default:
if (!td.Methods.Any(a => a.FullName == type.members[i].signature))
{
ok = false;
Log("Type {0} has a missing method: {1}", type.name, type.members[i].signature);
}
break;
}
}
return ok;
}
private static void Log(string p)
{
Console.Error.WriteLine(p);
}
private static void Log(string p, params object[] args)
{
Console.Error.WriteLine(string.Format(p, args));
}
private static int Generate()
{
Worker wrk = new Worker();
foreach (var el in input)
{
ReaderParameters rp = new ReaderParameters(ReadingMode.Immediate);
rp.AssemblyResolver = resolver;
rp.ReadSymbols = false;
ModuleDefinition md = ModuleDefinition.ReadModule(el, rp);
wrk.Work(md);
}
XmlSerializer ser = new XmlSerializer(wrk.Output.GetType());
if (output == null)
ser.Serialize(Console.Out, wrk.Output);
else
using (StreamWriter sw = new StreamWriter(output, false, Encoding.UTF8))
ser.Serialize(sw, wrk.Output);
return 0;
}
private static IEnumerable<string> ArgumentStringSplit(string args)
{
List<string> res = new List<string>();
StringBuilder sb = new StringBuilder();
int instr = 0;
for (int i = 0; i < args.Length; i++)
{
switch (args[i])
{
case '\'':
if (instr == 1) goto default;
if (instr == 2 && i < args.Length - 1 && args[i + 1] == '\'')
{
i++;
sb.Append("\'");
}
else
{
if (instr == 0)
instr = 2;
else
instr = 0;
}
break;
case '\"':
if (instr == 2) goto default;
if (instr == 1 && i < args.Length - 1 && args[i + 1] == '\"')
{
i++;
sb.Append("\"");
}
else
{
if (instr == 0)
instr = 1;
else
instr = 0;
}
break;
case ' ':
if (instr == 0)
{
res.Add(sb.ToString());
if (sb.Length > 0)
sb.Length = 0;
}
else
sb.Append(" ");
break;
default:
sb.Append(args[i]);
break;
}
}
if (sb.Length > 0)
res.Add(sb.ToString());
return res;
}
static AssemblyDefinition ResolveFailure(object sender, AssemblyNameReference reference)
{
for (int i =0; i < searchPath.Count; i++) {
string cmb = Path.Combine(searchPath[i], reference.Name);
if (File.Exists(cmb+".dll"))
{
try
{
ModuleDefinition md = ModuleDefinition.ReadModule(cmb+".dll");
return md.Assembly;
}
catch
{
// could be bad input
}
}
if (File.Exists(cmb + ".DLL"))
{
try
{
ModuleDefinition md = ModuleDefinition.ReadModule(cmb + ".DLL");
return md.Assembly;
}
catch
{
// could be bad input
}
}
if (File.Exists(cmb + ".exe"))
{
try
{
ModuleDefinition md = ModuleDefinition.ReadModule(cmb + ".exe");
return md.Assembly;
}
catch
{
// could be bad input
}
}
if (File.Exists(cmb + ".EXE"))
{
try
{
ModuleDefinition md = ModuleDefinition.ReadModule(cmb + ".EXE");
return md.Assembly;
}
catch
{
// could be bad input
}
}
}
return null;
}
}
}