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