forked from microsoft/Static-Module-Verifier
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
446 lines (409 loc) · 17.4 KB
/
Program.cs
File metadata and controls
446 lines (409 loc) · 17.4 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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.IO;
using System.Configuration;
using System.Xml;
using System.Xml.Schema;
using System.Diagnostics;
using System.Web;
using System.Collections.Specialized;
using System.Collections;
using StaticModuleVerifier.Properties;
using SmvLibrary;
using System.Reflection;
using System.Globalization;
using System.Data.SqlClient;
using SmvDb;
namespace SmvSkeleton
{
class Program
{
static SMVConfig smvConfig;
const string configXmlFileName = "Config.xml";
private static bool makeDefectsPortable = false; // TODO
private static bool doAnalysis = false;
private static string buildLogFileNamePrefix = "smvbuild";
private static bool cloud = false;
private static bool useDb = false;
/// <summary>
/// Prints the usage string to the console.
/// </summary>
static void PrintUsage()
{
Console.WriteLine(Resources.UsageString);
}
/// <summary>
/// Prints detailed help text to the console.
/// </summary>
static void PrintHelp()
{
PrintUsage();
Log.LogInfo(Resources.HelpTextWithoutUsageString);
}
/// <summary>
/// Processes command line arguments for Analysis.
/// </summary>
/// <param name="args">The list of command line arguments.</param>
/// <returns>true on success, false on failure.</returns>
static bool ProcessArgs(string[] args)
{
bool help = false;
bool unsupportedArgument = false;
for (int i = 0; i < args.Length;)
{
if (args[i].Equals("/help", StringComparison.InvariantCultureIgnoreCase) || args[i].Equals("/?"))
{
help = true;
PrintHelp();
break;
}
else if (args[i].Equals("/cloud", StringComparison.InvariantCultureIgnoreCase))
{
Log.LogInfo("Using cloud.");
cloud = true;
Utility.schedulerType = "cloud";
i++;
}
else if (args[i].Equals("/db", StringComparison.InvariantCultureIgnoreCase))
{
Log.LogInfo("Using db.");
useDb = true;
Utility.useDb = true;
i++;
}
else if (args[i].Equals("/jobobject", StringComparison.InvariantCultureIgnoreCase))
{
Log.LogInfo("Using job objects.");
Utility.useJobObject = true;
i++;
}
else if (args[i].StartsWith("/config:", StringComparison.InvariantCulture) || args[i].StartsWith("/log:", StringComparison.InvariantCulture))
{
String[] tokens = args[i].Split(new char[] { ':' }, 2);
if (tokens.Length == 2)
{
string value = tokens[1].Replace(@"""", String.Empty);
if (tokens[0].Equals("/config"))
{
Utility.SetSmvVar("configFilePath", value);
}
else if (tokens[0].Equals("/log"))
{
if (!Directory.Exists(value))
{
Log.LogFatalError("Log path does not exist.");
}
Log.SetLogPath(value);
}
}
i++;
}
else if (args[i].Equals("/analyze"))
{
doAnalysis = true;
i++;
}
else if (args[i].StartsWith("/plugin:", StringComparison.InvariantCulture))
{
String[] tokens = args[i].Split(new char[] { ':' }, 2);
if (File.Exists(tokens[1]))
{
Utility.pluginPath = tokens[1].Replace(Environment.GetEnvironmentVariable("smv"), "%smv%");
Assembly assembly = Assembly.LoadFrom(tokens[1]);
string fullName = assembly.ExportedTypes.ToList().Find(t => t.GetInterface(typeof(ISMVPlugin).FullName) != null).FullName;
Utility.plugin = (ISMVPlugin)assembly.CreateInstance(fullName);
if (Utility.plugin == null)
{
Log.LogFatalError("Could not load plugin.");
}
Utility.plugin.Initialize();
}
else
{
Log.LogFatalError("Plugin not found.");
}
i++;
}
else if (args[i].StartsWith("/projectfile:", StringComparison.InvariantCulture))
{
String[] tokens = args[i].Split(new char[] { ':' }, 2);
Utility.SetSmvVar("projectFileArg", tokens[1]);
i++;
}
else if (args[i].Equals("/debug"))
{
Utility.debugMode = true;
Utility.SetSmvVar("debugMode", "true");
i++;
}
else if (args[i].StartsWith("/sessionID:", StringComparison.InvariantCultureIgnoreCase))
{
String[] tokens = args[i].Split(new char[] { ':' }, 2);
if (!String.IsNullOrEmpty(tokens[1]))
{
Log.LogInfo("Setting session ID : " + tokens[1]);
Utility.sessionId = tokens[1];
}
else
{
Log.LogError("Session ID not found");
}
i++;
}
else if (args[i].StartsWith("/taskID:", StringComparison.InvariantCultureIgnoreCase))
{
String[] tokens = args[i].Split(new char[] { ':' }, 2);
if (!String.IsNullOrEmpty(tokens[1]))
{
Log.LogInfo("Setting task ID : " + tokens[1]);
Utility.taskId = tokens[1];
}
else
{
Log.LogError("Task ID not found");
}
i++;
}
else
{
unsupportedArgument = true;
i++;
}
}
if (Utility.plugin != null)
{
Utility.plugin.ProcessPluginArgument(args);
}
else if (unsupportedArgument)
{
Log.LogFatalError("Unsupported arguments. Please provide a Plugin.");
}
if (help)
{
if (Utility.plugin != null)
{
Utility.plugin.PrintPluginHelp();
}
return false;
}
return true;
}
static int Main(string[] args)
{
Utility.SetSmvVar("workingDir", Directory.GetCurrentDirectory());
Utility.SetSmvVar("logFilePath", null);
Utility.SetSmvVar("assemblyDir", Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location));
Utility.SetSmvVar("configFilePath", Path.Combine(Utility.GetSmvVar("workingDir"), configXmlFileName));
Utility.SetSmvVar("smvLogFileNamePrefix", buildLogFileNamePrefix);
try
{
Console.BufferHeight = Int16.MaxValue - 1;
}
catch (Exception)
{
}
// Process commandline arguments.
// Note that ProcessArgs will return false if execution should not continue.
// This happens in cases such as /help, /getAvailableModules, /searchmodules
if (!ProcessArgs(args))
{
return -1;
}
if (useDb)
{
try
{
using (var database = new SmvDbEntities())
{
SmvDb.Task task = database.Tasks.Where((x) => x.TaskID == Utility.taskId).FirstOrDefault();
if (task != null)
{
string argsString = string.Join(" ", args);
task.Arguments = argsString;
database.SaveChanges();
}
}
}
catch (Exception e)
{
Log.LogFatalError("Exception while updating database " + e);
}
}
// Get the SMV version name.
string smvVersionTxtPath = Path.Combine(Utility.GetSmvVar("assemblyDir"), "SmvVersionName.txt");
if (!File.Exists(smvVersionTxtPath))
{
Log.LogFatalError("SmvVersionName.txt must exist in the SMV bin directory.");
}
string[] lines = File.ReadAllLines(smvVersionTxtPath);
if (lines.Length < 1)
{
Log.LogFatalError("SmvVersionName.txt is empty.");
}
Utility.version = lines[0];
// Consume specified configuration file
smvConfig = Utility.GetSMVConfig();
if (smvConfig == null)
{
Log.LogFatalError("Could not load Config file");
}
// Set the variables defined in the Variables node in the config file
LoadGlobalVariables(smvConfig.Variables);
// Project file value from command line overrides the Config value
if (!String.IsNullOrEmpty(Utility.GetSmvVar("projectFileArg")))
{
Utility.SetSmvVar("projectFile", Utility.GetSmvVar("projectFileArg"));
}
bool buildResult = false;
bool analysisResult = false;
double buildTime = 0, analysisTime = 0;
int localThreadCount = Environment.ProcessorCount;
if (Utility.GetSmvVar("localThreads") != null)
{
localThreadCount = int.Parse(Utility.GetSmvVar("localThreads"));
}
Log.LogInfo(String.Format("Running local scheduler with {0} threads", localThreadCount));
// Load the cloud config from an XML file.
SMVCloudConfig cloudConfig = null;
// Set up the schedulers.
Utility.scheduler = new MasterSMVActionScheduler();
LocalSMVActionScheduler localScheduler = new LocalSMVActionScheduler(localThreadCount);
CloudSMVActionScheduler cloudScheduler = null;
if (cloud)
{
cloudConfig = Utility.GetSMVCloudConfig();
cloudScheduler = new CloudSMVActionScheduler(cloudConfig);
}
Utility.scheduler.AddScheduler("local", localScheduler);
Utility.scheduler.AddScheduler("cloud", cloudScheduler);
// Do build if specified in the configuration file
if (smvConfig.Build != null)
{
Stopwatch sw = Stopwatch.StartNew();
// Populate the actions dictionary that will be used by the schedulers.
Utility.PopulateActionsDictionary(smvConfig.Build);
if (string.IsNullOrEmpty(Utility.GetSmvVar("projectFile")))
{
Utility.scheduler.Dispose();
Log.LogFatalError("Project file not set");
}
List<SMVActionResult> buildActionsResult = Utility.ExecuteActions(Utility.GetRootActions(smvConfig.Build));
buildResult = Utility.IsExecuteActionsSuccessful(buildActionsResult);
if (Utility.plugin != null && buildResult == false)
{
Utility.plugin.Finally(true);
}
if (Utility.plugin != null)
{
Utility.plugin.PostBuild(smvConfig.Build);
}
sw.Stop();
buildTime = sw.Elapsed.TotalSeconds;
}
// If build succeeded or it was not specified, do analysis (if specified and called)
if (smvConfig.Build == null || buildResult)
{
if (smvConfig.Analysis != null)
{
if (doAnalysis)
{
Stopwatch sw = Stopwatch.StartNew();
Utility.PopulateActionsDictionary(smvConfig.Analysis);
if (Utility.plugin != null)
{
Log.LogInfo("Using plugin " + Utility.plugin + " for analysis.");
analysisResult = Utility.plugin.DoPluginAnalysis(smvConfig.Analysis);
Utility.plugin.PostAnalysis(smvConfig.Analysis);
}
else
{
List<SMVActionResult> analysisActionsResult = Utility.ExecuteActions(Utility.GetRootActions(smvConfig.Analysis));
analysisResult = Utility.IsExecuteActionsSuccessful(analysisActionsResult);
}
if (!analysisResult)
{
Utility.scheduler.Dispose();
Utility.plugin.Finally(true);
Log.LogFatalError("Analysis failed.");
}
sw.Stop();
analysisTime = sw.Elapsed.TotalSeconds;
}
}
Utility.plugin.Finally(false);
}
else
{
Utility.plugin.Finally(true);
Utility.scheduler.Dispose();
Log.LogFatalError("Build failed, skipping Analysis.");
}
Utility.PrintResult(Utility.result, (int)buildTime, (int)analysisTime, true);
Log.LogInfo(String.Format("Total time taken {0} seconds", (int)(buildTime + analysisTime)));
if (Utility.plugin != null)
{
int bugCount = Utility.plugin.GenerateBugsCount();
Log.LogInfo("Found " + bugCount + " bugs!");
if (useDb)
{
try
{
using (var database = new SmvDbEntities())
{
SmvDb.Task task = database.Tasks.Where((x) => x.TaskID == Utility.taskId).FirstOrDefault();
if (task != null)
{
string bugCountString = bugCount.ToString();
task.Bugs = bugCountString;
database.SaveChanges();
}
}
}
catch (Exception e)
{
Utility.scheduler.Dispose();
Log.LogFatalError("Exception while updating database " + e);
return -1;
}
}
}
localScheduler.Dispose();
if (cloud) cloudScheduler.Dispose();
if (makeDefectsPortable)
{
foreach (string bugDirectory in Directory.EnumerateDirectories(Path.Combine(Utility.smvVars["smvOutputDir"], "Bugs")))
{
try
{
Utility.makeDefectPortable(bugDirectory);
}
catch (Exception e)
{
Log.LogFatalError("Exception occurred when making defect portable." + e.ToString());
}
}
Log.LogInfo("Defects, if any, made portable successfully");
}
return Convert.ToInt32(Utility.scheduler.errorsEncountered);
}
/// <summary>
/// Sets the global variables, defined in the Config file, in the SmvVar dictionary
/// </summary>
/// <param name="globalVars">The variables defined in the config file.</param>
static void LoadGlobalVariables(SetVar[] globalVars)
{
if (globalVars != null)
{
foreach (SetVar smvVar in globalVars)
{
string value = Environment.ExpandEnvironmentVariables(smvVar.value);
Utility.SetSmvVar(smvVar.key, Utility.ExpandSmvVariables(value));
}
}
}
}
}