diff --git a/tools/CustomBuildTool/Build.cs b/tools/CustomBuildTool/Build.cs index b91a3fbaa..13d7b7a4c 100644 --- a/tools/CustomBuildTool/Build.cs +++ b/tools/CustomBuildTool/Build.cs @@ -35,49 +35,28 @@ namespace CustomBuildTool Console.InputEncoding = Encoding.UTF8; Console.OutputEncoding = Encoding.UTF8; - try - { - DirectoryInfo info = new DirectoryInfo("."); - - while (info.Parent != null && info.Parent.Parent != null) - { - info = info.Parent; - - if (File.Exists($"{info.FullName}\\SystemInformer.sln")) - { - Directory.SetCurrentDirectory(info.FullName); - break; - } - } - } - catch (Exception ex) - { - Program.PrintColorMessage($"Unable to find project root directory: {ex}", ConsoleColor.Red); - return false; - } - - if (!File.Exists("SystemInformer.sln")) + if (!Utils.SetCurrentDirectoryParent("SystemInformer.sln")) { Program.PrintColorMessage("Unable to find project solution.", ConsoleColor.Red); return false; } - Build.TimeStart = DateTime.Now; + Build.TimeStart = DateTime.UtcNow; Build.BuildWorkingFolder = Environment.CurrentDirectory; Build.BuildOutputFolder = Utils.GetOutputDirectoryPath(); - if (Win32.GetEnvironmentVariable("SYSTEM_BUILD", out string build_definition)) + if (Win32.GetEnvironmentVariableSpan("SYSTEM_BUILD", out ReadOnlySpan build_definition)) { - if (string.Equals(build_definition, "canary", StringComparison.OrdinalIgnoreCase)) + if (MemoryExtensions.Equals(build_definition, "canary", StringComparison.OrdinalIgnoreCase)) { Build.BuildCanary = true; Program.PrintColorMessage("[CANARY BUILD]", ConsoleColor.Cyan); } } - if (Win32.GetEnvironmentVariable("SYSTEM_DEBUG", out string build_debug)) + if (Win32.GetEnvironmentVariableSpan("SYSTEM_DEBUG", out ReadOnlySpan build_debug)) { - if (string.Equals(build_debug, "true", StringComparison.OrdinalIgnoreCase)) + if (MemoryExtensions.Equals(build_debug, "true", StringComparison.OrdinalIgnoreCase)) { Build.BuildToolsDebug = true; Program.PrintColorMessage("[DEBUG BUILD]", ConsoleColor.Cyan); @@ -151,11 +130,11 @@ namespace CustomBuildTool foreach (string folder in project_folders) { string path = Path.GetFullPath(folder); - string name = Path.GetFileName(path); + var name = Path.GetFileName(path.AsSpan()); if ( - string.Equals(name, ".vs", StringComparison.OrdinalIgnoreCase) || - string.Equals(name, "obj", StringComparison.OrdinalIgnoreCase) + name.Equals(".vs", StringComparison.OrdinalIgnoreCase) || + name.Equals("obj", StringComparison.OrdinalIgnoreCase) ) { if (Directory.Exists(path)) @@ -186,7 +165,7 @@ namespace CustomBuildTool foreach (string file in res_files) { string path = Path.GetFullPath(file); - string name = Path.GetFileName(path); + var name = Path.GetFileName(path.AsSpan()); if (name.EndsWith(".aps", StringComparison.OrdinalIgnoreCase)) { @@ -252,8 +231,8 @@ namespace CustomBuildTool if (instance != null) { Program.PrintColorMessage("WindowsSDK: ", ConsoleColor.DarkGray, false); - Program.PrintColorMessage(Utils.GetWindowsSdkVersion(), ConsoleColor.Green); - //Program.PrintColorMessage(Utils.GetWindowsSdkVersion() + " (" + instance.GetWindowsSdkFullVersion() + ")", ConsoleColor.Green, true); + //Program.PrintColorMessage(Utils.GetWindowsSdkVersion(), ConsoleColor.Green); + Program.PrintColorMessage(Utils.GetWindowsSdkVersion() + " (" + instance.GetWindowsSdkFullVersion() + ")", ConsoleColor.Green, true); Program.PrintColorMessage("VisualStudio: ", ConsoleColor.DarkGray, false); Program.PrintColorMessage(instance.Name, ConsoleColor.Green); //Program.PrintColorMessage(Utils.GetVisualStudioVersion(), ConsoleColor.Green, true); @@ -283,12 +262,12 @@ namespace CustomBuildTool public static string BuildTimeStamp() { - return $"[{DateTime.Now - TimeStart:mm\\:ss}] "; + return $"[{DateTime.UtcNow - TimeStart:mm\\:ss}] "; } public static void ShowBuildStats() { - TimeSpan buildTime = DateTime.Now - TimeStart; + TimeSpan buildTime = (DateTime.UtcNow - TimeStart); Program.PrintColorMessage($"{Environment.NewLine}Build Time: ", ConsoleColor.DarkGray, false); Program.PrintColorMessage(buildTime.Minutes.ToString(), ConsoleColor.Green, false); @@ -319,93 +298,35 @@ namespace CustomBuildTool public static bool CopyWow64Files(BuildFlags Flags) { - if (Flags.HasFlag(BuildFlags.BuildDebug)) + string[] Build_Wow64_Files = + [ + "SystemInformer.exe", + "SystemInformer.pdb", + "SystemInformer.sig", + "plugins\\DotNetTools.dll", + "plugins\\DotNetTools.pdb", + "plugins\\DotNetTools.sig", + "plugins\\ExtendedTools.dll", + "plugins\\ExtendedTools.pdb", + "plugins\\ExtendedTools.sig", + ]; + + foreach (string file in Build_Wow64_Files) { - if (Flags.HasFlag(BuildFlags.Build64bit)) + if (Flags.HasFlag(BuildFlags.BuildDebug)) { - if (Directory.Exists("bin\\Debug64")) - { - //Win32.CreateDirectory("bin\\Debug64\\x86"); - Win32.CreateDirectory("bin\\Debug64\\x86\\plugins"); // recursive - - Win32.CopyIfNewer("bin\\Debug32\\SystemInformer.exe", "bin\\Debug64\\x86\\SystemInformer.exe"); - Win32.CopyIfNewer("bin\\Debug32\\SystemInformer.pdb", "bin\\Debug64\\x86\\SystemInformer.pdb"); - Win32.CopyIfNewer("bin\\Debug32\\SystemInformer.sig", "bin\\Debug64\\x86\\SystemInformer.sig"); - - Win32.CopyIfNewer("bin\\Debug32\\plugins\\DotNetTools.dll", "bin\\Debug64\\x86\\plugins\\DotNetTools.dll"); - Win32.CopyIfNewer("bin\\Debug32\\plugins\\DotNetTools.pdb", "bin\\Debug64\\x86\\plugins\\DotNetTools.pdb"); - Win32.CopyIfNewer("bin\\Debug32\\plugins\\DotNetTools.sig", "bin\\Debug64\\x86\\plugins\\DotNetTools.sig"); - - Win32.CopyIfNewer("bin\\Debug32\\plugins\\ExtendedTools.dll", "bin\\Debug64\\x86\\plugins\\ExtendedTools.dll"); - Win32.CopyIfNewer("bin\\Debug32\\plugins\\ExtendedTools.pdb", "bin\\Debug64\\x86\\plugins\\ExtendedTools.pdb"); - Win32.CopyIfNewer("bin\\Debug32\\plugins\\ExtendedTools.sig", "bin\\Debug64\\x86\\plugins\\ExtendedTools.sig"); - } + if (Flags.HasFlag(BuildFlags.Build64bit)) + Win32.CopyIfNewer($"bin\\Debug32\\{file}", $"bin\\Debug64\\x86\\{file}"); + if (Flags.HasFlag(BuildFlags.BuildArm64bit)) + Win32.CopyIfNewer($"bin\\Debug32\\{file}", $"bin\\DebugARM64\\x86\\{file}"); } - if (Flags.HasFlag(BuildFlags.BuildArm64bit)) + if (Flags.HasFlag(BuildFlags.BuildRelease)) { - if (Directory.Exists("bin\\DebugARM64")) - { - //Win32.CreateDirectory("bin\\DebugARM64\\x86"); - Win32.CreateDirectory("bin\\DebugARM64\\x86\\plugins"); // recursive - - Win32.CopyIfNewer("bin\\Debug32\\SystemInformer.exe", "bin\\DebugARM64\\x86\\SystemInformer.exe"); - Win32.CopyIfNewer("bin\\Debug32\\SystemInformer.pdb", "bin\\DebugARM64\\x86\\SystemInformer.pdb"); - Win32.CopyIfNewer("bin\\Debug32\\SystemInformer.sig", "bin\\DebugARM64\\x86\\SystemInformer.sig"); - - Win32.CopyIfNewer("bin\\Debug32\\plugins\\DotNetTools.dll", "bin\\DebugARM64\\x86\\plugins\\DotNetTools.dll"); - Win32.CopyIfNewer("bin\\Debug32\\plugins\\DotNetTools.pdb", "bin\\DebugARM64\\x86\\plugins\\DotNetTools.pdb"); - Win32.CopyIfNewer("bin\\Debug32\\plugins\\DotNetTools.sig", "bin\\DebugARM64\\x86\\plugins\\DotNetTools.sig"); - - Win32.CopyIfNewer("bin\\Debug32\\plugins\\ExtendedTools.dll", "bin\\DebugARM64\\x86\\plugins\\ExtendedTools.dll"); - Win32.CopyIfNewer("bin\\Debug32\\plugins\\ExtendedTools.pdb", "bin\\DebugARM64\\x86\\plugins\\ExtendedTools.pdb"); - Win32.CopyIfNewer("bin\\Debug32\\plugins\\ExtendedTools.sig", "bin\\DebugARM64\\x86\\plugins\\ExtendedTools.sig"); - } - } - } - - if (Flags.HasFlag(BuildFlags.BuildRelease)) - { - if (Flags.HasFlag(BuildFlags.Build64bit)) - { - if (Directory.Exists("bin\\Release64")) - { - //Win32.CreateDirectory("bin\\Release64\\x86"); - Win32.CreateDirectory("bin\\Release64\\x86\\plugins"); // recursive - - Win32.CopyIfNewer("bin\\Release32\\SystemInformer.exe", "bin\\Release64\\x86\\SystemInformer.exe"); - Win32.CopyIfNewer("bin\\Release32\\SystemInformer.pdb", "bin\\Release64\\x86\\SystemInformer.pdb"); - Win32.CopyIfNewer("bin\\Release32\\SystemInformer.sig", "bin\\Release64\\x86\\SystemInformer.sig"); - - Win32.CopyIfNewer("bin\\Release32\\plugins\\DotNetTools.dll", "bin\\Release64\\x86\\plugins\\DotNetTools.dll"); - Win32.CopyIfNewer("bin\\Release32\\plugins\\DotNetTools.pdb", "bin\\Release64\\x86\\plugins\\DotNetTools.pdb"); - Win32.CopyIfNewer("bin\\Release32\\plugins\\DotNetTools.sig", "bin\\Release64\\x86\\plugins\\DotNetTools.sig"); - - Win32.CopyIfNewer("bin\\Release32\\plugins\\ExtendedTools.dll", "bin\\Release64\\x86\\plugins\\ExtendedTools.dll"); - Win32.CopyIfNewer("bin\\Release32\\plugins\\ExtendedTools.pdb", "bin\\Release64\\x86\\plugins\\ExtendedTools.pdb"); - Win32.CopyIfNewer("bin\\Release32\\plugins\\ExtendedTools.sig", "bin\\Release64\\x86\\plugins\\ExtendedTools.sig"); - } - } - - if (Flags.HasFlag(BuildFlags.BuildArm64bit)) - { - if (Directory.Exists("bin\\ReleaseARM64")) - { - //Win32.CreateDirectory("bin\\ReleaseARM64\\x86"); - Win32.CreateDirectory("bin\\ReleaseARM64\\x86\\plugins"); // recursive - - Win32.CopyIfNewer("bin\\Release32\\SystemInformer.exe", "bin\\ReleaseARM64\\x86\\SystemInformer.exe"); - Win32.CopyIfNewer("bin\\Release32\\SystemInformer.pdb", "bin\\ReleaseARM64\\x86\\SystemInformer.pdb"); - Win32.CopyIfNewer("bin\\Release32\\SystemInformer.sig", "bin\\ReleaseARM64\\x86\\SystemInformer.sig"); - - Win32.CopyIfNewer("bin\\Release32\\plugins\\DotNetTools.dll", "bin\\ReleaseARM64\\x86\\plugins\\DotNetTools.dll"); - Win32.CopyIfNewer("bin\\Release32\\plugins\\DotNetTools.pdb", "bin\\ReleaseARM64\\x86\\plugins\\DotNetTools.pdb"); - Win32.CopyIfNewer("bin\\Release32\\plugins\\DotNetTools.sig", "bin\\ReleaseARM64\\x86\\plugins\\DotNetTools.sig"); - - Win32.CopyIfNewer("bin\\Release32\\plugins\\ExtendedTools.dll", "bin\\ReleaseARM64\\x86\\plugins\\ExtendedTools.dll"); - Win32.CopyIfNewer("bin\\Release32\\plugins\\ExtendedTools.pdb", "bin\\ReleaseARM64\\x86\\plugins\\ExtendedTools.pdb"); - Win32.CopyIfNewer("bin\\Release32\\plugins\\ExtendedTools.sig", "bin\\ReleaseARM64\\x86\\plugins\\ExtendedTools.sig"); - } + if (Flags.HasFlag(BuildFlags.Build64bit)) + Win32.CopyIfNewer($"bin\\Release32\\{file}", $"bin\\Release64\\x86\\{file}"); + if (Flags.HasFlag(BuildFlags.BuildArm64bit)) + Win32.CopyIfNewer($"bin\\Release32\\{file}", $"bin\\ReleaseARM64\\x86\\{file}"); } } @@ -414,7 +335,7 @@ namespace CustomBuildTool public static bool CopyResourceFiles(BuildFlags Flags) { - var Build_Resource_Files = new Dictionary(StringComparer.OrdinalIgnoreCase) + var Build_Resource_Files = new Dictionary(4, StringComparer.OrdinalIgnoreCase) { { "SystemInformer.png", "icon.png" }, { "CapsList.txt", "CapsList.txt" }, @@ -448,6 +369,46 @@ namespace CustomBuildTool return true; } + public static bool CopyDebugEngineFiles(BuildFlags Flags) + { + var Build_DebugCore_Files = new string[] + { + "dbgcore.dll", + "dbghelp.dll", + "symsrv.dll" + }; + + string windowsSdkPath = Path.GetFullPath(Path.Join([Utils.GetWindowsSdkPath(), "..\\Debuggers\\"])); + + if (string.IsNullOrWhiteSpace(windowsSdkPath)) + return false; + + foreach (var file in Build_DebugCore_Files) + { + if (Flags.HasFlag(BuildFlags.BuildDebug)) + { + if (Flags.HasFlag(BuildFlags.Build32bit)) + Win32.CopyIfNewer($"{windowsSdkPath}\\x86\\{file}", $"bin\\Debug32\\{file}"); + if (Flags.HasFlag(BuildFlags.Build64bit)) + Win32.CopyIfNewer($"{windowsSdkPath}\\x64\\{file}", $"bin\\Debug64\\{file}"); + if (Flags.HasFlag(BuildFlags.BuildArm64bit)) + Win32.CopyIfNewer($"{windowsSdkPath}\\arm64\\{file}", $"bin\\DebugARM64\\{file}"); + } + + if (Flags.HasFlag(BuildFlags.BuildRelease)) + { + if (Flags.HasFlag(BuildFlags.Build32bit)) + Win32.CopyIfNewer($"{windowsSdkPath}\\x86\\{file}", $"bin\\Release32\\{file}"); + if (Flags.HasFlag(BuildFlags.Build64bit)) + Win32.CopyIfNewer($"{windowsSdkPath}\\x64\\{file}", $"bin\\Release64\\{file}"); + if (Flags.HasFlag(BuildFlags.BuildArm64bit)) + Win32.CopyIfNewer($"{windowsSdkPath}\\arm64\\{file}", $"bin\\ReleaseARM64\\{file}"); + } + } + + return true; + } + public static bool BuildPublicHeaderFiles() { Program.PrintColorMessage(BuildTimeStamp(), ConsoleColor.DarkGray, false); @@ -497,55 +458,21 @@ namespace CustomBuildTool if (Flags.HasFlag(BuildFlags.BuildDebug)) { if (Flags.HasFlag(BuildFlags.Build32bit)) - { - if (Directory.Exists("KSystemInformer\\bin-signed\\i386")) - { - Win32.CopyVersionIfNewer($"KSystemInformer\\bin-signed\\i386\\{file}", $"bin\\Debug32\\{file}"); - } - } - + Win32.CopyVersionIfNewer($"KSystemInformer\\bin-signed\\i386\\{file}", $"bin\\Debug32\\{file}"); if (Flags.HasFlag(BuildFlags.Build64bit)) - { - if (Directory.Exists("KSystemInformer\\bin-signed\\amd64")) - { - Win32.CopyVersionIfNewer($"KSystemInformer\\bin-signed\\amd64\\{file}", $"bin\\Debug64\\{file}"); - } - } - + Win32.CopyVersionIfNewer($"KSystemInformer\\bin-signed\\amd64\\{file}", $"bin\\Debug64\\{file}"); if (Flags.HasFlag(BuildFlags.BuildArm64bit)) - { - if (Directory.Exists("KSystemInformer\\bin-signed\\arm64")) - { - Win32.CopyVersionIfNewer($"KSystemInformer\\bin-signed\\arm64\\{file}", $"bin\\DebugARM64\\{file}"); - } - } + Win32.CopyVersionIfNewer($"KSystemInformer\\bin-signed\\arm64\\{file}", $"bin\\DebugARM64\\{file}"); } if (Flags.HasFlag(BuildFlags.BuildRelease)) { if (Flags.HasFlag(BuildFlags.Build32bit)) - { - if (Directory.Exists("KSystemInformer\\bin-signed\\i386")) - { - Win32.CopyVersionIfNewer($"KSystemInformer\\bin-signed\\i386\\{file}", $"bin\\Release32\\{file}"); - } - } - + Win32.CopyVersionIfNewer($"KSystemInformer\\bin-signed\\i386\\{file}", $"bin\\Release32\\{file}"); if (Flags.HasFlag(BuildFlags.Build64bit)) - { - if (Directory.Exists("KSystemInformer\\bin-signed\\amd64")) - { - Win32.CopyVersionIfNewer($"KSystemInformer\\bin-signed\\amd64\\{file}", $"bin\\Release64\\{file}"); - } - } - + Win32.CopyVersionIfNewer($"KSystemInformer\\bin-signed\\amd64\\{file}", $"bin\\Release64\\{file}"); if (Flags.HasFlag(BuildFlags.BuildArm64bit)) - { - if (Directory.Exists("KSystemInformer\\bin-signed\\arm64")) - { - Win32.CopyVersionIfNewer($"KSystemInformer\\bin-signed\\arm64\\{file}", $"bin\\ReleaseARM64\\{file}"); - } - } + Win32.CopyVersionIfNewer($"KSystemInformer\\bin-signed\\arm64\\{file}", $"bin\\ReleaseARM64\\{file}"); } } } @@ -700,18 +627,34 @@ namespace CustomBuildTool // Build the SDK HeaderGen.Execute(); - // Copy the resource header + // Copy the SDK headers Win32.CopyIfNewer("SystemInformer\\sdk\\phapppub.h", "sdk\\include\\phapppub.h"); Win32.CopyIfNewer("SystemInformer\\sdk\\phdk.h", "sdk\\include\\phdk.h"); - Win32.CopyIfNewer("SystemInformer\\resource.h", "sdk\\include\\phappresource.h"); - - // Append resource headers with SDK exports - string phappContent = Utils.ReadAllText("sdk\\include\\phappresource.h"); - - if (!string.IsNullOrWhiteSpace(phappContent)) + //Win32.CopyIfNewer("SystemInformer\\resource.h", "sdk\\include\\phappresource.h"); + + // Copy the resource header and prefix types with PHAPP { - phappContent = phappContent.Replace("#define ID", "#define PHAPP_ID", StringComparison.OrdinalIgnoreCase); - Utils.WriteAllText("sdk\\include\\phappresource.h", phappContent); + FileInfo sourceFile = new FileInfo("SystemInformer\\resource.h"); + FileInfo destinationFile = new FileInfo("sdk\\include\\phappresource.h"); + + if ( + sourceFile.CreationTimeUtc > destinationFile.CreationTimeUtc || + sourceFile.LastWriteTimeUtc > destinationFile.LastWriteTimeUtc + ) + { + string resourceContent = Utils.ReadAllText("SystemInformer\\resource.h"); + + if (!string.IsNullOrWhiteSpace(resourceContent)) + { + // Update resource headers with SDK definition + string sdkContent = resourceContent.Replace("#define ID", "#define PHAPP_ID", StringComparison.OrdinalIgnoreCase); + + Utils.WriteAllText("sdk\\include\\phappresource.h", sdkContent); + + destinationFile.CreationTimeUtc = sourceFile.CreationTimeUtc; + destinationFile.LastWriteTimeUtc = sourceFile.LastWriteTimeUtc; + } + } } return true; @@ -1024,16 +967,17 @@ namespace CustomBuildTool return false; } - if (!HaveArm64BuildTools) - { - Program.PrintColorMessage("[SKIPPED] ARM64 build tools not installed.", ConsoleColor.Yellow, true, Flags); - return true; - } - if (Flags.HasFlag(BuildFlags.BuildArm64bit)) { - if (!MsbuildCommand(Solution, "ARM64", Flags, Channel)) - return false; + if (HaveArm64BuildTools) + { + if (!MsbuildCommand(Solution, "ARM64", Flags, Channel)) + return false; + } + else + { + Program.PrintColorMessage("[SKIPPED] ARM64 build tools not installed.", ConsoleColor.Yellow, true, Flags); + } } return true; @@ -1173,31 +1117,25 @@ namespace CustomBuildTool if (buildPostString.LongLength == 0) return false; - using (HttpClientHandler httpClientHandler = new HttpClientHandler()) + using HttpClientHandler httpClientHandler = new HttpClientHandler(); + httpClientHandler.AutomaticDecompression = DecompressionMethods.All; + httpClientHandler.SslProtocols = SslProtocols.Tls12 | SslProtocols.Tls13; + + using HttpClient httpClient = new HttpClient(httpClientHandler); + httpClient.DefaultRequestHeaders.Add("X-ApiKey", buildPostSfApiKey); + httpClient.DefaultVersionPolicy = HttpVersionPolicy.RequestVersionOrHigher; + httpClient.DefaultRequestVersion = HttpVersion.Version20; + + using ByteArrayContent httpContent = new ByteArrayContent(buildPostString); + httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + + var httpTask = httpClient.PostAsync(buildPostSfUrl, httpContent); + httpTask.Wait(); + + if (!httpTask.Result.IsSuccessStatusCode) { - httpClientHandler.AutomaticDecompression = DecompressionMethods.All; - httpClientHandler.SslProtocols = SslProtocols.Tls12 | SslProtocols.Tls13; - - using (HttpClient httpClient = new HttpClient(httpClientHandler)) - { - httpClient.DefaultRequestHeaders.Add("X-ApiKey", buildPostSfApiKey); - httpClient.DefaultVersionPolicy = HttpVersionPolicy.RequestVersionOrHigher; - httpClient.DefaultRequestVersion = HttpVersion.Version20; - - using (ByteArrayContent httpContent = new ByteArrayContent(buildPostString)) - { - httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); - - var httpTask = httpClient.PostAsync(buildPostSfUrl, httpContent); - httpTask.Wait(); - - if (!httpTask.Result.IsSuccessStatusCode) - { - Program.PrintColorMessage($"[UpdateBuildWebService-SF] {httpTask.Result}", ConsoleColor.Red); - return false; - } - } - } + Program.PrintColorMessage($"[UpdateBuildWebService-SF] {httpTask.Result}", ConsoleColor.Red); + return false; } } catch (Exception ex) diff --git a/tools/CustomBuildTool/BuildConfig.cs b/tools/CustomBuildTool/BuildConfig.cs index 3a7f564c6..b21152c86 100644 --- a/tools/CustomBuildTool/BuildConfig.cs +++ b/tools/CustomBuildTool/BuildConfig.cs @@ -13,7 +13,7 @@ namespace CustomBuildTool { public static class BuildConfig { - public static readonly SortedDictionary Build_Channels = new SortedDictionary() + public static readonly SortedDictionary Build_Channels = new SortedDictionary(StringComparer.OrdinalIgnoreCase) { { "release", 0 }, // PhReleaseChannel //{ "preview", 1 }, // PhPreviewChannel @@ -21,8 +21,8 @@ namespace CustomBuildTool //{ "developer", 3 }, // PhDeveloperChannel }; - public static readonly BuildFile[] Build_Release_Files = - { + public static readonly ImmutableArray Build_Release_Files = + [ new BuildFile("\\systeminformer-build-release-setup.exe", true), new BuildFile("\\systeminformer-build-release-bin.zip", true), //new BuildFile("\\systeminformer-build-preview-setup.exe", true), @@ -35,10 +35,10 @@ namespace CustomBuildTool new BuildFile("\\systeminformer-build-sdk.zip", false), new BuildFile("\\systeminformer-build-pdb.zip", true), //new BuildFile("\\systeminformer-build-checksums.txt", false), - }; + ]; - public static readonly string[] Build_Sdk_Directories = - { + public static readonly ImmutableArray Build_Sdk_Directories = + [ "sdk", "sdk\\include", "sdk\\dbg\\amd64", @@ -49,12 +49,11 @@ namespace CustomBuildTool "sdk\\lib\\arm64", //"sdk\\samples\\SamplePlugin", //"sdk\\samples\\SamplePlugin\\bin\\Release32" - }; + ]; - public static readonly string[] Build_Phnt_Headers = - { + public static readonly ImmutableArray Build_Phnt_Headers = + [ "ntbcd.h", - "ntd3dkmt.h", "ntdbg.h", "ntexapi.h", "ntgdi.h", @@ -88,10 +87,10 @@ namespace CustomBuildTool "phnt_windows.h", "subprocesstag.h", "winsta.h" - }; + ]; - public static readonly string[] Build_Phlib_Headers = - { + public static readonly ImmutableArray Build_Phlib_Headers = + [ "appresolver.h", "circbuf.h", "circbuf_h.h", @@ -134,14 +133,14 @@ namespace CustomBuildTool "treenew.h", "verify.h", "workqueue.h" - }; + ]; - public static readonly string[] Build_Kphlib_Headers = - { + public static readonly ImmutableArray Build_Kphlib_Headers = + [ "kphapi.h", "kphmsg.h", - "kphmsgdefs.h", - }; + "kphmsgdefs.h" + ]; } public readonly struct BuildFile @@ -159,5 +158,10 @@ namespace CustomBuildTool { return this.FileName; } + + public override int GetHashCode() + { + return this.FileName.GetHashCode(); + } } } diff --git a/tools/CustomBuildTool/CustomBuildTool.csproj b/tools/CustomBuildTool/CustomBuildTool.csproj index 84f82e3e9..537030c3a 100644 --- a/tools/CustomBuildTool/CustomBuildTool.csproj +++ b/tools/CustomBuildTool/CustomBuildTool.csproj @@ -10,7 +10,7 @@ 65001 {CD644DF2-A658-4CBC-9497-CA5DD13CFEC3} True - + false enable full true @@ -23,9 +23,7 @@ false false true - false Size - false true True @@ -44,23 +42,33 @@ DEBUG;TRACE False + UpdateAndReset + true TRACE;DEBUG False + UpdateAndReset + true - True + True + false + false True + false + false + + diff --git a/tools/CustomBuildTool/DynData.cs b/tools/CustomBuildTool/DynData.cs index 7f9748637..d156d570e 100644 --- a/tools/CustomBuildTool/DynData.cs +++ b/tools/CustomBuildTool/DynData.cs @@ -226,7 +226,7 @@ typedef struct _KPH_DYNDATA Utils.WriteAllText(sourceFile, GenerateSource(BytesToString(config))); Program.PrintColorMessage($"Dynamic source -> {sourceFile}", ConsoleColor.Cyan); - if (OutDir.Length == 0) + if (string.IsNullOrWhiteSpace(OutDir)) return true; string configFile = $"{OutDir}\\ksidyn.bin"; @@ -287,27 +287,34 @@ typedef struct _KPH_DYNDATA ) { var xml = new XmlDocument(); - xml.Load(ManifestFile); - var dyn = xml.SelectSingleNode("/dyn"); var configs = new List(10); var configNames = new List(10); + var dynConfigType = typeof(DynConfig); - foreach (XmlNode data in dyn.SelectNodes("data")) + xml.Load(ManifestFile); + + var dyn = xml.SelectSingleNode("/dyn"); + var dataNodes = dyn?.SelectNodes("data"); + + foreach (XmlNode data in dataNodes) { var config = new DynConfig(); - var configName = data.Attributes.GetNamedItem("name").Value; + var configName = data.Attributes?.GetNamedItem("name")?.Value; + var fieldNodes = data.SelectNodes("field"); - //Program.PrintColorMessage(configName, ConsoleColor.Cyan); + Program.PrintColorMessage(configName, ConsoleColor.Cyan); - foreach (XmlNode field in data.SelectNodes("field")) + foreach (XmlNode field in fieldNodes) { - var value = field.Attributes.GetNamedItem("value").Value; - var name = field.Attributes.GetNamedItem("name").Value; - var member = typeof(DynConfig).GetField(name); + var attributes = field.Attributes; + var value = attributes?.GetNamedItem("value")?.Value; + var name = attributes?.GetNamedItem("name")?.Value; + var member = dynConfigType.GetField(name); if (value.StartsWith("0x", StringComparison.OrdinalIgnoreCase)) { - value = Convert.ToUInt64(value, 16).ToString(); + var hex = value.AsSpan(2, value.Length - 2); // Remove "0x" prefix + value = ulong.Parse(hex, NumberStyles.HexNumber, CultureInfo.InvariantCulture).ToString(); // Convert.ToUInt64(value, 16); } else if (value.Equals("-1", StringComparison.OrdinalIgnoreCase) && member.FieldType == typeof(ushort)) { diff --git a/tools/CustomBuildTool/Github.cs b/tools/CustomBuildTool/Github.cs index e526fb8eb..69b8506cc 100644 --- a/tools/CustomBuildTool/Github.cs +++ b/tools/CustomBuildTool/Github.cs @@ -36,7 +36,8 @@ namespace CustomBuildTool ReleaseTag = Version, Name = Version, Draft = true, - Prerelease = true + GenerateReleaseNotes = true, + //Prerelease = true }; byte[] buildPostString = JsonSerializer.SerializeToUtf8Bytes(buildUpdateRequest, GithubReleasesRequestContext.Default.GithubReleasesRequest); @@ -205,12 +206,12 @@ namespace CustomBuildTool var buildUpdateRequest = new GithubReleasesRequest { Draft = false, - Prerelease = true + //Prerelease = true }; byte[] buildPostString = JsonSerializer.SerializeToUtf8Bytes(buildUpdateRequest, GithubReleasesRequestContext.Default.GithubReleasesRequest); - if (buildPostString == null || buildPostString.LongLength == 0) + if (buildPostString.LongLength == 0) return null; using (HttpClientHandler httpClientHandler = new HttpClientHandler()) diff --git a/tools/CustomBuildTool/HeaderGen.cs b/tools/CustomBuildTool/HeaderGen.cs index 56768ce37..5dac58a16 100644 --- a/tools/CustomBuildTool/HeaderGen.cs +++ b/tools/CustomBuildTool/HeaderGen.cs @@ -15,14 +15,14 @@ namespace CustomBuildTool public static class HeaderGen { private static readonly string Header = "#ifndef _PH_PHAPPPUB_H\r\n#define _PH_PHAPPPUB_H\r\n\r\n// This file was automatically generated. Do not edit.\r\n\r\n#ifdef __cplusplus\r\nextern \"C\" {\r\n#endif\r\n"; - private static readonly string Footer = "\r\n#ifdef __cplusplus\r\n}\r\n#endif\r\n\r\n#endif\r\n"; + private const string Footer = "\r\n#ifdef __cplusplus\r\n}\r\n#endif\r\n\r\n#endif\r\n"; - private static readonly string BaseDirectory = "SystemInformer\\include"; - private static readonly string OutputFile = "..\\sdk\\phapppub.h"; + private const string BaseDirectory = "SystemInformer\\include"; + private const string OutputFile = "..\\sdk\\phapppub.h"; - private static readonly string[] Modes = new[] { "phapppub" }; - private static readonly string[] Files = new[] - { + private static readonly string[] Modes = ["phapppub"]; + private static readonly string[] Files = + [ "phapp.h", "appsup.h", "phfwddef.h", @@ -54,7 +54,7 @@ namespace CustomBuildTool "sysinfo.h", "procgrp.h", "miniinfo.h" - }; + ]; private static List OrderHeaderFiles(List headerFiles) { @@ -135,38 +135,43 @@ namespace CustomBuildTool foreach (string name in Files) { - string file = BaseDirectory + Path.DirectorySeparatorChar + name; + string file = Path.Join([BaseDirectory, name]); List lines = File.ReadAllLines(file).ToList(); - headerFiles.Add(name, new HeaderFile - { - Name = name, - Lines = lines - }); + headerFiles.Add(name, new HeaderFile(name, lines)); } foreach (HeaderFile h in headerFiles.Values) { - ILookup> partitions = h.Lines.Select(s => + List> partitions = new List>(); + List dependencies = new List(); + + foreach (string line in h.Lines) { - string trimmed = s.Trim(); + string trimmed = line.Trim(); if (trimmed.StartsWith("#include <", StringComparison.OrdinalIgnoreCase) && trimmed.EndsWith(">", StringComparison.OrdinalIgnoreCase)) { - if (headerFiles.TryGetValue(trimmed.Remove(trimmed.Length - 1).Remove(0, "#include <".Length), out HeaderFile d)) - return Tuple.Create(s, d); + string dependencyName = trimmed.AsSpan().Slice("#include <".Length, trimmed.Length - 1 - "#include <".Length).ToString(); + + if (headerFiles.TryGetValue(dependencyName, out HeaderFile dependency)) + { + partitions.Add(new KeyValuePair(line, dependency)); + dependencies.Add(dependencyName); + } else - return Tuple.Create(s, null); + { + partitions.Add(new KeyValuePair(line, null)); + } } - return Tuple.Create(s, null); - }) - .ToLookup(p => p.Item2 != null); + else + { + partitions.Add(new KeyValuePair(line, null)); + } + } - h.Lines = partitions[false].Select(p => p.Item1).ToList(); - h.Dependencies = partitions[true].Select(p => p.Item2).Distinct().ToList(); - - //foreach (var d in h.Dependencies) - //Console.WriteLine("Dependency: " + h.Name + " -> " + d.Name); + h.Lines = partitions.Where(p => p.Value == null).Select(p => p.Key).ToList(); + h.Dependencies = dependencies.Select(dependencyName => headerFiles[dependencyName]).Distinct().ToList(); } // Generate the ordering. @@ -187,10 +192,12 @@ namespace CustomBuildTool // Process each header file and remove irrelevant content. foreach (HeaderFile h in orderedHeaderFiles) + { h.Lines = ProcessHeaderLines(h.Lines); + } // Write out the result. - using (StreamWriter sw = new StreamWriter(BaseDirectory + Path.DirectorySeparatorChar + OutputFile)) + using (StreamWriter sw = new StreamWriter(Path.Join([BaseDirectory, OutputFile]), false, Utils.UTF8NoBOM)) { // Header sw.Write(Header); @@ -206,7 +213,9 @@ namespace CustomBuildTool sw.WriteLine(); foreach (string line in h.Lines) + { sw.WriteLine(line); + } } // Footer @@ -217,10 +226,16 @@ namespace CustomBuildTool public class HeaderFile : IEquatable { - public string Name; + public readonly string Name; public List Lines; public List Dependencies; + public HeaderFile(string Name, List Lines) + { + this.Name = Name; + this.Lines = Lines; + } + public override string ToString() { return this.Name; @@ -239,12 +254,12 @@ namespace CustomBuildTool if (obj is not HeaderFile file) return false; - return this.Name.Equals(file.Name, StringComparison.OrdinalIgnoreCase); + return string.Equals(this.Name, file.Name, StringComparison.OrdinalIgnoreCase); } public bool Equals(HeaderFile other) { - return other != null && this.Name.Equals(other.Name, StringComparison.OrdinalIgnoreCase); + return other != null && string.Equals(this.Name, other.Name, StringComparison.OrdinalIgnoreCase); } } } diff --git a/tools/CustomBuildTool/Program.cs b/tools/CustomBuildTool/Program.cs index 7eaede677..d7fe56578 100644 --- a/tools/CustomBuildTool/Program.cs +++ b/tools/CustomBuildTool/Program.cs @@ -29,14 +29,14 @@ namespace CustomBuildTool } else if (ProgramArgs.ContainsKey("-encrypt")) { - if (!Verify.EncryptFile(ProgramArgs["-input"], ProgramArgs["-output"], ProgramArgs["-secret"])) + if (!Verify.EncryptFile(ProgramArgs["-input"], ProgramArgs["-output"], ProgramArgs["-secret"], ProgramArgs["-salt"])) { Environment.Exit(1); } } else if (ProgramArgs.ContainsKey("-decrypt")) { - if (!Verify.DecryptFile(ProgramArgs["-input"], ProgramArgs["-output"], ProgramArgs["-secret"])) + if (!Verify.DecryptFile(ProgramArgs["-input"], ProgramArgs["-output"], ProgramArgs["-secret"], ProgramArgs["-salt"])) { Environment.Exit(1); } @@ -57,9 +57,9 @@ namespace CustomBuildTool } else if (ProgramArgs.ContainsKey("-sdk")) { - Build.SetupBuildEnvironment(false); + var flags = BuildFlags.BuildVerbose; - BuildFlags flags = BuildFlags.BuildVerbose; + Build.SetupBuildEnvironment(false); if (ProgramArgs.ContainsKey("-Debug")) { @@ -124,17 +124,15 @@ namespace CustomBuildTool } else if (ProgramArgs.ContainsKey("-bin")) { - BuildFlags flags = - BuildFlags.Build32bit | BuildFlags.Build64bit | BuildFlags.BuildArm64bit | - BuildFlags.BuildVerbose | BuildFlags.BuildApi; - Build.SetupBuildEnvironment(false); - if (!Build.BuildSolution("SystemInformer.sln", flags)) + if (!Build.BuildSolution("SystemInformer.sln", BuildFlags.Release)) Environment.Exit(1); - if (!Build.BuildSolution("plugins\\Plugins.sln", flags)) + if (!Build.BuildSolution("plugins\\Plugins.sln", BuildFlags.Release)) Environment.Exit(1); + if (!Build.CopyDebugEngineFiles(BuildFlags.Release)) + Environment.Exit(1); if (!Build.CopyTextFiles(true)) Environment.Exit(1); @@ -149,25 +147,21 @@ namespace CustomBuildTool } else if (ProgramArgs.ContainsKey("-debug")) { - BuildFlags flags = - BuildFlags.Build32bit | BuildFlags.Build64bit | BuildFlags.BuildArm64bit | - BuildFlags.BuildVerbose | BuildFlags.BuildApi; - Build.SetupBuildEnvironment(true); - if (!Build.BuildSolution("SystemInformer.sln", flags)) + if (!Build.BuildSolution("SystemInformer.sln", BuildFlags.Debug)) return; - if (!Build.BuildSolution("plugins\\Plugins.sln", flags)) + if (!Build.BuildSolution("plugins\\Plugins.sln", BuildFlags.Debug)) return; + if (!Build.CopyDebugEngineFiles(BuildFlags.Debug)) + Environment.Exit(1); + Build.ShowBuildStats(); } else if (ProgramArgs.ContainsKey("-pipeline-build")) { - BuildFlags flags = - BuildFlags.Build32bit | BuildFlags.Build64bit | BuildFlags.BuildArm64bit | - BuildFlags.BuildRelease | BuildFlags.BuildVerbose | - BuildFlags.BuildApi; + BuildFlags flags = BuildFlags.Release; if (ProgramArgs.ContainsKey("-msix-build")) flags |= BuildFlags.BuildMsix; @@ -178,7 +172,6 @@ namespace CustomBuildTool if (!Build.BuildSolution("SystemInformer.sln", flags)) Environment.Exit(1); - if (!Build.BuildSolution("plugins\\Plugins.sln", flags)) Environment.Exit(1); @@ -190,6 +183,8 @@ namespace CustomBuildTool if (!Build.ResignFiles()) Environment.Exit(1); + if (!Build.CopyDebugEngineFiles(BuildFlags.Release)) + Environment.Exit(1); if (!Build.CopyTextFiles(true)) Environment.Exit(1); @@ -229,10 +224,11 @@ namespace CustomBuildTool if (!Build.BuildSolution("SystemInformer.sln", flags)) Environment.Exit(1); - if (!Build.BuildSolution("plugins\\Plugins.sln", flags)) Environment.Exit(1); + if (!Build.CopyDebugEngineFiles(flags)) + Environment.Exit(1); if (!Build.CopyWow64Files(flags)) // required after plugin build (dmex) Environment.Exit(1); if (!Build.CopyTextFiles(true)) @@ -248,19 +244,21 @@ namespace CustomBuildTool { BuildFlags flags = BuildFlags.Build32bit | BuildFlags.Build64bit | BuildFlags.BuildArm64bit | - BuildFlags.BuildVerbose | BuildFlags.BuildApi; + BuildFlags.BuildRelease | BuildFlags.BuildVerbose | BuildFlags.BuildApi; Build.SetupBuildEnvironment(true); if (!Build.BuildSolution("SystemInformer.sln", flags)) - return; + Environment.Exit(1); if (!Build.BuildSolution("plugins\\Plugins.sln", flags)) - return; + Environment.Exit(1); + if (!Build.CopyDebugEngineFiles(flags)) + Environment.Exit(1); if (!Build.CopyWow64Files(flags)) - return; + Environment.Exit(1); if (!Build.CopyTextFiles(true)) - return; + Environment.Exit(1); foreach (var (channel, _) in BuildConfig.Build_Channels) { @@ -291,5 +289,18 @@ namespace CustomBuildTool Console.Write(Message); Console.ResetColor(); } + + public static void PrintColorMessage(LogInterpolatedStringHandler builder, ConsoleColor Color, bool Newline = true, BuildFlags Flags = BuildFlags.BuildVerbose) + { + if ((Flags & BuildFlags.BuildVerbose) != BuildFlags.BuildVerbose) + return; + + Console.ForegroundColor = Color; + if (Newline) + Console.WriteLine(builder.GetFormattedText()); + else + Console.Write(builder.GetFormattedText()); + Console.ResetColor(); + } } } diff --git a/tools/CustomBuildTool/Utils.cs b/tools/CustomBuildTool/Utils.cs index f570de3cf..b8aeb6110 100644 --- a/tools/CustomBuildTool/Utils.cs +++ b/tools/CustomBuildTool/Utils.cs @@ -94,9 +94,40 @@ namespace CustomBuildTool return output; } + public static bool SetCurrentDirectoryParent(string FileName) + { + try + { + DirectoryInfo info = new DirectoryInfo("."); + + while (info.Parent?.Parent != null) + { + info = info.Parent; + + if (File.Exists($"{info.FullName}\\{FileName}")) + { + Directory.SetCurrentDirectory(info.FullName); + break; + } + } + } + catch (Exception ex) + { + Program.PrintColorMessage($"Unable to find directory: {ex}", ConsoleColor.Red); + return false; + } + + return File.Exists(FileName); + } + public static string GetOutputDirectoryPath() { - return $"{Build.BuildWorkingFolder}\\build\\output"; + return GetPath("\\build\\output"); + } + + public static string GetPath(string FileName) + { + return Path.Combine([Build.BuildWorkingFolder, FileName]); } public static void CreateOutputDirectory() @@ -121,15 +152,15 @@ namespace CustomBuildTool if (string.IsNullOrWhiteSpace(VsWhereFilePath)) { string[] vswherePathArray = - { + [ "%ProgramFiles%\\Microsoft Visual Studio\\Installer\\vswhere.exe", "%ProgramFiles(x86)%\\Microsoft Visual Studio\\Installer\\vswhere.exe", "%ProgramW6432%\\Microsoft Visual Studio\\Installer\\vswhere.exe" - }; + ]; foreach (string path in vswherePathArray) { - string file = Environment.ExpandEnvironmentVariables(path); + string file = Utils.ExpandFullPath(path); if (File.Exists(file)) { @@ -157,11 +188,11 @@ namespace CustomBuildTool if (string.IsNullOrWhiteSpace(MsBuildFilePath)) { string[] MsBuildPathArray = - { + [ "\\MSBuild\\Current\\Bin\\amd64\\MSBuild.exe", "\\MSBuild\\Current\\Bin\\MSBuild.exe", "\\MSBuild\\15.0\\Bin\\MSBuild.exe" - }; + ]; VisualStudioInstance instance = VisualStudio.GetVisualStudioInstance(); @@ -215,15 +246,15 @@ namespace CustomBuildTool if (string.IsNullOrWhiteSpace(GitFilePath)) { string[] GitPathArray = - { + [ "%ProgramFiles%\\Git\\bin\\git.exe", "%ProgramFiles(x86)%\\Git\\bin\\git.exe", "%ProgramW6432%\\Git\\bin\\git.exe" - }; + ]; foreach (string path in GitPathArray) { - string file = Environment.ExpandEnvironmentVariables(path); + string file = Utils.ExpandFullPath(path); if (File.Exists(file)) { @@ -284,7 +315,7 @@ namespace CustomBuildTool { List> versionList = new List>(); string kitsRoot = Win32.GetKeyValue(true, "Software\\Microsoft\\Windows Kits\\Installed Roots", "KitsRoot10", "%ProgramFiles(x86)%\\Windows Kits\\10\\"); - string kitsPath = Environment.ExpandEnvironmentVariables($"{kitsRoot}\\Include"); + string kitsPath = Utils.ExpandFullPath(Path.Join([kitsRoot, "\\Include"])); if (Directory.Exists(kitsPath)) { @@ -320,7 +351,7 @@ namespace CustomBuildTool { List> versionList = new List>(); string kitsRoot = Win32.GetKeyValue(true, "Software\\Microsoft\\Windows Kits\\Installed Roots", "KitsRoot10", "%ProgramFiles(x86)%\\Windows Kits\\10\\"); - string kitsPath = Environment.ExpandEnvironmentVariables($"{kitsRoot}\\bin"); + string kitsPath = Utils.ExpandFullPath(Path.Join([kitsRoot, "\\bin"])); if (Directory.Exists(kitsPath)) { @@ -328,7 +359,7 @@ namespace CustomBuildTool foreach (string path in windowsKitsDirectory) { - string name = Path.GetFileName(path); + var name = Path.GetFileName(path); if (Version.TryParse(name, out var version)) { @@ -340,7 +371,7 @@ namespace CustomBuildTool if (versionList.Count > 0) { - var result = versionList[versionList.Count - 1]; + var result = versionList[^1]; if (!string.IsNullOrWhiteSpace(result.Value)) { @@ -354,9 +385,9 @@ namespace CustomBuildTool public static string GetWindowsSdkVersion() { - List versions = new List(); + List> versionList = new List>(); string kitsRoot = Win32.GetKeyValue(true, "Software\\Microsoft\\Windows Kits\\Installed Roots", "KitsRoot10", "%ProgramFiles(x86)%\\Windows Kits\\10\\"); - string kitsPath = Environment.ExpandEnvironmentVariables($"{kitsRoot}\\bin"); + string kitsPath = Utils.ExpandFullPath(Path.Join([kitsRoot, "\\bin"])); if (Directory.Exists(kitsPath)) { @@ -364,29 +395,24 @@ namespace CustomBuildTool foreach (string path in windowsKitsDirectory) { - string name = Path.GetFileName(path); + var name = Path.GetFileName(path.AsSpan()); - if (Version.TryParse(name, out _)) + if (Version.TryParse(name, out var version)) { - versions.Add(name); + versionList.Add(new KeyValuePair(version, path)); } } - versions.Sort((p1, p2) => - { - if (Version.TryParse(p1, out Version v1) && Version.TryParse(p2, out Version v2)) - return v1.CompareTo(v2); - else - return 1; - }); + versionList.Sort((first, second) => first.Key.CompareTo(second.Key)); - if (versions.Count > 0) + if (versionList.Count > 0) { - string result = versions[^1]; + var result = versionList[^1]; + var value = result.Key.ToString(); - if (!string.IsNullOrWhiteSpace(result)) + if (!string.IsNullOrWhiteSpace(value)) { - return result; + return value; } } } @@ -409,14 +435,14 @@ namespace CustomBuildTool return string.Empty; DirectoryInfo info = new DirectoryInfo(directory); - + while (info.Parent != null && info.Parent.Parent != null) { info = info.Parent; - if (File.Exists($"{info.FullName}\\Common7\\IDE\\devenv.exe")) + if (File.Exists(Path.Join([info.FullName, "\\Common7\\IDE\\devenv.exe"]))) { - FileVersionInfo currentInfo = FileVersionInfo.GetVersionInfo($"{info.FullName}\\Common7\\IDE\\devenv.exe"); + FileVersionInfo currentInfo = FileVersionInfo.GetVersionInfo(Path.Join([info.FullName, "\\Common7\\IDE\\devenv.exe"])); return currentInfo.ProductVersion ?? string.Empty; } } @@ -436,7 +462,7 @@ namespace CustomBuildTool if (string.IsNullOrWhiteSpace(windowsSdkPath)) return null; - string makeAppxPath = $"{windowsSdkPath}\\x64\\MakeAppx.exe"; + string makeAppxPath = Path.Join([windowsSdkPath, "\\x64\\MakeAppx.exe"]); if (string.IsNullOrWhiteSpace(makeAppxPath)) return null; @@ -448,7 +474,7 @@ namespace CustomBuildTool if (string.IsNullOrWhiteSpace(sdkRootPath)) return null; - makeAppxPath = Environment.ExpandEnvironmentVariables($"{sdkRootPath}\\x64\\MakeAppx.exe"); + makeAppxPath = Utils.ExpandFullPath(Path.Join([sdkRootPath, "\\x64\\MakeAppx.exe"])); if (!File.Exists(makeAppxPath)) return null; @@ -479,7 +505,7 @@ namespace CustomBuildTool if (string.IsNullOrWhiteSpace(windowsSdkPath)) return string.Empty; - string signToolPath = $"{windowsSdkPath}\\x64\\SignTool.exe"; + string signToolPath = Path.Join([windowsSdkPath, "\\x64\\SignTool.exe"]); if (string.IsNullOrWhiteSpace(signToolPath)) return string.Empty; @@ -618,6 +644,27 @@ namespace CustomBuildTool stream.CopyTo(filestream); } } + + public static bool IsSpanNullOrWhiteSpace(ReadOnlySpan value) + { + if (value == null) + return true; + if (value.IsEmpty) + return true; + if (value.IsWhiteSpace()) + return true; + + return false; + } + + public static string ExpandFullPath(string Name) + { + string value = Environment.ExpandEnvironmentVariables(Name); + + value = Path.GetFullPath(value); + + return value; + } } public class BuildUpdateRequest @@ -770,5 +817,43 @@ namespace CustomBuildTool BuildVerbose = 32, BuildApi = 64, BuildMsix = 128, + + Debug = Build32bit | Build64bit | BuildArm64bit | BuildDebug | BuildApi | BuildVerbose, + Release = Build32bit | Build64bit | BuildArm64bit | BuildRelease | BuildApi | BuildVerbose, + All = Build32bit | Build64bit | BuildArm64bit | BuildDebug | BuildRelease | BuildApi | BuildVerbose, + } + + /// + /// https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/tutorials/interpolated-string-handler + /// + [InterpolatedStringHandler] + public readonly ref struct LogInterpolatedStringHandler + { + public readonly StringBuilder builder; + + public LogInterpolatedStringHandler(int literalLength, int formattedCount) + { + builder = new StringBuilder(literalLength); + } + + public void AppendLiteral(string s) + { + builder.Append(s.AsSpan()); + } + + public void AppendFormatted(T t) + { + builder.Append(t?.ToString()); + } + + public void AppendFormatted(T t, string format) where T : IFormattable + { + builder.Append(t?.ToString(format, null)); + } + + internal string GetFormattedText() + { + return builder.ToString(); + } } } diff --git a/tools/CustomBuildTool/Verify.cs b/tools/CustomBuildTool/Verify.cs index ebd29022d..df479819b 100644 --- a/tools/CustomBuildTool/Verify.cs +++ b/tools/CustomBuildTool/Verify.cs @@ -13,21 +13,21 @@ namespace CustomBuildTool { public static class Verify { - public static readonly SortedDictionary KeyName_Vars = new SortedDictionary() + public static readonly SortedDictionary> KeyName_Vars = new(StringComparer.OrdinalIgnoreCase) { - { "kph", "KPH_BUILD_KEY" }, - { "release", "RELEASE_BUILD_KEY" }, - { "preview", "PREVIEW_BUILD_KEY" }, - { "canary", "CANARY_BUILD_KEY" }, - { "developer", "DEVELOPER_BUILD_KEY" }, + { "kph", new("KPH_BUILD_KEY", "KPH_BUILD_SALT")}, + { "release", new("RELEASE_BUILD_KEY", "RELEASE_BUILD_SALT")}, + { "preview", new("PREVIEW_BUILD_KEY", "PREVIEW_BUILD_SALT")}, + { "canary", new("CANARY_BUILD_KEY", "CANARY_BUILD_SALT")}, + { "developer", new("DEVELOPER_BUILD_KEY", "DEVELOPER_BUILD_SALT")}, }; - public static bool EncryptFile(string FileName, string OutFileName, string Secret) + public static bool EncryptFile(string FileName, string OutFileName, string Secret, string Salt) { try { var fileBytes = Utils.ReadAllBytes(FileName); - var encryptedBytes = Encrypt(fileBytes, Secret); + var encryptedBytes = Encrypt(fileBytes, Secret, Salt); Utils.WriteAllBytes(OutFileName, encryptedBytes); } catch (Exception e) @@ -39,12 +39,12 @@ namespace CustomBuildTool return true; } - public static bool DecryptFile(string FileName, string OutFileName, string Secret) + public static bool DecryptFile(string FileName, string OutFileName, string Secret, string Salt) { try { var fileBytes = Utils.ReadAllBytes(FileName); - var decryptedBytes = Decrypt(fileBytes, Secret); + var decryptedBytes = Decrypt(fileBytes, Secret, Salt); Utils.WriteAllBytes(OutFileName, decryptedBytes); } catch (Exception e) @@ -135,7 +135,7 @@ namespace CustomBuildTool return !string.IsNullOrWhiteSpace(Signature); } - private static byte[] Encrypt(byte[] Bytes, string Secret) + private static byte[] Encrypt(byte[] Bytes, string Secret, string Salt) { byte[] buffer = ArrayPool.Shared.Rent(0x1000); @@ -143,7 +143,7 @@ namespace CustomBuildTool { using (MemoryStream memoryStream = new MemoryStream(buffer, 0, 0x1000, true, true)) { - using (var rijndael = GetRijndael(Secret)) + using (var rijndael = GetRijndael(Secret, Salt)) using (var cryptoEncrypt = rijndael.CreateEncryptor()) using (MemoryStream blobStream = new MemoryStream(Bytes)) using (CryptoStream cryptoStream = new CryptoStream(memoryStream, cryptoEncrypt, CryptoStreamMode.Write, true)) @@ -168,7 +168,7 @@ namespace CustomBuildTool return null; } - private static byte[] Decrypt(byte[] Bytes, string Secret) + private static byte[] Decrypt(byte[] Bytes, string Secret, string Salt) { byte[] buffer = ArrayPool.Shared.Rent(0x1000); @@ -176,7 +176,7 @@ namespace CustomBuildTool { using (MemoryStream memoryStream = new MemoryStream(buffer, 0, 0x1000, true, true)) { - using (var rijndael = GetRijndael(Secret)) + using (var rijndael = GetRijndael(Secret, Salt)) using (var cryptoDecrypt = rijndael.CreateDecryptor()) using (MemoryStream blobStream = new MemoryStream(Bytes)) using (CryptoStream cryptoStream = new CryptoStream(memoryStream, cryptoDecrypt, CryptoStreamMode.Write, true)) @@ -201,7 +201,7 @@ namespace CustomBuildTool return null; } - private static Aes GetRijndael(string Secret) + private static Aes GetRijndael(string Secret, string Salt) { using (Rfc2898DeriveBytes rfc2898DeriveBytes = new Rfc2898DeriveBytes( Secret, @@ -234,15 +234,18 @@ namespace CustomBuildTool private static string GetPath(string FileName) { - return $"{Build.BuildWorkingFolder}\\tools\\CustomSignTool\\Resources\\{FileName}"; + return Path.Combine([Build.BuildWorkingFolder, "\\tools\\CustomSignTool\\Resources\\", FileName]); } private static bool GetKeyMaterial(string KeyName, out byte[] KeyMaterial) { - if (Win32.GetEnvironmentVariable(KeyName_Vars[KeyName], out string secret)) + if ( + Win32.GetEnvironmentVariable(KeyName_Vars[KeyName].Key, out string secret) && + Win32.GetEnvironmentVariable(KeyName_Vars[KeyName].Value, out string salt) + ) { byte[] bytes = Utils.ReadAllBytes(GetPath($"{KeyName}.s")); - KeyMaterial = Decrypt(bytes, secret); + KeyMaterial = Decrypt(bytes, secret, salt); return true; } else if (File.Exists(GetPath($"{KeyName}.key"))) diff --git a/tools/CustomBuildTool/VisualStudio.cs b/tools/CustomBuildTool/VisualStudio.cs index ec69eef16..233795b62 100644 --- a/tools/CustomBuildTool/VisualStudio.cs +++ b/tools/CustomBuildTool/VisualStudio.cs @@ -240,35 +240,35 @@ namespace CustomBuildTool // https://learn.microsoft.com/en-us/visualstudio/install/workload-component-id-vs-community - this.HasARM64BuildToolsComponents = - this.Packages.Any(p => p.Id.Equals("Microsoft.VisualStudio.Component.VC.Tools.ARM64", StringComparison.OrdinalIgnoreCase)) && - this.Packages.Any(p => p.Id.Equals("Microsoft.VisualStudio.Component.VC.Runtimes.ARM64.Spectre", StringComparison.OrdinalIgnoreCase)); + this.HasARM64BuildToolsComponents = this.Packages.Any(p => + { + return p.Id.AsSpan().Equals("Microsoft.VisualStudio.Component.VC.Tools.ARM64", StringComparison.OrdinalIgnoreCase) || + p.Id.AsSpan().Equals("Microsoft.VisualStudio.Component.VC.Runtimes.ARM64.Spectre", StringComparison.OrdinalIgnoreCase); + }); } - //private VisualStudioPackage GetLatestSdkPackage() - //{ - // var found = this.Packages.FindAll(p => - // { - // return p.Id.StartsWith("Microsoft.VisualStudio.Component.Windows10SDK", StringComparison.OrdinalIgnoreCase) || - // p.Id.StartsWith("Microsoft.VisualStudio.Component.Windows11SDK", StringComparison.OrdinalIgnoreCase); - // }); - // - // if (found == null) - // return null; - // if (found.Count == 0) - // return null; - // - // found.Sort((p1, p2) => - // { - // if (Version.TryParse(p1.Version, out Version v1) && Version.TryParse(p2.Version, out Version v2)) - // return v1.CompareTo(v2); - // else - // return 1; - // }); - // - // return found[^1]; - //} - // + private VisualStudioPackage GetLatestSdkPackage() + { + var found = this.Packages.FindAll(p => + { + return p.Id.AsSpan().StartsWith("Microsoft.VisualStudio.Component.Windows10SDK", StringComparison.OrdinalIgnoreCase) || + p.Id.AsSpan().StartsWith("Microsoft.VisualStudio.Component.Windows11SDK", StringComparison.OrdinalIgnoreCase); + }); + + if (found.Count == 0) + return null; + + found.Sort((p1, p2) => + { + if (Version.TryParse(p1.Version, out Version v1) && Version.TryParse(p2.Version, out Version v2)) + return v1.CompareTo(v2); + else + return 1; + }); + + return found[^1]; + } + //public string GetWindowsSdkVersion() //{ // List versions = new List(); @@ -315,16 +315,13 @@ namespace CustomBuildTool // } //} // - //public string GetWindowsSdkFullVersion() - //{ - // VisualStudioPackage package = GetLatestSdkPackage(); - // - // if (package == null) - // return string.Empty; - // - // return package.Version; - //} - // + public string GetWindowsSdkFullVersion() + { + VisualStudioPackage package = GetLatestSdkPackage(); + + return package == null ? string.Empty : package.Version; + } + //public bool HasRequiredDependency //{ // get diff --git a/tools/CustomBuildTool/Win32.cs b/tools/CustomBuildTool/Win32.cs index f54e6c93f..d469d0293 100644 --- a/tools/CustomBuildTool/Win32.cs +++ b/tools/CustomBuildTool/Win32.cs @@ -13,6 +13,8 @@ namespace CustomBuildTool { public static class Win32 { + private static readonly char[] PathSeparator = [';']; + /// /// Creates all directories and subdirectories in the specified path unless they already exist. /// @@ -163,7 +165,7 @@ namespace CustomBuildTool // System32 directory. { - string where = Path.Combine(Environment.SystemDirectory, FileName); + string where = Path.Join([Environment.SystemDirectory, FileName]); if (File.Exists(where)) return where; @@ -181,9 +183,9 @@ namespace CustomBuildTool { if (Win32.GetEnvironmentVariable("PATH", out string values)) { - foreach (string path in values.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries)) + foreach (string path in values.Split(PathSeparator, StringSplitOptions.RemoveEmptyEntries)) { - string where = Path.Combine(path, FileName); + string where = Path.Join([path, FileName]); if (File.Exists(where)) return where; @@ -249,14 +251,9 @@ namespace CustomBuildTool if (File.Exists(DestinationFile)) { - FileVersionInfo currentInfo = FileVersionInfo.GetVersionInfo(SourceFile); - FileVersionInfo newInfo = FileVersionInfo.GetVersionInfo(DestinationFile); - var currentInfoVersion = new Version(currentInfo.FileVersion); - var newInfoVersion = new Version(newInfo.FileVersion); - if ( - currentInfoVersion > newInfoVersion || - File.GetLastWriteTime(SourceFile) > File.GetLastWriteTime(DestinationFile) + File.GetLastWriteTime(SourceFile) > File.GetLastWriteTime(DestinationFile) || + Win32.GetFileVersion(SourceFile) > Win32.GetFileVersion(DestinationFile) ) { File.Copy(SourceFile, DestinationFile, true); @@ -291,6 +288,21 @@ namespace CustomBuildTool return !string.IsNullOrWhiteSpace(Value); } + /// + /// Retrieves the value of an environment variable from the current process. + /// + /// The name of the environment variable. + /// The value of the environment variable. + /// True if the environment variable was found. + public static bool GetEnvironmentVariableSpan(string Name, out ReadOnlySpan Value) + { + var value = Environment.GetEnvironmentVariable(Name, EnvironmentVariableTarget.Process); + + Value = value.AsSpan(); + + return !Utils.IsSpanNullOrWhiteSpace(Value); + } + /// /// Retrieves the value of an environment variable from the current process. /// @@ -298,7 +310,7 @@ namespace CustomBuildTool /// True if the environment variable was found. public static bool HasEnvironmentVariable(string Name) { - return GetEnvironmentVariable(Name, out _); + return GetEnvironmentVariableSpan(Name, out ReadOnlySpan _); } /// @@ -389,6 +401,18 @@ namespace CustomBuildTool return 0; } + public static Version GetFileVersion(string FileName) + { + FileVersionInfo versionInfo = FileVersionInfo.GetVersionInfo(FileName); + + if (string.IsNullOrWhiteSpace(versionInfo.FileVersion)) + { + return Version.Parse("0.0.0.0"); + } + + return Version.Parse(versionInfo.FileVersion); + } + public static void SetErrorMode() { NativeMethods.SetErrorMode(NativeMethods.SEM_NOGPFAULTERRORBOX | NativeMethods.SEM_NOOPENFILEERRORBOX);