/*
* Copyright (c) 2022 Winsider Seminars & Solutions, Inc. All rights reserved.
*
* This file is part of System Informer.
*
* Authors:
*
* dmex
*
*/
namespace CustomBuildTool
{
///
/// Provides utility methods for interacting with the Windows file system, environment variables, processes, and
/// registry, as well as other Win32-related operations.
///
public static unsafe class Win32
{
private static readonly FrozenSet RequiredPathEntries = new[]
{
// Windows system directories
"\\Windows\\System32",
"\\Windows\\",
"\\Windows\\System32\\Wbem",
"\\Windows\\System32\\WindowsPowerShell",
"\\Windows\\System32\\OpenSSH",
// Build tools
"\\Microsoft Visual Studio",
"\\MSBuild",
"\\Windows Kits",
"\\dotnet",
// Version control
"\\git",
"\\GitHub CLI",
// CMake and build tools
"\\CMake",
"\\vcpkg",
"\\ninja",
"\\LLVM",
"\\mingw",
}.ToFrozenSet(StringComparer.OrdinalIgnoreCase);
///
/// Creates all directories and subdirectories in the specified path unless they already exist.
///
/// The directory name or path.
public static DirectoryInfo CreateDirectory(string FileName)
{
if (string.IsNullOrWhiteSpace(FileName))
return null;
if (File.Exists(FileName))
return null;
return Directory.CreateDirectory(FileName);
}
///
/// Creates a new process and buffers the output into a string.
///
/// The name of the application to start.
/// The arguments to pass to the application.
/// The output from the application
///
///
/// If the creation succeeds, the return value is nonzero.
public static int CreateProcess(string FileName, IEnumerable Arguments, out string OutputString, bool FixNewLines = true, bool RedirectOutput = true)
{
int exitcode = int.MaxValue;
StringBuilder output = new StringBuilder(0x1000);
StringBuilder error = new StringBuilder(0x1000);
try
{
using (Process process = new Process())
{
process.StartInfo.FileName = FileName;
process.StartInfo.UseShellExecute = false;
if (Arguments != null)
{
foreach (string argument in Arguments)
{
process.StartInfo.ArgumentList.Add(argument);
}
}
if (RedirectOutput)
{
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.StandardErrorEncoding = Utils.UTF8NoBOM;
process.StartInfo.StandardOutputEncoding = Utils.UTF8NoBOM;
process.OutputDataReceived += (_, e) => { if (e.Data != null) output.AppendLine(e.Data); };
process.ErrorDataReceived += (_, e) => { if (e.Data != null) error.AppendLine(e.Data); };
}
process.Start();
if (RedirectOutput)
{
process.BeginOutputReadLine();
process.BeginErrorReadLine();
}
process.WaitForExit();
exitcode = process.ExitCode;
}
}
catch (Exception ex)
{
Program.PrintColorMessage($"[CreateProcess] {ex}", ConsoleColor.Red);
}
OutputString = (output.ToString().Trim() + error.ToString().Trim());
if (FixNewLines)
{
OutputString = OutputString.Replace("\n\n", "\r\n", StringComparison.OrdinalIgnoreCase).Trim();
}
return exitcode;
}
///
/// Creates a new process and buffers the output into a string using a raw command-line argument string.
///
/// The name of the application to start.
/// The raw argument string to pass to the application.
/// The output from the application
///
///
/// If the creation succeeds, the return value is nonzero.
public static int CreateProcess(string FileName, string Arguments, out string OutputString, bool FixNewLines = true, bool RedirectOutput = true)
{
int exitcode = int.MaxValue;
StringBuilder output = new StringBuilder(0x1000);
StringBuilder error = new StringBuilder(0x1000);
try
{
using (Process process = new Process())
{
process.StartInfo.FileName = FileName;
process.StartInfo.UseShellExecute = false;
if (!string.IsNullOrWhiteSpace(Arguments))
{
process.StartInfo.Arguments = Arguments;
}
if (RedirectOutput)
{
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.StandardErrorEncoding = Utils.UTF8NoBOM;
process.StartInfo.StandardOutputEncoding = Utils.UTF8NoBOM;
process.OutputDataReceived += (_, e) => { if (e.Data != null) output.AppendLine(e.Data); };
process.ErrorDataReceived += (_, e) => { if (e.Data != null) error.AppendLine(e.Data); };
}
process.Start();
if (RedirectOutput)
{
process.BeginOutputReadLine();
process.BeginErrorReadLine();
}
process.WaitForExit();
exitcode = process.ExitCode;
}
}
catch (Exception ex)
{
Program.PrintColorMessage($"[CreateProcess] {ex}", ConsoleColor.Red);
}
OutputString = (output.ToString().Trim() + error.ToString().Trim());
if (FixNewLines)
{
OutputString = OutputString.Replace("\n\n", "\r\n", StringComparison.OrdinalIgnoreCase).Trim();
}
return exitcode;
}
///
/// Create an empty file.
///
/// The file name or path.
public static void CreateEmptyFile(string FileName)
{
if (string.IsNullOrWhiteSpace(FileName))
return;
FileStreamOptions options = new FileStreamOptions
{
Mode = FileMode.Create, // Overwrite
Access = FileAccess.Write,
Share = FileShare.None
};
new FileStream(FileName, options).Dispose();
}
///
/// Deletes the specified file.
///
/// The file name or path.
///
public static void DeleteFile(string FileName, BuildFlags Flags = BuildFlags.None)
{
if (string.IsNullOrWhiteSpace(FileName))
return;
if (File.Exists(FileName))
{
if (Flags.HasFlag(BuildFlags.BuildVerbose))
{
Program.PrintColorMessage($"Deleting: {FileName}", ConsoleColor.DarkGray);
}
File.Delete(FileName);
}
}
///
/// Searches for a specified file using environment paths.
///
/// The name of the file for which to search.
/// The path and file name of the file found.
public static string SearchPath(string FileName)
{
if (string.IsNullOrWhiteSpace(FileName))
return null;
// System32 directory.
{
string where = Path.Join([Environment.SystemDirectory, FileName]);
if (File.Exists(where))
return where;
}
// %PATH% directory.
{
if (Win32.GetEnvironmentVariable("PATH", out string values))
{
foreach (var range in values.AsSpan().Split(';'))
{
var path = values.AsSpan(range);
if (path.IsWhiteSpace())
continue;
string where = Path.Join(path, FileName.AsSpan());
if (File.Exists(where))
return where;
}
}
}
// Current directory.
{
if (File.Exists(FileName))
{
return Path.GetFullPath(FileName);
}
}
return null;
}
//
// Number of times, and delay between, retries for a transiently-locked file operation.
//
private const int FileRetryAttempts = 10;
private const int FileRetryDelay = 200;
///
/// Determines whether the exception represents a transient file lock (a sharing or lock
/// violation) that is expected to clear once another process releases the file.
///
/// The IO exception to inspect.
/// True if the failure is a transient sharing/lock violation; otherwise false.
private static bool IsTransientFileLock(IOException Exception)
{
int code = Exception.HResult & 0xffff;
return code == 32 /* ERROR_SHARING_VIOLATION */ || code == 33 /* ERROR_LOCK_VIOLATION */;
}
///
/// Invokes a file operation, retrying briefly when the file is transiently locked by another
/// process. During parallel multi-platform builds the linker for one architecture can still
/// hold a binary that another architecture's post-build step needs to read (for example the
/// WOW64 payload copied into the x64/ARM64 output); the lock clears once the linker finishes.
///
/// The return type of the operation.
/// The file operation to invoke.
/// The result of the operation.
private static T InvokeWithFileRetry(Func Operation)
{
for (int attempt = 1; ; attempt++)
{
try
{
return Operation();
}
catch (IOException exception) when (attempt < FileRetryAttempts && IsTransientFileLock(exception))
{
Thread.Sleep(FileRetryDelay);
}
}
}
///
/// Invokes a file operation, retrying briefly when the file is transiently locked by another process.
///
/// The file operation to invoke.
private static void InvokeWithFileRetry(Action Operation)
{
InvokeWithFileRetry