/*
* Copyright (c) 2022 Winsider Seminars & Solutions, Inc. All rights reserved.
*
* This file is part of System Informer.
*
* Authors:
*
* wj32
* dmex
*
*/
namespace CustomBuildTool
{
///
/// Provides functionality to generate a merged public header file from a set of input headers.
///
public static class HeaderGen
{
///
/// The copyright and license notice to prepend to the generated header.
///
private static readonly string Notice = "/*\r\n * Copyright (c) Winsider Seminars & Solutions, Inc. All rights reserved.\r\n *\r\n * This file is part of System Informer.\r\n *\r\n */\r\n\r\n";
///
/// The header guard and C++ extern block for the generated header.
///
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";
///
/// The footer for the generated header, closing extern and guard.
///
private const string Footer = "\r\n#ifdef __cplusplus\r\n}\r\n#endif\r\n\r\n#endif\r\n";
///
/// The base directory containing the input header files.
///
private const string BaseDirectory = "SystemInformer\\include";
///
/// The relative output path for the generated header file.
///
private const string OutputFile = "..\\sdk\\phapppub.h";
///
/// The set of modes used to filter header content.
///
private static readonly string[] Modes = ["phapppub"];
///
/// The list of header files to merge, in order.
///
private static readonly string[] Files =
[
"phapp.h",
"appsup.h",
"phfwddef.h",
"phsettings.h",
"procprv.h",
"srvprv.h",
"netprv.h",
"modprv.h",
"thrdprv.h",
"hndlprv.h",
"memprv.h",
"devprv.h",
"phuisup.h",
"colmgr.h",
"proctree.h",
"srvlist.h",
"netlist.h",
"thrdlist.h",
"modlist.h",
"hndllist.h",
"memlist.h",
"extmgr.h",
"mainwnd.h",
"notifico.h",
"phplug.h",
"actions.h",
"procprp.h",
"procprpp.h",
"phsvccl.h",
"sysinfo.h",
"procgrp.h",
"miniinfo.h",
"hndlmenu.h"
];
///
/// Orders header files based on their dependencies.
///
/// The list of header files to order.
/// A list of header files in dependency order.
private static List OrderHeaderFiles(List HeaderFiles)
{
var result = new List();
var done = new HashSet();
foreach (HeaderFile h in HeaderFiles)
OrderHeaderFiles(result, done, h);
return result;
}
///
/// Recursively orders header files by dependencies.
///
/// The result list to populate.
/// A set of already processed headers.
/// The header file to process.
private static void OrderHeaderFiles(List Result, HashSet Done, HeaderFile HeaderFile)
{
if (!Done.Add(HeaderFile))
return;
foreach (HeaderFile h in HeaderFile.Dependencies)
OrderHeaderFiles(Result, Done, h);
Result.Add(HeaderFile);
}
///
/// Processes header lines, filtering by mode and removing irrelevant content.
///
/// The lines of the header file.
/// A filtered list of lines relevant to the current mode.
private static List ProcessHeaderLines(List Lines)
{
var result = new List(Lines.Count);
var activeModes = new HashSet(StringComparer.OrdinalIgnoreCase);
bool blankLine = false;
const string beginPrefix = "// begin_";
const string endPrefix = "// end_";
// Optimization: Pre-cache markers to avoid allocation and interpolation in the hot loop.
string[] cachedModeMarkers = new string[Modes.Length];
for (int i = 0; i < Modes.Length; i++)
{
cachedModeMarkers[i] = "// " + Modes[i];
}
foreach (string line in Lines)
{
ReadOnlySpan span = line.AsSpan().Trim();
if (span.IsEmpty)
{
blankLine = true;
continue;
}
// Optimization: Use spans for prefix checking and mode extraction to avoid heap allocations.
if (span.StartsWith(beginPrefix, StringComparison.OrdinalIgnoreCase))
{
ReadOnlySpan modeName = span.Slice(beginPrefix.Length);
string modeStr = null;
foreach (string m in Modes)
{
if (modeName.Equals(m, StringComparison.OrdinalIgnoreCase))
{
modeStr = m;
break;
}
}
activeModes.Add(modeStr ?? modeName.ToString());
}
else if (span.StartsWith(endPrefix, StringComparison.OrdinalIgnoreCase))
{
ReadOnlySpan modeName = span.Slice(endPrefix.Length);
string modeStr = null;
foreach (string m in Modes)
{
if (modeName.Equals(m, StringComparison.OrdinalIgnoreCase))
{
modeStr = m;
break;
}
}
activeModes.Remove(modeStr ?? modeName.ToString());
}
else
{
bool blockMode = false;
foreach (string mode in Modes)
{
if (activeModes.Contains(mode))
{
blockMode = true;
break;
}
}
bool lineMode = false;
if (!blockMode) // Optimization: Skip line-based mode checking if we are already in a block.
{
foreach (string marker in cachedModeMarkers)
{
int indexOfMarker = span.LastIndexOf(marker.AsSpan(), StringComparison.OrdinalIgnoreCase);
if (indexOfMarker != -1)
{
// Optimization: Validate the marker using spans instead of All(...) and Trim() on strings.
ReadOnlySpan validatedPart = span.Slice(indexOfMarker).Trim();
bool isValid = true;
foreach (char c in validatedPart)
{
if (!char.IsLetterOrDigit(c) && c != ' ' && c != '/')
{
isValid = false;
break;
}
}
if (isValid)
{
lineMode = true;
break;
}
}
}
}
if (blockMode || lineMode)
{
if (blankLine && result.Count > 0)
result.Add(string.Empty);
result.Add(line);
blankLine = false;
}
}
}
return result;
}
///
/// Executes the header generation process, merging and filtering headers, and writing the output file if needed.
///
public static void Execute()
{
// Read in all header files into a dictionary for O(1) lookup.
var headerFiles = new Dictionary(Files.Length, StringComparer.OrdinalIgnoreCase);
foreach (string name in Files)
{
string file = Path.Join([BaseDirectory, name]);
headerFiles.Add(name, new HeaderFile(name, [..File.ReadLines(file)]));
}
// Dependency resolution and Line Filtering:
// Identify #include dependencies and remove those lines from the internal representation.
foreach (HeaderFile h in headerFiles.Values)
{
var uniqueDeps = new HashSet();
var filteredLines = new List(h.Lines.Count);
foreach (string line in h.Lines)
{
ReadOnlySpan span = line.AsSpan().Trim();
const string includePrefix = "#include <";
if (span.Length > includePrefix.Length && span.StartsWith(includePrefix, StringComparison.OrdinalIgnoreCase) && span.EndsWith(">"))
{
ReadOnlySpan dependencyNameSpan = span.Slice(includePrefix.Length, span.Length - includePrefix.Length - 1);
string dependencyName = dependencyNameSpan.ToString();
if (headerFiles.TryGetValue(dependencyName, out HeaderFile dependency))
{
uniqueDeps.Add(dependency);
continue; // Dependency found: skip this line to avoid duplicate inclusions in the merged header.
}
}
filteredLines.Add(line);
}
h.Lines = filteredLines;
h.Dependencies = new List(uniqueDeps);
}
// Generate the dependency ordering.
var orderedHeaderFilesList = new List(Files.Length);
foreach (string file in Files)
{
// Note: Path.GetFileName is used to handle potential subdirectories in the Files array.
string name = Path.GetFileName(file);
if (headerFiles.TryGetValue(name, out HeaderFile value))
{
orderedHeaderFilesList.Add(value);
}
}
List orderedHeaderFiles = OrderHeaderFiles(orderedHeaderFilesList);
// Process each header file to remove irrelevant content based on Modes.
foreach (HeaderFile h in orderedHeaderFiles)
{
h.Lines = ProcessHeaderLines(h.Lines);
}
string headerFileName = Path.Join([BaseDirectory, OutputFile]);
if (Utils.WriteTextIfChanged(headerFileName, sw =>
{
sw.Write(Notice);
sw.Write(Header);
foreach (HeaderFile h in orderedHeaderFiles)
{
sw.WriteLine();
sw.WriteLine("//");
sw.WriteLine($"// {Path.GetFileNameWithoutExtension(h.Name)}");
sw.WriteLine("//");
sw.WriteLine();
foreach (string line in h.Lines)
sw.WriteLine(line);
}
sw.Write(Footer);
}))
Program.PrintColorMessage($"HeaderGen -> {headerFileName}", ConsoleColor.Cyan);
}
}
///
/// Represents a header file and its dependencies for merging.
///
public class HeaderFile : IEquatable
{
///
/// The name of the header file.
///
public readonly string Name;
///
/// The lines of the header file.
///
public List Lines;
///
/// The list of dependent header files.
///
public List Dependencies;
///
/// Initializes a new instance of the class.
///
/// The name of the header file.
/// The lines of the header file.
public HeaderFile(string Name, List Lines)
{
this.Name = Name;
this.Lines = Lines;
}
///
public override string ToString()
{
return this.Name;
}
///
public override int GetHashCode()
{
return this.Name.GetHashCode(StringComparison.OrdinalIgnoreCase);
}
///
public override bool Equals(object Obj)
{
if (Obj is not HeaderFile file)
return false;
return string.Equals(this.Name, file.Name, StringComparison.OrdinalIgnoreCase);
}
///
public bool Equals(HeaderFile Other)
{
return Other != null && string.Equals(this.Name, Other.Name, StringComparison.OrdinalIgnoreCase);
}
}
///
/// Provides functionality to generate a single merged NT header from multiple input headers.
///
public static class SingleHeaderGen
{
///
/// The list of NT header files to merge into a single header.
///
private static readonly string[] Headers =
[
"phnt_ntdef.h",
"ntnls.h",
"ntkeapi.h",
"ntldr.h",
"ntexapi.h",
"ntmmapi.h",
"ntobapi.h",
"ntpsapi.h",
"ntbcd.h",
"ntdbg.h",
"ntintsafe.h",
"ntimage.h",
"ntioapi.h",
"ntlsa.h",
"ntlpcapi.h",
"ntmisc.h",
"ntpfapi.h",
"ntpnpapi.h",
"ntpoapi.h",
"ntregapi.h",
"ntnsi.h",
"ntrtl.h",
"ntsam.h",
"ntseapi.h",
"nttmapi.h",
"nttp.h",
"ntuser.h",
"ntwmi.h",
"ntwow64.h",
"ntxcapi.h"
];
///
/// Executes the single header generation process, merging NT headers into a single file.
///
/// True if the operation succeeded; otherwise, false.
public static bool Execute()
{
try
{
if (File.Exists("phnt\\include\\nt.h"))
File.Delete("phnt\\include\\nt.h");
string configPath = "phnt\\include\\phnt.h";
int startIndex = -1;
int endIndex = -1;
int lineIndex = 0;
foreach (string line in File.ReadLines(configPath))
{
if (startIndex < 0 && line.StartsWith("EXTERN_C_START", StringComparison.OrdinalIgnoreCase))
startIndex = lineIndex;
if (line.StartsWith("#endif", StringComparison.OrdinalIgnoreCase))
endIndex = lineIndex;
lineIndex++;
}
using (var output = new StreamWriter("phnt\\include\\nt.h"))
{
output.WriteLine("/*\r\n * This file was automatically generated. Do not edit.\r\n */");
{
long i = 0;
foreach (string line in File.ReadLines(configPath))
{
// Skip everything between startIndex and endIndex (inclusive)
if (startIndex != -1 && endIndex != -1 && i >= startIndex && i < endIndex)
{
i++;
continue;
}
output.WriteLine(line);
i++;
}
}
foreach (string file in Headers)
{
if (
file.Equals("ntzwapi.h", StringComparison.OrdinalIgnoreCase) ||
file.Equals("nt.h", StringComparison.OrdinalIgnoreCase)
)
{
continue;
}
string headerPath;
if (File.Exists($"phnt\\include\\{file}"))
{
headerPath = $"phnt\\include\\{file}";
}
else
{
// required for the ESDK
var sdk_include_path = Utils.GetWindowsSdkIncludePath();
if (string.IsNullOrWhiteSpace(sdk_include_path))
{
Program.PrintErrorMessage("Could not find Windows SDK include paths.");
continue;
}
var found = Directory.EnumerateFiles(sdk_include_path, file, SearchOption.AllDirectories).FirstOrDefault();
if (string.IsNullOrWhiteSpace(found))
{
Program.PrintErrorMessage($"Could not find {file} in phnt or Windows SDK include paths.");
continue;
}
headerPath = found;
}
long headerStartIndex = 0;
// Skip the /* ... */ block
{
using var headerReader = new StreamReader(headerPath);
string firstLine = headerReader.ReadLine();
if (firstLine != null && firstLine.Contains("/*", StringComparison.OrdinalIgnoreCase))
{
bool foundBlockEnd = false;
long headerLineIndex = 0;
string currentLine = firstLine;
do
{
if (currentLine.Contains("*/", StringComparison.OrdinalIgnoreCase))
{
headerStartIndex = headerLineIndex + 1;
foundBlockEnd = true;
break;
}
headerLineIndex++;
} while ((currentLine = headerReader.ReadLine()) != null);
if (!foundBlockEnd)
{
headerStartIndex = 0;
}
}
}
long currentIndex = 0;
foreach (string line in File.ReadLines(headerPath))
{
if (currentIndex++ < headerStartIndex)
continue;
if (
line.Equals("#include ", StringComparison.OrdinalIgnoreCase) ||
line.Equals("#include ", StringComparison.OrdinalIgnoreCase)
)
{
continue;
}
output.WriteLine(line);
}
}
}
}
catch (Exception ex)
{
Program.PrintColorMessage($"Unable to merge headers: {ex}", ConsoleColor.Red);
return false;
}
return true;
}
}
}