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
|
// Copyright (c) .NET Foundation and contributors. All rights reserved. Licensed under the Microsoft Reciprocal License. See LICENSE.TXT file in the project root for full license information.
namespace WixToolset.BuildTasks
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Text;
using System.Threading;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
/// <summary>
/// Base class for WiX tool tasks; executes tools in-process
/// so that repeated invocations are much faster.
/// </summary>
public abstract class WixToolTask : ToolTask, IDisposable
{
private string additionalOptions;
private bool disposed;
private bool noLogo;
private bool runAsSeparateProcess;
private bool suppressAllWarnings;
private string[] suppressSpecificWarnings;
private string[] treatSpecificWarningsAsErrors;
private bool treatWarningsAsErrors;
private bool verboseOutput;
private Queue<string> messageQueue;
private ManualResetEvent messagesAvailable;
private ManualResetEvent toolExited;
private int exitCode;
/// <summary>
/// Gets or sets additional options that are appended the the tool command-line.
/// </summary>
/// <remarks>
/// This allows the task to support extended options in the tool which are not
/// explicitly implemented as properties on the task.
/// </remarks>
public string AdditionalOptions
{
get { return this.additionalOptions; }
set { this.additionalOptions = value; }
}
/// <summary>
/// Gets or sets a flag indicating whether the task should be run as separate
/// process instead of in-proc with MSBuild which is the default.
/// </summary>
public bool RunAsSeparateProcess
{
get { return this.runAsSeparateProcess; }
set { this.runAsSeparateProcess = value; }
}
#region Common Options
/// <summary>
/// Gets or sets whether all warnings should be suppressed.
/// </summary>
public bool SuppressAllWarnings
{
get { return this.suppressAllWarnings; }
set { this.suppressAllWarnings = value; }
}
/// <summary>
/// Gets or sets a list of specific warnings to be suppressed.
/// </summary>
public string[] SuppressSpecificWarnings
{
get { return this.suppressSpecificWarnings; }
set { this.suppressSpecificWarnings = value; }
}
/// <summary>
/// Gets or sets whether all warnings should be treated as errors.
/// </summary>
public bool TreatWarningsAsErrors
{
get { return this.treatWarningsAsErrors; }
set { this.treatWarningsAsErrors = value; }
}
/// <summary>
/// Gets or sets a list of specific warnings to treat as errors.
/// </summary>
public string[] TreatSpecificWarningsAsErrors
{
get { return this.treatSpecificWarningsAsErrors; }
set { this.treatSpecificWarningsAsErrors = value; }
}
/// <summary>
/// Gets or sets whether to display verbose output.
/// </summary>
public bool VerboseOutput
{
get { return this.verboseOutput; }
set { this.verboseOutput = value; }
}
/// <summary>
/// Gets or sets whether to display the logo.
/// </summary>
public bool NoLogo
{
get { return this.noLogo; }
set { this.noLogo = value; }
}
#endregion
/// <summary>
/// Cleans up the ManualResetEvent members
/// </summary>
public void Dispose()
{
if (!this.disposed)
{
this.Dispose(true);
GC.SuppressFinalize(this);
disposed = true;
}
}
/// <summary>
/// Cleans up the ManualResetEvent members
/// </summary>
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
messagesAvailable.Close();
toolExited.Close();
}
}
/// <summary>
/// Generate the command line arguments to write to the response file from the properties.
/// </summary>
/// <returns>Command line string.</returns>
protected override string GenerateResponseFileCommands()
{
WixCommandLineBuilder commandLineBuilder = new WixCommandLineBuilder();
this.BuildCommandLine(commandLineBuilder);
return commandLineBuilder.ToString();
}
/// <summary>
/// Builds a command line from options in this and derivative tasks.
/// </summary>
/// <remarks>
/// Derivative classes should call BuildCommandLine() on the base class to ensure that common command line options are added to the command.
/// </remarks>
protected virtual void BuildCommandLine(WixCommandLineBuilder commandLineBuilder)
{
commandLineBuilder.AppendIfTrue("-nologo", this.NoLogo);
commandLineBuilder.AppendArrayIfNotNull("-sw", this.SuppressSpecificWarnings);
commandLineBuilder.AppendIfTrue("-sw", this.SuppressAllWarnings);
commandLineBuilder.AppendIfTrue("-v", this.VerboseOutput);
commandLineBuilder.AppendArrayIfNotNull("-wx", this.TreatSpecificWarningsAsErrors);
commandLineBuilder.AppendIfTrue("-wx", this.TreatWarningsAsErrors);
}
/// <summary>
/// Executes a tool in-process by loading the tool assembly and invoking its entrypoint.
/// </summary>
/// <param name="pathToTool">Path to the tool to be executed; must be a managed executable.</param>
/// <param name="responseFileCommands">Commands to be written to a response file.</param>
/// <param name="commandLineCommands">Commands to be passed directly on the command-line.</param>
/// <returns>The tool exit code.</returns>
protected override int ExecuteTool(string pathToTool, string responseFileCommands, string commandLineCommands)
{
if (this.RunAsSeparateProcess)
{
return base.ExecuteTool(pathToTool, responseFileCommands, commandLineCommands);
}
this.messageQueue = new Queue<string>();
this.messagesAvailable = new ManualResetEvent(false);
this.toolExited = new ManualResetEvent(false);
Util.RunningInMsBuild = true;
WixToolTaskLogger logger = new WixToolTaskLogger(this.messageQueue, this.messagesAvailable);
TextWriter saveConsoleOut = Console.Out;
TextWriter saveConsoleError = Console.Error;
Console.SetOut(logger);
Console.SetError(logger);
string responseFile = null;
try
{
string responseFileSwitch;
responseFile = this.GetTemporaryResponseFile(responseFileCommands, out responseFileSwitch);
if (!String.IsNullOrEmpty(responseFileSwitch))
{
commandLineCommands = commandLineCommands + " " + responseFileSwitch;
}
string[] arguments = CommandLineResponseFile.ParseArgumentsToArray(commandLineCommands);
Thread toolThread = new Thread(new ParameterizedThreadStart(this.ExecuteToolThread));
toolThread.Start(new object[] { pathToTool, arguments });
this.HandleToolMessages();
if (this.exitCode == 0 && this.Log.HasLoggedErrors)
{
this.exitCode = -1;
}
return this.exitCode;
}
finally
{
if (responseFile != null)
{
File.Delete(responseFile);
}
Console.SetOut(saveConsoleOut);
Console.SetError(saveConsoleError);
}
}
/// <summary>
/// Called by a new thread to execute the tool in that thread.
/// </summary>
/// <param name="parameters">Tool path and arguments array.</param>
private void ExecuteToolThread(object parameters)
{
try
{
object[] pathAndArguments = (object[])parameters;
Assembly toolAssembly = Assembly.LoadFrom((string)pathAndArguments[0]);
this.exitCode = (int)toolAssembly.EntryPoint.Invoke(null, new object[] { pathAndArguments[1] });
}
catch (FileNotFoundException fnfe)
{
Log.LogError("Unable to load tool from path {0}. Consider setting the ToolPath parameter to $(WixToolPath).", fnfe.FileName);
this.exitCode = -1;
}
catch (Exception ex)
{
this.exitCode = -1;
this.LogEventsFromTextOutput(ex.Message, MessageImportance.High);
foreach (string stackTraceLine in ex.StackTrace.Split('\n'))
{
this.LogEventsFromTextOutput(stackTraceLine.TrimEnd(), MessageImportance.High);
}
throw;
}
finally
{
this.toolExited.Set();
}
}
/// <summary>
/// Waits for messages from the tool thread and sends them to the MSBuild logger on the original thread.
/// Returns when the tool thread exits.
/// </summary>
private void HandleToolMessages()
{
WaitHandle[] waitHandles = new WaitHandle[] { this.messagesAvailable, this.toolExited };
while (WaitHandle.WaitAny(waitHandles) == 0)
{
lock (this.messageQueue)
{
while (this.messageQueue.Count > 0)
{
this.LogEventsFromTextOutput(messageQueue.Dequeue(), MessageImportance.Normal);
}
this.messagesAvailable.Reset();
}
}
}
/// <summary>
/// Creates a temporary response file for tool execution.
/// </summary>
/// <returns>Path to the response file.</returns>
/// <remarks>
/// The temporary file should be deleted after the tool execution is finished.
/// </remarks>
private string GetTemporaryResponseFile(string responseFileCommands, out string responseFileSwitch)
{
string responseFile = null;
responseFileSwitch = null;
if (!String.IsNullOrEmpty(responseFileCommands))
{
responseFile = Path.GetTempFileName();
using (StreamWriter writer = new StreamWriter(responseFile, false, this.ResponseFileEncoding))
{
writer.Write(responseFileCommands);
}
responseFileSwitch = this.GetResponseFileSwitch(responseFile);
}
return responseFile;
}
/// <summary>
/// Cycles thru each task to find correct path of the file in question.
/// Looks at item spec, hintpath and then in user defined Reference Paths
/// </summary>
/// <param name="tasks">Input task array</param>
/// <param name="referencePaths">SemiColon delimited directories to search</param>
/// <returns>List of task item file paths</returns>
[SuppressMessage("Microsoft.Design", "CA1002:DoNotExposeGenericLists")]
protected static List<string> AdjustFilePaths(ITaskItem[] tasks, string[] referencePaths)
{
List<string> sourceFilePaths = new List<string>();
if (tasks == null)
{
return sourceFilePaths;
}
foreach (ITaskItem task in tasks)
{
string filePath = task.ItemSpec;
if (!File.Exists(filePath))
{
filePath = task.GetMetadata("HintPath");
if (!File.Exists(filePath))
{
string searchPath = FileSearchHelperMethods.SearchFilePaths(referencePaths, filePath);
if (!String.IsNullOrEmpty(searchPath))
{
filePath = searchPath;
}
}
}
sourceFilePaths.Add(filePath);
}
return sourceFilePaths;
}
/// <summary>
/// Used as a replacement for Console.Out to capture output from a tool
/// and redirect it to the MSBuild logging system.
/// </summary>
private class WixToolTaskLogger : TextWriter
{
private StringBuilder buffer;
private Queue<string> messageQueue;
private ManualResetEvent messagesAvailable;
/// <summary>
/// Creates a new logger that sends tool output to the tool task's log handler.
/// </summary>
public WixToolTaskLogger(Queue<string> messageQueue, ManualResetEvent messagesAvailable) : base(CultureInfo.CurrentCulture)
{
this.messageQueue = messageQueue;
this.messagesAvailable = messagesAvailable;
this.buffer = new StringBuilder();
}
/// <summary>
/// Gets the encoding of the logger.
/// </summary>
public override Encoding Encoding
{
get { return Encoding.Unicode; }
}
/// <summary>
/// Redirects output to a buffer; watches for newlines and sends each line to the
/// MSBuild logging system.
/// </summary>
/// <param name="value">Character being written.</param>
/// <remarks>All other Write() variants eventually call into this one.</remarks>
public override void Write(char value)
{
lock (this.messageQueue)
{
if (value == '\n')
{
if (this.buffer.Length > 0 && this.buffer[this.buffer.Length - 1] == '\r')
{
this.buffer.Length = this.buffer.Length - 1;
}
this.messageQueue.Enqueue(this.buffer.ToString());
this.messagesAvailable.Set();
this.buffer.Length = 0;
}
else
{
this.buffer.Append(value);
}
}
}
}
}
}
|