]>
Commit | Line | Data |
---|---|---|
f4626df5 | 1 | #include "../git-compat-util.h" |
444dc903 | 2 | #include "win32.h" |
bdc77d1d | 3 | #include <aclapi.h> |
e883e04b | 4 | #include <sddl.h> |
28a559c0 | 5 | #include <conio.h> |
85faec9d | 6 | #include <wchar.h> |
7e5d7768 | 7 | #include "../strbuf.h" |
c9b78400 | 8 | #include "../run-command.h" |
0b027f6c | 9 | #include "../abspath.h" |
36bf1958 | 10 | #include "../alloc.h" |
564be791 | 11 | #include "win32/lazyload.h" |
bdfbb0ea | 12 | #include "../config.h" |
32a8f510 | 13 | #include "../environment.h" |
74ea5c95 | 14 | #include "../trace2.h" |
cb2a5135 | 15 | #include "../symlinks.h" |
d5ebb50d | 16 | #include "../wrapper.h" |
9e9da23c | 17 | #include "dir.h" |
f394e093 | 18 | #include "gettext.h" |
4a9b2049 MA |
19 | #define SECURITY_WIN32 |
20 | #include <sspi.h> | |
f4626df5 | 21 | |
7c00bc39 JS |
22 | #define HCAST(type, handle) ((type)(intptr_t)handle) |
23 | ||
19e12549 HV |
24 | static const int delay[] = { 0, 1, 10, 20, 40 }; |
25 | ||
08809c09 JS |
26 | void open_in_gdb(void) |
27 | { | |
28 | static struct child_process cp = CHILD_PROCESS_INIT; | |
29 | extern char *_pgmptr; | |
30 | ||
ef8d7ac4 JK |
31 | strvec_pushl(&cp.args, "mintty", "gdb", NULL); |
32 | strvec_pushf(&cp.args, "--pid=%d", getpid()); | |
08809c09 JS |
33 | cp.clean_on_exit = 1; |
34 | if (start_command(&cp) < 0) | |
35 | die_errno("Could not start gdb"); | |
36 | sleep(1); | |
37 | } | |
38 | ||
44626dc7 | 39 | int err_win_to_posix(DWORD winerr) |
b3debd2b PK |
40 | { |
41 | int error = ENOSYS; | |
42 | switch(winerr) { | |
43 | case ERROR_ACCESS_DENIED: error = EACCES; break; | |
44 | case ERROR_ACCOUNT_DISABLED: error = EACCES; break; | |
45 | case ERROR_ACCOUNT_RESTRICTION: error = EACCES; break; | |
46 | case ERROR_ALREADY_ASSIGNED: error = EBUSY; break; | |
47 | case ERROR_ALREADY_EXISTS: error = EEXIST; break; | |
48 | case ERROR_ARITHMETIC_OVERFLOW: error = ERANGE; break; | |
49 | case ERROR_BAD_COMMAND: error = EIO; break; | |
50 | case ERROR_BAD_DEVICE: error = ENODEV; break; | |
51 | case ERROR_BAD_DRIVER_LEVEL: error = ENXIO; break; | |
52 | case ERROR_BAD_EXE_FORMAT: error = ENOEXEC; break; | |
53 | case ERROR_BAD_FORMAT: error = ENOEXEC; break; | |
54 | case ERROR_BAD_LENGTH: error = EINVAL; break; | |
55 | case ERROR_BAD_PATHNAME: error = ENOENT; break; | |
56 | case ERROR_BAD_PIPE: error = EPIPE; break; | |
57 | case ERROR_BAD_UNIT: error = ENODEV; break; | |
58 | case ERROR_BAD_USERNAME: error = EINVAL; break; | |
59 | case ERROR_BROKEN_PIPE: error = EPIPE; break; | |
60 | case ERROR_BUFFER_OVERFLOW: error = ENAMETOOLONG; break; | |
61 | case ERROR_BUSY: error = EBUSY; break; | |
62 | case ERROR_BUSY_DRIVE: error = EBUSY; break; | |
63 | case ERROR_CALL_NOT_IMPLEMENTED: error = ENOSYS; break; | |
64 | case ERROR_CANNOT_MAKE: error = EACCES; break; | |
65 | case ERROR_CANTOPEN: error = EIO; break; | |
66 | case ERROR_CANTREAD: error = EIO; break; | |
67 | case ERROR_CANTWRITE: error = EIO; break; | |
68 | case ERROR_CRC: error = EIO; break; | |
69 | case ERROR_CURRENT_DIRECTORY: error = EACCES; break; | |
70 | case ERROR_DEVICE_IN_USE: error = EBUSY; break; | |
71 | case ERROR_DEV_NOT_EXIST: error = ENODEV; break; | |
72 | case ERROR_DIRECTORY: error = EINVAL; break; | |
73 | case ERROR_DIR_NOT_EMPTY: error = ENOTEMPTY; break; | |
74 | case ERROR_DISK_CHANGE: error = EIO; break; | |
75 | case ERROR_DISK_FULL: error = ENOSPC; break; | |
76 | case ERROR_DRIVE_LOCKED: error = EBUSY; break; | |
77 | case ERROR_ENVVAR_NOT_FOUND: error = EINVAL; break; | |
78 | case ERROR_EXE_MARKED_INVALID: error = ENOEXEC; break; | |
79 | case ERROR_FILENAME_EXCED_RANGE: error = ENAMETOOLONG; break; | |
80 | case ERROR_FILE_EXISTS: error = EEXIST; break; | |
81 | case ERROR_FILE_INVALID: error = ENODEV; break; | |
82 | case ERROR_FILE_NOT_FOUND: error = ENOENT; break; | |
83 | case ERROR_GEN_FAILURE: error = EIO; break; | |
84 | case ERROR_HANDLE_DISK_FULL: error = ENOSPC; break; | |
85 | case ERROR_INSUFFICIENT_BUFFER: error = ENOMEM; break; | |
86 | case ERROR_INVALID_ACCESS: error = EACCES; break; | |
87 | case ERROR_INVALID_ADDRESS: error = EFAULT; break; | |
88 | case ERROR_INVALID_BLOCK: error = EFAULT; break; | |
89 | case ERROR_INVALID_DATA: error = EINVAL; break; | |
90 | case ERROR_INVALID_DRIVE: error = ENODEV; break; | |
91 | case ERROR_INVALID_EXE_SIGNATURE: error = ENOEXEC; break; | |
92 | case ERROR_INVALID_FLAGS: error = EINVAL; break; | |
93 | case ERROR_INVALID_FUNCTION: error = ENOSYS; break; | |
94 | case ERROR_INVALID_HANDLE: error = EBADF; break; | |
95 | case ERROR_INVALID_LOGON_HOURS: error = EACCES; break; | |
96 | case ERROR_INVALID_NAME: error = EINVAL; break; | |
97 | case ERROR_INVALID_OWNER: error = EINVAL; break; | |
98 | case ERROR_INVALID_PARAMETER: error = EINVAL; break; | |
99 | case ERROR_INVALID_PASSWORD: error = EPERM; break; | |
100 | case ERROR_INVALID_PRIMARY_GROUP: error = EINVAL; break; | |
101 | case ERROR_INVALID_SIGNAL_NUMBER: error = EINVAL; break; | |
102 | case ERROR_INVALID_TARGET_HANDLE: error = EIO; break; | |
103 | case ERROR_INVALID_WORKSTATION: error = EACCES; break; | |
104 | case ERROR_IO_DEVICE: error = EIO; break; | |
105 | case ERROR_IO_INCOMPLETE: error = EINTR; break; | |
106 | case ERROR_LOCKED: error = EBUSY; break; | |
107 | case ERROR_LOCK_VIOLATION: error = EACCES; break; | |
108 | case ERROR_LOGON_FAILURE: error = EACCES; break; | |
109 | case ERROR_MAPPED_ALIGNMENT: error = EINVAL; break; | |
110 | case ERROR_META_EXPANSION_TOO_LONG: error = E2BIG; break; | |
111 | case ERROR_MORE_DATA: error = EPIPE; break; | |
112 | case ERROR_NEGATIVE_SEEK: error = ESPIPE; break; | |
113 | case ERROR_NOACCESS: error = EFAULT; break; | |
114 | case ERROR_NONE_MAPPED: error = EINVAL; break; | |
115 | case ERROR_NOT_ENOUGH_MEMORY: error = ENOMEM; break; | |
116 | case ERROR_NOT_READY: error = EAGAIN; break; | |
117 | case ERROR_NOT_SAME_DEVICE: error = EXDEV; break; | |
118 | case ERROR_NO_DATA: error = EPIPE; break; | |
119 | case ERROR_NO_MORE_SEARCH_HANDLES: error = EIO; break; | |
120 | case ERROR_NO_PROC_SLOTS: error = EAGAIN; break; | |
121 | case ERROR_NO_SUCH_PRIVILEGE: error = EACCES; break; | |
122 | case ERROR_OPEN_FAILED: error = EIO; break; | |
123 | case ERROR_OPEN_FILES: error = EBUSY; break; | |
124 | case ERROR_OPERATION_ABORTED: error = EINTR; break; | |
125 | case ERROR_OUTOFMEMORY: error = ENOMEM; break; | |
126 | case ERROR_PASSWORD_EXPIRED: error = EACCES; break; | |
127 | case ERROR_PATH_BUSY: error = EBUSY; break; | |
128 | case ERROR_PATH_NOT_FOUND: error = ENOENT; break; | |
129 | case ERROR_PIPE_BUSY: error = EBUSY; break; | |
130 | case ERROR_PIPE_CONNECTED: error = EPIPE; break; | |
131 | case ERROR_PIPE_LISTENING: error = EPIPE; break; | |
132 | case ERROR_PIPE_NOT_CONNECTED: error = EPIPE; break; | |
133 | case ERROR_PRIVILEGE_NOT_HELD: error = EACCES; break; | |
134 | case ERROR_READ_FAULT: error = EIO; break; | |
135 | case ERROR_SEEK: error = EIO; break; | |
136 | case ERROR_SEEK_ON_DEVICE: error = ESPIPE; break; | |
137 | case ERROR_SHARING_BUFFER_EXCEEDED: error = ENFILE; break; | |
138 | case ERROR_SHARING_VIOLATION: error = EACCES; break; | |
139 | case ERROR_STACK_OVERFLOW: error = ENOMEM; break; | |
3ba3720b | 140 | case ERROR_SUCCESS: BUG("err_win_to_posix() called without an error!"); |
b3debd2b PK |
141 | case ERROR_SWAPERROR: error = ENOENT; break; |
142 | case ERROR_TOO_MANY_MODULES: error = EMFILE; break; | |
143 | case ERROR_TOO_MANY_OPEN_FILES: error = EMFILE; break; | |
144 | case ERROR_UNRECOGNIZED_MEDIA: error = ENXIO; break; | |
145 | case ERROR_UNRECOGNIZED_VOLUME: error = ENODEV; break; | |
146 | case ERROR_WAIT_NO_CHILDREN: error = ECHILD; break; | |
147 | case ERROR_WRITE_FAULT: error = EIO; break; | |
148 | case ERROR_WRITE_PROTECT: error = EROFS; break; | |
149 | } | |
150 | return error; | |
151 | } | |
152 | ||
19e12549 HV |
153 | static inline int is_file_in_use_error(DWORD errcode) |
154 | { | |
155 | switch (errcode) { | |
156 | case ERROR_SHARING_VIOLATION: | |
157 | case ERROR_ACCESS_DENIED: | |
158 | return 1; | |
159 | } | |
160 | ||
161 | return 0; | |
162 | } | |
163 | ||
c9b78400 HV |
164 | static int read_yes_no_answer(void) |
165 | { | |
166 | char answer[1024]; | |
167 | ||
168 | if (fgets(answer, sizeof(answer), stdin)) { | |
169 | size_t answer_len = strlen(answer); | |
170 | int got_full_line = 0, c; | |
171 | ||
172 | /* remove the newline */ | |
173 | if (answer_len >= 2 && answer[answer_len-2] == '\r') { | |
174 | answer[answer_len-2] = '\0'; | |
175 | got_full_line = 1; | |
176 | } else if (answer_len >= 1 && answer[answer_len-1] == '\n') { | |
177 | answer[answer_len-1] = '\0'; | |
178 | got_full_line = 1; | |
179 | } | |
180 | /* flush the buffer in case we did not get the full line */ | |
181 | if (!got_full_line) | |
182 | while ((c = getchar()) != EOF && c != '\n') | |
183 | ; | |
184 | } else | |
185 | /* we could not read, return the | |
186 | * default answer which is no */ | |
187 | return 0; | |
188 | ||
189 | if (tolower(answer[0]) == 'y' && !answer[1]) | |
190 | return 1; | |
191 | if (!strncasecmp(answer, "yes", sizeof(answer))) | |
192 | return 1; | |
193 | if (tolower(answer[0]) == 'n' && !answer[1]) | |
194 | return 0; | |
195 | if (!strncasecmp(answer, "no", sizeof(answer))) | |
196 | return 0; | |
197 | ||
198 | /* did not find an answer we understand */ | |
199 | return -1; | |
200 | } | |
201 | ||
202 | static int ask_yes_no_if_possible(const char *format, ...) | |
203 | { | |
204 | char question[4096]; | |
4120294c | 205 | const char *retry_hook; |
c9b78400 HV |
206 | va_list args; |
207 | ||
208 | va_start(args, format); | |
209 | vsnprintf(question, sizeof(question), format, args); | |
210 | va_end(args); | |
211 | ||
4120294c RS |
212 | retry_hook = mingw_getenv("GIT_ASK_YESNO"); |
213 | if (retry_hook) { | |
214 | struct child_process cmd = CHILD_PROCESS_INIT; | |
215 | ||
216 | strvec_pushl(&cmd.args, retry_hook, question, NULL); | |
217 | return !run_command(&cmd); | |
c9b78400 HV |
218 | } |
219 | ||
220 | if (!isatty(_fileno(stdin)) || !isatty(_fileno(stderr))) | |
221 | return 0; | |
222 | ||
223 | while (1) { | |
224 | int answer; | |
225 | fprintf(stderr, "%s (y/n) ", question); | |
226 | ||
227 | if ((answer = read_yes_no_answer()) >= 0) | |
228 | return answer; | |
229 | ||
230 | fprintf(stderr, "Sorry, I did not understand your answer. " | |
231 | "Please type 'y' or 'n'\n"); | |
232 | } | |
233 | } | |
234 | ||
bdfbb0ea JS |
235 | /* Windows only */ |
236 | enum hide_dotfiles_type { | |
237 | HIDE_DOTFILES_FALSE = 0, | |
238 | HIDE_DOTFILES_TRUE, | |
239 | HIDE_DOTFILES_DOTGITONLY | |
240 | }; | |
241 | ||
ac33519d | 242 | static int core_restrict_inherited_handles = -1; |
bdfbb0ea | 243 | static enum hide_dotfiles_type hide_dotfiles = HIDE_DOTFILES_DOTGITONLY; |
0e218f91 | 244 | static char *unset_environment_variables; |
bdfbb0ea | 245 | |
70fc5793 JS |
246 | int mingw_core_config(const char *var, const char *value, void *cb) |
247 | { | |
bdfbb0ea JS |
248 | if (!strcmp(var, "core.hidedotfiles")) { |
249 | if (value && !strcasecmp(value, "dotgitonly")) | |
250 | hide_dotfiles = HIDE_DOTFILES_DOTGITONLY; | |
251 | else | |
252 | hide_dotfiles = git_config_bool(var, value); | |
253 | return 0; | |
254 | } | |
255 | ||
0e218f91 JS |
256 | if (!strcmp(var, "core.unsetenvvars")) { |
257 | free(unset_environment_variables); | |
258 | unset_environment_variables = xstrdup(value); | |
259 | return 0; | |
260 | } | |
261 | ||
ac33519d JS |
262 | if (!strcmp(var, "core.restrictinheritedhandles")) { |
263 | if (value && !strcasecmp(value, "auto")) | |
264 | core_restrict_inherited_handles = -1; | |
265 | else | |
266 | core_restrict_inherited_handles = | |
267 | git_config_bool(var, value); | |
268 | return 0; | |
269 | } | |
270 | ||
70fc5793 JS |
271 | return 0; |
272 | } | |
273 | ||
4745feeb AS |
274 | /* Normalizes NT paths as returned by some low-level APIs. */ |
275 | static wchar_t *normalize_ntpath(wchar_t *wbuf) | |
276 | { | |
277 | int i; | |
278 | /* fix absolute path prefixes */ | |
279 | if (wbuf[0] == '\\') { | |
280 | /* strip NT namespace prefixes */ | |
281 | if (!wcsncmp(wbuf, L"\\??\\", 4) || | |
282 | !wcsncmp(wbuf, L"\\\\?\\", 4)) | |
283 | wbuf += 4; | |
284 | else if (!wcsnicmp(wbuf, L"\\DosDevices\\", 12)) | |
285 | wbuf += 12; | |
286 | /* replace remaining '...UNC\' with '\\' */ | |
287 | if (!wcsnicmp(wbuf, L"UNC\\", 4)) { | |
288 | wbuf += 2; | |
289 | *wbuf = '\\'; | |
290 | } | |
291 | } | |
292 | /* convert backslashes to slashes */ | |
293 | for (i = 0; wbuf[i]; i++) | |
294 | if (wbuf[i] == '\\') | |
295 | wbuf[i] = '/'; | |
296 | return wbuf; | |
297 | } | |
298 | ||
337967fb HV |
299 | int mingw_unlink(const char *pathname) |
300 | { | |
19e12549 | 301 | int ret, tries = 0; |
85faec9d KB |
302 | wchar_t wpathname[MAX_PATH]; |
303 | if (xutftowcs_path(wpathname, pathname) < 0) | |
304 | return -1; | |
19e12549 | 305 | |
680e0b45 JH |
306 | if (DeleteFileW(wpathname)) |
307 | return 0; | |
308 | ||
337967fb | 309 | /* read-only files cannot be removed */ |
85faec9d KB |
310 | _wchmod(wpathname, 0666); |
311 | while ((ret = _wunlink(wpathname)) == -1 && tries < ARRAY_SIZE(delay)) { | |
19e12549 HV |
312 | if (!is_file_in_use_error(GetLastError())) |
313 | break; | |
314 | /* | |
315 | * We assume that some other process had the source or | |
316 | * destination file open at the wrong moment and retry. | |
317 | * In order to give the other process a higher chance to | |
318 | * complete its operation, we give up our time slice now. | |
319 | * If we have to retry again, we do sleep a bit. | |
320 | */ | |
321 | Sleep(delay[tries]); | |
322 | tries++; | |
323 | } | |
c9b78400 HV |
324 | while (ret == -1 && is_file_in_use_error(GetLastError()) && |
325 | ask_yes_no_if_possible("Unlink of file '%s' failed. " | |
326 | "Should I try again?", pathname)) | |
85faec9d | 327 | ret = _wunlink(wpathname); |
19e12549 | 328 | return ret; |
337967fb HV |
329 | } |
330 | ||
85faec9d | 331 | static int is_dir_empty(const wchar_t *wpath) |
ab1a11be | 332 | { |
85faec9d | 333 | WIN32_FIND_DATAW findbuf; |
ab1a11be | 334 | HANDLE handle; |
85faec9d KB |
335 | wchar_t wbuf[MAX_PATH + 2]; |
336 | wcscpy(wbuf, wpath); | |
337 | wcscat(wbuf, L"\\*"); | |
338 | handle = FindFirstFileW(wbuf, &findbuf); | |
339 | if (handle == INVALID_HANDLE_VALUE) | |
ab1a11be | 340 | return GetLastError() == ERROR_NO_MORE_FILES; |
ab1a11be | 341 | |
85faec9d KB |
342 | while (!wcscmp(findbuf.cFileName, L".") || |
343 | !wcscmp(findbuf.cFileName, L"..")) | |
344 | if (!FindNextFileW(handle, &findbuf)) { | |
345 | DWORD err = GetLastError(); | |
346 | FindClose(handle); | |
347 | return err == ERROR_NO_MORE_FILES; | |
ab1a11be JS |
348 | } |
349 | FindClose(handle); | |
ab1a11be JS |
350 | return 0; |
351 | } | |
352 | ||
4f288100 HV |
353 | int mingw_rmdir(const char *pathname) |
354 | { | |
355 | int ret, tries = 0; | |
85faec9d | 356 | wchar_t wpathname[MAX_PATH]; |
3e7d4888 TB |
357 | struct stat st; |
358 | ||
359 | /* | |
360 | * Contrary to Linux' `rmdir()`, Windows' _wrmdir() and _rmdir() | |
361 | * (and `RemoveDirectoryW()`) will attempt to remove the target of a | |
362 | * symbolic link (if it points to a directory). | |
363 | * | |
364 | * This behavior breaks the assumption of e.g. `remove_path()` which | |
365 | * upon successful deletion of a file will attempt to remove its parent | |
366 | * directories recursively until failure (which usually happens when | |
367 | * the directory is not empty). | |
368 | * | |
369 | * Therefore, before calling `_wrmdir()`, we first check if the path is | |
370 | * a symbolic link. If it is, we exit and return the same error as | |
371 | * Linux' `rmdir()` would, i.e. `ENOTDIR`. | |
372 | */ | |
373 | if (!mingw_lstat(pathname, &st) && S_ISLNK(st.st_mode)) { | |
374 | errno = ENOTDIR; | |
375 | return -1; | |
376 | } | |
377 | ||
85faec9d KB |
378 | if (xutftowcs_path(wpathname, pathname) < 0) |
379 | return -1; | |
4f288100 | 380 | |
85faec9d | 381 | while ((ret = _wrmdir(wpathname)) == -1 && tries < ARRAY_SIZE(delay)) { |
4f288100 | 382 | if (!is_file_in_use_error(GetLastError())) |
a83b2b57 EFL |
383 | errno = err_win_to_posix(GetLastError()); |
384 | if (errno != EACCES) | |
4f288100 | 385 | break; |
85faec9d | 386 | if (!is_dir_empty(wpathname)) { |
ab1a11be JS |
387 | errno = ENOTEMPTY; |
388 | break; | |
389 | } | |
4f288100 HV |
390 | /* |
391 | * We assume that some other process had the source or | |
392 | * destination file open at the wrong moment and retry. | |
393 | * In order to give the other process a higher chance to | |
394 | * complete its operation, we give up our time slice now. | |
395 | * If we have to retry again, we do sleep a bit. | |
396 | */ | |
397 | Sleep(delay[tries]); | |
398 | tries++; | |
399 | } | |
a83b2b57 | 400 | while (ret == -1 && errno == EACCES && is_file_in_use_error(GetLastError()) && |
4f288100 HV |
401 | ask_yes_no_if_possible("Deletion of directory '%s' failed. " |
402 | "Should I try again?", pathname)) | |
85faec9d | 403 | ret = _wrmdir(wpathname); |
684dd4c2 MT |
404 | if (!ret) |
405 | invalidate_lstat_cache(); | |
85faec9d KB |
406 | return ret; |
407 | } | |
408 | ||
f30afdab JS |
409 | static inline int needs_hiding(const char *path) |
410 | { | |
411 | const char *basename; | |
412 | ||
413 | if (hide_dotfiles == HIDE_DOTFILES_FALSE) | |
414 | return 0; | |
415 | ||
416 | /* We cannot use basename(), as it would remove trailing slashes */ | |
1cadad6f | 417 | win32_skip_dos_drive_prefix((char **)&path); |
f30afdab JS |
418 | if (!*path) |
419 | return 0; | |
420 | ||
421 | for (basename = path; *path; path++) | |
422 | if (is_dir_sep(*path)) { | |
423 | do { | |
424 | path++; | |
425 | } while (is_dir_sep(*path)); | |
426 | /* ignore trailing slashes */ | |
427 | if (*path) | |
428 | basename = path; | |
60e6569a JS |
429 | else |
430 | break; | |
f30afdab JS |
431 | } |
432 | ||
433 | if (hide_dotfiles == HIDE_DOTFILES_TRUE) | |
434 | return *basename == '.'; | |
435 | ||
436 | assert(hide_dotfiles == HIDE_DOTFILES_DOTGITONLY); | |
437 | return !strncasecmp(".git", basename, 4) && | |
438 | (!basename[4] || is_dir_sep(basename[4])); | |
439 | } | |
440 | ||
441 | static int set_hidden_flag(const wchar_t *path, int set) | |
442 | { | |
443 | DWORD original = GetFileAttributesW(path), modified; | |
444 | if (set) | |
445 | modified = original | FILE_ATTRIBUTE_HIDDEN; | |
446 | else | |
447 | modified = original & ~FILE_ATTRIBUTE_HIDDEN; | |
448 | if (original == modified || SetFileAttributesW(path, modified)) | |
449 | return 0; | |
450 | errno = err_win_to_posix(GetLastError()); | |
451 | return -1; | |
452 | } | |
453 | ||
85faec9d KB |
454 | int mingw_mkdir(const char *path, int mode) |
455 | { | |
456 | int ret; | |
457 | wchar_t wpath[MAX_PATH]; | |
d2c84dad | 458 | |
4dc42c6c | 459 | if (!is_valid_win32_path(path, 0)) { |
d2c84dad JS |
460 | errno = EINVAL; |
461 | return -1; | |
462 | } | |
463 | ||
85faec9d KB |
464 | if (xutftowcs_path(wpath, path) < 0) |
465 | return -1; | |
466 | ret = _wmkdir(wpath); | |
f30afdab JS |
467 | if (!ret && needs_hiding(path)) |
468 | return set_hidden_flag(wpath, 1); | |
4f288100 HV |
469 | return ret; |
470 | } | |
471 | ||
eeaf7dda JH |
472 | /* |
473 | * Calling CreateFile() using FILE_APPEND_DATA and without FILE_WRITE_DATA | |
474 | * is documented in [1] as opening a writable file handle in append mode. | |
475 | * (It is believed that) this is atomic since it is maintained by the | |
476 | * kernel unlike the O_APPEND flag which is racily maintained by the CRT. | |
477 | * | |
478 | * [1] https://docs.microsoft.com/en-us/windows/desktop/fileio/file-access-rights-constants | |
479 | * | |
480 | * This trick does not appear to work for named pipes. Instead it creates | |
481 | * a named pipe client handle that cannot be written to. Callers should | |
482 | * just use the regular _wopen() for them. (And since client handle gets | |
483 | * bound to a unique server handle, it isn't really an issue.) | |
484 | */ | |
d6410975 JS |
485 | static int mingw_open_append(wchar_t const *wfilename, int oflags, ...) |
486 | { | |
487 | HANDLE handle; | |
488 | int fd; | |
489 | DWORD create = (oflags & O_CREAT) ? OPEN_ALWAYS : OPEN_EXISTING; | |
490 | ||
491 | /* only these flags are supported */ | |
492 | if ((oflags & ~O_CREAT) != (O_WRONLY | O_APPEND)) | |
493 | return errno = ENOSYS, -1; | |
494 | ||
495 | /* | |
496 | * FILE_SHARE_WRITE is required to permit child processes | |
497 | * to append to the file. | |
498 | */ | |
499 | handle = CreateFileW(wfilename, FILE_APPEND_DATA, | |
500 | FILE_SHARE_WRITE | FILE_SHARE_READ, | |
501 | NULL, create, FILE_ATTRIBUTE_NORMAL, NULL); | |
23eafd92 NS |
502 | if (handle == INVALID_HANDLE_VALUE) { |
503 | DWORD err = GetLastError(); | |
504 | ||
505 | /* | |
506 | * Some network storage solutions (e.g. Isilon) might return | |
507 | * ERROR_INVALID_PARAMETER instead of expected error | |
508 | * ERROR_PATH_NOT_FOUND, which results in an unknown error. If | |
509 | * so, let's turn the error to ERROR_PATH_NOT_FOUND instead. | |
510 | */ | |
511 | if (err == ERROR_INVALID_PARAMETER) | |
512 | err = ERROR_PATH_NOT_FOUND; | |
513 | ||
514 | errno = err_win_to_posix(err); | |
515 | return -1; | |
516 | } | |
eeaf7dda | 517 | |
d6410975 JS |
518 | /* |
519 | * No O_APPEND here, because the CRT uses it only to reset the | |
eeaf7dda JH |
520 | * file pointer to EOF before each write(); but that is not |
521 | * necessary (and may lead to races) for a file created with | |
522 | * FILE_APPEND_DATA. | |
d6410975 JS |
523 | */ |
524 | fd = _open_osfhandle((intptr_t)handle, O_BINARY); | |
525 | if (fd < 0) | |
526 | CloseHandle(handle); | |
527 | return fd; | |
528 | } | |
529 | ||
eeaf7dda JH |
530 | /* |
531 | * Does the pathname map to the local named pipe filesystem? | |
532 | * That is, does it have a "//./pipe/" prefix? | |
533 | */ | |
534 | static int is_local_named_pipe_path(const char *filename) | |
535 | { | |
536 | return (is_dir_sep(filename[0]) && | |
537 | is_dir_sep(filename[1]) && | |
538 | filename[2] == '.' && | |
539 | is_dir_sep(filename[3]) && | |
540 | !strncasecmp(filename+4, "pipe", 4) && | |
541 | is_dir_sep(filename[8]) && | |
542 | filename[9]); | |
543 | } | |
544 | ||
3e4a1ba0 JS |
545 | int mingw_open (const char *filename, int oflags, ...) |
546 | { | |
d6410975 | 547 | typedef int (*open_fn_t)(wchar_t const *wfilename, int oflags, ...); |
3e4a1ba0 JS |
548 | va_list args; |
549 | unsigned mode; | |
d2c84dad | 550 | int fd, create = (oflags & (O_CREAT | O_EXCL)) == (O_CREAT | O_EXCL); |
85faec9d | 551 | wchar_t wfilename[MAX_PATH]; |
d6410975 | 552 | open_fn_t open_fn; |
0d30ad71 | 553 | |
3e4a1ba0 JS |
554 | va_start(args, oflags); |
555 | mode = va_arg(args, int); | |
556 | va_end(args); | |
557 | ||
4dc42c6c | 558 | if (!is_valid_win32_path(filename, !create)) { |
d2c84dad JS |
559 | errno = create ? EINVAL : ENOENT; |
560 | return -1; | |
561 | } | |
562 | ||
eeaf7dda | 563 | if ((oflags & O_APPEND) && !is_local_named_pipe_path(filename)) |
d6410975 JS |
564 | open_fn = mingw_open_append; |
565 | else | |
566 | open_fn = _wopen; | |
567 | ||
98d9b23e JS |
568 | if (filename && !strcmp(filename, "/dev/null")) |
569 | wcscpy(wfilename, L"nul"); | |
570 | else if (xutftowcs_path(wfilename, filename) < 0) | |
85faec9d | 571 | return -1; |
98d9b23e | 572 | |
d6410975 | 573 | fd = open_fn(wfilename, oflags, mode); |
0d30ad71 | 574 | |
ba6fad02 | 575 | if (fd < 0 && (oflags & O_ACCMODE) != O_RDONLY && errno == EACCES) { |
85faec9d | 576 | DWORD attrs = GetFileAttributesW(wfilename); |
3e4a1ba0 JS |
577 | if (attrs != INVALID_FILE_ATTRIBUTES && (attrs & FILE_ATTRIBUTE_DIRECTORY)) |
578 | errno = EISDIR; | |
579 | } | |
f30afdab JS |
580 | if ((oflags & O_CREAT) && needs_hiding(filename)) { |
581 | /* | |
582 | * Internally, _wopen() uses the CreateFile() API which errors | |
583 | * out with an ERROR_ACCESS_DENIED if CREATE_ALWAYS was | |
584 | * specified and an already existing file's attributes do not | |
585 | * match *exactly*. As there is no mode or flag we can set that | |
586 | * would correspond to FILE_ATTRIBUTE_HIDDEN, let's just try | |
587 | * again *without* the O_CREAT flag (that corresponds to the | |
588 | * CREATE_ALWAYS flag of CreateFile()). | |
589 | */ | |
590 | if (fd < 0 && errno == EACCES) | |
d6410975 | 591 | fd = open_fn(wfilename, oflags & ~O_CREAT, mode); |
f30afdab JS |
592 | if (fd >= 0 && set_hidden_flag(wfilename, 1)) |
593 | warning("could not mark '%s' as hidden.", filename); | |
594 | } | |
3e4a1ba0 JS |
595 | return fd; |
596 | } | |
597 | ||
176478a8 EFL |
598 | static BOOL WINAPI ctrl_ignore(DWORD type) |
599 | { | |
600 | return TRUE; | |
601 | } | |
602 | ||
603 | #undef fgetc | |
604 | int mingw_fgetc(FILE *stream) | |
605 | { | |
606 | int ch; | |
607 | if (!isatty(_fileno(stream))) | |
608 | return fgetc(stream); | |
609 | ||
610 | SetConsoleCtrlHandler(ctrl_ignore, TRUE); | |
611 | while (1) { | |
612 | ch = fgetc(stream); | |
613 | if (ch != EOF || GetLastError() != ERROR_OPERATION_ABORTED) | |
614 | break; | |
615 | ||
616 | /* Ctrl+C was pressed, simulate SIGINT and retry */ | |
617 | mingw_raise(SIGINT); | |
618 | } | |
619 | SetConsoleCtrlHandler(ctrl_ignore, FALSE); | |
620 | return ch; | |
621 | } | |
622 | ||
3fdcdbdf JS |
623 | #undef fopen |
624 | FILE *mingw_fopen (const char *filename, const char *otype) | |
625 | { | |
f30afdab | 626 | int hide = needs_hiding(filename); |
85faec9d KB |
627 | FILE *file; |
628 | wchar_t wfilename[MAX_PATH], wotype[4]; | |
4dc42c6c JS |
629 | if (filename && !strcmp(filename, "/dev/null")) |
630 | wcscpy(wfilename, L"nul"); | |
631 | else if (!is_valid_win32_path(filename, 1)) { | |
d2c84dad JS |
632 | int create = otype && strchr(otype, 'w'); |
633 | errno = create ? EINVAL : ENOENT; | |
634 | return NULL; | |
4dc42c6c | 635 | } else if (xutftowcs_path(wfilename, filename) < 0) |
85faec9d | 636 | return NULL; |
98d9b23e JS |
637 | |
638 | if (xutftowcs(wotype, otype, ARRAY_SIZE(wotype)) < 0) | |
85faec9d | 639 | return NULL; |
98d9b23e | 640 | |
f30afdab JS |
641 | if (hide && !access(filename, F_OK) && set_hidden_flag(wfilename, 0)) { |
642 | error("could not unhide %s", filename); | |
643 | return NULL; | |
644 | } | |
85faec9d | 645 | file = _wfopen(wfilename, wotype); |
e5b31344 JS |
646 | if (!file && GetLastError() == ERROR_INVALID_NAME) |
647 | errno = ENOENT; | |
f30afdab JS |
648 | if (file && hide && set_hidden_flag(wfilename, 1)) |
649 | warning("could not mark '%s' as hidden.", filename); | |
85faec9d | 650 | return file; |
3fdcdbdf JS |
651 | } |
652 | ||
3fdcdbdf JS |
653 | FILE *mingw_freopen (const char *filename, const char *otype, FILE *stream) |
654 | { | |
f30afdab | 655 | int hide = needs_hiding(filename); |
85faec9d KB |
656 | FILE *file; |
657 | wchar_t wfilename[MAX_PATH], wotype[4]; | |
4dc42c6c JS |
658 | if (filename && !strcmp(filename, "/dev/null")) |
659 | wcscpy(wfilename, L"nul"); | |
660 | else if (!is_valid_win32_path(filename, 1)) { | |
d2c84dad JS |
661 | int create = otype && strchr(otype, 'w'); |
662 | errno = create ? EINVAL : ENOENT; | |
663 | return NULL; | |
4dc42c6c | 664 | } else if (xutftowcs_path(wfilename, filename) < 0) |
85faec9d | 665 | return NULL; |
98d9b23e JS |
666 | |
667 | if (xutftowcs(wotype, otype, ARRAY_SIZE(wotype)) < 0) | |
85faec9d | 668 | return NULL; |
98d9b23e | 669 | |
f30afdab JS |
670 | if (hide && !access(filename, F_OK) && set_hidden_flag(wfilename, 0)) { |
671 | error("could not unhide %s", filename); | |
672 | return NULL; | |
673 | } | |
85faec9d | 674 | file = _wfreopen(wfilename, wotype, stream); |
f30afdab JS |
675 | if (file && hide && set_hidden_flag(wfilename, 1)) |
676 | warning("could not mark '%s' as hidden.", filename); | |
85faec9d | 677 | return file; |
3fdcdbdf JS |
678 | } |
679 | ||
84adb641 JS |
680 | #undef fflush |
681 | int mingw_fflush(FILE *stream) | |
682 | { | |
683 | int ret = fflush(stream); | |
684 | ||
685 | /* | |
686 | * write() is used behind the scenes of stdio output functions. | |
687 | * Since git code does not check for errors after each stdio write | |
688 | * operation, it can happen that write() is called by a later | |
689 | * stdio function even if an earlier write() call failed. In the | |
690 | * case of a pipe whose readable end was closed, only the first | |
691 | * call to write() reports EPIPE on Windows. Subsequent write() | |
692 | * calls report EINVAL. It is impossible to notice whether this | |
693 | * fflush invocation triggered such a case, therefore, we have to | |
694 | * catch all EINVAL errors whole-sale. | |
695 | */ | |
696 | if (ret && errno == EINVAL) | |
697 | errno = EPIPE; | |
698 | ||
699 | return ret; | |
700 | } | |
701 | ||
2b86292e JS |
702 | #undef write |
703 | ssize_t mingw_write(int fd, const void *buf, size_t len) | |
704 | { | |
705 | ssize_t result = write(fd, buf, len); | |
706 | ||
707 | if (result < 0 && errno == EINVAL && buf) { | |
708 | /* check if fd is a pipe */ | |
709 | HANDLE h = (HANDLE) _get_osfhandle(fd); | |
710 | if (GetFileType(h) == FILE_TYPE_PIPE) | |
711 | errno = EPIPE; | |
712 | else | |
713 | errno = EINVAL; | |
714 | } | |
715 | ||
716 | return result; | |
717 | } | |
718 | ||
85faec9d KB |
719 | int mingw_access(const char *filename, int mode) |
720 | { | |
721 | wchar_t wfilename[MAX_PATH]; | |
9160068a JS |
722 | if (!strcmp("nul", filename) || !strcmp("/dev/null", filename)) |
723 | return 0; | |
85faec9d KB |
724 | if (xutftowcs_path(wfilename, filename) < 0) |
725 | return -1; | |
726 | /* X_OK is not supported by the MSVCRT version */ | |
727 | return _waccess(wfilename, mode & ~X_OK); | |
728 | } | |
729 | ||
730 | int mingw_chdir(const char *dirname) | |
731 | { | |
732 | wchar_t wdirname[MAX_PATH]; | |
733 | if (xutftowcs_path(wdirname, dirname) < 0) | |
734 | return -1; | |
735 | return _wchdir(wdirname); | |
736 | } | |
737 | ||
738 | int mingw_chmod(const char *filename, int mode) | |
739 | { | |
740 | wchar_t wfilename[MAX_PATH]; | |
741 | if (xutftowcs_path(wfilename, filename) < 0) | |
742 | return -1; | |
743 | return _wchmod(wfilename, mode); | |
744 | } | |
745 | ||
a6d15bc3 JS |
746 | /* |
747 | * The unit of FILETIME is 100-nanoseconds since January 1, 1601, UTC. | |
748 | * Returns the 100-nanoseconds ("hekto nanoseconds") since the epoch. | |
749 | */ | |
750 | static inline long long filetime_to_hnsec(const FILETIME *ft) | |
5411bdc4 MSO |
751 | { |
752 | long long winTime = ((long long)ft->dwHighDateTime << 32) + ft->dwLowDateTime; | |
a6d15bc3 JS |
753 | /* Windows to Unix Epoch conversion */ |
754 | return winTime - 116444736000000000LL; | |
755 | } | |
756 | ||
d7e8c874 | 757 | static inline void filetime_to_timespec(const FILETIME *ft, struct timespec *ts) |
a6d15bc3 | 758 | { |
d7e8c874 KB |
759 | long long hnsec = filetime_to_hnsec(ft); |
760 | ts->tv_sec = (time_t)(hnsec / 10000000); | |
761 | ts->tv_nsec = (hnsec % 10000000) * 100; | |
5411bdc4 MSO |
762 | } |
763 | ||
4b0abd5c JS |
764 | /** |
765 | * Verifies that safe_create_leading_directories() would succeed. | |
766 | */ | |
767 | static int has_valid_directory_prefix(wchar_t *wfilename) | |
768 | { | |
769 | int n = wcslen(wfilename); | |
770 | ||
771 | while (n > 0) { | |
772 | wchar_t c = wfilename[--n]; | |
773 | DWORD attributes; | |
774 | ||
775 | if (!is_dir_sep(c)) | |
776 | continue; | |
777 | ||
778 | wfilename[n] = L'\0'; | |
779 | attributes = GetFileAttributesW(wfilename); | |
780 | wfilename[n] = c; | |
82ba1191 JS |
781 | if (attributes & |
782 | (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_DEVICE)) | |
4b0abd5c JS |
783 | return 1; |
784 | if (attributes == INVALID_FILE_ATTRIBUTES) | |
785 | switch (GetLastError()) { | |
786 | case ERROR_PATH_NOT_FOUND: | |
787 | continue; | |
788 | case ERROR_FILE_NOT_FOUND: | |
789 | /* This implies parent directory exists. */ | |
790 | return 1; | |
791 | } | |
792 | return 0; | |
793 | } | |
794 | return 1; | |
795 | } | |
796 | ||
5411bdc4 MSO |
797 | /* We keep the do_lstat code in a separate function to avoid recursion. |
798 | * When a path ends with a slash, the stat will fail with ENOENT. In | |
799 | * this case, we strip the trailing slashes and stat again. | |
9b9784ca PT |
800 | * |
801 | * If follow is true then act like stat() and report on the link | |
802 | * target. Otherwise report on the link itself. | |
5411bdc4 | 803 | */ |
9b9784ca | 804 | static int do_lstat(int follow, const char *file_name, struct stat *buf) |
5411bdc4 MSO |
805 | { |
806 | WIN32_FILE_ATTRIBUTE_DATA fdata; | |
85faec9d KB |
807 | wchar_t wfilename[MAX_PATH]; |
808 | if (xutftowcs_path(wfilename, file_name) < 0) | |
809 | return -1; | |
5411bdc4 | 810 | |
85faec9d | 811 | if (GetFileAttributesExW(wfilename, GetFileExInfoStandard, &fdata)) { |
5411bdc4 MSO |
812 | buf->st_ino = 0; |
813 | buf->st_gid = 0; | |
814 | buf->st_uid = 0; | |
180964f0 | 815 | buf->st_nlink = 1; |
444dc903 | 816 | buf->st_mode = file_attr_to_st_mode(fdata.dwFileAttributes); |
1d4e4cd4 JS |
817 | buf->st_size = fdata.nFileSizeLow | |
818 | (((off_t)fdata.nFileSizeHigh)<<32); | |
8252df62 | 819 | buf->st_dev = buf->st_rdev = 0; /* not used by Git */ |
d7e8c874 KB |
820 | filetime_to_timespec(&(fdata.ftLastAccessTime), &(buf->st_atim)); |
821 | filetime_to_timespec(&(fdata.ftLastWriteTime), &(buf->st_mtim)); | |
822 | filetime_to_timespec(&(fdata.ftCreationTime), &(buf->st_ctim)); | |
9b9784ca | 823 | if (fdata.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) { |
85faec9d KB |
824 | WIN32_FIND_DATAW findbuf; |
825 | HANDLE handle = FindFirstFileW(wfilename, &findbuf); | |
9b9784ca PT |
826 | if (handle != INVALID_HANDLE_VALUE) { |
827 | if ((findbuf.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) && | |
828 | (findbuf.dwReserved0 == IO_REPARSE_TAG_SYMLINK)) { | |
829 | if (follow) { | |
830 | char buffer[MAXIMUM_REPARSE_DATA_BUFFER_SIZE]; | |
831 | buf->st_size = readlink(file_name, buffer, MAXIMUM_REPARSE_DATA_BUFFER_SIZE); | |
832 | } else { | |
833 | buf->st_mode = S_IFLNK; | |
834 | } | |
835 | buf->st_mode |= S_IREAD; | |
836 | if (!(findbuf.dwFileAttributes & FILE_ATTRIBUTE_READONLY)) | |
837 | buf->st_mode |= S_IWRITE; | |
838 | } | |
839 | FindClose(handle); | |
840 | } | |
841 | } | |
5411bdc4 MSO |
842 | return 0; |
843 | } | |
85faec9d KB |
844 | switch (GetLastError()) { |
845 | case ERROR_ACCESS_DENIED: | |
846 | case ERROR_SHARING_VIOLATION: | |
847 | case ERROR_LOCK_VIOLATION: | |
848 | case ERROR_SHARING_BUFFER_EXCEEDED: | |
849 | errno = EACCES; | |
850 | break; | |
851 | case ERROR_BUFFER_OVERFLOW: | |
852 | errno = ENAMETOOLONG; | |
853 | break; | |
854 | case ERROR_NOT_ENOUGH_MEMORY: | |
855 | errno = ENOMEM; | |
856 | break; | |
4b0abd5c JS |
857 | case ERROR_PATH_NOT_FOUND: |
858 | if (!has_valid_directory_prefix(wfilename)) { | |
859 | errno = ENOTDIR; | |
860 | break; | |
861 | } | |
862 | /* fallthru */ | |
85faec9d KB |
863 | default: |
864 | errno = ENOENT; | |
865 | break; | |
866 | } | |
5411bdc4 MSO |
867 | return -1; |
868 | } | |
869 | ||
870 | /* We provide our own lstat/fstat functions, since the provided | |
871 | * lstat/fstat functions are so slow. These stat functions are | |
872 | * tailored for Git's usage (read: fast), and are not meant to be | |
873 | * complete. Note that Git stat()s are redirected to mingw_lstat() | |
874 | * too, since Windows doesn't really handle symlinks that well. | |
875 | */ | |
9b9784ca | 876 | static int do_stat_internal(int follow, const char *file_name, struct stat *buf) |
5411bdc4 MSO |
877 | { |
878 | int namelen; | |
58aa3d2a | 879 | char alt_name[PATH_MAX]; |
5411bdc4 | 880 | |
9b9784ca | 881 | if (!do_lstat(follow, file_name, buf)) |
5411bdc4 MSO |
882 | return 0; |
883 | ||
884 | /* if file_name ended in a '/', Windows returned ENOENT; | |
885 | * try again without trailing slashes | |
886 | */ | |
887 | if (errno != ENOENT) | |
888 | return -1; | |
889 | ||
890 | namelen = strlen(file_name); | |
891 | if (namelen && file_name[namelen-1] != '/') | |
892 | return -1; | |
893 | while (namelen && file_name[namelen-1] == '/') | |
894 | --namelen; | |
895 | if (!namelen || namelen >= PATH_MAX) | |
896 | return -1; | |
897 | ||
898 | memcpy(alt_name, file_name, namelen); | |
899 | alt_name[namelen] = 0; | |
9b9784ca PT |
900 | return do_lstat(follow, alt_name, buf); |
901 | } | |
902 | ||
7bf19838 JS |
903 | static int get_file_info_by_handle(HANDLE hnd, struct stat *buf) |
904 | { | |
905 | BY_HANDLE_FILE_INFORMATION fdata; | |
906 | ||
907 | if (!GetFileInformationByHandle(hnd, &fdata)) { | |
908 | errno = err_win_to_posix(GetLastError()); | |
909 | return -1; | |
910 | } | |
911 | ||
912 | buf->st_ino = 0; | |
913 | buf->st_gid = 0; | |
914 | buf->st_uid = 0; | |
915 | buf->st_nlink = 1; | |
916 | buf->st_mode = file_attr_to_st_mode(fdata.dwFileAttributes); | |
917 | buf->st_size = fdata.nFileSizeLow | | |
918 | (((off_t)fdata.nFileSizeHigh)<<32); | |
919 | buf->st_dev = buf->st_rdev = 0; /* not used by Git */ | |
d7e8c874 KB |
920 | filetime_to_timespec(&(fdata.ftLastAccessTime), &(buf->st_atim)); |
921 | filetime_to_timespec(&(fdata.ftLastWriteTime), &(buf->st_mtim)); | |
922 | filetime_to_timespec(&(fdata.ftCreationTime), &(buf->st_ctim)); | |
7bf19838 JS |
923 | return 0; |
924 | } | |
925 | ||
9b9784ca PT |
926 | int mingw_lstat(const char *file_name, struct stat *buf) |
927 | { | |
928 | return do_stat_internal(0, file_name, buf); | |
929 | } | |
930 | int mingw_stat(const char *file_name, struct stat *buf) | |
931 | { | |
932 | return do_stat_internal(1, file_name, buf); | |
5411bdc4 MSO |
933 | } |
934 | ||
180964f0 | 935 | int mingw_fstat(int fd, struct stat *buf) |
5411bdc4 MSO |
936 | { |
937 | HANDLE fh = (HANDLE)_get_osfhandle(fd); | |
d75e6973 | 938 | DWORD avail, type = GetFileType(fh) & ~FILE_TYPE_REMOTE; |
5411bdc4 | 939 | |
d75e6973 KB |
940 | switch (type) { |
941 | case FILE_TYPE_DISK: | |
942 | return get_file_info_by_handle(fh, buf); | |
5411bdc4 | 943 | |
d75e6973 KB |
944 | case FILE_TYPE_CHAR: |
945 | case FILE_TYPE_PIPE: | |
946 | /* initialize stat fields */ | |
947 | memset(buf, 0, sizeof(*buf)); | |
180964f0 | 948 | buf->st_nlink = 1; |
d75e6973 KB |
949 | |
950 | if (type == FILE_TYPE_CHAR) { | |
951 | buf->st_mode = _S_IFCHR; | |
952 | } else { | |
953 | buf->st_mode = _S_IFIFO; | |
954 | if (PeekNamedPipe(fh, NULL, 0, NULL, &avail, NULL)) | |
955 | buf->st_size = avail; | |
956 | } | |
5411bdc4 | 957 | return 0; |
7bf19838 | 958 | |
d75e6973 KB |
959 | default: |
960 | errno = EBADF; | |
961 | return -1; | |
5411bdc4 | 962 | } |
5411bdc4 MSO |
963 | } |
964 | ||
7c0ffa1c JS |
965 | static inline void time_t_to_filetime(time_t t, FILETIME *ft) |
966 | { | |
967 | long long winTime = t * 10000000LL + 116444736000000000LL; | |
968 | ft->dwLowDateTime = winTime; | |
969 | ft->dwHighDateTime = winTime >> 32; | |
970 | } | |
971 | ||
972 | int mingw_utime (const char *file_name, const struct utimbuf *times) | |
973 | { | |
974 | FILETIME mft, aft; | |
090a3085 | 975 | int rc; |
85faec9d KB |
976 | DWORD attrs; |
977 | wchar_t wfilename[MAX_PATH]; | |
090a3085 TK |
978 | HANDLE osfilehandle; |
979 | ||
85faec9d KB |
980 | if (xutftowcs_path(wfilename, file_name) < 0) |
981 | return -1; | |
7c0ffa1c JS |
982 | |
983 | /* must have write permission */ | |
85faec9d | 984 | attrs = GetFileAttributesW(wfilename); |
852f098c JS |
985 | if (attrs != INVALID_FILE_ATTRIBUTES && |
986 | (attrs & FILE_ATTRIBUTE_READONLY)) { | |
987 | /* ignore errors here; open() will report them */ | |
85faec9d | 988 | SetFileAttributesW(wfilename, attrs & ~FILE_ATTRIBUTE_READONLY); |
852f098c JS |
989 | } |
990 | ||
090a3085 TK |
991 | osfilehandle = CreateFileW(wfilename, |
992 | FILE_WRITE_ATTRIBUTES, | |
993 | 0 /*FileShare.None*/, | |
994 | NULL, | |
995 | OPEN_EXISTING, | |
996 | (attrs != INVALID_FILE_ATTRIBUTES && | |
997 | (attrs & FILE_ATTRIBUTE_DIRECTORY)) ? | |
998 | FILE_FLAG_BACKUP_SEMANTICS : 0, | |
999 | NULL); | |
1000 | if (osfilehandle == INVALID_HANDLE_VALUE) { | |
1001 | errno = err_win_to_posix(GetLastError()); | |
852f098c JS |
1002 | rc = -1; |
1003 | goto revert_attrs; | |
1004 | } | |
7c0ffa1c | 1005 | |
ded2d476 SG |
1006 | if (times) { |
1007 | time_t_to_filetime(times->modtime, &mft); | |
1008 | time_t_to_filetime(times->actime, &aft); | |
1009 | } else { | |
1010 | GetSystemTimeAsFileTime(&mft); | |
1011 | aft = mft; | |
1012 | } | |
090a3085 TK |
1013 | |
1014 | if (!SetFileTime(osfilehandle, NULL, &aft, &mft)) { | |
7c0ffa1c JS |
1015 | errno = EINVAL; |
1016 | rc = -1; | |
1017 | } else | |
1018 | rc = 0; | |
090a3085 TK |
1019 | |
1020 | if (osfilehandle != INVALID_HANDLE_VALUE) | |
1021 | CloseHandle(osfilehandle); | |
852f098c JS |
1022 | |
1023 | revert_attrs: | |
1024 | if (attrs != INVALID_FILE_ATTRIBUTES && | |
1025 | (attrs & FILE_ATTRIBUTE_READONLY)) { | |
1026 | /* ignore errors again */ | |
85faec9d | 1027 | SetFileAttributesW(wfilename, attrs); |
852f098c | 1028 | } |
7c0ffa1c JS |
1029 | return rc; |
1030 | } | |
1031 | ||
9ee0540a JS |
1032 | #undef strftime |
1033 | size_t mingw_strftime(char *s, size_t max, | |
1034 | const char *format, const struct tm *tm) | |
1035 | { | |
a748f3f3 MA |
1036 | /* a pointer to the original strftime in case we can't find the UCRT version */ |
1037 | static size_t (*fallback)(char *, size_t, const char *, const struct tm *) = strftime; | |
1038 | size_t ret; | |
4a9b2049 | 1039 | DECLARE_PROC_ADDR(ucrtbase.dll, size_t, __cdecl, strftime, char *, size_t, |
a748f3f3 MA |
1040 | const char *, const struct tm *); |
1041 | ||
1042 | if (INIT_PROC_ADDR(strftime)) | |
1043 | ret = strftime(s, max, format, tm); | |
1044 | else | |
1045 | ret = fallback(s, max, format, tm); | |
9ee0540a JS |
1046 | |
1047 | if (!ret && errno == EINVAL) | |
1048 | die("invalid strftime format: '%s'", format); | |
1049 | return ret; | |
1050 | } | |
1051 | ||
f4626df5 JS |
1052 | unsigned int sleep (unsigned int seconds) |
1053 | { | |
1054 | Sleep(seconds*1000); | |
1055 | return 0; | |
1056 | } | |
1057 | ||
85faec9d KB |
1058 | char *mingw_mktemp(char *template) |
1059 | { | |
1060 | wchar_t wtemplate[MAX_PATH]; | |
1061 | if (xutftowcs_path(wtemplate, template) < 0) | |
1062 | return NULL; | |
1063 | if (!_wmktemp(wtemplate)) | |
1064 | return NULL; | |
1065 | if (xwcstoutf(template, wtemplate, strlen(template) + 1) < 0) | |
1066 | return NULL; | |
1067 | return template; | |
1068 | } | |
1069 | ||
f4626df5 JS |
1070 | int mkstemp(char *template) |
1071 | { | |
ae25974d | 1072 | return git_mkstemp_mode(template, 0600); |
f4626df5 JS |
1073 | } |
1074 | ||
1075 | int gettimeofday(struct timeval *tv, void *tz) | |
1076 | { | |
a6d15bc3 JS |
1077 | FILETIME ft; |
1078 | long long hnsec; | |
1079 | ||
1080 | GetSystemTimeAsFileTime(&ft); | |
1081 | hnsec = filetime_to_hnsec(&ft); | |
1082 | tv->tv_sec = hnsec / 10000000; | |
1083 | tv->tv_usec = (hnsec % 10000000) / 10; | |
a42a0c2e | 1084 | return 0; |
f4626df5 JS |
1085 | } |
1086 | ||
897bb8cb JS |
1087 | int pipe(int filedes[2]) |
1088 | { | |
3e34d665 | 1089 | HANDLE h[2]; |
897bb8cb | 1090 | |
3e34d665 JS |
1091 | /* this creates non-inheritable handles */ |
1092 | if (!CreatePipe(&h[0], &h[1], NULL, 8192)) { | |
1093 | errno = err_win_to_posix(GetLastError()); | |
897bb8cb JS |
1094 | return -1; |
1095 | } | |
7c00bc39 | 1096 | filedes[0] = _open_osfhandle(HCAST(int, h[0]), O_NOINHERIT); |
3e34d665 | 1097 | if (filedes[0] < 0) { |
897bb8cb JS |
1098 | CloseHandle(h[0]); |
1099 | CloseHandle(h[1]); | |
1100 | return -1; | |
1101 | } | |
7c00bc39 | 1102 | filedes[1] = _open_osfhandle(HCAST(int, h[1]), O_NOINHERIT); |
c3cb7b6f | 1103 | if (filedes[1] < 0) { |
897bb8cb | 1104 | close(filedes[0]); |
897bb8cb JS |
1105 | CloseHandle(h[1]); |
1106 | return -1; | |
1107 | } | |
897bb8cb JS |
1108 | return 0; |
1109 | } | |
1110 | ||
9e12400d | 1111 | #ifndef __MINGW64__ |
f4626df5 JS |
1112 | struct tm *gmtime_r(const time_t *timep, struct tm *result) |
1113 | { | |
0109d676 ĐTCD |
1114 | if (gmtime_s(result, timep) == 0) |
1115 | return result; | |
1116 | return NULL; | |
f4626df5 JS |
1117 | } |
1118 | ||
1119 | struct tm *localtime_r(const time_t *timep, struct tm *result) | |
1120 | { | |
0109d676 ĐTCD |
1121 | if (localtime_s(result, timep) == 0) |
1122 | return result; | |
1123 | return NULL; | |
f4626df5 | 1124 | } |
9e12400d | 1125 | #endif |
f4626df5 | 1126 | |
25fe217b JS |
1127 | char *mingw_getcwd(char *pointer, int len) |
1128 | { | |
937974fc JS |
1129 | wchar_t cwd[MAX_PATH], wpointer[MAX_PATH]; |
1130 | DWORD ret = GetCurrentDirectoryW(ARRAY_SIZE(cwd), cwd); | |
1131 | ||
1132 | if (!ret || ret >= ARRAY_SIZE(cwd)) { | |
1133 | errno = ret ? ENAMETOOLONG : err_win_to_posix(GetLastError()); | |
1134 | return NULL; | |
1135 | } | |
1136 | ret = GetLongPathNameW(cwd, wpointer, ARRAY_SIZE(wpointer)); | |
4745feeb AS |
1137 | if (!ret && GetLastError() == ERROR_ACCESS_DENIED) { |
1138 | HANDLE hnd = CreateFileW(cwd, 0, | |
1139 | FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, | |
1140 | OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL); | |
1141 | if (hnd == INVALID_HANDLE_VALUE) | |
1142 | return NULL; | |
1143 | ret = GetFinalPathNameByHandleW(hnd, wpointer, ARRAY_SIZE(wpointer), 0); | |
1144 | CloseHandle(hnd); | |
1145 | if (!ret || ret >= ARRAY_SIZE(wpointer)) | |
1146 | return NULL; | |
1147 | if (xwcstoutf(pointer, normalize_ntpath(wpointer), len) < 0) | |
1148 | return NULL; | |
1149 | return pointer; | |
1150 | } | |
937974fc | 1151 | if (!ret || ret >= ARRAY_SIZE(wpointer)) |
85faec9d | 1152 | return NULL; |
e2724c1e JS |
1153 | if (GetFileAttributesW(wpointer) == INVALID_FILE_ATTRIBUTES) { |
1154 | errno = ENOENT; | |
1155 | return NULL; | |
1156 | } | |
85faec9d KB |
1157 | if (xwcstoutf(pointer, wpointer, len) < 0) |
1158 | return NULL; | |
8e9b2080 | 1159 | convert_slashes(pointer); |
85faec9d | 1160 | return pointer; |
25fe217b JS |
1161 | } |
1162 | ||
7e5d7768 | 1163 | /* |
2ef2ae29 JS |
1164 | * See "Parsing C++ Command-Line Arguments" at Microsoft's Docs: |
1165 | * https://docs.microsoft.com/en-us/cpp/cpp/parsing-cpp-command-line-arguments | |
7e5d7768 | 1166 | */ |
9e9da23c | 1167 | static const char *quote_arg_msvc(const char *arg) |
7e5d7768 JS |
1168 | { |
1169 | /* count chars to quote */ | |
1170 | int len = 0, n = 0; | |
1171 | int force_quotes = 0; | |
1172 | char *q, *d; | |
1173 | const char *p = arg; | |
1174 | if (!*p) force_quotes = 1; | |
1175 | while (*p) { | |
3aea1a5a | 1176 | if (isspace(*p) || *p == '*' || *p == '?' || *p == '{' || *p == '\'') |
7e5d7768 JS |
1177 | force_quotes = 1; |
1178 | else if (*p == '"') | |
1179 | n++; | |
1180 | else if (*p == '\\') { | |
1181 | int count = 0; | |
1182 | while (*p == '\\') { | |
1183 | count++; | |
1184 | p++; | |
1185 | len++; | |
1186 | } | |
6d868416 | 1187 | if (*p == '"' || !*p) |
7e5d7768 JS |
1188 | n += count*2 + 1; |
1189 | continue; | |
1190 | } | |
1191 | len++; | |
1192 | p++; | |
1193 | } | |
1194 | if (!force_quotes && n == 0) | |
1195 | return arg; | |
1196 | ||
1197 | /* insert \ where necessary */ | |
50a6c8ef | 1198 | d = q = xmalloc(st_add3(len, n, 3)); |
7e5d7768 JS |
1199 | *d++ = '"'; |
1200 | while (*arg) { | |
1201 | if (*arg == '"') | |
1202 | *d++ = '\\'; | |
1203 | else if (*arg == '\\') { | |
1204 | int count = 0; | |
1205 | while (*arg == '\\') { | |
1206 | count++; | |
1207 | *d++ = *arg++; | |
1208 | } | |
6d868416 | 1209 | if (*arg == '"' || !*arg) { |
7e5d7768 JS |
1210 | while (count-- > 0) |
1211 | *d++ = '\\'; | |
6d868416 JS |
1212 | /* don't escape the surrounding end quote */ |
1213 | if (!*arg) | |
1214 | break; | |
7e5d7768 JS |
1215 | *d++ = '\\'; |
1216 | } | |
1217 | } | |
1218 | *d++ = *arg++; | |
1219 | } | |
1220 | *d++ = '"'; | |
6d868416 | 1221 | *d++ = '\0'; |
7e5d7768 JS |
1222 | return q; |
1223 | } | |
1224 | ||
9e9da23c JS |
1225 | #include "quote.h" |
1226 | ||
1227 | static const char *quote_arg_msys2(const char *arg) | |
1228 | { | |
1229 | struct strbuf buf = STRBUF_INIT; | |
1230 | const char *p2 = arg, *p; | |
1231 | ||
1232 | for (p = arg; *p; p++) { | |
1233 | int ws = isspace(*p); | |
7d8b6769 JS |
1234 | if (!ws && *p != '\\' && *p != '"' && *p != '{' && *p != '\'' && |
1235 | *p != '?' && *p != '*' && *p != '~') | |
9e9da23c JS |
1236 | continue; |
1237 | if (!buf.len) | |
1238 | strbuf_addch(&buf, '"'); | |
1239 | if (p != p2) | |
1240 | strbuf_add(&buf, p2, p - p2); | |
7d8b6769 | 1241 | if (*p == '\\' || *p == '"') |
9e9da23c JS |
1242 | strbuf_addch(&buf, '\\'); |
1243 | p2 = p; | |
1244 | } | |
1245 | ||
1246 | if (p == arg) | |
1247 | strbuf_addch(&buf, '"'); | |
1248 | else if (!buf.len) | |
1249 | return arg; | |
1250 | else | |
04522edb | 1251 | strbuf_add(&buf, p2, p - p2); |
9e9da23c JS |
1252 | |
1253 | strbuf_addch(&buf, '"'); | |
1254 | return strbuf_detach(&buf, 0); | |
1255 | } | |
1256 | ||
f1a4dfb8 JS |
1257 | static const char *parse_interpreter(const char *cmd) |
1258 | { | |
1259 | static char buf[100]; | |
1260 | char *p, *opt; | |
1261 | int n, fd; | |
1262 | ||
1263 | /* don't even try a .exe */ | |
1264 | n = strlen(cmd); | |
1265 | if (n >= 4 && !strcasecmp(cmd+n-4, ".exe")) | |
1266 | return NULL; | |
1267 | ||
1268 | fd = open(cmd, O_RDONLY); | |
1269 | if (fd < 0) | |
1270 | return NULL; | |
1271 | n = read(fd, buf, sizeof(buf)-1); | |
1272 | close(fd); | |
1273 | if (n < 4) /* at least '#!/x' and not error */ | |
1274 | return NULL; | |
1275 | ||
1276 | if (buf[0] != '#' || buf[1] != '!') | |
1277 | return NULL; | |
1278 | buf[n] = '\0'; | |
bedc4279 PH |
1279 | p = buf + strcspn(buf, "\r\n"); |
1280 | if (!*p) | |
f1a4dfb8 JS |
1281 | return NULL; |
1282 | ||
1283 | *p = '\0'; | |
1284 | if (!(p = strrchr(buf+2, '/')) && !(p = strrchr(buf+2, '\\'))) | |
1285 | return NULL; | |
1286 | /* strip options */ | |
1287 | if ((opt = strchr(p+1, ' '))) | |
1288 | *opt = '\0'; | |
1289 | return p+1; | |
1290 | } | |
1291 | ||
f1a4dfb8 JS |
1292 | /* |
1293 | * exe_only means that we only want to detect .exe files, but not scripts | |
1294 | * (which do not have an extension) | |
1295 | */ | |
e0ca1ca2 RS |
1296 | static char *lookup_prog(const char *dir, int dirlen, const char *cmd, |
1297 | int isexe, int exe_only) | |
f1a4dfb8 JS |
1298 | { |
1299 | char path[MAX_PATH]; | |
4e1a641e | 1300 | wchar_t wpath[MAX_PATH]; |
e0ca1ca2 | 1301 | snprintf(path, sizeof(path), "%.*s\\%s.exe", dirlen, dir, cmd); |
f1a4dfb8 | 1302 | |
4e1a641e AR |
1303 | if (xutftowcs_path(wpath, path) < 0) |
1304 | return NULL; | |
1305 | ||
1306 | if (!isexe && _waccess(wpath, F_OK) == 0) | |
f1a4dfb8 | 1307 | return xstrdup(path); |
4e1a641e AR |
1308 | wpath[wcslen(wpath)-4] = '\0'; |
1309 | if ((!exe_only || isexe) && _waccess(wpath, F_OK) == 0) { | |
1310 | if (!(GetFileAttributesW(wpath) & FILE_ATTRIBUTE_DIRECTORY)) { | |
1311 | path[strlen(path)-4] = '\0'; | |
fe77b695 | 1312 | return xstrdup(path); |
4e1a641e AR |
1313 | } |
1314 | } | |
f1a4dfb8 JS |
1315 | return NULL; |
1316 | } | |
1317 | ||
1318 | /* | |
22e5e58a | 1319 | * Determines the absolute path of cmd using the split path in path. |
f1a4dfb8 JS |
1320 | * If cmd contains a slash or backslash, no lookup is performed. |
1321 | */ | |
e0ca1ca2 | 1322 | static char *path_lookup(const char *cmd, int exe_only) |
f1a4dfb8 | 1323 | { |
e0ca1ca2 | 1324 | const char *path; |
f1a4dfb8 JS |
1325 | char *prog = NULL; |
1326 | int len = strlen(cmd); | |
1327 | int isexe = len >= 4 && !strcasecmp(cmd+len-4, ".exe"); | |
1328 | ||
2ce6d075 | 1329 | if (strpbrk(cmd, "/\\")) |
e0ca1ca2 RS |
1330 | return xstrdup(cmd); |
1331 | ||
1332 | path = mingw_getenv("PATH"); | |
1333 | if (!path) | |
1334 | return NULL; | |
f1a4dfb8 | 1335 | |
e0ca1ca2 RS |
1336 | while (!prog) { |
1337 | const char *sep = strchrnul(path, ';'); | |
1338 | int dirlen = sep - path; | |
1339 | if (dirlen) | |
1340 | prog = lookup_prog(path, dirlen, cmd, isexe, exe_only); | |
1341 | if (!*sep) | |
1342 | break; | |
1343 | path = sep + 1; | |
1344 | } | |
f1a4dfb8 JS |
1345 | |
1346 | return prog; | |
1347 | } | |
1348 | ||
fe21c6b2 JS |
1349 | static const wchar_t *wcschrnul(const wchar_t *s, wchar_t c) |
1350 | { | |
1351 | while (*s && *s != c) | |
1352 | s++; | |
1353 | return s; | |
1354 | } | |
1355 | ||
1356 | /* Compare only keys */ | |
1357 | static int wenvcmp(const void *a, const void *b) | |
1358 | { | |
1359 | wchar_t *p = *(wchar_t **)a, *q = *(wchar_t **)b; | |
1360 | size_t p_len, q_len; | |
1361 | ||
1362 | /* Find the keys */ | |
1363 | p_len = wcschrnul(p, L'=') - p; | |
1364 | q_len = wcschrnul(q, L'=') - q; | |
f279242d | 1365 | |
fe21c6b2 JS |
1366 | /* If the length differs, include the shorter key's NUL */ |
1367 | if (p_len < q_len) | |
1368 | p_len++; | |
1369 | else if (p_len > q_len) | |
1370 | p_len = q_len + 1; | |
1371 | ||
1372 | return _wcsnicmp(p, q, p_len); | |
1373 | } | |
f279242d | 1374 | |
df0e998c | 1375 | /* |
fe21c6b2 JS |
1376 | * Build an environment block combining the inherited environment |
1377 | * merged with the given list of settings. | |
1378 | * | |
1379 | * Values of the form "KEY=VALUE" in deltaenv override inherited values. | |
1380 | * Values of the form "KEY" in deltaenv delete inherited values. | |
1381 | * | |
1382 | * Multiple entries in deltaenv for the same key are explicitly allowed. | |
1383 | * | |
1384 | * We return a contiguous block of UNICODE strings with a final trailing | |
1385 | * zero word. | |
df0e998c | 1386 | */ |
77734da2 | 1387 | static wchar_t *make_environment_block(char **deltaenv) |
7e5d7768 | 1388 | { |
fe21c6b2 JS |
1389 | wchar_t *wenv = GetEnvironmentStringsW(), *wdeltaenv, *result, *p; |
1390 | size_t wlen, s, delta_size, size; | |
df0e998c | 1391 | |
fe21c6b2 JS |
1392 | wchar_t **array = NULL; |
1393 | size_t alloc = 0, nr = 0, i; | |
df0e998c | 1394 | |
fe21c6b2 JS |
1395 | size = 1; /* for extra NUL at the end */ |
1396 | ||
1397 | /* If there is no deltaenv to apply, simply return a copy. */ | |
1398 | if (!deltaenv || !*deltaenv) { | |
1399 | for (p = wenv; p && *p; ) { | |
1400 | size_t s = wcslen(p) + 1; | |
1401 | size += s; | |
1402 | p += s; | |
1403 | } | |
77734da2 | 1404 | |
6e578410 | 1405 | DUP_ARRAY(result, wenv, size); |
fe21c6b2 JS |
1406 | FreeEnvironmentStringsW(wenv); |
1407 | return result; | |
1408 | } | |
77734da2 | 1409 | |
fe21c6b2 JS |
1410 | /* |
1411 | * If there is a deltaenv, let's accumulate all keys into `array`, | |
97fff610 JS |
1412 | * sort them using the stable git_stable_qsort() and then copy, |
1413 | * skipping duplicate keys | |
fe21c6b2 JS |
1414 | */ |
1415 | for (p = wenv; p && *p; ) { | |
1416 | ALLOC_GROW(array, nr + 1, alloc); | |
1417 | s = wcslen(p) + 1; | |
1418 | array[nr++] = p; | |
1419 | p += s; | |
1420 | size += s; | |
df0e998c | 1421 | } |
fe21c6b2 JS |
1422 | |
1423 | /* (over-)assess size needed for wchar version of deltaenv */ | |
1424 | for (delta_size = 0, i = 0; deltaenv[i]; i++) | |
1425 | delta_size += strlen(deltaenv[i]) * 2 + 1; | |
1426 | ALLOC_ARRAY(wdeltaenv, delta_size); | |
1427 | ||
1428 | /* convert the deltaenv, appending to array */ | |
1429 | for (i = 0, p = wdeltaenv; deltaenv[i]; i++) { | |
1430 | ALLOC_GROW(array, nr + 1, alloc); | |
1431 | wlen = xutftowcs(p, deltaenv[i], wdeltaenv + delta_size - p); | |
1432 | array[nr++] = p; | |
1433 | p += wlen + 1; | |
1434 | } | |
df0e998c | 1435 | |
97fff610 | 1436 | git_stable_qsort(array, nr, sizeof(*array), wenvcmp); |
fe21c6b2 | 1437 | ALLOC_ARRAY(result, size + delta_size); |
df0e998c | 1438 | |
fe21c6b2 JS |
1439 | for (p = result, i = 0; i < nr; i++) { |
1440 | /* Skip any duplicate keys; last one wins */ | |
1441 | while (i + 1 < nr && !wenvcmp(array + i, array + i + 1)) | |
1442 | i++; | |
77734da2 | 1443 | |
fe21c6b2 JS |
1444 | /* Skip "to delete" entry */ |
1445 | if (!wcschr(array[i], L'=')) | |
1446 | continue; | |
77734da2 | 1447 | |
fe21c6b2 | 1448 | size = wcslen(array[i]) + 1; |
552fc501 | 1449 | COPY_ARRAY(p, array[i], size); |
fe21c6b2 | 1450 | p += size; |
df0e998c | 1451 | } |
fe21c6b2 JS |
1452 | *p = L'\0'; |
1453 | ||
1454 | free(array); | |
1455 | free(wdeltaenv); | |
1456 | FreeEnvironmentStringsW(wenv); | |
1457 | return result; | |
7e5d7768 JS |
1458 | } |
1459 | ||
0e218f91 JS |
1460 | static void do_unset_environment_variables(void) |
1461 | { | |
1462 | static int done; | |
1463 | char *p = unset_environment_variables; | |
1464 | ||
1465 | if (done || !p) | |
1466 | return; | |
1467 | done = 1; | |
1468 | ||
1469 | for (;;) { | |
1470 | char *comma = strchr(p, ','); | |
1471 | ||
1472 | if (comma) | |
1473 | *comma = '\0'; | |
1474 | unsetenv(p); | |
1475 | if (!comma) | |
1476 | break; | |
1477 | p = comma + 1; | |
1478 | } | |
1479 | } | |
1480 | ||
52de4db5 EFL |
1481 | struct pinfo_t { |
1482 | struct pinfo_t *next; | |
1483 | pid_t pid; | |
1484 | HANDLE proc; | |
657b35f4 RJ |
1485 | }; |
1486 | static struct pinfo_t *pinfo = NULL; | |
52de4db5 EFL |
1487 | CRITICAL_SECTION pinfo_cs; |
1488 | ||
9e9da23c JS |
1489 | /* Used to match and chomp off path components */ |
1490 | static inline int match_last_path_component(const char *path, size_t *len, | |
1491 | const char *component) | |
1492 | { | |
1493 | size_t component_len = strlen(component); | |
1494 | if (*len < component_len + 1 || | |
1495 | !is_dir_sep(path[*len - component_len - 1]) || | |
1496 | fspathncmp(path + *len - component_len, component, component_len)) | |
1497 | return 0; | |
1498 | *len -= component_len + 1; | |
1499 | /* chomp off repeated dir separators */ | |
1500 | while (*len > 0 && is_dir_sep(path[*len - 1])) | |
1501 | (*len)--; | |
1502 | return 1; | |
1503 | } | |
1504 | ||
1505 | static int is_msys2_sh(const char *cmd) | |
1506 | { | |
e2ba3d6f JS |
1507 | if (!cmd) |
1508 | return 0; | |
1509 | ||
1510 | if (!strcmp(cmd, "sh")) { | |
9e9da23c JS |
1511 | static int ret = -1; |
1512 | char *p; | |
1513 | ||
1514 | if (ret >= 0) | |
1515 | return ret; | |
1516 | ||
1517 | p = path_lookup(cmd, 0); | |
1518 | if (!p) | |
1519 | ret = 0; | |
1520 | else { | |
1521 | size_t len = strlen(p); | |
1522 | ||
1523 | ret = match_last_path_component(p, &len, "sh.exe") && | |
1524 | match_last_path_component(p, &len, "bin") && | |
1525 | match_last_path_component(p, &len, "usr"); | |
1526 | free(p); | |
1527 | } | |
1528 | return ret; | |
1529 | } | |
e2ba3d6f JS |
1530 | |
1531 | if (ends_with(cmd, "\\sh.exe")) { | |
1532 | static char *sh; | |
1533 | ||
1534 | if (!sh) | |
1535 | sh = path_lookup("sh", 0); | |
1536 | ||
1537 | return !fspathcmp(cmd, sh); | |
1538 | } | |
1539 | ||
9e9da23c JS |
1540 | return 0; |
1541 | } | |
1542 | ||
77734da2 | 1543 | static pid_t mingw_spawnve_fd(const char *cmd, const char **argv, char **deltaenv, |
f9a2743c | 1544 | const char *dir, |
75301f90 | 1545 | int prepend_cmd, int fhin, int fhout, int fherr) |
7e5d7768 | 1546 | { |
ac33519d | 1547 | static int restrict_handle_inheritance = -1; |
9a780a38 | 1548 | STARTUPINFOEXW si; |
7e5d7768 | 1549 | PROCESS_INFORMATION pi; |
9a780a38 JS |
1550 | LPPROC_THREAD_ATTRIBUTE_LIST attr_list = NULL; |
1551 | HANDLE stdhandles[3]; | |
1552 | DWORD stdhandles_count = 0; | |
1553 | SIZE_T size; | |
7eb2619c KB |
1554 | struct strbuf args; |
1555 | wchar_t wcmd[MAX_PATH], wdir[MAX_PATH], *wargs, *wenvblk = NULL; | |
1556 | unsigned flags = CREATE_UNICODE_ENVIRONMENT; | |
7e5d7768 | 1557 | BOOL ret; |
0e218f91 | 1558 | HANDLE cons; |
9e9da23c | 1559 | const char *(*quote_arg)(const char *arg) = |
49f7a76d JS |
1560 | is_msys2_sh(cmd ? cmd : *argv) ? |
1561 | quote_arg_msys2 : quote_arg_msvc; | |
3efc128c | 1562 | const char *strace_env; |
0e218f91 | 1563 | |
4d0375ca JS |
1564 | /* Make sure to override previous errors, if any */ |
1565 | errno = 0; | |
1566 | ||
ac33519d JS |
1567 | if (restrict_handle_inheritance < 0) |
1568 | restrict_handle_inheritance = core_restrict_inherited_handles; | |
1569 | /* | |
1570 | * The following code to restrict which handles are inherited seems | |
1571 | * to work properly only on Windows 7 and later, so let's disable it | |
1572 | * on Windows Vista and 2008. | |
1573 | */ | |
1574 | if (restrict_handle_inheritance < 0) | |
1575 | restrict_handle_inheritance = GetVersion() >> 16 >= 7601; | |
1576 | ||
0e218f91 | 1577 | do_unset_environment_variables(); |
7e5d7768 JS |
1578 | |
1579 | /* Determine whether or not we are associated to a console */ | |
94238859 | 1580 | cons = CreateFileW(L"CONOUT$", GENERIC_WRITE, |
7e5d7768 JS |
1581 | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, |
1582 | FILE_ATTRIBUTE_NORMAL, NULL); | |
1583 | if (cons == INVALID_HANDLE_VALUE) { | |
1584 | /* There is no console associated with this process. | |
1585 | * Since the child is a console process, Windows | |
1586 | * would normally create a console window. But | |
1587 | * since we'll be redirecting std streams, we do | |
1588 | * not need the console. | |
19fb896f AG |
1589 | * It is necessary to use DETACHED_PROCESS |
1590 | * instead of CREATE_NO_WINDOW to make ssh | |
1591 | * recognize that it has no console. | |
7e5d7768 | 1592 | */ |
7eb2619c | 1593 | flags |= DETACHED_PROCESS; |
7e5d7768 JS |
1594 | } else { |
1595 | /* There is already a console. If we specified | |
19fb896f | 1596 | * DETACHED_PROCESS here, too, Windows would |
7e5d7768 | 1597 | * disassociate the child from the console. |
19fb896f | 1598 | * The same is true for CREATE_NO_WINDOW. |
7e5d7768 JS |
1599 | * Go figure! |
1600 | */ | |
7e5d7768 JS |
1601 | CloseHandle(cons); |
1602 | } | |
1603 | memset(&si, 0, sizeof(si)); | |
9a780a38 JS |
1604 | si.StartupInfo.cb = sizeof(si); |
1605 | si.StartupInfo.hStdInput = winansi_get_osfhandle(fhin); | |
1606 | si.StartupInfo.hStdOutput = winansi_get_osfhandle(fhout); | |
1607 | si.StartupInfo.hStdError = winansi_get_osfhandle(fherr); | |
1608 | ||
1609 | /* The list of handles cannot contain duplicates */ | |
1610 | if (si.StartupInfo.hStdInput != INVALID_HANDLE_VALUE) | |
1611 | stdhandles[stdhandles_count++] = si.StartupInfo.hStdInput; | |
1612 | if (si.StartupInfo.hStdOutput != INVALID_HANDLE_VALUE && | |
1613 | si.StartupInfo.hStdOutput != si.StartupInfo.hStdInput) | |
1614 | stdhandles[stdhandles_count++] = si.StartupInfo.hStdOutput; | |
1615 | if (si.StartupInfo.hStdError != INVALID_HANDLE_VALUE && | |
1616 | si.StartupInfo.hStdError != si.StartupInfo.hStdInput && | |
1617 | si.StartupInfo.hStdError != si.StartupInfo.hStdOutput) | |
1618 | stdhandles[stdhandles_count++] = si.StartupInfo.hStdError; | |
1619 | if (stdhandles_count) | |
1620 | si.StartupInfo.dwFlags |= STARTF_USESTDHANDLES; | |
7e5d7768 | 1621 | |
eb7c7863 JS |
1622 | if (*argv && !strcmp(cmd, *argv)) |
1623 | wcmd[0] = L'\0'; | |
1624 | else if (xutftowcs_path(wcmd, cmd) < 0) | |
99c3c76d KB |
1625 | return -1; |
1626 | if (dir && xutftowcs_path(wdir, dir) < 0) | |
1627 | return -1; | |
1628 | ||
7e5d7768 JS |
1629 | /* concatenate argv, quoting args as we go */ |
1630 | strbuf_init(&args, 0); | |
1631 | if (prepend_cmd) { | |
1632 | char *quoted = (char *)quote_arg(cmd); | |
1633 | strbuf_addstr(&args, quoted); | |
1634 | if (quoted != cmd) | |
1635 | free(quoted); | |
1636 | } | |
1637 | for (; *argv; argv++) { | |
1638 | char *quoted = (char *)quote_arg(*argv); | |
1639 | if (*args.buf) | |
1640 | strbuf_addch(&args, ' '); | |
1641 | strbuf_addstr(&args, quoted); | |
1642 | if (quoted != *argv) | |
1643 | free(quoted); | |
1644 | } | |
1645 | ||
3efc128c JS |
1646 | strace_env = getenv("GIT_STRACE_COMMANDS"); |
1647 | if (strace_env) { | |
1648 | char *p = path_lookup("strace.exe", 1); | |
1649 | if (!p) | |
1650 | return error("strace not found!"); | |
1651 | if (xutftowcs_path(wcmd, p) < 0) { | |
1652 | free(p); | |
1653 | return -1; | |
1654 | } | |
1655 | free(p); | |
1656 | if (!strcmp("1", strace_env) || | |
1657 | !strcasecmp("yes", strace_env) || | |
1658 | !strcasecmp("true", strace_env)) | |
1659 | strbuf_insert(&args, 0, "strace ", 7); | |
1660 | else { | |
1661 | const char *quoted = quote_arg(strace_env); | |
1662 | struct strbuf buf = STRBUF_INIT; | |
1663 | strbuf_addf(&buf, "strace -o %s ", quoted); | |
1664 | if (quoted != strace_env) | |
1665 | free((char *)quoted); | |
1666 | strbuf_insert(&args, 0, buf.buf, buf.len); | |
1667 | strbuf_release(&buf); | |
1668 | } | |
1669 | } | |
1670 | ||
8d5b3325 | 1671 | ALLOC_ARRAY(wargs, st_add(st_mult(2, args.len), 1)); |
99c3c76d KB |
1672 | xutftowcs(wargs, args.buf, 2 * args.len + 1); |
1673 | strbuf_release(&args); | |
1674 | ||
77734da2 | 1675 | wenvblk = make_environment_block(deltaenv); |
7e5d7768 JS |
1676 | |
1677 | memset(&pi, 0, sizeof(pi)); | |
9a780a38 JS |
1678 | if (restrict_handle_inheritance && stdhandles_count && |
1679 | (InitializeProcThreadAttributeList(NULL, 1, 0, &size) || | |
1680 | GetLastError() == ERROR_INSUFFICIENT_BUFFER) && | |
1681 | (attr_list = (LPPROC_THREAD_ATTRIBUTE_LIST) | |
1682 | (HeapAlloc(GetProcessHeap(), 0, size))) && | |
1683 | InitializeProcThreadAttributeList(attr_list, 1, 0, &size) && | |
1684 | UpdateProcThreadAttribute(attr_list, 0, | |
1685 | PROC_THREAD_ATTRIBUTE_HANDLE_LIST, | |
1686 | stdhandles, | |
1687 | stdhandles_count * sizeof(HANDLE), | |
1688 | NULL, NULL)) { | |
1689 | si.lpAttributeList = attr_list; | |
1690 | flags |= EXTENDED_STARTUPINFO_PRESENT; | |
1691 | } | |
1692 | ||
1693 | ret = CreateProcessW(*wcmd ? wcmd : NULL, wargs, NULL, NULL, | |
1694 | stdhandles_count ? TRUE : FALSE, | |
1695 | flags, wenvblk, dir ? wdir : NULL, | |
1696 | &si.StartupInfo, &pi); | |
1697 | ||
1698 | /* | |
1699 | * On Windows 2008 R2, it seems that specifying certain types of handles | |
1700 | * (such as FILE_TYPE_CHAR or FILE_TYPE_PIPE) will always produce an | |
1701 | * error. Rather than playing finicky and fragile games, let's just try | |
1702 | * to detect this situation and simply try again without restricting any | |
1703 | * handle inheritance. This is still better than failing to create | |
1704 | * processes. | |
1705 | */ | |
1706 | if (!ret && restrict_handle_inheritance && stdhandles_count) { | |
1707 | DWORD err = GetLastError(); | |
1708 | struct strbuf buf = STRBUF_INIT; | |
1709 | ||
1710 | if (err != ERROR_NO_SYSTEM_RESOURCES && | |
1711 | /* | |
1712 | * On Windows 7 and earlier, handles on pipes and character | |
1713 | * devices are inherited automatically, and cannot be | |
1714 | * specified in the thread handle list. Rather than trying | |
1715 | * to catch each and every corner case (and running the | |
1716 | * chance of *still* forgetting a few), let's just fall | |
1717 | * back to creating the process without trying to limit the | |
1718 | * handle inheritance. | |
1719 | */ | |
1720 | !(err == ERROR_INVALID_PARAMETER && | |
1721 | GetVersion() >> 16 < 9200) && | |
1722 | !getenv("SUPPRESS_HANDLE_INHERITANCE_WARNING")) { | |
1723 | DWORD fl = 0; | |
1724 | int i; | |
1725 | ||
1726 | setenv("SUPPRESS_HANDLE_INHERITANCE_WARNING", "1", 1); | |
1727 | ||
1728 | for (i = 0; i < stdhandles_count; i++) { | |
1729 | HANDLE h = stdhandles[i]; | |
1730 | strbuf_addf(&buf, "handle #%d: %p (type %lx, " | |
1731 | "handle info (%d) %lx\n", i, h, | |
1732 | GetFileType(h), | |
1733 | GetHandleInformation(h, &fl), | |
1734 | fl); | |
1735 | } | |
1736 | strbuf_addstr(&buf, "\nThis is a bug; please report it " | |
1737 | "at\nhttps://github.com/git-for-windows/" | |
1738 | "git/issues/new\n\n" | |
1739 | "To suppress this warning, please set " | |
1740 | "the environment variable\n\n" | |
1741 | "\tSUPPRESS_HANDLE_INHERITANCE_WARNING=1" | |
1742 | "\n"); | |
1743 | } | |
1744 | restrict_handle_inheritance = 0; | |
1745 | flags &= ~EXTENDED_STARTUPINFO_PRESENT; | |
1746 | ret = CreateProcessW(*wcmd ? wcmd : NULL, wargs, NULL, NULL, | |
1747 | TRUE, flags, wenvblk, dir ? wdir : NULL, | |
1748 | &si.StartupInfo, &pi); | |
4d0375ca | 1749 | if (!ret) |
9a780a38 | 1750 | errno = err_win_to_posix(GetLastError()); |
4d0375ca | 1751 | if (ret && buf.len) { |
9a780a38 JS |
1752 | warning("failed to restrict file handles (%ld)\n\n%s", |
1753 | err, buf.buf); | |
1754 | } | |
1755 | strbuf_release(&buf); | |
1756 | } else if (!ret) | |
1757 | errno = err_win_to_posix(GetLastError()); | |
1758 | ||
1759 | if (si.lpAttributeList) | |
1760 | DeleteProcThreadAttributeList(si.lpAttributeList); | |
1761 | if (attr_list) | |
1762 | HeapFree(GetProcessHeap(), 0, attr_list); | |
7e5d7768 | 1763 | |
7eb2619c | 1764 | free(wenvblk); |
99c3c76d | 1765 | free(wargs); |
7e5d7768 | 1766 | |
9a780a38 | 1767 | if (!ret) |
7e5d7768 | 1768 | return -1; |
9a780a38 | 1769 | |
7e5d7768 | 1770 | CloseHandle(pi.hThread); |
52de4db5 EFL |
1771 | |
1772 | /* | |
1773 | * The process ID is the human-readable identifier of the process | |
1774 | * that we want to present in log and error messages. The handle | |
1775 | * is not useful for this purpose. But we cannot close it, either, | |
1776 | * because it is not possible to turn a process ID into a process | |
1777 | * handle after the process terminated. | |
1778 | * Keep the handle in a list for waitpid. | |
1779 | */ | |
1780 | EnterCriticalSection(&pinfo_cs); | |
1781 | { | |
1782 | struct pinfo_t *info = xmalloc(sizeof(struct pinfo_t)); | |
1783 | info->pid = pi.dwProcessId; | |
1784 | info->proc = pi.hProcess; | |
1785 | info->next = pinfo; | |
1786 | pinfo = info; | |
1787 | } | |
1788 | LeaveCriticalSection(&pinfo_cs); | |
1789 | ||
1790 | return (pid_t)pi.dwProcessId; | |
7e5d7768 JS |
1791 | } |
1792 | ||
3e66e47b | 1793 | static pid_t mingw_spawnv(const char *cmd, const char **argv, int prepend_cmd) |
75301f90 | 1794 | { |
77734da2 | 1795 | return mingw_spawnve_fd(cmd, argv, NULL, NULL, prepend_cmd, 0, 1, 2); |
75301f90 JS |
1796 | } |
1797 | ||
77734da2 | 1798 | pid_t mingw_spawnvpe(const char *cmd, const char **argv, char **deltaenv, |
f9a2743c | 1799 | const char *dir, |
75301f90 | 1800 | int fhin, int fhout, int fherr) |
7e5d7768 JS |
1801 | { |
1802 | pid_t pid; | |
e0ca1ca2 | 1803 | char *prog = path_lookup(cmd, 0); |
7e5d7768 JS |
1804 | |
1805 | if (!prog) { | |
1806 | errno = ENOENT; | |
1807 | pid = -1; | |
1808 | } | |
1809 | else { | |
1810 | const char *interpr = parse_interpreter(prog); | |
1811 | ||
1812 | if (interpr) { | |
1813 | const char *argv0 = argv[0]; | |
e0ca1ca2 | 1814 | char *iprog = path_lookup(interpr, 1); |
7e5d7768 JS |
1815 | argv[0] = prog; |
1816 | if (!iprog) { | |
1817 | errno = ENOENT; | |
1818 | pid = -1; | |
1819 | } | |
1820 | else { | |
77734da2 | 1821 | pid = mingw_spawnve_fd(iprog, argv, deltaenv, dir, 1, |
75301f90 | 1822 | fhin, fhout, fherr); |
7e5d7768 JS |
1823 | free(iprog); |
1824 | } | |
1825 | argv[0] = argv0; | |
1826 | } | |
1827 | else | |
77734da2 | 1828 | pid = mingw_spawnve_fd(prog, argv, deltaenv, dir, 0, |
75301f90 | 1829 | fhin, fhout, fherr); |
7e5d7768 JS |
1830 | free(prog); |
1831 | } | |
7e5d7768 JS |
1832 | return pid; |
1833 | } | |
1834 | ||
3e66e47b | 1835 | static int try_shell_exec(const char *cmd, char *const *argv) |
f1a4dfb8 JS |
1836 | { |
1837 | const char *interpr = parse_interpreter(cmd); | |
f1a4dfb8 JS |
1838 | char *prog; |
1839 | int pid = 0; | |
1840 | ||
1841 | if (!interpr) | |
1842 | return 0; | |
e0ca1ca2 | 1843 | prog = path_lookup(interpr, 1); |
f1a4dfb8 | 1844 | if (prog) { |
ee4512ed | 1845 | int exec_id; |
f1a4dfb8 | 1846 | int argc = 0; |
12fb9bd8 | 1847 | char **argv2; |
f1a4dfb8 | 1848 | while (argv[argc]) argc++; |
b32fa95f | 1849 | ALLOC_ARRAY(argv2, argc + 1); |
7e5d7768 | 1850 | argv2[0] = (char *)cmd; /* full path to the script file */ |
51bd6be3 | 1851 | COPY_ARRAY(&argv2[1], &argv[1], argc); |
09884f35 RS |
1852 | exec_id = trace2_exec(prog, (const char **)argv2); |
1853 | pid = mingw_spawnv(prog, (const char **)argv2, 1); | |
f1a4dfb8 JS |
1854 | if (pid >= 0) { |
1855 | int status; | |
1856 | if (waitpid(pid, &status, 0) < 0) | |
1857 | status = 255; | |
ee4512ed | 1858 | trace2_exec_result(exec_id, status); |
f1a4dfb8 JS |
1859 | exit(status); |
1860 | } | |
ee4512ed | 1861 | trace2_exec_result(exec_id, -1); |
f1a4dfb8 JS |
1862 | pid = 1; /* indicate that we tried but failed */ |
1863 | free(prog); | |
1864 | free(argv2); | |
1865 | } | |
f1a4dfb8 JS |
1866 | return pid; |
1867 | } | |
1868 | ||
3e66e47b | 1869 | int mingw_execv(const char *cmd, char *const *argv) |
f1a4dfb8 JS |
1870 | { |
1871 | /* check if git_command is a shell script */ | |
3e66e47b | 1872 | if (!try_shell_exec(cmd, argv)) { |
f1a4dfb8 | 1873 | int pid, status; |
ee4512ed | 1874 | int exec_id; |
f1a4dfb8 | 1875 | |
ee4512ed | 1876 | exec_id = trace2_exec(cmd, (const char **)argv); |
3e66e47b | 1877 | pid = mingw_spawnv(cmd, (const char **)argv, 0); |
ee4512ed JH |
1878 | if (pid < 0) { |
1879 | trace2_exec_result(exec_id, -1); | |
570f1e6e | 1880 | return -1; |
ee4512ed | 1881 | } |
f1a4dfb8 JS |
1882 | if (waitpid(pid, &status, 0) < 0) |
1883 | status = 255; | |
ee4512ed | 1884 | trace2_exec_result(exec_id, status); |
f1a4dfb8 JS |
1885 | exit(status); |
1886 | } | |
570f1e6e | 1887 | return -1; |
f1a4dfb8 JS |
1888 | } |
1889 | ||
1696d723 | 1890 | int mingw_execvp(const char *cmd, char *const *argv) |
f1a4dfb8 | 1891 | { |
e0ca1ca2 | 1892 | char *prog = path_lookup(cmd, 0); |
f1a4dfb8 JS |
1893 | |
1894 | if (prog) { | |
3e66e47b | 1895 | mingw_execv(prog, argv); |
f1a4dfb8 JS |
1896 | free(prog); |
1897 | } else | |
1898 | errno = ENOENT; | |
1899 | ||
1696d723 | 1900 | return -1; |
f1a4dfb8 JS |
1901 | } |
1902 | ||
82fc07b7 EFL |
1903 | int mingw_kill(pid_t pid, int sig) |
1904 | { | |
1905 | if (pid > 0 && sig == SIGTERM) { | |
1906 | HANDLE h = OpenProcess(PROCESS_TERMINATE, FALSE, pid); | |
1907 | ||
1908 | if (TerminateProcess(h, -1)) { | |
1909 | CloseHandle(h); | |
1910 | return 0; | |
1911 | } | |
1912 | ||
1913 | errno = err_win_to_posix(GetLastError()); | |
1914 | CloseHandle(h); | |
1915 | return -1; | |
64a99eb4 NTND |
1916 | } else if (pid > 0 && sig == 0) { |
1917 | HANDLE h = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pid); | |
1918 | if (h) { | |
1919 | CloseHandle(h); | |
1920 | return 0; | |
1921 | } | |
82fc07b7 EFL |
1922 | } |
1923 | ||
1924 | errno = EINVAL; | |
1925 | return -1; | |
1926 | } | |
1927 | ||
343ff06d | 1928 | /* |
fe21c6b2 JS |
1929 | * UTF-8 versions of getenv(), putenv() and unsetenv(). |
1930 | * Internally, they use the CRT's stock UNICODE routines | |
1931 | * to avoid data loss. | |
343ff06d | 1932 | */ |
fe21c6b2 | 1933 | char *mingw_getenv(const char *name) |
343ff06d | 1934 | { |
ca1b4116 | 1935 | #define GETENV_MAX_RETAIN 64 |
fe21c6b2 JS |
1936 | static char *values[GETENV_MAX_RETAIN]; |
1937 | static int value_counter; | |
1938 | int len_key, len_value; | |
1939 | wchar_t *w_key; | |
1940 | char *value; | |
1941 | wchar_t w_value[32768]; | |
343ff06d | 1942 | |
fe21c6b2 JS |
1943 | if (!name || !*name) |
1944 | return NULL; | |
ba26f296 | 1945 | |
fe21c6b2 JS |
1946 | len_key = strlen(name) + 1; |
1947 | /* We cannot use xcalloc() here because that uses getenv() itself */ | |
1948 | w_key = calloc(len_key, sizeof(wchar_t)); | |
1949 | if (!w_key) | |
1950 | die("Out of memory, (tried to allocate %u wchar_t's)", len_key); | |
1951 | xutftowcs(w_key, name, len_key); | |
61d1d92a JS |
1952 | /* GetEnvironmentVariableW() only sets the last error upon failure */ |
1953 | SetLastError(ERROR_SUCCESS); | |
fe21c6b2 JS |
1954 | len_value = GetEnvironmentVariableW(w_key, w_value, ARRAY_SIZE(w_value)); |
1955 | if (!len_value && GetLastError() == ERROR_ENVVAR_NOT_FOUND) { | |
1956 | free(w_key); | |
1957 | return NULL; | |
ba26f296 | 1958 | } |
fe21c6b2 JS |
1959 | free(w_key); |
1960 | ||
1961 | len_value = len_value * 3 + 1; | |
1962 | /* We cannot use xcalloc() here because that uses getenv() itself */ | |
1963 | value = calloc(len_value, sizeof(char)); | |
1964 | if (!value) | |
1965 | die("Out of memory, (tried to allocate %u bytes)", len_value); | |
1966 | xwcstoutf(value, w_value, len_value); | |
1967 | ||
1968 | /* | |
1969 | * We return `value` which is an allocated value and the caller is NOT | |
1970 | * expecting to have to free it, so we keep a round-robin array, | |
1971 | * invalidating the buffer after GETENV_MAX_RETAIN getenv() calls. | |
1972 | */ | |
1973 | free(values[value_counter]); | |
1974 | values[value_counter++] = value; | |
1975 | if (value_counter >= ARRAY_SIZE(values)) | |
1976 | value_counter = 0; | |
1977 | ||
1978 | return value; | |
ba26f296 JS |
1979 | } |
1980 | ||
fe21c6b2 | 1981 | int mingw_putenv(const char *namevalue) |
ba26f296 | 1982 | { |
fe21c6b2 JS |
1983 | int size; |
1984 | wchar_t *wide, *equal; | |
1985 | BOOL result; | |
ba26f296 | 1986 | |
fe21c6b2 JS |
1987 | if (!namevalue || !*namevalue) |
1988 | return 0; | |
ba26f296 | 1989 | |
fe21c6b2 JS |
1990 | size = strlen(namevalue) * 2 + 1; |
1991 | wide = calloc(size, sizeof(wchar_t)); | |
1992 | if (!wide) | |
1993 | die("Out of memory, (tried to allocate %u wchar_t's)", size); | |
1994 | xutftowcs(wide, namevalue, size); | |
1995 | equal = wcschr(wide, L'='); | |
1996 | if (!equal) | |
1997 | result = SetEnvironmentVariableW(wide, NULL); | |
1998 | else { | |
1999 | *equal = L'\0'; | |
2000 | result = SetEnvironmentVariableW(wide, equal + 1); | |
ba26f296 | 2001 | } |
fe21c6b2 | 2002 | free(wide); |
2affea41 | 2003 | |
fe21c6b2 JS |
2004 | if (!result) |
2005 | errno = err_win_to_posix(GetLastError()); | |
df599e96 | 2006 | |
fe21c6b2 | 2007 | return result ? 0 : -1; |
06bc4b79 JS |
2008 | } |
2009 | ||
b7cc9f82 | 2010 | static void ensure_socket_initialization(void) |
746fb857 JS |
2011 | { |
2012 | WSADATA wsa; | |
b7cc9f82 MS |
2013 | static int initialized = 0; |
2014 | ||
2015 | if (initialized) | |
2016 | return; | |
746fb857 JS |
2017 | |
2018 | if (WSAStartup(MAKEWORD(2,2), &wsa)) | |
2019 | die("unable to initialize winsock subsystem, error %d", | |
2020 | WSAGetLastError()); | |
fe3b2b7b | 2021 | |
b9f0193b | 2022 | atexit((void(*)(void)) WSACleanup); |
b7cc9f82 MS |
2023 | initialized = 1; |
2024 | } | |
2025 | ||
13d24b01 PT |
2026 | #undef gethostname |
2027 | int mingw_gethostname(char *name, int namelen) | |
2028 | { | |
2029 | ensure_socket_initialization(); | |
2030 | return gethostname(name, namelen); | |
2031 | } | |
2032 | ||
b7cc9f82 MS |
2033 | #undef gethostbyname |
2034 | struct hostent *mingw_gethostbyname(const char *host) | |
2035 | { | |
2036 | ensure_socket_initialization(); | |
746fb857 JS |
2037 | return gethostbyname(host); |
2038 | } | |
2039 | ||
b9f0193b | 2040 | #undef getaddrinfo |
fe3b2b7b MS |
2041 | int mingw_getaddrinfo(const char *node, const char *service, |
2042 | const struct addrinfo *hints, struct addrinfo **res) | |
2043 | { | |
2044 | ensure_socket_initialization(); | |
b9f0193b | 2045 | return getaddrinfo(node, service, hints, res); |
fe3b2b7b MS |
2046 | } |
2047 | ||
746fb857 JS |
2048 | int mingw_socket(int domain, int type, int protocol) |
2049 | { | |
2050 | int sockfd; | |
772991af MP |
2051 | SOCKET s; |
2052 | ||
2053 | ensure_socket_initialization(); | |
2054 | s = WSASocket(domain, type, protocol, NULL, 0, 0); | |
746fb857 JS |
2055 | if (s == INVALID_SOCKET) { |
2056 | /* | |
2057 | * WSAGetLastError() values are regular BSD error codes | |
2058 | * biased by WSABASEERR. | |
2059 | * However, strerror() does not know about networking | |
2060 | * specific errors, which are values beginning at 38 or so. | |
2061 | * Therefore, we choose to leave the biased error code | |
2062 | * in errno so that _if_ someone looks up the code somewhere, | |
2063 | * then it is at least the number that are usually listed. | |
2064 | */ | |
2065 | errno = WSAGetLastError(); | |
2066 | return -1; | |
2067 | } | |
2068 | /* convert into a file descriptor */ | |
2069 | if ((sockfd = _open_osfhandle(s, O_RDWR|O_BINARY)) < 0) { | |
2070 | closesocket(s); | |
2071 | return error("unable to make a socket file descriptor: %s", | |
2072 | strerror(errno)); | |
2073 | } | |
2074 | return sockfd; | |
2075 | } | |
2076 | ||
2077 | #undef connect | |
2078 | int mingw_connect(int sockfd, struct sockaddr *sa, size_t sz) | |
2079 | { | |
2080 | SOCKET s = (SOCKET)_get_osfhandle(sockfd); | |
2081 | return connect(s, sa, sz); | |
2082 | } | |
2083 | ||
772991af MP |
2084 | #undef bind |
2085 | int mingw_bind(int sockfd, struct sockaddr *sa, size_t sz) | |
2086 | { | |
2087 | SOCKET s = (SOCKET)_get_osfhandle(sockfd); | |
2088 | return bind(s, sa, sz); | |
2089 | } | |
2090 | ||
2091 | #undef setsockopt | |
2092 | int mingw_setsockopt(int sockfd, int lvl, int optname, void *optval, int optlen) | |
2093 | { | |
2094 | SOCKET s = (SOCKET)_get_osfhandle(sockfd); | |
2095 | return setsockopt(s, lvl, optname, (const char*)optval, optlen); | |
2096 | } | |
2097 | ||
a7941795 JS |
2098 | #undef shutdown |
2099 | int mingw_shutdown(int sockfd, int how) | |
2100 | { | |
2101 | SOCKET s = (SOCKET)_get_osfhandle(sockfd); | |
2102 | return shutdown(s, how); | |
2103 | } | |
2104 | ||
772991af MP |
2105 | #undef listen |
2106 | int mingw_listen(int sockfd, int backlog) | |
2107 | { | |
2108 | SOCKET s = (SOCKET)_get_osfhandle(sockfd); | |
2109 | return listen(s, backlog); | |
2110 | } | |
2111 | ||
2112 | #undef accept | |
2113 | int mingw_accept(int sockfd1, struct sockaddr *sa, socklen_t *sz) | |
2114 | { | |
2115 | int sockfd2; | |
2116 | ||
2117 | SOCKET s1 = (SOCKET)_get_osfhandle(sockfd1); | |
2118 | SOCKET s2 = accept(s1, sa, sz); | |
2119 | ||
2120 | /* convert into a file descriptor */ | |
2121 | if ((sockfd2 = _open_osfhandle(s2, O_RDWR|O_BINARY)) < 0) { | |
2122 | int err = errno; | |
2123 | closesocket(s2); | |
2124 | return error("unable to make a socket file descriptor: %s", | |
2125 | strerror(err)); | |
2126 | } | |
2127 | return sockfd2; | |
2128 | } | |
2129 | ||
ea9e98c3 JS |
2130 | #undef rename |
2131 | int mingw_rename(const char *pold, const char *pnew) | |
2132 | { | |
6ac6f878 JS |
2133 | DWORD attrs, gle; |
2134 | int tries = 0; | |
85faec9d KB |
2135 | wchar_t wpold[MAX_PATH], wpnew[MAX_PATH]; |
2136 | if (xutftowcs_path(wpold, pold) < 0 || xutftowcs_path(wpnew, pnew) < 0) | |
2137 | return -1; | |
632f7017 | 2138 | |
ea9e98c3 JS |
2139 | /* |
2140 | * Try native rename() first to get errno right. | |
2141 | * It is based on MoveFile(), which cannot overwrite existing files. | |
2142 | */ | |
85faec9d | 2143 | if (!_wrename(wpold, wpnew)) |
ea9e98c3 JS |
2144 | return 0; |
2145 | if (errno != EEXIST) | |
2146 | return -1; | |
6ac6f878 | 2147 | repeat: |
85faec9d | 2148 | if (MoveFileExW(wpold, wpnew, MOVEFILE_REPLACE_EXISTING)) |
ea9e98c3 JS |
2149 | return 0; |
2150 | /* TODO: translate more errors */ | |
6ac6f878 JS |
2151 | gle = GetLastError(); |
2152 | if (gle == ERROR_ACCESS_DENIED && | |
85faec9d | 2153 | (attrs = GetFileAttributesW(wpnew)) != INVALID_FILE_ATTRIBUTES) { |
632f7017 | 2154 | if (attrs & FILE_ATTRIBUTE_DIRECTORY) { |
4426fb51 | 2155 | DWORD attrsold = GetFileAttributesW(wpold); |
2156 | if (attrsold == INVALID_FILE_ATTRIBUTES || | |
2157 | !(attrsold & FILE_ATTRIBUTE_DIRECTORY)) | |
2158 | errno = EISDIR; | |
2159 | else if (!_wrmdir(wpnew)) | |
2160 | goto repeat; | |
ea9e98c3 JS |
2161 | return -1; |
2162 | } | |
632f7017 | 2163 | if ((attrs & FILE_ATTRIBUTE_READONLY) && |
85faec9d KB |
2164 | SetFileAttributesW(wpnew, attrs & ~FILE_ATTRIBUTE_READONLY)) { |
2165 | if (MoveFileExW(wpold, wpnew, MOVEFILE_REPLACE_EXISTING)) | |
632f7017 | 2166 | return 0; |
6ac6f878 | 2167 | gle = GetLastError(); |
632f7017 | 2168 | /* revert file attributes on failure */ |
85faec9d | 2169 | SetFileAttributesW(wpnew, attrs); |
632f7017 | 2170 | } |
ea9e98c3 | 2171 | } |
6ac6f878 JS |
2172 | if (tries < ARRAY_SIZE(delay) && gle == ERROR_ACCESS_DENIED) { |
2173 | /* | |
2174 | * We assume that some other process had the source or | |
2175 | * destination file open at the wrong moment and retry. | |
2176 | * In order to give the other process a higher chance to | |
2177 | * complete its operation, we give up our time slice now. | |
2178 | * If we have to retry again, we do sleep a bit. | |
2179 | */ | |
2180 | Sleep(delay[tries]); | |
2181 | tries++; | |
2182 | goto repeat; | |
2183 | } | |
c9b78400 HV |
2184 | if (gle == ERROR_ACCESS_DENIED && |
2185 | ask_yes_no_if_possible("Rename from '%s' to '%s' failed. " | |
2186 | "Should I try again?", pold, pnew)) | |
2187 | goto repeat; | |
2188 | ||
ea9e98c3 JS |
2189 | errno = EACCES; |
2190 | return -1; | |
2191 | } | |
2192 | ||
b1b95204 RJ |
2193 | /* |
2194 | * Note that this doesn't return the actual pagesize, but | |
2195 | * the allocation granularity. If future Windows specific git code | |
2196 | * needs the real getpagesize function, we need to find another solution. | |
2197 | */ | |
2198 | int mingw_getpagesize(void) | |
2199 | { | |
2200 | SYSTEM_INFO si; | |
2201 | GetSystemInfo(&si); | |
2202 | return si.dwAllocationGranularity; | |
2203 | } | |
2204 | ||
564be791 JS |
2205 | /* See https://msdn.microsoft.com/en-us/library/windows/desktop/ms724435.aspx */ |
2206 | enum EXTENDED_NAME_FORMAT { | |
2207 | NameDisplay = 3, | |
2208 | NameUserPrincipal = 8 | |
2209 | }; | |
2210 | ||
2211 | static char *get_extended_user_info(enum EXTENDED_NAME_FORMAT type) | |
2212 | { | |
4a9b2049 | 2213 | DECLARE_PROC_ADDR(secur32.dll, BOOL, SEC_ENTRY, GetUserNameExW, |
564be791 JS |
2214 | enum EXTENDED_NAME_FORMAT, LPCWSTR, PULONG); |
2215 | static wchar_t wbuffer[1024]; | |
2216 | DWORD len; | |
2217 | ||
2218 | if (!INIT_PROC_ADDR(GetUserNameExW)) | |
2219 | return NULL; | |
2220 | ||
2221 | len = ARRAY_SIZE(wbuffer); | |
2222 | if (GetUserNameExW(type, wbuffer, &len)) { | |
2223 | char *converted = xmalloc((len *= 3)); | |
2224 | if (xwcstoutf(converted, wbuffer, len) >= 0) | |
2225 | return converted; | |
2226 | free(converted); | |
2227 | } | |
2228 | ||
2229 | return NULL; | |
2230 | } | |
2231 | ||
501afcb8 JS |
2232 | char *mingw_query_user_email(void) |
2233 | { | |
2234 | return get_extended_user_info(NameUserPrincipal); | |
2235 | } | |
2236 | ||
f4626df5 JS |
2237 | struct passwd *getpwuid(int uid) |
2238 | { | |
55b6513e | 2239 | static unsigned initialized; |
f7597aca | 2240 | static char user_name[100]; |
55b6513e | 2241 | static struct passwd *p; |
39a98e9b | 2242 | wchar_t buf[100]; |
55b6513e | 2243 | DWORD len; |
f7597aca | 2244 | |
55b6513e JS |
2245 | if (initialized) |
2246 | return p; | |
f7597aca | 2247 | |
697bdd22 | 2248 | len = ARRAY_SIZE(buf); |
39a98e9b JS |
2249 | if (!GetUserNameW(buf, &len)) { |
2250 | initialized = 1; | |
2251 | return NULL; | |
2252 | } | |
2253 | ||
2254 | if (xwcstoutf(user_name, buf, sizeof(user_name)) < 0) { | |
55b6513e | 2255 | initialized = 1; |
f7597aca | 2256 | return NULL; |
55b6513e JS |
2257 | } |
2258 | ||
2259 | p = xmalloc(sizeof(*p)); | |
2260 | p->pw_name = user_name; | |
564be791 JS |
2261 | p->pw_gecos = get_extended_user_info(NameDisplay); |
2262 | if (!p->pw_gecos) | |
2263 | p->pw_gecos = "unknown"; | |
55b6513e JS |
2264 | p->pw_dir = NULL; |
2265 | ||
2266 | initialized = 1; | |
2267 | return p; | |
f4626df5 JS |
2268 | } |
2269 | ||
6072fc31 JS |
2270 | static HANDLE timer_event; |
2271 | static HANDLE timer_thread; | |
2272 | static int timer_interval; | |
2273 | static int one_shot; | |
176478a8 | 2274 | static sig_handler_t timer_fn = SIG_DFL, sigint_fn = SIG_DFL; |
6072fc31 JS |
2275 | |
2276 | /* The timer works like this: | |
2277 | * The thread, ticktack(), is a trivial routine that most of the time | |
2278 | * only waits to receive the signal to terminate. The main thread tells | |
2279 | * the thread to terminate by setting the timer_event to the signalled | |
2280 | * state. | |
2281 | * But ticktack() interrupts the wait state after the timer's interval | |
2282 | * length to call the signal handler. | |
2283 | */ | |
2284 | ||
d7fa500f | 2285 | static unsigned __stdcall ticktack(void *dummy) |
6072fc31 JS |
2286 | { |
2287 | while (WaitForSingleObject(timer_event, timer_interval) == WAIT_TIMEOUT) { | |
176478a8 | 2288 | mingw_raise(SIGALRM); |
6072fc31 JS |
2289 | if (one_shot) |
2290 | break; | |
2291 | } | |
2292 | return 0; | |
2293 | } | |
2294 | ||
2295 | static int start_timer_thread(void) | |
2296 | { | |
2297 | timer_event = CreateEvent(NULL, FALSE, FALSE, NULL); | |
2298 | if (timer_event) { | |
2299 | timer_thread = (HANDLE) _beginthreadex(NULL, 0, ticktack, NULL, 0, NULL); | |
2300 | if (!timer_thread ) | |
2301 | return errno = ENOMEM, | |
2302 | error("cannot start timer thread"); | |
2303 | } else | |
2304 | return errno = ENOMEM, | |
2305 | error("cannot allocate resources for timer"); | |
2306 | return 0; | |
2307 | } | |
2308 | ||
2309 | static void stop_timer_thread(void) | |
2310 | { | |
2311 | if (timer_event) | |
2312 | SetEvent(timer_event); /* tell thread to terminate */ | |
2313 | if (timer_thread) { | |
72d63b2f | 2314 | int rc = WaitForSingleObject(timer_thread, 10000); |
6072fc31 JS |
2315 | if (rc == WAIT_TIMEOUT) |
2316 | error("timer thread did not terminate timely"); | |
2317 | else if (rc != WAIT_OBJECT_0) | |
2318 | error("waiting for timer thread failed: %lu", | |
2319 | GetLastError()); | |
2320 | CloseHandle(timer_thread); | |
2321 | } | |
2322 | if (timer_event) | |
2323 | CloseHandle(timer_event); | |
2324 | timer_event = NULL; | |
2325 | timer_thread = NULL; | |
2326 | } | |
2327 | ||
2328 | static inline int is_timeval_eq(const struct timeval *i1, const struct timeval *i2) | |
2329 | { | |
2330 | return i1->tv_sec == i2->tv_sec && i1->tv_usec == i2->tv_usec; | |
2331 | } | |
2332 | ||
f4626df5 JS |
2333 | int setitimer(int type, struct itimerval *in, struct itimerval *out) |
2334 | { | |
6072fc31 JS |
2335 | static const struct timeval zero; |
2336 | static int atexit_done; | |
2337 | ||
afe8a907 | 2338 | if (out) |
6072fc31 JS |
2339 | return errno = EINVAL, |
2340 | error("setitimer param 3 != NULL not implemented"); | |
2341 | if (!is_timeval_eq(&in->it_interval, &zero) && | |
2342 | !is_timeval_eq(&in->it_interval, &in->it_value)) | |
2343 | return errno = EINVAL, | |
2344 | error("setitimer: it_interval must be zero or eq it_value"); | |
2345 | ||
2346 | if (timer_thread) | |
2347 | stop_timer_thread(); | |
2348 | ||
2349 | if (is_timeval_eq(&in->it_value, &zero) && | |
2350 | is_timeval_eq(&in->it_interval, &zero)) | |
2351 | return 0; | |
2352 | ||
2353 | timer_interval = in->it_value.tv_sec * 1000 + in->it_value.tv_usec / 1000; | |
2354 | one_shot = is_timeval_eq(&in->it_interval, &zero); | |
2355 | if (!atexit_done) { | |
2356 | atexit(stop_timer_thread); | |
2357 | atexit_done = 1; | |
2358 | } | |
2359 | return start_timer_thread(); | |
f4626df5 JS |
2360 | } |
2361 | ||
2362 | int sigaction(int sig, struct sigaction *in, struct sigaction *out) | |
2363 | { | |
6072fc31 JS |
2364 | if (sig != SIGALRM) |
2365 | return errno = EINVAL, | |
2366 | error("sigaction only implemented for SIGALRM"); | |
afe8a907 | 2367 | if (out) |
6072fc31 JS |
2368 | return errno = EINVAL, |
2369 | error("sigaction: param 3 != NULL not implemented"); | |
2370 | ||
2371 | timer_fn = in->sa_handler; | |
2372 | return 0; | |
2373 | } | |
2374 | ||
2375 | #undef signal | |
2376 | sig_handler_t mingw_signal(int sig, sig_handler_t handler) | |
2377 | { | |
a4540658 | 2378 | sig_handler_t old; |
176478a8 EFL |
2379 | |
2380 | switch (sig) { | |
2381 | case SIGALRM: | |
a4540658 | 2382 | old = timer_fn; |
176478a8 EFL |
2383 | timer_fn = handler; |
2384 | break; | |
2385 | ||
2386 | case SIGINT: | |
a4540658 | 2387 | old = sigint_fn; |
176478a8 EFL |
2388 | sigint_fn = handler; |
2389 | break; | |
2390 | ||
2391 | default: | |
6072fc31 | 2392 | return signal(sig, handler); |
176478a8 EFL |
2393 | } |
2394 | ||
6072fc31 | 2395 | return old; |
f4626df5 | 2396 | } |
4804aabc | 2397 | |
176478a8 EFL |
2398 | #undef raise |
2399 | int mingw_raise(int sig) | |
2400 | { | |
2401 | switch (sig) { | |
2402 | case SIGALRM: | |
2403 | if (timer_fn == SIG_DFL) { | |
2404 | if (isatty(STDERR_FILENO)) | |
2405 | fputs("Alarm clock\n", stderr); | |
2406 | exit(128 + SIGALRM); | |
2407 | } else if (timer_fn != SIG_IGN) | |
2408 | timer_fn(SIGALRM); | |
2409 | return 0; | |
2410 | ||
2411 | case SIGINT: | |
2412 | if (sigint_fn == SIG_DFL) | |
2413 | exit(128 + SIGINT); | |
2414 | else if (sigint_fn != SIG_IGN) | |
2415 | sigint_fn(SIGINT); | |
2416 | return 0; | |
2417 | ||
446df603 JH |
2418 | #if defined(_MSC_VER) |
2419 | case SIGILL: | |
2420 | case SIGFPE: | |
2421 | case SIGSEGV: | |
2422 | case SIGTERM: | |
2423 | case SIGBREAK: | |
2424 | case SIGABRT: | |
2425 | case SIGABRT_COMPAT: | |
2426 | /* | |
2427 | * The <signal.h> header in the MS C Runtime defines 8 signals | |
2428 | * as being supported on the platform. Anything else causes an | |
2429 | * "Invalid signal or error" (which in DEBUG builds causes the | |
2430 | * Abort/Retry/Ignore dialog). We by-pass the CRT for things we | |
2431 | * already know will fail. | |
2432 | */ | |
2433 | return raise(sig); | |
2434 | default: | |
2435 | errno = EINVAL; | |
2436 | return -1; | |
2437 | ||
2438 | #else | |
2439 | ||
176478a8 EFL |
2440 | default: |
2441 | return raise(sig); | |
446df603 JH |
2442 | |
2443 | #endif | |
2444 | ||
176478a8 EFL |
2445 | } |
2446 | } | |
2447 | ||
7be401e0 PK |
2448 | int link(const char *oldpath, const char *newpath) |
2449 | { | |
85faec9d KB |
2450 | wchar_t woldpath[MAX_PATH], wnewpath[MAX_PATH]; |
2451 | if (xutftowcs_path(woldpath, oldpath) < 0 || | |
2452 | xutftowcs_path(wnewpath, newpath) < 0) | |
2453 | return -1; | |
2454 | ||
1e1a876b | 2455 | if (!CreateHardLinkW(wnewpath, woldpath, NULL)) { |
7be401e0 PK |
2456 | errno = err_win_to_posix(GetLastError()); |
2457 | return -1; | |
2458 | } | |
2459 | return 0; | |
2460 | } | |
0dbbbc1e | 2461 | |
956d86d1 | 2462 | pid_t waitpid(pid_t pid, int *status, int options) |
52de4db5 EFL |
2463 | { |
2464 | HANDLE h = OpenProcess(SYNCHRONIZE | PROCESS_QUERY_INFORMATION, | |
2465 | FALSE, pid); | |
2466 | if (!h) { | |
2467 | errno = ECHILD; | |
2468 | return -1; | |
2469 | } | |
2470 | ||
ef7108ca EFL |
2471 | if (pid > 0 && options & WNOHANG) { |
2472 | if (WAIT_OBJECT_0 != WaitForSingleObject(h, 0)) { | |
2473 | CloseHandle(h); | |
2474 | return 0; | |
2475 | } | |
2476 | options &= ~WNOHANG; | |
2477 | } | |
2478 | ||
52de4db5 EFL |
2479 | if (options == 0) { |
2480 | struct pinfo_t **ppinfo; | |
2481 | if (WaitForSingleObject(h, INFINITE) != WAIT_OBJECT_0) { | |
2482 | CloseHandle(h); | |
2483 | return 0; | |
2484 | } | |
2485 | ||
2486 | if (status) | |
2487 | GetExitCodeProcess(h, (LPDWORD)status); | |
2488 | ||
2489 | EnterCriticalSection(&pinfo_cs); | |
2490 | ||
2491 | ppinfo = &pinfo; | |
2492 | while (*ppinfo) { | |
2493 | struct pinfo_t *info = *ppinfo; | |
2494 | if (info->pid == pid) { | |
2495 | CloseHandle(info->proc); | |
2496 | *ppinfo = info->next; | |
2497 | free(info); | |
2498 | break; | |
2499 | } | |
2500 | ppinfo = &info->next; | |
2501 | } | |
2502 | ||
2503 | LeaveCriticalSection(&pinfo_cs); | |
2504 | ||
2505 | CloseHandle(h); | |
2506 | return pid; | |
2507 | } | |
2508 | CloseHandle(h); | |
2509 | ||
2510 | errno = EINVAL; | |
2511 | return -1; | |
2512 | } | |
c2369bdf | 2513 | |
1c950a59 KB |
2514 | int xutftowcsn(wchar_t *wcs, const char *utfs, size_t wcslen, int utflen) |
2515 | { | |
2516 | int upos = 0, wpos = 0; | |
2517 | const unsigned char *utf = (const unsigned char*) utfs; | |
2518 | if (!utf || !wcs || wcslen < 1) { | |
2519 | errno = EINVAL; | |
2520 | return -1; | |
2521 | } | |
2522 | /* reserve space for \0 */ | |
2523 | wcslen--; | |
2524 | if (utflen < 0) | |
2525 | utflen = INT_MAX; | |
2526 | ||
2527 | while (upos < utflen) { | |
2528 | int c = utf[upos++] & 0xff; | |
2529 | if (utflen == INT_MAX && c == 0) | |
2530 | break; | |
2531 | ||
2532 | if (wpos >= wcslen) { | |
2533 | wcs[wpos] = 0; | |
2534 | errno = ERANGE; | |
2535 | return -1; | |
2536 | } | |
2537 | ||
2538 | if (c < 0x80) { | |
2539 | /* ASCII */ | |
2540 | wcs[wpos++] = c; | |
2541 | } else if (c >= 0xc2 && c < 0xe0 && upos < utflen && | |
2542 | (utf[upos] & 0xc0) == 0x80) { | |
2543 | /* 2-byte utf-8 */ | |
2544 | c = ((c & 0x1f) << 6); | |
2545 | c |= (utf[upos++] & 0x3f); | |
2546 | wcs[wpos++] = c; | |
2547 | } else if (c >= 0xe0 && c < 0xf0 && upos + 1 < utflen && | |
2548 | !(c == 0xe0 && utf[upos] < 0xa0) && /* over-long encoding */ | |
2549 | (utf[upos] & 0xc0) == 0x80 && | |
2550 | (utf[upos + 1] & 0xc0) == 0x80) { | |
2551 | /* 3-byte utf-8 */ | |
2552 | c = ((c & 0x0f) << 12); | |
2553 | c |= ((utf[upos++] & 0x3f) << 6); | |
2554 | c |= (utf[upos++] & 0x3f); | |
2555 | wcs[wpos++] = c; | |
2556 | } else if (c >= 0xf0 && c < 0xf5 && upos + 2 < utflen && | |
2557 | wpos + 1 < wcslen && | |
2558 | !(c == 0xf0 && utf[upos] < 0x90) && /* over-long encoding */ | |
2559 | !(c == 0xf4 && utf[upos] >= 0x90) && /* > \u10ffff */ | |
2560 | (utf[upos] & 0xc0) == 0x80 && | |
2561 | (utf[upos + 1] & 0xc0) == 0x80 && | |
2562 | (utf[upos + 2] & 0xc0) == 0x80) { | |
2563 | /* 4-byte utf-8: convert to \ud8xx \udcxx surrogate pair */ | |
2564 | c = ((c & 0x07) << 18); | |
2565 | c |= ((utf[upos++] & 0x3f) << 12); | |
2566 | c |= ((utf[upos++] & 0x3f) << 6); | |
2567 | c |= (utf[upos++] & 0x3f); | |
2568 | c -= 0x10000; | |
2569 | wcs[wpos++] = 0xd800 | (c >> 10); | |
2570 | wcs[wpos++] = 0xdc00 | (c & 0x3ff); | |
2571 | } else if (c >= 0xa0) { | |
2572 | /* invalid utf-8 byte, printable unicode char: convert 1:1 */ | |
2573 | wcs[wpos++] = c; | |
2574 | } else { | |
2575 | /* invalid utf-8 byte, non-printable unicode: convert to hex */ | |
2576 | static const char *hex = "0123456789abcdef"; | |
2577 | wcs[wpos++] = hex[c >> 4]; | |
2578 | if (wpos < wcslen) | |
2579 | wcs[wpos++] = hex[c & 0x0f]; | |
2580 | } | |
2581 | } | |
2582 | wcs[wpos] = 0; | |
2583 | return wpos; | |
2584 | } | |
2585 | ||
2586 | int xwcstoutf(char *utf, const wchar_t *wcs, size_t utflen) | |
2587 | { | |
2588 | if (!wcs || !utf || utflen < 1) { | |
2589 | errno = EINVAL; | |
2590 | return -1; | |
2591 | } | |
2592 | utflen = WideCharToMultiByte(CP_UTF8, 0, wcs, -1, utf, utflen, NULL, NULL); | |
2593 | if (utflen) | |
2594 | return utflen - 1; | |
2595 | errno = ERANGE; | |
2596 | return -1; | |
2597 | } | |
2598 | ||
0767172b | 2599 | static void setup_windows_environment(void) |
02e6edc0 | 2600 | { |
1fc7bf79 JS |
2601 | char *tmp = getenv("TMPDIR"); |
2602 | ||
02e6edc0 | 2603 | /* on Windows it is TMP and TEMP */ |
1fc7bf79 JS |
2604 | if (!tmp) { |
2605 | if (!(tmp = getenv("TMP"))) | |
02e6edc0 | 2606 | tmp = getenv("TEMP"); |
1fc7bf79 | 2607 | if (tmp) { |
02e6edc0 | 2608 | setenv("TMPDIR", tmp, 1); |
1fc7bf79 JS |
2609 | tmp = getenv("TMPDIR"); |
2610 | } | |
2611 | } | |
2612 | ||
2613 | if (tmp) { | |
2614 | /* | |
2615 | * Convert all dir separators to forward slashes, | |
2616 | * to help shell commands called from the Git | |
2617 | * executable (by not mistaking the dir separators | |
2618 | * for escape characters). | |
2619 | */ | |
8e9b2080 | 2620 | convert_slashes(tmp); |
02e6edc0 KB |
2621 | } |
2622 | ||
2623 | /* simulate TERM to enable auto-color (see color.c) */ | |
2624 | if (!getenv("TERM")) | |
2625 | setenv("TERM", "cygwin", 1); | |
e12a9556 KB |
2626 | |
2627 | /* calculate HOME if not set */ | |
2628 | if (!getenv("HOME")) { | |
2629 | /* | |
2630 | * try $HOMEDRIVE$HOMEPATH - the home share may be a network | |
2631 | * location, thus also check if the path exists (i.e. is not | |
2632 | * disconnected) | |
2633 | */ | |
2634 | if ((tmp = getenv("HOMEDRIVE"))) { | |
2635 | struct strbuf buf = STRBUF_INIT; | |
2636 | strbuf_addstr(&buf, tmp); | |
2637 | if ((tmp = getenv("HOMEPATH"))) { | |
2638 | strbuf_addstr(&buf, tmp); | |
2639 | if (is_directory(buf.buf)) | |
2640 | setenv("HOME", buf.buf, 1); | |
2641 | else | |
2642 | tmp = NULL; /* use $USERPROFILE */ | |
2643 | } | |
2644 | strbuf_release(&buf); | |
2645 | } | |
2646 | /* use $USERPROFILE if the home share is not available */ | |
2647 | if (!tmp && (tmp = getenv("USERPROFILE"))) | |
2648 | setenv("HOME", tmp, 1); | |
2649 | } | |
02e6edc0 KB |
2650 | } |
2651 | ||
bdc77d1d JS |
2652 | static PSID get_current_user_sid(void) |
2653 | { | |
2654 | HANDLE token; | |
2655 | DWORD len = 0; | |
2656 | PSID result = NULL; | |
2657 | ||
2658 | if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token)) | |
2659 | return NULL; | |
2660 | ||
2661 | if (!GetTokenInformation(token, TokenUser, NULL, 0, &len)) { | |
2662 | TOKEN_USER *info = xmalloc((size_t)len); | |
2663 | if (GetTokenInformation(token, TokenUser, info, len, &len)) { | |
2664 | len = GetLengthSid(info->User.Sid); | |
2665 | result = xmalloc(len); | |
2666 | if (!CopySid(len, result, info->User.Sid)) { | |
2667 | error(_("failed to copy SID (%ld)"), | |
2668 | GetLastError()); | |
2669 | FREE_AND_NULL(result); | |
2670 | } | |
2671 | } | |
2672 | FREE_AND_NULL(info); | |
2673 | } | |
2674 | CloseHandle(token); | |
2675 | ||
2676 | return result; | |
2677 | } | |
2678 | ||
7c83470e JS |
2679 | static int acls_supported(const char *path) |
2680 | { | |
2681 | size_t offset = offset_1st_component(path); | |
2682 | WCHAR wroot[MAX_PATH]; | |
2683 | DWORD file_system_flags; | |
2684 | ||
2685 | if (offset && | |
2686 | xutftowcsn(wroot, path, MAX_PATH, offset) > 0 && | |
2687 | GetVolumeInformationW(wroot, NULL, 0, NULL, NULL, | |
2688 | &file_system_flags, NULL, 0)) | |
2689 | return !!(file_system_flags & FILE_PERSISTENT_ACLS); | |
2690 | ||
2691 | return 0; | |
2692 | } | |
2693 | ||
17d3883f | 2694 | int is_path_owned_by_current_sid(const char *path, struct strbuf *report) |
bdc77d1d JS |
2695 | { |
2696 | WCHAR wpath[MAX_PATH]; | |
2697 | PSID sid = NULL; | |
2698 | PSECURITY_DESCRIPTOR descriptor = NULL; | |
2699 | DWORD err; | |
2700 | ||
2701 | static wchar_t home[MAX_PATH]; | |
2702 | ||
2703 | int result = 0; | |
2704 | ||
2705 | if (xutftowcs_path(wpath, path) < 0) | |
2706 | return 0; | |
2707 | ||
2708 | /* | |
2709 | * On Windows, the home directory is owned by the administrator, but for | |
2710 | * all practical purposes, it belongs to the user. Do pretend that it is | |
2711 | * owned by the user. | |
2712 | */ | |
2713 | if (!*home) { | |
2714 | DWORD size = ARRAY_SIZE(home); | |
2715 | DWORD len = GetEnvironmentVariableW(L"HOME", home, size); | |
2716 | if (!len || len > size) | |
2717 | wcscpy(home, L"::N/A::"); | |
2718 | } | |
2719 | if (!wcsicmp(wpath, home)) | |
2720 | return 1; | |
2721 | ||
2722 | /* Get the owner SID */ | |
2723 | err = GetNamedSecurityInfoW(wpath, SE_FILE_OBJECT, | |
2724 | OWNER_SECURITY_INFORMATION | | |
2725 | DACL_SECURITY_INFORMATION, | |
2726 | &sid, NULL, NULL, NULL, &descriptor); | |
2727 | ||
2728 | if (err != ERROR_SUCCESS) | |
2729 | error(_("failed to get owner for '%s' (%ld)"), path, err); | |
2730 | else if (sid && IsValidSid(sid)) { | |
2731 | /* Now, verify that the SID matches the current user's */ | |
2732 | static PSID current_user_sid; | |
3f7207e2 | 2733 | BOOL is_member; |
bdc77d1d JS |
2734 | |
2735 | if (!current_user_sid) | |
2736 | current_user_sid = get_current_user_sid(); | |
2737 | ||
2738 | if (current_user_sid && | |
2739 | IsValidSid(current_user_sid) && | |
2740 | EqualSid(sid, current_user_sid)) | |
2741 | result = 1; | |
3f7207e2 JS |
2742 | else if (IsWellKnownSid(sid, WinBuiltinAdministratorsSid) && |
2743 | CheckTokenMembership(NULL, sid, &is_member) && | |
2744 | is_member) | |
2745 | /* | |
2746 | * If owned by the Administrators group, and the | |
2747 | * current user is an administrator, we consider that | |
2748 | * okay, too. | |
2749 | */ | |
2750 | result = 1; | |
7c83470e JS |
2751 | else if (report && |
2752 | IsWellKnownSid(sid, WinWorldSid) && | |
2753 | !acls_supported(path)) { | |
2754 | /* | |
2755 | * On FAT32 volumes, ownership is not actually recorded. | |
2756 | */ | |
4eb1ccec | 2757 | strbuf_addf(report, "'%s' is on a file system that does " |
7c83470e JS |
2758 | "not record ownership\n", path); |
2759 | } else if (report) { | |
e883e04b JS |
2760 | LPSTR str1, str2, to_free1 = NULL, to_free2 = NULL; |
2761 | ||
2762 | if (ConvertSidToStringSidA(sid, &str1)) | |
2763 | to_free1 = str1; | |
2764 | else | |
2765 | str1 = "(inconvertible)"; | |
2766 | ||
2767 | if (!current_user_sid) | |
2768 | str2 = "(none)"; | |
2769 | else if (!IsValidSid(current_user_sid)) | |
2770 | str2 = "(invalid)"; | |
2771 | else if (ConvertSidToStringSidA(current_user_sid, &str2)) | |
2772 | to_free2 = str2; | |
2773 | else | |
2774 | str2 = "(inconvertible)"; | |
2775 | strbuf_addf(report, | |
2776 | "'%s' is owned by:\n" | |
2777 | "\t'%s'\nbut the current user is:\n" | |
2778 | "\t'%s'\n", path, str1, str2); | |
2779 | LocalFree(to_free1); | |
2780 | LocalFree(to_free2); | |
2781 | } | |
bdc77d1d JS |
2782 | } |
2783 | ||
2784 | /* | |
2785 | * We can release the security descriptor struct only now because `sid` | |
2786 | * actually points into this struct. | |
2787 | */ | |
2788 | if (descriptor) | |
2789 | LocalFree(descriptor); | |
2790 | ||
2791 | return result; | |
2792 | } | |
2793 | ||
4dc42c6c | 2794 | int is_valid_win32_path(const char *path, int allow_literal_nul) |
d2c84dad | 2795 | { |
4dc42c6c | 2796 | const char *p = path; |
d2c84dad JS |
2797 | int preceding_space_or_period = 0, i = 0, periods = 0; |
2798 | ||
2799 | if (!protect_ntfs) | |
2800 | return 1; | |
2801 | ||
817ddd64 | 2802 | skip_dos_drive_prefix((char **)&path); |
4dc42c6c | 2803 | goto segment_start; |
817ddd64 | 2804 | |
d2c84dad JS |
2805 | for (;;) { |
2806 | char c = *(path++); | |
2807 | switch (c) { | |
2808 | case '\0': | |
2809 | case '/': case '\\': | |
2810 | /* cannot end in ` ` or `.`, except for `.` and `..` */ | |
2811 | if (preceding_space_or_period && | |
2812 | (i != periods || periods > 2)) | |
2813 | return 0; | |
2814 | if (!c) | |
2815 | return 1; | |
2816 | ||
2817 | i = periods = preceding_space_or_period = 0; | |
4dc42c6c JS |
2818 | |
2819 | segment_start: | |
2820 | switch (*path) { | |
2821 | case 'a': case 'A': /* AUX */ | |
2822 | if (((c = path[++i]) != 'u' && c != 'U') || | |
2823 | ((c = path[++i]) != 'x' && c != 'X')) { | |
2824 | not_a_reserved_name: | |
2825 | path += i; | |
2826 | continue; | |
2827 | } | |
2828 | break; | |
b6852e19 JS |
2829 | case 'c': case 'C': |
2830 | /* COM1 ... COM9, CON, CONIN$, CONOUT$ */ | |
4dc42c6c JS |
2831 | if ((c = path[++i]) != 'o' && c != 'O') |
2832 | goto not_a_reserved_name; | |
2833 | c = path[++i]; | |
b6852e19 JS |
2834 | if (c == 'm' || c == 'M') { /* COM1 ... COM9 */ |
2835 | c = path[++i]; | |
2836 | if (c < '1' || c > '9') | |
4dc42c6c JS |
2837 | goto not_a_reserved_name; |
2838 | } else if (c == 'n' || c == 'N') { /* CON */ | |
2839 | c = path[i + 1]; | |
2840 | if ((c == 'i' || c == 'I') && | |
2841 | ((c = path[i + 2]) == 'n' || | |
2842 | c == 'N') && | |
2843 | path[i + 3] == '$') | |
2844 | i += 3; /* CONIN$ */ | |
2845 | else if ((c == 'o' || c == 'O') && | |
2846 | ((c = path[i + 2]) == 'u' || | |
2847 | c == 'U') && | |
2848 | ((c = path[i + 3]) == 't' || | |
2849 | c == 'T') && | |
2850 | path[i + 4] == '$') | |
2851 | i += 4; /* CONOUT$ */ | |
2852 | } else | |
2853 | goto not_a_reserved_name; | |
2854 | break; | |
2855 | case 'l': case 'L': /* LPT<N> */ | |
2856 | if (((c = path[++i]) != 'p' && c != 'P') || | |
2857 | ((c = path[++i]) != 't' && c != 'T') || | |
2858 | !isdigit(path[++i])) | |
2859 | goto not_a_reserved_name; | |
2860 | break; | |
2861 | case 'n': case 'N': /* NUL */ | |
2862 | if (((c = path[++i]) != 'u' && c != 'U') || | |
2863 | ((c = path[++i]) != 'l' && c != 'L') || | |
2864 | (allow_literal_nul && | |
2865 | !path[i + 1] && p == path)) | |
2866 | goto not_a_reserved_name; | |
2867 | break; | |
2868 | case 'p': case 'P': /* PRN */ | |
2869 | if (((c = path[++i]) != 'r' && c != 'R') || | |
2870 | ((c = path[++i]) != 'n' && c != 'N')) | |
2871 | goto not_a_reserved_name; | |
2872 | break; | |
2873 | default: | |
2874 | continue; | |
2875 | } | |
2876 | ||
2877 | /* | |
2878 | * So far, this looks like a reserved name. Let's see | |
2879 | * whether it actually is one: trailing spaces, a file | |
2880 | * extension, or an NTFS Alternate Data Stream do not | |
2881 | * matter, the name is still reserved if any of those | |
2882 | * follow immediately after the actual name. | |
2883 | */ | |
2884 | i++; | |
2885 | if (path[i] == ' ') { | |
2886 | preceding_space_or_period = 1; | |
2887 | while (path[++i] == ' ') | |
2888 | ; /* skip all spaces */ | |
2889 | } | |
2890 | ||
2891 | c = path[i]; | |
9fd512c8 | 2892 | if (c && c != '.' && c != ':' && !is_xplatform_dir_sep(c)) |
4dc42c6c JS |
2893 | goto not_a_reserved_name; |
2894 | ||
2895 | /* contains reserved name */ | |
2896 | return 0; | |
d2c84dad JS |
2897 | case '.': |
2898 | periods++; | |
2899 | /* fallthru */ | |
2900 | case ' ': | |
2901 | preceding_space_or_period = 1; | |
2902 | i++; | |
2903 | continue; | |
817ddd64 JS |
2904 | case ':': /* DOS drive prefix was already skipped */ |
2905 | case '<': case '>': case '"': case '|': case '?': case '*': | |
2906 | /* illegal character */ | |
2907 | return 0; | |
2908 | default: | |
2909 | if (c > '\0' && c < '\x20') | |
2910 | /* illegal character */ | |
2911 | return 0; | |
d2c84dad JS |
2912 | } |
2913 | preceding_space_or_period = 0; | |
2914 | i++; | |
2915 | } | |
2916 | } | |
2917 | ||
396ff754 | 2918 | #if !defined(_MSC_VER) |
5901dc66 KB |
2919 | /* |
2920 | * Disable MSVCRT command line wildcard expansion (__getmainargs called from | |
2921 | * mingw startup code, see init.c in mingw runtime). | |
2922 | */ | |
2923 | int _CRT_glob = 0; | |
396ff754 | 2924 | #endif |
3f046148 | 2925 | |
0767172b | 2926 | static NORETURN void die_startup(void) |
3f046148 KB |
2927 | { |
2928 | fputs("fatal: not enough memory for initialization", stderr); | |
2929 | exit(128); | |
2930 | } | |
2931 | ||
6f1c189c KB |
2932 | static void *malloc_startup(size_t size) |
2933 | { | |
2934 | void *result = malloc(size); | |
2935 | if (!result) | |
2936 | die_startup(); | |
2937 | return result; | |
2938 | } | |
2939 | ||
2940 | static char *wcstoutfdup_startup(char *buffer, const wchar_t *wcs, size_t len) | |
2941 | { | |
2942 | len = xwcstoutf(buffer, wcs, len) + 1; | |
2943 | return memcpy(malloc_startup(len), buffer, len); | |
2944 | } | |
2945 | ||
3f944424 JS |
2946 | static void maybe_redirect_std_handle(const wchar_t *key, DWORD std_id, int fd, |
2947 | DWORD desired_access, DWORD flags) | |
2948 | { | |
2949 | DWORD create_flag = fd ? OPEN_ALWAYS : OPEN_EXISTING; | |
2950 | wchar_t buf[MAX_PATH]; | |
2951 | DWORD max = ARRAY_SIZE(buf); | |
2952 | HANDLE handle; | |
2953 | DWORD ret = GetEnvironmentVariableW(key, buf, max); | |
2954 | ||
2955 | if (!ret || ret >= max) | |
2956 | return; | |
2957 | ||
2958 | /* make sure this does not leak into child processes */ | |
2959 | SetEnvironmentVariableW(key, NULL); | |
2960 | if (!wcscmp(buf, L"off")) { | |
2961 | close(fd); | |
2962 | handle = GetStdHandle(std_id); | |
2963 | if (handle != INVALID_HANDLE_VALUE) | |
2964 | CloseHandle(handle); | |
2965 | return; | |
2966 | } | |
1a172e4a JS |
2967 | if (std_id == STD_ERROR_HANDLE && !wcscmp(buf, L"2>&1")) { |
2968 | handle = GetStdHandle(STD_OUTPUT_HANDLE); | |
2969 | if (handle == INVALID_HANDLE_VALUE) { | |
2970 | close(fd); | |
2971 | handle = GetStdHandle(std_id); | |
2972 | if (handle != INVALID_HANDLE_VALUE) | |
2973 | CloseHandle(handle); | |
2974 | } else { | |
2975 | int new_fd = _open_osfhandle((intptr_t)handle, O_BINARY); | |
2976 | SetStdHandle(std_id, handle); | |
2977 | dup2(new_fd, fd); | |
2978 | /* do *not* close the new_fd: that would close stdout */ | |
2979 | } | |
2980 | return; | |
2981 | } | |
3f944424 JS |
2982 | handle = CreateFileW(buf, desired_access, 0, NULL, create_flag, |
2983 | flags, NULL); | |
2984 | if (handle != INVALID_HANDLE_VALUE) { | |
2985 | int new_fd = _open_osfhandle((intptr_t)handle, O_BINARY); | |
2986 | SetStdHandle(std_id, handle); | |
2987 | dup2(new_fd, fd); | |
2988 | close(new_fd); | |
2989 | } | |
2990 | } | |
2991 | ||
2992 | static void maybe_redirect_std_handles(void) | |
2993 | { | |
2994 | maybe_redirect_std_handle(L"GIT_REDIRECT_STDIN", STD_INPUT_HANDLE, 0, | |
2995 | GENERIC_READ, FILE_ATTRIBUTE_NORMAL); | |
2996 | maybe_redirect_std_handle(L"GIT_REDIRECT_STDOUT", STD_OUTPUT_HANDLE, 1, | |
2997 | GENERIC_WRITE, FILE_ATTRIBUTE_NORMAL); | |
2998 | maybe_redirect_std_handle(L"GIT_REDIRECT_STDERR", STD_ERROR_HANDLE, 2, | |
2999 | GENERIC_WRITE, FILE_FLAG_NO_BUFFERING); | |
3000 | } | |
3001 | ||
dce7d295 JH |
3002 | #ifdef _MSC_VER |
3003 | #ifdef _DEBUG | |
3004 | #include <crtdbg.h> | |
3005 | #endif | |
3006 | #endif | |
3007 | ||
396ff754 JS |
3008 | /* |
3009 | * We implement wmain() and compile with -municode, which would | |
3010 | * normally ignore main(), but we call the latter from the former | |
3011 | * so that we can handle non-ASCII command-line parameters | |
3012 | * appropriately. | |
3013 | * | |
3014 | * To be more compatible with the core git code, we convert | |
3015 | * argv into UTF8 and pass them directly to main(). | |
3016 | */ | |
3017 | int wmain(int argc, const wchar_t **wargv) | |
13f1df43 | 3018 | { |
396ff754 JS |
3019 | int i, maxlen, exit_status; |
3020 | char *buffer, **save; | |
3021 | const char **argv; | |
3f046148 | 3022 | |
a0897249 JH |
3023 | trace2_initialize_clock(); |
3024 | ||
556702f8 | 3025 | #ifdef _MSC_VER |
f6a63937 JS |
3026 | #ifdef _DEBUG |
3027 | _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_DEBUG); | |
3028 | #endif | |
3029 | ||
556702f8 JH |
3030 | #ifdef USE_MSVC_CRTDBG |
3031 | _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF); | |
3032 | #endif | |
3033 | #endif | |
3034 | ||
3f944424 JS |
3035 | maybe_redirect_std_handles(); |
3036 | ||
3f046148 | 3037 | /* determine size of argv and environ conversion buffer */ |
86e25458 | 3038 | maxlen = wcslen(wargv[0]); |
3f046148 KB |
3039 | for (i = 1; i < argc; i++) |
3040 | maxlen = max(maxlen, wcslen(wargv[i])); | |
3041 | ||
3042 | /* allocate buffer (wchar_t encodes to max 3 UTF-8 bytes) */ | |
3043 | maxlen = 3 * maxlen + 1; | |
6f1c189c | 3044 | buffer = malloc_startup(maxlen); |
3f046148 | 3045 | |
396ff754 JS |
3046 | /* |
3047 | * Create a UTF-8 version of w_argv. Also create a "save" copy | |
3048 | * to remember all the string pointers because parse_options() | |
3049 | * will remove claimed items from the argv that we pass down. | |
3050 | */ | |
3051 | ALLOC_ARRAY(argv, argc + 1); | |
3052 | ALLOC_ARRAY(save, argc + 1); | |
86e25458 | 3053 | for (i = 0; i < argc; i++) |
396ff754 JS |
3054 | argv[i] = save[i] = wcstoutfdup_startup(buffer, wargv[i], maxlen); |
3055 | argv[i] = save[i] = NULL; | |
3f046148 | 3056 | free(buffer); |
13f1df43 | 3057 | |
6dc71543 | 3058 | /* fix Windows specific environment settings */ |
02e6edc0 | 3059 | setup_windows_environment(); |
baea068d | 3060 | |
0e218f91 JS |
3061 | unset_environment_variables = xstrdup("PERL5LIB"); |
3062 | ||
13f1df43 KB |
3063 | /* initialize critical section for waitpid pinfo_t list */ |
3064 | InitializeCriticalSection(&pinfo_cs); | |
3065 | ||
3066 | /* set up default file mode and file modes for stdin/out/err */ | |
3067 | _fmode = _O_BINARY; | |
3068 | _setmode(_fileno(stdin), _O_BINARY); | |
3069 | _setmode(_fileno(stdout), _O_BINARY); | |
3070 | _setmode(_fileno(stderr), _O_BINARY); | |
eac14f89 KB |
3071 | |
3072 | /* initialize Unicode console */ | |
3073 | winansi_init(); | |
396ff754 JS |
3074 | |
3075 | /* invoke the real main() using our utf8 version of argv. */ | |
3076 | exit_status = main(argc, argv); | |
3077 | ||
3078 | for (i = 0; i < argc; i++) | |
3079 | free(save[i]); | |
3080 | free(save); | |
3081 | free(argv); | |
3082 | ||
3083 | return exit_status; | |
13f1df43 | 3084 | } |
7b6aff06 NTND |
3085 | |
3086 | int uname(struct utsname *buf) | |
3087 | { | |
d62c89af | 3088 | unsigned v = (unsigned)GetVersion(); |
7b6aff06 | 3089 | memset(buf, 0, sizeof(*buf)); |
5096d490 JK |
3090 | xsnprintf(buf->sysname, sizeof(buf->sysname), "Windows"); |
3091 | xsnprintf(buf->release, sizeof(buf->release), | |
3092 | "%u.%u", v & 0xff, (v >> 8) & 0xff); | |
7b6aff06 | 3093 | /* assuming NT variants only.. */ |
5096d490 JK |
3094 | xsnprintf(buf->version, sizeof(buf->version), |
3095 | "%u", (v >> 16) & 0x7fff); | |
7b6aff06 NTND |
3096 | return 0; |
3097 | } |