Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/git/blob/master/compat/winansi.c # git [Ported from github.com/git/git] Sync with Git 2.56.1 Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `master` Branches Tags History `git / compat / winansi.c` 647 lines ยท 16008 bytes Raw Blame History 1 /* 2 * Copyright 2008 Peter Harris 3 */ 4 5 #undef NOGDI 6 7 #define DISABLE_SIGN_COMPARE_WARNINGS 8 9 #include "../git-compat-util.h" 10 #include 11 #include 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 #undef dup2 440 int winansi_dup2(int oldfd, int newfd) 441 { 442 int ret = dup2(oldfd, newfd); 443 444 if (!ret && newfd >= 0 && newfd <= 2) 445 fd_is_interactive[newfd] = oldfd < 0 || oldfd > 2 ? 446 0 : fd_is_interactive[oldfd]; 447 448 return ret; 449 } 450 451 static HANDLE duplicate_handle(HANDLE hnd) 452 { 453 HANDLE hresult, hproc = GetCurrentProcess(); 454 if (!DuplicateHandle(hproc, hnd, hproc, &hresult, 0, TRUE, 455 DUPLICATE_SAME_ACCESS)) 456 die("DuplicateHandle(%li) failed: %lu", 457 (long) (intptr_t) hnd, GetLastError()); 458 return hresult; 459 } 460 461 static HANDLE swap_osfhnd(int fd, HANDLE new_handle) 462 { 463 /* 464 * Create a copy of the original handle associated with fd 465 * because the original will get closed when we dup2(). 466 */ 467 HANDLE handle = (HANDLE)_get_osfhandle(fd); 468 HANDLE duplicate = duplicate_handle(handle); 469 470 /* Create a temp fd associated with the already open "new_handle". */ 471 int new_fd = _open_osfhandle((intptr_t)new_handle, O_BINARY); 472 473 assert((fd == 1) || (fd == 2)); 474 475 /* 476 * Use stock dup2() to re-bind fd to the new handle. Note that 477 * this will implicitly close(1) and close both fd=1 and the 478 * originally associated handle. It will open a new fd=1 and 479 * call DuplicateHandle() on the handle associated with new_fd. 480 * It is because of this implicit close() that we created the 481 * copy of the original. 482 * 483 * Note that we need to update the cached console handle to the 484 * duplicated one because the dup2() call will implicitly close 485 * the original one. 486 * 487 * Note that dup2() when given target := {0,1,2} will also 488 * call SetStdHandle(), so we don't need to worry about that. 489 */ 490 if (console == handle) 491 console = duplicate; 492 dup2(new_fd, fd); 493 494 /* Close the temp fd. This explicitly closes "new_handle" 495 * (because it has been associated with it). 496 */ 497 close(new_fd); 498 499 if (fd == 2) 500 setvbuf(stderr, NULL, _IONBF, BUFSIZ); 501 fd_is_interactive[fd] |= FD_SWAPPED; 502 503 return duplicate; 504 } 505 506 #ifdef DETECT_MSYS_TTY 507 508 #include 509 510 #if defined(_MSC_VER) 511 512 typedef struct _OBJECT_NAME_INFORMATION 513 { 514 UNICODE_STRING Name; 515 WCHAR NameBuffer[FLEX_ARRAY]; 516 } OBJECT_NAME_INFORMATION, *POBJECT_NAME_INFORMATION; 517 518 #define ObjectNameInformation 1 519 520 #else 521 #include 522 #endif 523 524 static void detect_msys_tty(int fd) 525 { 526 ULONG result; 527 BYTE buffer[1024]; 528 POBJECT_NAME_INFORMATION nameinfo = (POBJECT_NAME_INFORMATION) buffer; 529 PWSTR name; 530 531 /* check if fd is a pipe */ 532 HANDLE h = (HANDLE) _get_osfhandle(fd); 533 if (GetFileType(h) != FILE_TYPE_PIPE) 534 return; 535 536 /* get pipe name */ 537 if (!NT_SUCCESS(NtQueryObject(h, ObjectNameInformation, 538 buffer, sizeof(buffer) - 2, &result))) 539 return; 540 name = nameinfo->Name.Buffer; 541 name[nameinfo->Name.Length / sizeof(*name)] = 0; 542 543 /* 544 * Check if this could be a MSYS2 pty pipe ('msys-XXXX-ptyN-XX') 545 * or a cygwin pty pipe ('cygwin-XXXX-ptyN-XX') 546 */ 547 if ((!wcsstr(name, L"msys-") && !wcsstr(name, L"cygwin-")) || 548 !wcsstr(name, L"-pty")) 549 return; 550 551 if (fd == 2) 552 setvbuf(stderr, NULL, _IONBF, BUFSIZ); 553 fd_is_interactive[fd] |= FD_MSYS; 554 } 555 556 #endif 557 558 /* 559 * Wrapper for isatty(). Most calls in the main git code 560 * call isatty(1 or 2) to see if the instance is interactive 561 * and should: be colored, show progress, paginate output. 562 * We lie and give results for what the descriptor WAS at 563 * startup (and ignore any pipe redirection we internally 564 * do). 565 */ 566 #undef isatty 567 int winansi_isatty(int fd) 568 { 569 if (fd >= 0 && fd <= 2) 570 return fd_is_interactive[fd] != 0; 571 return isatty(fd); 572 } 573 574 void winansi_init(void) 575 { 576 int con1, con2; 577 wchar_t name[32]; 578 579 /* check if either stdout or stderr is a console output screen buffer */ 580 con1 = is_console(1); 581 con2 = is_console(2); 582 583 /* Also compute console bit for fd 0 even though we don't need the result here. */ 584 is_console(0); 585 586 if (!con1 && !con2) { 587 #ifdef DETECT_MSYS_TTY 588 /* check if stdin / stdout / stderr are MSYS2 pty pipes */ 589 detect_msys_tty(0); 590 detect_msys_tty(1); 591 detect_msys_tty(2); 592 #endif 593 return; 594 } 595 596 /* create a named pipe to communicate with the console thread */ 597 if (swprintf(name, ARRAY_SIZE(name) - 1, L"\\\\.\\pipe\\winansi%lu", 598 GetCurrentProcessId()) < 0) 599 die("Could not initialize winansi pipe name"); 600 hwrite = CreateNamedPipeW(name, PIPE_ACCESS_OUTBOUND, 601 PIPE_TYPE_BYTE | PIPE_WAIT, 1, BUFFER_SIZE, 0, 0, NULL); 602 if (hwrite == INVALID_HANDLE_VALUE) 603 die("CreateNamedPipe failed: %lu", GetLastError()); 604 605 hread = CreateFileW(name, GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL); 606 if (hread == INVALID_HANDLE_VALUE) 607 die("CreateFile for named pipe failed: %lu", GetLastError()); 608 609 /* start console spool thread on the pipe's read end */ 610 hthread = CreateThread(NULL, 0, console_thread, NULL, 0, NULL); 611 if (!hthread) 612 die("CreateThread(console_thread) failed: %lu", GetLastError()); 613 614 /* schedule cleanup routine */ 615 if (atexit(winansi_exit)) 616 die_errno("atexit(winansi_exit) failed"); 617 618 /* redirect stdout / stderr to the pipe */ 619 if (con1) 620 hconsole1 = swap_osfhnd(1, duplicate_handle(hwrite)); 621 if (con2) 622 hconsole2 = swap_osfhnd(2, duplicate_handle(hwrite)); 623 } 624 625 /* 626 * Returns the real console handle if stdout / stderr is a pipe redirecting 627 * to the console. Allows spawn / exec to pass the console to the next process. 628 */ 629 HANDLE winansi_get_osfhandle(int fd) 630 { 631 HANDLE ret; 632 633 if (fd == 1 && (fd_is_interactive[1] & FD_SWAPPED)) 634 return hconsole1; 635 if (fd == 2 && (fd_is_interactive[2] & FD_SWAPPED)) 636 return hconsole2; 637 638 ret = (HANDLE)_get_osfhandle(fd); 639 640 /* 641 * There are obviously circumstances under which _get_osfhandle() 642 * returns (HANDLE)-2. This is not documented anywhere, but that is so 643 * clearly an invalid handle value that we can just work around this 644 * and return the correct value for invalid handles. 645 */ 646 return ret == (HANDLE)-2 ? INVALID_HANDLE_VALUE : ret; 647 }