compat / winansi.con commit Win32: Thread-safe windows console output (eac14f8)
   1/*
   2 * Copyright 2008 Peter Harris <git@peter.is-a-geek.org>
   3 */
   4
   5#undef NOGDI
   6#include "../git-compat-util.h"
   7#include <wingdi.h>
   8#include <winreg.h>
   9
  10/*
  11 Functions to be wrapped:
  12*/
  13#undef isatty
  14
  15/*
  16 ANSI codes used by git: m, K
  17
  18 This file is git-specific. Therefore, this file does not attempt
  19 to implement any codes that are not used by git.
  20*/
  21
  22static HANDLE console;
  23static WORD plain_attr;
  24static WORD attr;
  25static int negative;
  26static int non_ascii_used = 0;
  27static HANDLE hthread, hread, hwrite;
  28static HANDLE hwrite1 = INVALID_HANDLE_VALUE, hwrite2 = INVALID_HANDLE_VALUE;
  29static HANDLE hconsole1, hconsole2;
  30
  31#ifdef __MINGW32__
  32typedef struct _CONSOLE_FONT_INFOEX {
  33        ULONG cbSize;
  34        DWORD nFont;
  35        COORD dwFontSize;
  36        UINT FontFamily;
  37        UINT FontWeight;
  38        WCHAR FaceName[LF_FACESIZE];
  39} CONSOLE_FONT_INFOEX, *PCONSOLE_FONT_INFOEX;
  40#endif
  41
  42typedef BOOL (WINAPI *PGETCURRENTCONSOLEFONTEX)(HANDLE, BOOL,
  43                PCONSOLE_FONT_INFOEX);
  44
  45static void warn_if_raster_font(void)
  46{
  47        DWORD fontFamily = 0;
  48        PGETCURRENTCONSOLEFONTEX pGetCurrentConsoleFontEx;
  49
  50        /* don't bother if output was ascii only */
  51        if (!non_ascii_used)
  52                return;
  53
  54        /* GetCurrentConsoleFontEx is available since Vista */
  55        pGetCurrentConsoleFontEx = (PGETCURRENTCONSOLEFONTEX) GetProcAddress(
  56                        GetModuleHandle("kernel32.dll"),
  57                        "GetCurrentConsoleFontEx");
  58        if (pGetCurrentConsoleFontEx) {
  59                CONSOLE_FONT_INFOEX cfi;
  60                cfi.cbSize = sizeof(cfi);
  61                if (pGetCurrentConsoleFontEx(console, 0, &cfi))
  62                        fontFamily = cfi.FontFamily;
  63        } else {
  64                /* pre-Vista: check default console font in registry */
  65                HKEY hkey;
  66                if (ERROR_SUCCESS == RegOpenKeyExA(HKEY_CURRENT_USER, "Console",
  67                                0, KEY_READ, &hkey)) {
  68                        DWORD size = sizeof(fontFamily);
  69                        RegQueryValueExA(hkey, "FontFamily", NULL, NULL,
  70                                        (LPVOID) &fontFamily, &size);
  71                        RegCloseKey(hkey);
  72                }
  73        }
  74
  75        if (!(fontFamily & TMPF_TRUETYPE)) {
  76                const wchar_t *msg = L"\nWarning: Your console font probably "
  77                        L"doesn\'t support Unicode. If you experience strange "
  78                        L"characters in the output, consider switching to a "
  79                        L"TrueType font such as Consolas!\n";
  80                DWORD dummy;
  81                WriteConsoleW(console, msg, wcslen(msg), &dummy, NULL);
  82        }
  83}
  84
  85static int is_console(int fd)
  86{
  87        CONSOLE_SCREEN_BUFFER_INFO sbi;
  88        HANDLE hcon;
  89
  90        static int initialized = 0;
  91
  92        /* get OS handle of the file descriptor */
  93        hcon = (HANDLE) _get_osfhandle(fd);
  94        if (hcon == INVALID_HANDLE_VALUE)
  95                return 0;
  96
  97        /* check if its a device (i.e. console, printer, serial port) */
  98        if (GetFileType(hcon) != FILE_TYPE_CHAR)
  99                return 0;
 100
 101        /* check if its a handle to a console output screen buffer */
 102        if (!GetConsoleScreenBufferInfo(hcon, &sbi))
 103                return 0;
 104
 105        /* initialize attributes */
 106        if (!initialized) {
 107                attr = plain_attr = sbi.wAttributes;
 108                negative = 0;
 109                initialized = 1;
 110        }
 111
 112        return 1;
 113}
 114
 115#define BUFFER_SIZE 4096
 116#define MAX_PARAMS 16
 117
 118static void write_console(unsigned char *str, size_t len)
 119{
 120        /* only called from console_thread, so a static buffer will do */
 121        static wchar_t wbuf[2 * BUFFER_SIZE + 1];
 122        DWORD dummy;
 123
 124        /* convert utf-8 to utf-16 */
 125        int wlen = xutftowcsn(wbuf, (char*) str, ARRAY_SIZE(wbuf), len);
 126
 127        /* write directly to console */
 128        WriteConsoleW(console, wbuf, wlen, &dummy, NULL);
 129
 130        /* remember if non-ascii characters are printed */
 131        if (wlen != len)
 132                non_ascii_used = 1;
 133}
 134
 135#define FOREGROUND_ALL (FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE)
 136#define BACKGROUND_ALL (BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_BLUE)
 137
 138static void set_console_attr(void)
 139{
 140        WORD attributes = attr;
 141        if (negative) {
 142                attributes &= ~FOREGROUND_ALL;
 143                attributes &= ~BACKGROUND_ALL;
 144
 145                /* This could probably use a bitmask
 146                   instead of a series of ifs */
 147                if (attr & FOREGROUND_RED)
 148                        attributes |= BACKGROUND_RED;
 149                if (attr & FOREGROUND_GREEN)
 150                        attributes |= BACKGROUND_GREEN;
 151                if (attr & FOREGROUND_BLUE)
 152                        attributes |= BACKGROUND_BLUE;
 153
 154                if (attr & BACKGROUND_RED)
 155                        attributes |= FOREGROUND_RED;
 156                if (attr & BACKGROUND_GREEN)
 157                        attributes |= FOREGROUND_GREEN;
 158                if (attr & BACKGROUND_BLUE)
 159                        attributes |= FOREGROUND_BLUE;
 160        }
 161        SetConsoleTextAttribute(console, attributes);
 162}
 163
 164static void erase_in_line(void)
 165{
 166        CONSOLE_SCREEN_BUFFER_INFO sbi;
 167        DWORD dummy; /* Needed for Windows 7 (or Vista) regression */
 168
 169        if (!console)
 170                return;
 171
 172        GetConsoleScreenBufferInfo(console, &sbi);
 173        FillConsoleOutputCharacterA(console, ' ',
 174                sbi.dwSize.X - sbi.dwCursorPosition.X, sbi.dwCursorPosition,
 175                &dummy);
 176}
 177
 178static void set_attr(char func, const int *params, int paramlen)
 179{
 180        int i;
 181        switch (func) {
 182        case 'm':
 183                for (i = 0; i < paramlen; i++) {
 184                        switch (params[i]) {
 185                        case 0: /* reset */
 186                                attr = plain_attr;
 187                                negative = 0;
 188                                break;
 189                        case 1: /* bold */
 190                                attr |= FOREGROUND_INTENSITY;
 191                                break;
 192                        case 2:  /* faint */
 193                        case 22: /* normal */
 194                                attr &= ~FOREGROUND_INTENSITY;
 195                                break;
 196                        case 3:  /* italic */
 197                                /* Unsupported */
 198                                break;
 199                        case 4:  /* underline */
 200                        case 21: /* double underline */
 201                                /* Wikipedia says this flag does nothing */
 202                                /* Furthermore, mingw doesn't define this flag
 203                                attr |= COMMON_LVB_UNDERSCORE; */
 204                                break;
 205                        case 24: /* no underline */
 206                                /* attr &= ~COMMON_LVB_UNDERSCORE; */
 207                                break;
 208                        case 5:  /* slow blink */
 209                        case 6:  /* fast blink */
 210                                /* We don't have blink, but we do have
 211                                   background intensity */
 212                                attr |= BACKGROUND_INTENSITY;
 213                                break;
 214                        case 25: /* no blink */
 215                                attr &= ~BACKGROUND_INTENSITY;
 216                                break;
 217                        case 7:  /* negative */
 218                                negative = 1;
 219                                break;
 220                        case 27: /* positive */
 221                                negative = 0;
 222                                break;
 223                        case 8:  /* conceal */
 224                        case 28: /* reveal */
 225                                /* Unsupported */
 226                                break;
 227                        case 30: /* Black */
 228                                attr &= ~FOREGROUND_ALL;
 229                                break;
 230                        case 31: /* Red */
 231                                attr &= ~FOREGROUND_ALL;
 232                                attr |= FOREGROUND_RED;
 233                                break;
 234                        case 32: /* Green */
 235                                attr &= ~FOREGROUND_ALL;
 236                                attr |= FOREGROUND_GREEN;
 237                                break;
 238                        case 33: /* Yellow */
 239                                attr &= ~FOREGROUND_ALL;
 240                                attr |= FOREGROUND_RED | FOREGROUND_GREEN;
 241                                break;
 242                        case 34: /* Blue */
 243                                attr &= ~FOREGROUND_ALL;
 244                                attr |= FOREGROUND_BLUE;
 245                                break;
 246                        case 35: /* Magenta */
 247                                attr &= ~FOREGROUND_ALL;
 248                                attr |= FOREGROUND_RED | FOREGROUND_BLUE;
 249                                break;
 250                        case 36: /* Cyan */
 251                                attr &= ~FOREGROUND_ALL;
 252                                attr |= FOREGROUND_GREEN | FOREGROUND_BLUE;
 253                                break;
 254                        case 37: /* White */
 255                                attr |= FOREGROUND_RED |
 256                                        FOREGROUND_GREEN |
 257                                        FOREGROUND_BLUE;
 258                                break;
 259                        case 38: /* Unknown */
 260                                break;
 261                        case 39: /* reset */
 262                                attr &= ~FOREGROUND_ALL;
 263                                attr |= (plain_attr & FOREGROUND_ALL);
 264                                break;
 265                        case 40: /* Black */
 266                                attr &= ~BACKGROUND_ALL;
 267                                break;
 268                        case 41: /* Red */
 269                                attr &= ~BACKGROUND_ALL;
 270                                attr |= BACKGROUND_RED;
 271                                break;
 272                        case 42: /* Green */
 273                                attr &= ~BACKGROUND_ALL;
 274                                attr |= BACKGROUND_GREEN;
 275                                break;
 276                        case 43: /* Yellow */
 277                                attr &= ~BACKGROUND_ALL;
 278                                attr |= BACKGROUND_RED | BACKGROUND_GREEN;
 279                                break;
 280                        case 44: /* Blue */
 281                                attr &= ~BACKGROUND_ALL;
 282                                attr |= BACKGROUND_BLUE;
 283                                break;
 284                        case 45: /* Magenta */
 285                                attr &= ~BACKGROUND_ALL;
 286                                attr |= BACKGROUND_RED | BACKGROUND_BLUE;
 287                                break;
 288                        case 46: /* Cyan */
 289                                attr &= ~BACKGROUND_ALL;
 290                                attr |= BACKGROUND_GREEN | BACKGROUND_BLUE;
 291                                break;
 292                        case 47: /* White */
 293                                attr |= BACKGROUND_RED |
 294                                        BACKGROUND_GREEN |
 295                                        BACKGROUND_BLUE;
 296                                break;
 297                        case 48: /* Unknown */
 298                                break;
 299                        case 49: /* reset */
 300                                attr &= ~BACKGROUND_ALL;
 301                                attr |= (plain_attr & BACKGROUND_ALL);
 302                                break;
 303                        default:
 304                                /* Unsupported code */
 305                                break;
 306                        }
 307                }
 308                set_console_attr();
 309                break;
 310        case 'K':
 311                erase_in_line();
 312                break;
 313        default:
 314                /* Unsupported code */
 315                break;
 316        }
 317}
 318
 319enum {
 320        TEXT = 0, ESCAPE = 033, BRACKET = '['
 321};
 322
 323static DWORD WINAPI console_thread(LPVOID unused)
 324{
 325        unsigned char buffer[BUFFER_SIZE];
 326        DWORD bytes;
 327        int start, end = 0, c, parampos = 0, state = TEXT;
 328        int params[MAX_PARAMS];
 329
 330        while (1) {
 331                /* read next chunk of bytes from the pipe */
 332                if (!ReadFile(hread, buffer + end, BUFFER_SIZE - end, &bytes,
 333                                NULL)) {
 334                        /* exit if pipe has been closed or disconnected */
 335                        if (GetLastError() == ERROR_PIPE_NOT_CONNECTED ||
 336                                        GetLastError() == ERROR_BROKEN_PIPE)
 337                                break;
 338                        /* ignore other errors */
 339                        continue;
 340                }
 341
 342                /* scan the bytes and handle ANSI control codes */
 343                bytes += end;
 344                start = end = 0;
 345                while (end < bytes) {
 346                        c = buffer[end++];
 347                        switch (state) {
 348                        case TEXT:
 349                                if (c == ESCAPE) {
 350                                        /* print text seen so far */
 351                                        if (end - 1 > start)
 352                                                write_console(buffer + start,
 353                                                        end - 1 - start);
 354
 355                                        /* then start parsing escape sequence */
 356                                        start = end - 1;
 357                                        memset(params, 0, sizeof(params));
 358                                        parampos = 0;
 359                                        state = ESCAPE;
 360                                }
 361                                break;
 362
 363                        case ESCAPE:
 364                                /* continue if "\033[", otherwise bail out */
 365                                state = (c == BRACKET) ? BRACKET : TEXT;
 366                                break;
 367
 368                        case BRACKET:
 369                                /* parse [0-9;]* into array of parameters */
 370                                if (c >= '0' && c <= '9') {
 371                                        params[parampos] *= 10;
 372                                        params[parampos] += c - '0';
 373                                } else if (c == ';') {
 374                                        /*
 375                                         * next parameter, bail out if out of
 376                                         * bounds
 377                                         */
 378                                        parampos++;
 379                                        if (parampos >= MAX_PARAMS)
 380                                                state = TEXT;
 381                                } else {
 382                                        /*
 383                                         * end of escape sequence, change
 384                                         * console attributes
 385                                         */
 386                                        set_attr(c, params, parampos + 1);
 387                                        start = end;
 388                                        state = TEXT;
 389                                }
 390                                break;
 391                        }
 392                }
 393
 394                /* print remaining text unless parsing an escape sequence */
 395                if (state == TEXT && end > start) {
 396                        /* check for incomplete UTF-8 sequences and fix end */
 397                        if (buffer[end - 1] >= 0x80) {
 398                                if (buffer[end -1] >= 0xc0)
 399                                        end--;
 400                                else if (end - 1 > start &&
 401                                                buffer[end - 2] >= 0xe0)
 402                                        end -= 2;
 403                                else if (end - 2 > start &&
 404                                                buffer[end - 3] >= 0xf0)
 405                                        end -= 3;
 406                        }
 407
 408                        /* print remaining complete UTF-8 sequences */
 409                        if (end > start)
 410                                write_console(buffer + start, end - start);
 411
 412                        /* move remaining bytes to the front */
 413                        if (end < bytes)
 414                                memmove(buffer, buffer + end, bytes - end);
 415                        end = bytes - end;
 416                } else {
 417                        /* all data has been consumed, mark buffer empty */
 418                        end = 0;
 419                }
 420        }
 421
 422        /* check if the console font supports unicode */
 423        warn_if_raster_font();
 424
 425        CloseHandle(hread);
 426        return 0;
 427}
 428
 429static void winansi_exit(void)
 430{
 431        /* flush all streams */
 432        _flushall();
 433
 434        /* signal console thread to exit */
 435        FlushFileBuffers(hwrite);
 436        DisconnectNamedPipe(hwrite);
 437
 438        /* wait for console thread to copy remaining data */
 439        WaitForSingleObject(hthread, INFINITE);
 440
 441        /* cleanup handles... */
 442        if (hwrite1 != INVALID_HANDLE_VALUE)
 443                CloseHandle(hwrite1);
 444        if (hwrite2 != INVALID_HANDLE_VALUE)
 445                CloseHandle(hwrite2);
 446        CloseHandle(hwrite);
 447        CloseHandle(hthread);
 448}
 449
 450static void die_lasterr(const char *fmt, ...)
 451{
 452        va_list params;
 453        va_start(params, fmt);
 454        errno = err_win_to_posix(GetLastError());
 455        die_errno(fmt, params);
 456        va_end(params);
 457}
 458
 459static HANDLE duplicate_handle(HANDLE hnd)
 460{
 461        HANDLE hresult, hproc = GetCurrentProcess();
 462        if (!DuplicateHandle(hproc, hnd, hproc, &hresult, 0, TRUE,
 463                        DUPLICATE_SAME_ACCESS))
 464                die_lasterr("DuplicateHandle(%li) failed", (long) hnd);
 465        return hresult;
 466}
 467
 468static HANDLE redirect_console(FILE *stream, HANDLE *phcon, int new_fd)
 469{
 470        /* get original console handle */
 471        int fd = _fileno(stream);
 472        HANDLE hcon = (HANDLE) _get_osfhandle(fd);
 473        if (hcon == INVALID_HANDLE_VALUE)
 474                die_errno("_get_osfhandle(%i) failed", fd);
 475
 476        /* save a copy to phcon and console (used by the background thread) */
 477        console = *phcon = duplicate_handle(hcon);
 478
 479        /* duplicate new_fd over fd (closes fd and associated handle (hcon)) */
 480        if (_dup2(new_fd, fd))
 481                die_errno("_dup2(%i, %i) failed", new_fd, fd);
 482
 483        /* no buffering, or stdout / stderr will be out of sync */
 484        setbuf(stream, NULL);
 485        return (HANDLE) _get_osfhandle(fd);
 486}
 487
 488void winansi_init(void)
 489{
 490        int con1, con2, hwrite_fd;
 491        char name[32];
 492
 493        /* check if either stdout or stderr is a console output screen buffer */
 494        con1 = is_console(1);
 495        con2 = is_console(2);
 496        if (!con1 && !con2)
 497                return;
 498
 499        /* create a named pipe to communicate with the console thread */
 500        sprintf(name, "\\\\.\\pipe\\winansi%lu", GetCurrentProcessId());
 501        hwrite = CreateNamedPipe(name, PIPE_ACCESS_OUTBOUND,
 502                PIPE_TYPE_BYTE | PIPE_WAIT, 1, BUFFER_SIZE, 0, 0, NULL);
 503        if (hwrite == INVALID_HANDLE_VALUE)
 504                die_lasterr("CreateNamedPipe failed");
 505
 506        hread = CreateFile(name, GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL);
 507        if (hread == INVALID_HANDLE_VALUE)
 508                die_lasterr("CreateFile for named pipe failed");
 509
 510        /* start console spool thread on the pipe's read end */
 511        hthread = CreateThread(NULL, 0, console_thread, NULL, 0, NULL);
 512        if (hthread == INVALID_HANDLE_VALUE)
 513                die_lasterr("CreateThread(console_thread) failed");
 514
 515        /* schedule cleanup routine */
 516        if (atexit(winansi_exit))
 517                die_errno("atexit(winansi_exit) failed");
 518
 519        /* create a file descriptor for the write end of the pipe */
 520        hwrite_fd = _open_osfhandle((long) duplicate_handle(hwrite), _O_BINARY);
 521        if (hwrite_fd == -1)
 522                die_errno("_open_osfhandle(%li) failed", (long) hwrite);
 523
 524        /* redirect stdout / stderr to the pipe */
 525        if (con1)
 526                hwrite1 = redirect_console(stdout, &hconsole1, hwrite_fd);
 527        if (con2)
 528                hwrite2 = redirect_console(stderr, &hconsole2, hwrite_fd);
 529
 530        /* close pipe file descriptor (also closes the duped hwrite) */
 531        close(hwrite_fd);
 532}
 533
 534static int is_same_handle(HANDLE hnd, int fd)
 535{
 536        return hnd != INVALID_HANDLE_VALUE && hnd == (HANDLE) _get_osfhandle(fd);
 537}
 538
 539/*
 540 * Return true if stdout / stderr is a pipe redirecting to the console.
 541 */
 542int winansi_isatty(int fd)
 543{
 544        if (fd == 1 && is_same_handle(hwrite1, 1))
 545                return 1;
 546        else if (fd == 2 && is_same_handle(hwrite2, 2))
 547                return 1;
 548        else
 549                return isatty(fd);
 550}
 551
 552/*
 553 * Returns the real console handle if stdout / stderr is a pipe redirecting
 554 * to the console. Allows spawn / exec to pass the console to the next process.
 555 */
 556HANDLE winansi_get_osfhandle(int fd)
 557{
 558        if (fd == 1 && is_same_handle(hwrite1, 1))
 559                return hconsole1;
 560        else if (fd == 2 && is_same_handle(hwrite2, 2))
 561                return hconsole2;
 562        else
 563                return (HANDLE) _get_osfhandle(fd);
 564}