-
Notifications
You must be signed in to change notification settings - Fork 4.1k
/
util.cc
298 lines (262 loc) · 10.5 KB
/
util.cc
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
// Copyright 2016 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include "src/main/native/windows/util.h"
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <algorithm>
#include <memory>
#include <sstream>
#include <string>
#include "src/main/native/windows/file.h"
namespace bazel {
namespace windows {
using std::wstring;
using std::wstringstream;
wstring MakeErrorMessage(const wchar_t* file, int line,
const wchar_t* failed_func, const wstring& func_arg,
const wstring& message) {
wstringstream result;
result << L"ERROR: " << file << L"(" << line << L"): " << failed_func << L"("
<< func_arg << L"): " << message;
return result.str();
}
wstring MakeErrorMessage(const wchar_t* file, int line,
const wchar_t* failed_func, const wstring& func_arg,
DWORD error_code) {
return MakeErrorMessage(file, line, failed_func, func_arg,
GetLastErrorString(error_code));
}
wstring GetLastErrorString(DWORD error_code) {
if (error_code == 0) {
return L"";
}
LPWSTR message = NULL;
DWORD size = FormatMessageW(
FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS |
FORMAT_MESSAGE_ALLOCATE_BUFFER,
NULL, error_code, LANG_USER_DEFAULT, (LPWSTR)&message, 0, NULL);
if (size == 0) {
wstringstream err;
DWORD format_message_error = GetLastError();
err << L"Error code " << error_code
<< L"; cannot format message due to error code "
<< format_message_error;
return err.str();
}
wstring result(message);
HeapFree(GetProcessHeap(), LMEM_FIXED, message);
return result;
}
bool AutoAttributeList::Create(HANDLE stdin_h, HANDLE stdout_h, HANDLE stderr_h,
std::unique_ptr<AutoAttributeList>* result,
wstring* error_msg) {
if (stdin_h == INVALID_HANDLE_VALUE && stdout_h == INVALID_HANDLE_VALUE &&
stderr_h == INVALID_HANDLE_VALUE) {
result->reset(new AutoAttributeList());
return true;
}
static constexpr DWORD kAttributeCount = 1;
SIZE_T size = 0;
// According to MSDN, the first call to InitializeProcThreadAttributeList is
// expected to fail.
InitializeProcThreadAttributeList(NULL, kAttributeCount, 0, &size);
SetLastError(ERROR_SUCCESS);
std::unique_ptr<uint8_t[]> data(new uint8_t[size]);
LPPROC_THREAD_ATTRIBUTE_LIST attrs =
reinterpret_cast<LPPROC_THREAD_ATTRIBUTE_LIST>(data.get());
if (!InitializeProcThreadAttributeList(attrs, kAttributeCount, 0, &size)) {
if (error_msg) {
DWORD err = GetLastError();
*error_msg =
MakeErrorMessage(WSTR(__FILE__), __LINE__,
L"InitializeProcThreadAttributeList", L"", err);
}
return false;
}
std::unique_ptr<AutoAttributeList> attr_list(
new AutoAttributeList(std::move(data), stdin_h, stdout_h, stderr_h));
if (!UpdateProcThreadAttribute(
attrs, 0, PROC_THREAD_ATTRIBUTE_HANDLE_LIST,
attr_list->handles_.ValidHandles(),
attr_list->handles_.ValidHandlesCount() * sizeof(HANDLE), NULL,
NULL)) {
if (error_msg) {
DWORD err = GetLastError();
*error_msg = MakeErrorMessage(WSTR(__FILE__), __LINE__,
L"UpdateProcThreadAttribute", L"", err);
}
return false;
}
*result = std::move(attr_list);
return true;
}
AutoAttributeList::StdHandles::StdHandles()
: valid_handles_(0),
stdin_h_(INVALID_HANDLE_VALUE),
stdout_h_(INVALID_HANDLE_VALUE),
stderr_h_(INVALID_HANDLE_VALUE) {
valid_handle_array_[0] = INVALID_HANDLE_VALUE;
valid_handle_array_[1] = INVALID_HANDLE_VALUE;
valid_handle_array_[2] = INVALID_HANDLE_VALUE;
}
AutoAttributeList::StdHandles::StdHandles(HANDLE stdin_h, HANDLE stdout_h,
HANDLE stderr_h)
: valid_handles_(0),
stdin_h_(stdin_h),
stdout_h_(stdout_h),
stderr_h_(stderr_h) {
valid_handle_array_[0] = INVALID_HANDLE_VALUE;
valid_handle_array_[1] = INVALID_HANDLE_VALUE;
valid_handle_array_[2] = INVALID_HANDLE_VALUE;
if (stdin_h != INVALID_HANDLE_VALUE) {
valid_handle_array_[valid_handles_++] = stdin_h;
}
if (stdout_h != INVALID_HANDLE_VALUE) {
valid_handle_array_[valid_handles_++] = stdout_h;
}
if (stderr_h != INVALID_HANDLE_VALUE) {
valid_handle_array_[valid_handles_++] = stderr_h;
}
}
AutoAttributeList::AutoAttributeList(std::unique_ptr<uint8_t[]>&& data,
HANDLE stdin_h, HANDLE stdout_h,
HANDLE stderr_h)
: data_(std::move(data)), handles_(stdin_h, stdout_h, stderr_h) {}
AutoAttributeList::~AutoAttributeList() {
DeleteProcThreadAttributeList(*this);
}
AutoAttributeList::operator LPPROC_THREAD_ATTRIBUTE_LIST() const {
return reinterpret_cast<LPPROC_THREAD_ATTRIBUTE_LIST>(data_.get());
}
void AutoAttributeList::InitStartupInfoExW(STARTUPINFOEXW* startup_info) const {
ZeroMemory(startup_info, sizeof(STARTUPINFOEXW));
startup_info->StartupInfo.cb = sizeof(STARTUPINFOEXW);
if (InheritAnyHandles()) {
startup_info->StartupInfo.dwFlags = STARTF_USESTDHANDLES;
startup_info->StartupInfo.hStdInput = handles_.StdIn();
startup_info->StartupInfo.hStdOutput = handles_.StdOut();
startup_info->StartupInfo.hStdError = handles_.StdErr();
startup_info->lpAttributeList = *this;
}
}
static void QuotePath(const wstring& path, wstring* result) {
*result = wstring(L"\"") + path + L"\"";
}
static bool IsSeparator(WCHAR c) { return c == L'/' || c == L'\\'; }
static bool HasSeparator(const wstring& s) {
return s.find_first_of(L'/') != wstring::npos ||
s.find_first_of(L'\\') != wstring::npos;
}
static bool Contains(const wstring& s, const WCHAR* substr) {
return s.find(substr) != wstring::npos;
}
wstring AsShortPath(wstring path, wstring* result) {
if (path.empty()) {
result->clear();
return L"";
}
if (path[0] == '"') {
return MakeErrorMessage(WSTR(__FILE__), __LINE__, L"AsShortPath", path,
L"path should not be quoted");
}
if (IsSeparator(path[0])) {
return MakeErrorMessage(WSTR(__FILE__), __LINE__, L"AsShortPath", path,
L"path is absolute without a drive letter");
}
if (Contains(path, L"/./") || Contains(path, L"\\.\\") ||
Contains(path, L"/..") || Contains(path, L"\\..")) {
return MakeErrorMessage(WSTR(__FILE__), __LINE__, L"AsShortPath", path,
L"path is not normalized");
}
if (path.size() >= MAX_PATH && !HasSeparator(path)) {
return MakeErrorMessage(WSTR(__FILE__), __LINE__, L"AsShortPath", path,
L"path is just a file name but too long");
}
if (HasSeparator(path) && !HasDriveSpecifierPrefix(path.c_str())) {
return MakeErrorMessage(WSTR(__FILE__), __LINE__, L"AsShortPath", path,
L"path is not absolute");
}
// At this point we know the path is either just a file name (shorter than
// MAX_PATH), or an absolute, normalized, Windows-style path (of any length).
std::replace(path.begin(), path.end(), '/', '\\');
// Fast-track: the path is already short.
if (path.size() < MAX_PATH) {
*result = path;
return L"";
}
// At this point we know that the path is at least MAX_PATH long and that it's
// absolute, normalized, and Windows-style.
wstring wlong = wstring(L"\\\\?\\") + path;
// Experience shows that:
// - GetShortPathNameW's result has a "\\?\" prefix if and only if the input
// did too (though this behavior is not documented on MSDN)
// - CreateProcess{A,W} only accept an executable of MAX_PATH - 1 length
// Therefore for our purposes the acceptable shortened length is
// MAX_PATH + 4 (null-terminated). That is, MAX_PATH - 1 for the shortened
// path, plus a potential "\\?\" prefix that's only there if `wlong` also had
// it and which we'll omit from `result`, plus a null terminator.
static const size_t kMaxShortPath = MAX_PATH + 4;
WCHAR wshort[kMaxShortPath];
DWORD wshort_size = ::GetShortPathNameW(wlong.c_str(), NULL, 0);
if (wshort_size == 0) {
DWORD err_code = GetLastError();
wstring res = MakeErrorMessage(WSTR(__FILE__), __LINE__,
L"GetShortPathNameW", wlong, err_code);
return res;
}
if (wshort_size >= kMaxShortPath) {
return MakeErrorMessage(WSTR(__FILE__), __LINE__, L"GetShortPathNameW",
wlong, L"cannot shorten the path enough");
}
GetShortPathNameW(wlong.c_str(), wshort, kMaxShortPath);
result->assign(wshort + 4);
return L"";
}
wstring AsExecutablePathForCreateProcess(wstring path, wstring* result) {
if (path.empty()) {
return MakeErrorMessage(WSTR(__FILE__), __LINE__,
L"AsExecutablePathForCreateProcess", path,
L"path should not be empty");
}
if (IsSeparator(path[0])) {
return MakeErrorMessage(WSTR(__FILE__), __LINE__,
L"AsExecutablePathForCreateProcess", path,
L"path is absolute without a drive letter");
}
if (HasSeparator(path) && !HasDriveSpecifierPrefix(path.c_str())) {
wstring cwd;
DWORD err;
if (!GetCwd(&cwd, &err)) {
return MakeErrorMessage(WSTR(__FILE__), __LINE__,
L"AsExecutablePathForCreateProcess", path, err);
}
path = cwd + L"\\" + path;
}
wstring error = AsShortPath(path, result);
if (!error.empty()) {
return MakeErrorMessage(WSTR(__FILE__), __LINE__,
L"AsExecutablePathForCreateProcess", path, error);
}
// Quote the path in case it's something like "c:\foo\app name.exe".
// Do this unconditionally, there's no harm in quoting. Quotes are not
// allowed inside paths so we don't need to escape quotes.
QuotePath(*result, result);
return L"";
}
} // namespace windows
} // namespace bazel