winansi.c 17 KB

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