Raw
1 /*
2 * Copyright 2008 Peter Harris <git@peter.is-a-geek.org>
3 */
4
5 #undef NOGDI
6
7 #define DISABLE_SIGN_COMPARE_WARNINGS
8
9 #include "../git-compat-util.h"
10 #include <wingdi.h>
11 #include <winreg.h>
12 #include "win32.h"
13 #include "win32/lazyload.h"
14
15 static int fd_is_interactive[3] = { 0, 0, 0 };
16 #define FD_CONSOLE 0x1
17 #define FD_SWAPPED 0x2
18 #define FD_MSYS 0x4
19
20 /*
21 ANSI codes used by git: m, K
22
23 This file is git-specific. Therefore, this file does not attempt
24 to implement any codes that are not used by git.
25 */
26
27 static HANDLE console;
28 static WORD plain_attr;
29 static WORD attr;
30 static int negative;
31 static int non_ascii_used = 0;
32 static HANDLE hthread, hread, hwrite;
33 static HANDLE hconsole1, hconsole2;
34
35 static void warn_if_raster_font(void)
36 {
37 DWORD fontFamily = 0;
38 CONSOLE_FONT_INFOEX cfi;
39
40 /* don't bother if output was ascii only */
41 if (!non_ascii_used)
42 return;
43
44 cfi.cbSize = sizeof(cfi);
45 if (GetCurrentConsoleFontEx(console, 0, &cfi))
46 fontFamily = cfi.FontFamily;
47
48 if (!(fontFamily & TMPF_TRUETYPE)) {
49 const wchar_t *msg = L"\nWarning: Your console font probably "
50 L"doesn\'t support Unicode. If you experience strange "
51 L"characters in the output, consider switching to a "
52 L"TrueType font such as Consolas!\n";
53 DWORD dummy;
54 WriteConsoleW(console, msg, wcslen(msg), &dummy, NULL);
55 }
56 }
57
58 static int is_console(int fd)
59 {
60 CONSOLE_SCREEN_BUFFER_INFO sbi;
61 DWORD mode;
62 HANDLE hcon;
63
64 static int initialized = 0;
65
66 /* get OS handle of the file descriptor */
67 hcon = (HANDLE) _get_osfhandle(fd);
68 if (hcon == INVALID_HANDLE_VALUE)
69 return 0;
70
71 /* check if its a device (i.e. console, printer, serial port) */
72 if (GetFileType(hcon) != FILE_TYPE_CHAR)
73 return 0;
74
75 /* check if its a handle to a console output screen buffer */
76 if (!fd) {
77 if (!GetConsoleMode(hcon, &mode))
78 return 0;
79 /*
80 * This code path is only reached if there is no console
81 * attached to stdout/stderr, i.e. we will not need to output
82 * any text to any console, therefore we might just as well
83 * use black as foreground color.
84 */
85 sbi.wAttributes = 0;
86 } else if (!GetConsoleScreenBufferInfo(hcon, &sbi))
87 return 0;
88
89 if (fd >= 0 && fd <= 2)
90 fd_is_interactive[fd] |= FD_CONSOLE;
91
92 /* initialize attributes */
93 if (!initialized) {
94 console = hcon;
95 attr = plain_attr = sbi.wAttributes;
96 negative = 0;
97 initialized = 1;
98 }
99
100 return 1;
101 }
102
103 #define BUFFER_SIZE 4096
104 #define MAX_PARAMS 16
105
106 static void write_console(unsigned char *str, size_t len)
107 {
108 /* only called from console_thread, so a static buffer will do */
109 static wchar_t wbuf[2 * BUFFER_SIZE + 1];
110 DWORD dummy;
111
112 /* convert utf-8 to utf-16 */
113 int wlen = xutftowcsn(wbuf, (char*) str, ARRAY_SIZE(wbuf), len);
114 if (wlen < 0) {
115 const wchar_t *err = L"[invalid]";
116 WriteConsoleW(console, err, wcslen(err), &dummy, NULL);
117 return;
118 }
119
120 /* write directly to console */
121 WriteConsoleW(console, wbuf, wlen, &dummy, NULL);
122
123 /* remember if non-ascii characters are printed */
124 if (wlen != len)
125 non_ascii_used = 1;
126 }
127
128 #define FOREGROUND_ALL (FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE)
129 #define BACKGROUND_ALL (BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_BLUE)
130
131 static void set_console_attr(void)
132 {
133 WORD attributes = attr;
134 if (negative) {
135 attributes &= ~FOREGROUND_ALL;
136 attributes &= ~BACKGROUND_ALL;
137
138 /* This could probably use a bitmask
139 instead of a series of ifs */
140 if (attr & FOREGROUND_RED)
141 attributes |= BACKGROUND_RED;
142 if (attr & FOREGROUND_GREEN)
143 attributes |= BACKGROUND_GREEN;
144 if (attr & FOREGROUND_BLUE)
145 attributes |= BACKGROUND_BLUE;
146
147 if (attr & BACKGROUND_RED)
148 attributes |= FOREGROUND_RED;
149 if (attr & BACKGROUND_GREEN)
150 attributes |= FOREGROUND_GREEN;
151 if (attr & BACKGROUND_BLUE)
152 attributes |= FOREGROUND_BLUE;
153 }
154 SetConsoleTextAttribute(console, attributes);
155 }
156
157 static void erase_in_line(void)
158 {
159 CONSOLE_SCREEN_BUFFER_INFO sbi;
160 DWORD dummy; /* Needed for Windows 7 (or Vista) regression */
161
162 if (!console)
163 return;
164
165 GetConsoleScreenBufferInfo(console, &sbi);
166 FillConsoleOutputCharacterA(console, ' ',
167 sbi.dwSize.X - sbi.dwCursorPosition.X, sbi.dwCursorPosition,
168 &dummy);
169 }
170
171 static void set_attr(char func, const int *params, int paramlen)
172 {
173 int i;
174 switch (func) {
175 case 'm':
176 for (i = 0; i < paramlen; i++) {
177 switch (params[i]) {
178 case 0: /* reset */
179 attr = plain_attr;
180 negative = 0;
181 break;
182 case 1: /* bold */
183 attr |= FOREGROUND_INTENSITY;
184 break;
185 case 2: /* faint */
186 case 22: /* normal */
187 attr &= ~FOREGROUND_INTENSITY;
188 break;
189 case 3: /* italic */
190 /* Unsupported */
191 break;
192 case 4: /* underline */
193 case 21: /* double underline */
194 /* Wikipedia says this flag does nothing */
195 /* Furthermore, mingw doesn't define this flag
196 attr |= COMMON_LVB_UNDERSCORE; */
197 break;
198 case 24: /* no underline */
199 /* attr &= ~COMMON_LVB_UNDERSCORE; */
200 break;
201 case 5: /* slow blink */
202 case 6: /* fast blink */
203 /* We don't have blink, but we do have
204 background intensity */
205 attr |= BACKGROUND_INTENSITY;
206 break;
207 case 25: /* no blink */
208 attr &= ~BACKGROUND_INTENSITY;
209 break;
210 case 7: /* negative */
211 negative = 1;
212 break;
213 case 27: /* positive */
214 negative = 0;
215 break;
216 case 8: /* conceal */
217 case 28: /* reveal */
218 /* Unsupported */
219 break;
220 case 30: /* Black */
221 attr &= ~FOREGROUND_ALL;
222 break;
223 case 31: /* Red */
224 attr &= ~FOREGROUND_ALL;
225 attr |= FOREGROUND_RED;
226 break;
227 case 32: /* Green */
228 attr &= ~FOREGROUND_ALL;
229 attr |= FOREGROUND_GREEN;
230 break;
231 case 33: /* Yellow */
232 attr &= ~FOREGROUND_ALL;
233 attr |= FOREGROUND_RED | FOREGROUND_GREEN;
234 break;
235 case 34: /* Blue */
236 attr &= ~FOREGROUND_ALL;
237 attr |= FOREGROUND_BLUE;
238 break;
239 case 35: /* Magenta */
240 attr &= ~FOREGROUND_ALL;
241 attr |= FOREGROUND_RED | FOREGROUND_BLUE;
242 break;
243 case 36: /* Cyan */
244 attr &= ~FOREGROUND_ALL;
245 attr |= FOREGROUND_GREEN | FOREGROUND_BLUE;
246 break;
247 case 37: /* White */
248 attr |= FOREGROUND_RED |
249 FOREGROUND_GREEN |
250 FOREGROUND_BLUE;
251 break;
252 case 38: /* Unknown */
253 break;
254 case 39: /* reset */
255 attr &= ~FOREGROUND_ALL;
256 attr |= (plain_attr & FOREGROUND_ALL);
257 break;
258 case 40: /* Black */
259 attr &= ~BACKGROUND_ALL;
260 break;
261 case 41: /* Red */
262 attr &= ~BACKGROUND_ALL;
263 attr |= BACKGROUND_RED;
264 break;
265 case 42: /* Green */
266 attr &= ~BACKGROUND_ALL;
267 attr |= BACKGROUND_GREEN;
268 break;
269 case 43: /* Yellow */
270 attr &= ~BACKGROUND_ALL;
271 attr |= BACKGROUND_RED | BACKGROUND_GREEN;
272 break;
273 case 44: /* Blue */
274 attr &= ~BACKGROUND_ALL;
275 attr |= BACKGROUND_BLUE;
276 break;
277 case 45: /* Magenta */
278 attr &= ~BACKGROUND_ALL;
279 attr |= BACKGROUND_RED | BACKGROUND_BLUE;
280 break;
281 case 46: /* Cyan */
282 attr &= ~BACKGROUND_ALL;
283 attr |= BACKGROUND_GREEN | BACKGROUND_BLUE;
284 break;
285 case 47: /* White */
286 attr |= BACKGROUND_RED |
287 BACKGROUND_GREEN |
288 BACKGROUND_BLUE;
289 break;
290 case 48: /* Unknown */
291 break;
292 case 49: /* reset */
293 attr &= ~BACKGROUND_ALL;
294 attr |= (plain_attr & BACKGROUND_ALL);
295 break;
296 default:
297 /* Unsupported code */
298 break;
299 }
300 }
301 set_console_attr();
302 break;
303 case 'K':
304 erase_in_line();
305 break;
306 default:
307 /* Unsupported code */
308 break;
309 }
310 }
311
312 enum {
313 TEXT = 0, ESCAPE = 033, BRACKET = '['
314 };
315
316 static DWORD WINAPI console_thread(LPVOID data UNUSED)
317 {
318 unsigned char buffer[BUFFER_SIZE];
319 DWORD bytes;
320 int start, end = 0, c, parampos = 0, state = TEXT;
321 int params[MAX_PARAMS];
322
323 while (1) {
324 /* read next chunk of bytes from the pipe */
325 if (!ReadFile(hread, buffer + end, BUFFER_SIZE - end, &bytes,
326 NULL)) {
327 /* exit if pipe has been closed or disconnected */
328 if (GetLastError() == ERROR_PIPE_NOT_CONNECTED ||
329 GetLastError() == ERROR_BROKEN_PIPE)
330 break;
331 /* ignore other errors */
332 continue;
333 }
334
335 /* scan the bytes and handle ANSI control codes */
336 bytes += end;
337 start = end = 0;
338 while (end < bytes) {
339 c = buffer[end++];
340 switch (state) {
341 case TEXT:
342 if (c == ESCAPE) {
343 /* print text seen so far */
344 if (end - 1 > start)
345 write_console(buffer + start,
346 end - 1 - start);
347
348 /* then start parsing escape sequence */
349 start = end - 1;
350 memset(params, 0, sizeof(params));
351 parampos = 0;
352 state = ESCAPE;
353 }
354 break;
355
356 case ESCAPE:
357 /* continue if "\033[", otherwise bail out */
358 state = (c == BRACKET) ? BRACKET : TEXT;
359 break;
360
361 case BRACKET:
362 /* parse [0-9;]* into array of parameters */
363 if (c >= '0' && c <= '9') {
364 params[parampos] *= 10;
365 params[parampos] += c - '0';
366 } else if (c == ';') {
367 /*
368 * next parameter, bail out if out of
369 * bounds
370 */
371 parampos++;
372 if (parampos >= MAX_PARAMS)
373 state = TEXT;
374 } else {
375 /*
376 * end of escape sequence, change
377 * console attributes
378 */
379 set_attr(c, params, parampos + 1);
380 start = end;
381 state = TEXT;
382 }
383 break;
384 }
385 }
386
387 /* print remaining text unless parsing an escape sequence */
388 if (state == TEXT && end > start) {
389 /* check for incomplete UTF-8 sequences and fix end */
390 if (buffer[end - 1] >= 0x80) {
391 if (buffer[end -1] >= 0xc0)
392 end--;
393 else if (end - 1 > start &&
394 buffer[end - 2] >= 0xe0)
395 end -= 2;
396 else if (end - 2 > start &&
397 buffer[end - 3] >= 0xf0)
398 end -= 3;
399 }
400
401 /* print remaining complete UTF-8 sequences */
402 if (end > start)
403 write_console(buffer + start, end - start);
404
405 /* move remaining bytes to the front */
406 if (end < bytes)
407 memmove(buffer, buffer + end, bytes - end);
408 end = bytes - end;
409 } else {
410 /* all data has been consumed, mark buffer empty */
411 end = 0;
412 }
413 }
414
415 /* check if the console font supports unicode */
416 warn_if_raster_font();
417
418 CloseHandle(hread);
419 return 0;
420 }
421
422 static void winansi_exit(void)
423 {
424 /* flush all streams */
425 _flushall();
426
427 /* signal console thread to exit */
428 FlushFileBuffers(hwrite);
429 DisconnectNamedPipe(hwrite);
430
431 /* wait for console thread to copy remaining data */
432 WaitForSingleObject(hthread, INFINITE);
433
434 /* cleanup handles... */
435 CloseHandle(hwrite);
436 CloseHandle(hthread);
437 }
438
439 static void die_lasterr(const char *fmt, ...)
440 {
441 va_list params;
442 va_start(params, fmt);
443 errno = err_win_to_posix(GetLastError());
444 die_errno(fmt, params);
445 va_end(params);
446 }
447
448 #undef dup2
449 int winansi_dup2(int oldfd, int newfd)
450 {
451 int ret = dup2(oldfd, newfd);
452
453 if (!ret && newfd >= 0 && newfd <= 2)
454 fd_is_interactive[newfd] = oldfd < 0 || oldfd > 2 ?
455 0 : fd_is_interactive[oldfd];
456
457 return ret;
458 }
459
460 static HANDLE duplicate_handle(HANDLE hnd)
461 {
462 HANDLE hresult, hproc = GetCurrentProcess();
463 if (!DuplicateHandle(hproc, hnd, hproc, &hresult, 0, TRUE,
464 DUPLICATE_SAME_ACCESS))
465 die_lasterr("DuplicateHandle(%li) failed",
466 (long) (intptr_t) hnd);
467 return hresult;
468 }
469
470 static HANDLE swap_osfhnd(int fd, HANDLE new_handle)
471 {
472 /*
473 * Create a copy of the original handle associated with fd
474 * because the original will get closed when we dup2().
475 */
476 HANDLE handle = (HANDLE)_get_osfhandle(fd);
477 HANDLE duplicate = duplicate_handle(handle);
478
479 /* Create a temp fd associated with the already open "new_handle". */
480 int new_fd = _open_osfhandle((intptr_t)new_handle, O_BINARY);
481
482 assert((fd == 1) || (fd == 2));
483
484 /*
485 * Use stock dup2() to re-bind fd to the new handle. Note that
486 * this will implicitly close(1) and close both fd=1 and the
487 * originally associated handle. It will open a new fd=1 and
488 * call DuplicateHandle() on the handle associated with new_fd.
489 * It is because of this implicit close() that we created the
490 * copy of the original.
491 *
492 * Note that we need to update the cached console handle to the
493 * duplicated one because the dup2() call will implicitly close
494 * the original one.
495 *
496 * Note that dup2() when given target := {0,1,2} will also
497 * call SetStdHandle(), so we don't need to worry about that.
498 */
499 if (console == handle)
500 console = duplicate;
501 dup2(new_fd, fd);
502
503 /* Close the temp fd. This explicitly closes "new_handle"
504 * (because it has been associated with it).
505 */
506 close(new_fd);
507
508 if (fd == 2)
509 setvbuf(stderr, NULL, _IONBF, BUFSIZ);
510 fd_is_interactive[fd] |= FD_SWAPPED;
511
512 return duplicate;
513 }
514
515 #ifdef DETECT_MSYS_TTY
516
517 #include <winternl.h>
518
519 #if defined(_MSC_VER)
520
521 typedef struct _OBJECT_NAME_INFORMATION
522 {
523 UNICODE_STRING Name;
524 WCHAR NameBuffer[FLEX_ARRAY];
525 } OBJECT_NAME_INFORMATION, *POBJECT_NAME_INFORMATION;
526
527 #define ObjectNameInformation 1
528
529 #else
530 #include <ntstatus.h>
531 #endif
532
533 static void detect_msys_tty(int fd)
534 {
535 ULONG result;
536 BYTE buffer[1024];
537 POBJECT_NAME_INFORMATION nameinfo = (POBJECT_NAME_INFORMATION) buffer;
538 PWSTR name;
539
540 /* check if fd is a pipe */
541 HANDLE h = (HANDLE) _get_osfhandle(fd);
542 if (GetFileType(h) != FILE_TYPE_PIPE)
543 return;
544
545 /* get pipe name */
546 if (!NT_SUCCESS(NtQueryObject(h, ObjectNameInformation,
547 buffer, sizeof(buffer) - 2, &result)))
548 return;
549 name = nameinfo->Name.Buffer;
550 name[nameinfo->Name.Length / sizeof(*name)] = 0;
551
552 /*
553 * Check if this could be a MSYS2 pty pipe ('msys-XXXX-ptyN-XX')
554 * or a cygwin pty pipe ('cygwin-XXXX-ptyN-XX')
555 */
556 if ((!wcsstr(name, L"msys-") && !wcsstr(name, L"cygwin-")) ||
557 !wcsstr(name, L"-pty"))
558 return;
559
560 if (fd == 2)
561 setvbuf(stderr, NULL, _IONBF, BUFSIZ);
562 fd_is_interactive[fd] |= FD_MSYS;
563 }
564
565 #endif
566
567 /*
568 * Wrapper for isatty(). Most calls in the main git code
569 * call isatty(1 or 2) to see if the instance is interactive
570 * and should: be colored, show progress, paginate output.
571 * We lie and give results for what the descriptor WAS at
572 * startup (and ignore any pipe redirection we internally
573 * do).
574 */
575 #undef isatty
576 int winansi_isatty(int fd)
577 {
578 if (fd >= 0 && fd <= 2)
579 return fd_is_interactive[fd] != 0;
580 return isatty(fd);
581 }
582
583 void winansi_init(void)
584 {
585 int con1, con2;
586 wchar_t name[32];
587
588 /* check if either stdout or stderr is a console output screen buffer */
589 con1 = is_console(1);
590 con2 = is_console(2);
591
592 /* Also compute console bit for fd 0 even though we don't need the result here. */
593 is_console(0);
594
595 if (!con1 && !con2) {
596 #ifdef DETECT_MSYS_TTY
597 /* check if stdin / stdout / stderr are MSYS2 pty pipes */
598 detect_msys_tty(0);
599 detect_msys_tty(1);
600 detect_msys_tty(2);
601 #endif
602 return;
603 }
604
605 /* create a named pipe to communicate with the console thread */
606 if (swprintf(name, ARRAY_SIZE(name) - 1, L"\\\\.\\pipe\\winansi%lu",
607 GetCurrentProcessId()) < 0)
608 die("Could not initialize winansi pipe name");
609 hwrite = CreateNamedPipeW(name, PIPE_ACCESS_OUTBOUND,
610 PIPE_TYPE_BYTE | PIPE_WAIT, 1, BUFFER_SIZE, 0, 0, NULL);
611 if (hwrite == INVALID_HANDLE_VALUE)
612 die_lasterr("CreateNamedPipe failed");
613
614 hread = CreateFileW(name, GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
615 if (hread == INVALID_HANDLE_VALUE)
616 die_lasterr("CreateFile for named pipe failed");
617
618 /* start console spool thread on the pipe's read end */
619 hthread = CreateThread(NULL, 0, console_thread, NULL, 0, NULL);
620 if (!hthread)
621 die_lasterr("CreateThread(console_thread) failed");
622
623 /* schedule cleanup routine */
624 if (atexit(winansi_exit))
625 die_errno("atexit(winansi_exit) failed");
626
627 /* redirect stdout / stderr to the pipe */
628 if (con1)
629 hconsole1 = swap_osfhnd(1, duplicate_handle(hwrite));
630 if (con2)
631 hconsole2 = swap_osfhnd(2, duplicate_handle(hwrite));
632 }
633
634 /*
635 * Returns the real console handle if stdout / stderr is a pipe redirecting
636 * to the console. Allows spawn / exec to pass the console to the next process.
637 */
638 HANDLE winansi_get_osfhandle(int fd)
639 {
640 HANDLE ret;
641
642 if (fd == 1 && (fd_is_interactive[1] & FD_SWAPPED))
643 return hconsole1;
644 if (fd == 2 && (fd_is_interactive[2] & FD_SWAPPED))
645 return hconsole2;
646
647 ret = (HANDLE)_get_osfhandle(fd);
648
649 /*
650 * There are obviously circumstances under which _get_osfhandle()
651 * returns (HANDLE)-2. This is not documented anywhere, but that is so
652 * clearly an invalid handle value that we can just work around this
653 * and return the correct value for invalid handles.
654 */
655 return ret == (HANDLE)-2 ? INVALID_HANDLE_VALUE : ret;
656 }