Process Hacker
ZwGen.cs
Go to the documentation of this file.
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5 using System.IO;
6 using System.Text.RegularExpressions;
7 
8 namespace GenerateZw
9 {
11  {
12  public string Name;
13  public string Text;
14  public int NameIndex;
15  }
16 
17  class ServiceDefinitionComparer : IEqualityComparer<ServiceDefinition>
18  {
20  {
21  return string.Equals(x.Name, y.Name);
22  }
23 
25  {
26  return obj.Name.GetHashCode();
27  }
28  }
29 
30  class ZwGen
31  {
32  private string _baseDirectory;
33  private string[] _files;
34  private string _outputFile;
35  private string _header = "";
36  private string _footer = "";
37 
38  private List<ServiceDefinition> _defs;
39 
40  private string UnEscape(string text)
41  {
42  return text.Replace("\\r", "\r").Replace("\\n", "\n").Replace("\\\\", "\\");
43  }
44 
45  public void LoadConfig(string fileName)
46  {
47  string[] lines = File.ReadAllLines(fileName);
48 
49  foreach (string line in lines)
50  {
51  string[] split = line.Split(new char[] { '=' }, 2);
52 
53  switch (split[0])
54  {
55  case "base":
56  _baseDirectory = split[1];
57  break;
58  case "in":
59  _files = split[1].Split(';');
60  break;
61  case "out":
62  _outputFile = split[1];
63  break;
64  case "header":
65  _header = UnEscape(split[1]);
66  break;
67  case "footer":
68  _footer = UnEscape(split[1]);
69  break;
70  }
71  }
72  }
73 
74  private void Parse(string text)
75  {
76  Regex regex = new Regex(@"NTSYSCALLAPI[\w\s_]*NTAPI\s*(Nt(\w)*)\(.*?\);", RegexOptions.Compiled | RegexOptions.Singleline);
77  MatchCollection matches;
78 
79  matches = regex.Matches(text);
80 
81  foreach (Match match in matches)
82  {
83  _defs.Add(new ServiceDefinition() { Name = match.Groups[1].Value, Text = match.Value, NameIndex = match.Groups[1].Index - match.Index });
84  }
85  }
86 
87  public void Execute()
88  {
89  // Build up a list of definitions.
90 
91  _defs = new List<ServiceDefinition>();
92 
93  foreach (string fileName in _files)
94  Parse(File.ReadAllText(_baseDirectory + "\\" + fileName));
95 
96  StreamWriter sw = new StreamWriter(_baseDirectory + "\\" + _outputFile);
97 
98  // Remove duplicates and sort.
99  _defs = new List<ServiceDefinition>(_defs.Distinct(new ServiceDefinitionComparer()));
100  _defs.Sort((x, y) => string.CompareOrdinal(x.Name, y.Name));
101 
102  // Header
103 
104  sw.Write(_header);
105 
106  // Definitions
107 
108  foreach (var d in _defs)
109  {
110  Console.WriteLine("System service: " + d.Name);
111 
112  // Write the original definition, replacing "Nt" with "Zw".
113  sw.Write(d.Text.Substring(0, d.NameIndex) + "Zw" + d.Text.Substring(d.NameIndex + 2) + "\r\n\r\n");
114  }
115 
116  // Footer
117 
118  sw.Write(_footer);
119 
120  sw.Close();
121  }
122  }
123 }