-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolutionBuilder.cs
More file actions
496 lines (408 loc) · 20.6 KB
/
Copy pathSolutionBuilder.cs
File metadata and controls
496 lines (408 loc) · 20.6 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
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.Pipes;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Web.Script.Serialization;
#if WINDOWS
using Microsoft.Build.Evaluation;
using Microsoft.Build.Execution;
using Microsoft.Build.Framework;
using Microsoft.Build.Logging;
#endif
namespace JSIL.SolutionBuilder {
public static class SolutionBuilder {
private static object GetField (object target, string fieldName, BindingFlags fieldFlags) {
return target.GetType().GetField(fieldName, fieldFlags).GetValue(target);
}
private static void SetField (object target, string fieldName, BindingFlags fieldFlags, object value) {
target.GetType().GetField(fieldName, fieldFlags).SetValue(target, value);
}
#if WINDOWS
// The only way to actually specify a solution configuration/platform is by messing around with internal/private types!
// Using the normal globalProperties method to set configuration/platform will break all the projects inside the
// solution by forcibly overriding their configuration/platform. MSBuild is garbage.
public static ProjectInstance[] ParseSolutionFile (
string solutionFile, string buildConfiguration, string buildPlatform,
Dictionary<string, string> globalProperties, BuildManager manager
) {
var asmBuild = manager.GetType().Assembly;
// Find the types used internally by MSBuild to convert .sln files into MSBuild projects.
var tSolutionParser = asmBuild.GetType("Microsoft.Build.Construction.SolutionParser", true);
var tProjectGenerator = asmBuild.GetType("Microsoft.Build.Construction.SolutionProjectGenerator", true);
// Create an instance of the solution parser. The ctor is internal, hence the second arg.
var solutionParser = Activator.CreateInstance(tSolutionParser, true);
const BindingFlags fieldFlags = BindingFlags.Instance |
BindingFlags.FlattenHierarchy |
BindingFlags.NonPublic |
BindingFlags.Public;
Func<object, string, object> getField = (target, fieldName) =>
GetField(target, fieldName, fieldFlags);
Action<object, string, object> setField = (target, fieldName, value) =>
SetField(target, fieldName, fieldFlags, value);
// Point the solution parser instance to the solution file.
setField(solutionParser, "solutionFile", solutionFile);
// Parse the solution file. The generator will use the parsed information later.
solutionParser.GetType().InvokeMember(
"ParseSolutionFile",
BindingFlags.Instance | BindingFlags.InvokeMethod | BindingFlags.NonPublic,
null, solutionParser, new object[0]
);
// Override the configuration and platform that may have been selected when parsing the solution
// file.
if (buildConfiguration != null)
setField(solutionParser, "defaultConfigurationName", buildConfiguration);
if (buildPlatform != null)
setField(solutionParser, "defaultPlatformName", buildPlatform);
// Forces the solution parser to scan project dependencies and select the configuration/platform
// that we provided above.
if ((buildConfiguration != null) || (buildPlatform != null))
setField(solutionParser, "solutionContainsWebDeploymentProjects", true);
// The generator needs a logging service and build context.
var loggingService = manager.GetType().InvokeMember(
"Microsoft.Build.BackEnd.IBuildComponentHost.get_LoggingService",
BindingFlags.Instance | BindingFlags.InvokeMethod | BindingFlags.NonPublic,
null, manager, new object[0]
);
var context = new BuildEventContext(0, 0, 0, 0);
// Convert the parsed solution into one or more project instances that we can build.
var result = tProjectGenerator.InvokeMember(
"Generate",
BindingFlags.Static | BindingFlags.InvokeMethod | BindingFlags.NonPublic,
null, null, new object[] {
solutionParser,
globalProperties,
null,
context,
loggingService
}
);
return (ProjectInstance[])result;
}
#endif
public static void HandleCommandLine (int connectTimeoutMs = 2500) {
var commandLineArgs = Environment.GetCommandLineArgs();
if ((commandLineArgs.Length == 3) && (commandLineArgs[1] == "--buildSolution")) {
try {
var jss = new JavaScriptSerializer {
MaxJsonLength = 1024 * 1024 * 64
};
var pipeId = commandLineArgs[2];
using (var pipe = new NamedPipeClientStream(pipeId)) {
pipe.Connect(connectTimeoutMs);
using (var sr = new StreamReader(pipe))
using (var sw = new StreamWriter(pipe)) {
var argsJson = sr.ReadLine();
var argsDict = jss.Deserialize<Dictionary<string, object>>(argsJson);
var buildResult = Build(
(string)argsDict["solutionFile"],
(string)argsDict["buildConfiguration"],
(string)argsDict["buildPlatform"],
(string)argsDict["buildTarget"],
(string)argsDict["logVerbosity"],
true
);
var resultJson = jss.Serialize(buildResult);
sw.WriteLine(resultJson);
sw.Flush();
pipe.Flush();
pipe.WaitForPipeDrain();
}
}
} catch (Exception exc) {
Console.Error.WriteLine(exc.ToString());
Environment.Exit(1);
}
Environment.Exit(0);
}
}
private static BuildResult OutOfProcessBuild (Dictionary<string, object> arguments, int startupTimeoutMs = 5000) {
var jss = new JavaScriptSerializer {
MaxJsonLength = 1024 * 1024 * 64
};
var argsJson = jss.Serialize(arguments);
var pipeId = String.Format("JSIL.Build{0:X4}", (new Random()).Next());
Console.Error.WriteLine("// Starting out-of-process solution build with ID '{0}'...", pipeId);
using (var pipe = new NamedPipeServerStream(
pipeId, PipeDirection.InOut, 1, PipeTransmissionMode.Message, PipeOptions.Asynchronous
)) {
var psi = new ProcessStartInfo {
FileName = JSIL.Internal.Util.GetPathOfAssembly(Assembly.GetExecutingAssembly()),
Arguments = String.Format("--buildSolution {0}", pipeId),
WorkingDirectory = Environment.CurrentDirectory,
CreateNoWindow = false,
UseShellExecute = false,
ErrorDialog = false
};
var childProcess = Process.Start(psi);
if (childProcess == null)
throw new InvalidOperationException("Failed to start child process");
var connectedEvent = new ManualResetEventSlim(false);
var exitedEvent = new ManualResetEventSlim(false);
try {
var connectAR = pipe.BeginWaitForConnection((_) => connectedEvent.Set(), null);
try {
childProcess.Exited += (s, e) => exitedEvent.Set();
if (childProcess.HasExited)
exitedEvent.Set();
} catch {
}
WaitHandle.WaitAny(
new[] { connectedEvent.WaitHandle, exitedEvent.WaitHandle }, startupTimeoutMs
);
if (connectedEvent.IsSet) {
pipe.EndWaitForConnection(connectAR);
} else if (exitedEvent.IsSet) {
Console.Error.WriteLine("// Out-of-process solution build terminated unexpectedly with code {0}!", childProcess.ExitCode);
Environment.Exit(1);
} else {
Console.Error.WriteLine("// Out-of-process solution build timed out!");
Environment.Exit(2);
}
using (var sr = new StreamReader(pipe))
using (var sw = new StreamWriter(pipe)) {
sw.WriteLine(argsJson);
sw.Flush();
pipe.Flush();
pipe.WaitForPipeDrain();
var resultJson = sr.ReadLine();
var buildResult = jss.Deserialize<BuildResult>(resultJson);
Console.Error.WriteLine("// Out-of-process solution build completed successfully.");
return buildResult;
}
} finally {
try {
if (!childProcess.HasExited)
childProcess.Kill();
} catch {
}
childProcess.Dispose();
}
}
}
public static BuildResult Build (
string solutionFile, string buildConfiguration = null,
string buildPlatform = null, string buildTarget = "Build",
string logVerbosity = null, bool? inProcess = null
) {
bool defaultInProcess = Debugger.IsAttached;
#if WINDOWS
if (!inProcess.GetValueOrDefault(defaultInProcess)) {
var argsDict = new Dictionary<string, object> {
{"solutionFile", solutionFile},
{"buildConfiguration", buildConfiguration},
{"buildPlatform", buildPlatform},
{"buildTarget", buildTarget},
{"logVerbosity", logVerbosity}
};
return OutOfProcessBuild(argsDict);
}
string configString = String.Format("{0}|{1}", buildConfiguration ?? "<default>", buildPlatform ?? "<default>");
if ((buildConfiguration ?? buildPlatform) != null)
Console.Error.WriteLine("// Running target '{2}' of '{0}' ({1}) ...", JSIL.Compiler.Program.ShortenPath(solutionFile), configString, buildTarget);
else
Console.Error.WriteLine("// Running target '{1}' of '{0}' ...", JSIL.Compiler.Program.ShortenPath(solutionFile), buildTarget);
var pc = new ProjectCollection();
var parms = new BuildParameters(pc);
var globalProperties = new Dictionary<string, string> {
{"JSIL", "building"},
{"JSILVersion", Assembly.GetExecutingAssembly().GetName().ToString() }
};
var hostServices = new HostServices();
var eventRecorder = new BuildEventRecorder();
LoggerVerbosity _logVerbosity;
if ((logVerbosity == null) || !Enum.TryParse(logVerbosity, out _logVerbosity))
_logVerbosity = LoggerVerbosity.Quiet;
parms.Loggers = new ILogger[] {
new ConsoleLogger(_logVerbosity), eventRecorder
};
var manager = BuildManager.DefaultBuildManager;
Console.Error.Write("// Generating MSBuild projects for solution '{0}'...", Path.GetFileName(solutionFile));
// Begin a fake build so the manager has a logger available.
manager.BeginBuild(parms);
var projects = ParseSolutionFile(
solutionFile, buildConfiguration, buildPlatform,
globalProperties, manager
);
manager.EndBuild();
Console.Error.WriteLine(" {0} project(s) generated.", projects.Length);
if (File.ReadAllText(solutionFile).Contains("ProjectSection(ProjectDependencies)")) {
Console.Error.WriteLine("// WARNING: Your solution file contains project dependencies. MSBuild ignores these, so your build may fail. If it does, try building it in Visual Studio first to resolve the dependencies.");
}
var allItemsBuilt = new List<BuiltItem>();
var resultFiles = new HashSet<string>();
foreach (var project in projects) {
// Save out the generated msbuild project for each solution, to aid debugging.
try {
project.ToProjectRootElement().Save(project.FullPath, Encoding.UTF8);
} catch (Exception exc) {
Console.Error.WriteLine("// Failed to save generated project '{0}': {1}", Path.GetFileName(project.FullPath), exc.Message);
}
}
foreach (var project in projects) {
Console.Error.WriteLine("// Building project '{0}'...", project.FullPath);
var request = new BuildRequestData(
project,
new string[] { buildTarget },
hostServices, BuildRequestDataFlags.None
);
Microsoft.Build.Execution.BuildResult result;
try {
result = manager.Build(parms, request);
} catch (Exception exc) {
Console.Error.WriteLine("// Compilation failed: {0}", exc.Message);
continue;
}
allItemsBuilt.AddRange(ExtractChildProjectResults(manager));
foreach (var kvp in result.ResultsByTarget) {
var targetResult = kvp.Value;
if ((targetResult.Exception != null) || (targetResult.ResultCode == TargetResultCode.Failure)) {
string errorMessage = "Unknown error";
if (targetResult.Exception != null)
errorMessage = targetResult.Exception.Message;
Console.Error.WriteLine("// Compilation failed for target '{0}': {1}", kvp.Key, errorMessage);
}
}
}
// ResultsByTarget doesn't reliably produce all the output executables, so we must
// extract them by hand.
foreach (var builtItem in allItemsBuilt) {
if (builtItem.TargetName != "Build")
continue;
if (!File.Exists(builtItem.OutputPath)) {
Console.Error.WriteLine("// Ignoring nonexistent build output '" + Path.GetFileName(builtItem.OutputPath) + "'.");
continue;
}
var extension = Path.GetExtension(builtItem.OutputPath).ToLowerInvariant();
switch (extension) {
case ".exe":
case ".dll":
resultFiles.Add(builtItem.OutputPath);
break;
default:
Console.Error.WriteLine("// Ignoring build output '" + Path.GetFileName(builtItem.OutputPath) + "' due to unknown file type.");
break;
}
}
return new BuildResult(
Path.GetFullPath(solutionFile),
resultFiles.ToArray(),
eventRecorder.ProjectsById.Values.ToArray(),
eventRecorder.TargetFiles.ToArray(),
allItemsBuilt.ToArray()
);
#else // !WINDOWS
throw new NotImplementedException("Solution building is only supported on Windows when JSILc is compiled using MSBuild/Visual Studio.");
#endif
}
#if WINDOWS
// Enumerate all the projects the BuildManager built while building the projects we asked it to build.
// This will allow us to identify any secondary outputs (like XNB files).
private static BuiltItem[] ExtractChildProjectResults (BuildManager manager) {
var resultsCache = GetField(manager, "resultsCache", BindingFlags.Instance | BindingFlags.NonPublic);
var tResultsCache = resultsCache.GetType();
var pResultsDictionary = tResultsCache.GetProperty("ResultsDictionary", BindingFlags.NonPublic | BindingFlags.Instance);
var oResultsDictionary = pResultsDictionary.GetValue(resultsCache, null);
IDictionary<int, Microsoft.Build.Execution.BuildResult> resultsDictionary = oResultsDictionary as Dictionary<int, Microsoft.Build.Execution.BuildResult>;
if (resultsDictionary == null)
resultsDictionary = oResultsDictionary as ConcurrentDictionary<int, Microsoft.Build.Execution.BuildResult>;
if (resultsDictionary == null)
throw new Exception("Unsupported version of MSBuild");
var result = new List<BuiltItem>();
foreach (var projectResult in resultsDictionary.Values) {
foreach (var kvp in projectResult.ResultsByTarget) {
result.AddRange(
from taskItem in kvp.Value.Items
select new BuiltItem(kvp.Key, taskItem)
);
}
}
return result.ToArray();
}
#endif
}
public class BuiltProject {
public BuiltProject Parent;
public int Id;
public string File;
public override string ToString () {
return String.Format("{0} '{1}'", Id, File);
}
}
#if WINDOWS
public class BuildEventRecorder : ILogger {
public readonly Dictionary<int, BuiltProject> ProjectsById = new Dictionary<int, BuiltProject>();
public readonly HashSet<string> TargetFiles = new HashSet<string>();
public void Initialize (IEventSource eventSource) {
eventSource.ProjectStarted += (sender, args) => {
var parentId = args.ParentProjectBuildEventContext.ProjectInstanceId;
BuiltProject parentProject;
ProjectsById.TryGetValue(parentId, out parentProject);
var obj = new BuiltProject {
Parent = parentProject,
Id = args.ProjectId,
File = args.ProjectFile
};
ProjectsById[args.ProjectId] = obj;
};
eventSource.TargetStarted += (sender, args) =>
TargetFiles.Add(args.TargetFile);
}
public string Parameters {
get;
set;
}
public void Shutdown () {
}
public LoggerVerbosity Verbosity {
get;
set;
}
}
#endif
public class BuiltItem {
public readonly string TargetName;
public readonly string OutputPath;
public readonly Dictionary<string, string> Metadata = new Dictionary<string, string>();
// XMLSerializer sucks.
public BuiltItem () {
}
#if WINDOWS
internal BuiltItem (string targetName, ITaskItem item) {
TargetName = targetName;
OutputPath = item.ItemSpec;
foreach (var name in item.MetadataNames)
Metadata.Add((string)name, item.GetMetadata((string)name));
}
#endif
public override string ToString () {
return String.Format("{0}: {1} ({2} metadata)", TargetName, OutputPath, Metadata.Count);
}
}
public class BuildResult {
public readonly string[] OutputFiles;
public readonly BuiltProject[] ProjectsBuilt;
public readonly string[] TargetFilesUsed;
public readonly BuiltItem[] AllItemsBuilt;
public readonly string SolutionPath;
// XMLSerializer sucks.
public BuildResult () {
}
internal BuildResult (
string solutionPath,
string[] outputFiles, BuiltProject[] projectsBuilt,
string[] targetFiles, BuiltItem[] allItemsBuilt
) {
SolutionPath = solutionPath;
OutputFiles = outputFiles;
ProjectsBuilt = projectsBuilt;
TargetFilesUsed = targetFiles;
AllItemsBuilt = allItemsBuilt;
}
}
}