forked from crosire/blink
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathblink.cpp
303 lines (241 loc) · 8.48 KB
/
blink.cpp
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
#include "blink.hpp"
#include "pdb_reader.hpp"
#include "file_watcher.hpp"
#include <string>
#include <atomic>
#include <unordered_map>
#include <algorithm>
#include <Windows.h>
namespace blink
{
std::string longest_path(const std::vector<std::string> &paths)
{
if (paths.empty())
{
return std::string();
}
size_t length = paths[0].length();
for (auto it = paths.cbegin(); it != paths.cend(); ++it)
{
if (it->length() < length)
{
length = it->length();
continue;
}
const size_t l = std::mismatch(paths[0].cbegin(), paths[0].cend(), it->cbegin(), it->cend()).first - paths[0].cbegin();
if (l < length)
{
length = l;
}
}
return paths[0].substr(0, length);
}
application::application() : _initialized(false), _executing(false), _compiler_stdin(INVALID_HANDLE_VALUE), _compiler_stdout(INVALID_HANDLE_VALUE)
{
_imagebase = reinterpret_cast<BYTE *>(GetModuleHandle(nullptr));
const auto headers = reinterpret_cast<const IMAGE_NT_HEADERS *>(_imagebase + reinterpret_cast<const IMAGE_DOS_HEADER *>(_imagebase)->e_lfanew);
print("Reading PE import directory ...\n");
#pragma region // Search import directory for additional symbols
const IMAGE_DATA_DIRECTORY import_directory = headers->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT];
const auto import_directory_entries = reinterpret_cast<const IMAGE_IMPORT_DESCRIPTOR *>(_imagebase + import_directory.VirtualAddress);
for (unsigned int i = 0; import_directory_entries[i].FirstThunk != 0; i++)
{
const auto import_name_table = reinterpret_cast<const IMAGE_THUNK_DATA *>(_imagebase + import_directory_entries[i].Characteristics);
const auto import_address_table = reinterpret_cast<const IMAGE_THUNK_DATA *>(_imagebase + import_directory_entries[i].FirstThunk);
for (unsigned int k = 0; import_name_table[k].u1.AddressOfData != 0; k++)
{
const auto import = reinterpret_cast<const IMAGE_IMPORT_BY_NAME *>(_imagebase + import_name_table[k].u1.AddressOfData);
_symbols.insert({ import->Name, reinterpret_cast<void *>(import_address_table[k].u1.AddressOfData) });
}
}
#pragma endregion
print("Reading PE debug info directory ...\n");
#pragma region // Search debug directory for program debug database file name
guid pdb_guid;
std::string pdb_path;
const IMAGE_DATA_DIRECTORY debug_directory = headers->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DEBUG];
const auto debug_directory_entries = reinterpret_cast<const IMAGE_DEBUG_DIRECTORY *>(_imagebase + debug_directory.VirtualAddress);
for (unsigned int i = 0; i < debug_directory.Size / sizeof(IMAGE_DEBUG_DIRECTORY); i++)
{
if (debug_directory_entries[i].Type != IMAGE_DEBUG_TYPE_CODEVIEW)
{
continue;
}
const auto data = reinterpret_cast<const BYTE *>(_imagebase + debug_directory_entries[i].AddressOfRawData);
if (*reinterpret_cast<const DWORD *>(data) == 0x53445352)
{
pdb_guid = *reinterpret_cast<const guid *>(data + 4);
pdb_path = reinterpret_cast<const char *>(data + 24);
break;
}
}
#pragma endregion
if (!pdb_path.empty())
{
print(" Found program debug database: " + pdb_path + '\n');
pdb_reader pdb(pdb_path);
// Check if the debug information actually matches the executable
if (pdb.guid() == pdb_guid)
{
for (const auto &symbol : pdb.symbols())
{
_symbols.insert({ symbol.first, _imagebase + symbol.second });
}
_source_files = pdb.sourcefiles();
}
else
{
print(" Error: Program debug database was created for a different executable file.\n");
return;
}
}
else
{
print(" Error: Could not find path to program debug database in executable image.\n");
return;
}
_symbols.insert({ "__ImageBase", _imagebase });
std::vector<std::string> cpp_files;
for (const auto &path : _source_files)
{
print(" Found source file: " + path + '\n');
// Let's add include directories for all source files and their parent folders
for (size_t i = 0, offset = std::string::npos; i < 2; ++i, --offset)
{
offset = path.find_last_of('\\', offset);
if (offset == std::string::npos)
break;
_include_dirs.insert(path.substr(0, offset));
}
if (path.rfind(".cpp") != std::string::npos && path.find("f:\\dd") == std::string::npos)
cpp_files.push_back(path);
}
_source_dir = longest_path(cpp_files);
if (_source_dir.empty())
{
print(" Error: Could not find any source files.\n");
return;
}
print("Starting compiler process ...\n");
#pragma region // Launch compiler process
STARTUPINFO si = { sizeof(si) };
si.dwFlags = STARTF_USESTDHANDLES;
SECURITY_ATTRIBUTES sa = { sizeof(sa) };
sa.bInheritHandle = TRUE;
if (!CreatePipe(&si.hStdInput, &_compiler_stdin, &sa, 0))
{
return;
}
SetHandleInformation(_compiler_stdin, HANDLE_FLAG_INHERIT, FALSE);
if (!CreatePipe(&_compiler_stdout, &si.hStdOutput, &sa, 0))
{
CloseHandle(si.hStdInput);
return;
}
SetHandleInformation(_compiler_stdout, HANDLE_FLAG_INHERIT, FALSE);
si.hStdError = si.hStdOutput;
TCHAR cmdline[] = TEXT("cmd.exe /q /d");
PROCESS_INFORMATION pi;
if (!CreateProcess(nullptr, cmdline, nullptr, nullptr, TRUE, CREATE_NO_WINDOW, nullptr, nullptr, &si, &pi))
{
CloseHandle(si.hStdInput);
CloseHandle(si.hStdOutput);
return;
}
CloseHandle(pi.hThread);
CloseHandle(pi.hProcess);
CloseHandle(si.hStdInput);
CloseHandle(si.hStdOutput);
#pragma endregion
print(" Started process with PID " + std::to_string(pi.dwProcessId) + '\n');
#pragma region // Set up compiler process environment variables
#if _M_IX86
//const std::string command = "\"" + _build_tool + "\\..\\..\\vcvarsall.bat\" x86\n";
const std::string command = "\"C:\\Program Files (x86)\\Microsoft Visual Studio 15.0\\VC\\Auxiliary\\Build\\vcvarsall.bat\" x86\n";
#endif
#if _M_AMD64
//const std::string command = "\"" + _build_tool + "\\..\\..\\..\\vcvarsall.bat\" x86_amd64\n";
const std::string command = "\"C:\\Program Files (x86)\\Microsoft Visual Studio 15.0\\VC\\Auxiliary\\Build\\vcvarsall.bat\" x86_amd64\n";
#endif
DWORD size = 0;
WriteFile(_compiler_stdin, command.c_str(), static_cast<DWORD>(command.size()), &size, nullptr);
#pragma endregion
print("Starting file system watcher for '" + _source_dir + "' ...\n");
// Start file system watcher
_filewatcher.reset(new filewatcher(_source_dir));
_initialized = true;
}
application::~application()
{
CloseHandle(_compiler_stdin);
CloseHandle(_compiler_stdout);
}
void application::run()
{
if (!_initialized)
{
return;
}
while (true)
{
Sleep(1);
// Read compiler output messages
DWORD size = 0;
if (PeekNamedPipe(_compiler_stdout, nullptr, 0, nullptr, &size, nullptr) && size != 0)
{
std::string message(size, '\0');
ReadFile(_compiler_stdout, const_cast<char *>(message.data()), size, &size, nullptr);
for (size_t pos = 0, prev = 0; (pos = message.find('\n', prev)) != std::string::npos; prev = pos + 1)
{
const auto line = message.substr(prev, pos - prev + 1);
if (line.find("error") != std::string::npos || line.find("warning") != std::string::npos)
{
print(line.c_str());
}
}
if (message.find("compile complete") != std::string::npos)
{
print("Finished compiling \"" + _compiled_module_file + "\".\n");
_executing = false;
}
}
if (_executing)
{
continue;
}
// Load compiled modules
if (!_compiled_module_file.empty())
{
link(_compiled_module_file);
_compiled_module_file.clear();
}
// Check for source modifications and recompile on changes
std::vector<std::string> files;
if (_filewatcher->check(files))
{
for (const auto &path : files)
{
if (path.substr(path.find_last_of('.') + 1) != "cpp")
{
continue;
}
_executing = true;
_compiled_module_file = path.substr(0, path.find_last_of('.')) + ".obj";
print("Detected modification to: " + path + '\n');
// Build compiler command line
std::string cmdline = "cl.exe /c /nologo /GS /W3 /Zc:wchar_t /Z7 /Od /fp:precise /errorReport:prompt /WX- /Zc:forScope /Gd /MDd /EHsc /std:c++latest";
cmdline += " /Fo\"" + _compiled_module_file + "\"";
cmdline += " \"" + path + "\"";
for (const auto &include_path : _include_dirs)
{
cmdline += " /I \"" + include_path + "\"";
}
cmdline += "\necho compile complete\n";
// Execute compiler command line
WriteFile(_compiler_stdin, cmdline.c_str(), static_cast<DWORD>(cmdline.size()), &size, nullptr);
break;
}
}
}
}
}