ser-mingw.c 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376
  1. /* Serial interface for local (hardwired) serial ports on Windows systems
  2. Copyright (C) 2006-2022 Free Software Foundation, Inc.
  3. This file is part of GDB.
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 3 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program. If not, see <http://www.gnu.org/licenses/>. */
  14. #include "defs.h"
  15. #include "serial.h"
  16. #include "ser-base.h"
  17. #include "ser-tcp.h"
  18. #include <windows.h>
  19. #include <conio.h>
  20. #include <fcntl.h>
  21. #include <unistd.h>
  22. #include <sys/types.h>
  23. #include "command.h"
  24. #include "gdbsupport/buildargv.h"
  25. struct ser_windows_state
  26. {
  27. int in_progress;
  28. OVERLAPPED ov;
  29. DWORD lastCommMask;
  30. HANDLE except_event;
  31. };
  32. /* CancelIo is not available for Windows 95 OS, so we need to use
  33. LoadLibrary/GetProcAddress to avoid a startup failure. */
  34. #define CancelIo dyn_CancelIo
  35. typedef BOOL WINAPI (CancelIo_ftype) (HANDLE);
  36. static CancelIo_ftype *CancelIo;
  37. /* Open up a real live device for serial I/O. */
  38. static int
  39. ser_windows_open (struct serial *scb, const char *name)
  40. {
  41. HANDLE h;
  42. struct ser_windows_state *state;
  43. COMMTIMEOUTS timeouts;
  44. h = CreateFile (name, GENERIC_READ | GENERIC_WRITE, 0, NULL,
  45. OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL);
  46. if (h == INVALID_HANDLE_VALUE)
  47. {
  48. errno = ENOENT;
  49. return -1;
  50. }
  51. scb->fd = _open_osfhandle ((intptr_t) h, O_RDWR);
  52. if (scb->fd < 0)
  53. {
  54. errno = ENOENT;
  55. return -1;
  56. }
  57. if (!SetCommMask (h, EV_RXCHAR))
  58. {
  59. errno = EINVAL;
  60. return -1;
  61. }
  62. timeouts.ReadIntervalTimeout = MAXDWORD;
  63. timeouts.ReadTotalTimeoutConstant = 0;
  64. timeouts.ReadTotalTimeoutMultiplier = 0;
  65. timeouts.WriteTotalTimeoutConstant = 0;
  66. timeouts.WriteTotalTimeoutMultiplier = 0;
  67. if (!SetCommTimeouts (h, &timeouts))
  68. {
  69. errno = EINVAL;
  70. return -1;
  71. }
  72. state = XCNEW (struct ser_windows_state);
  73. scb->state = state;
  74. /* Create a manual reset event to watch the input buffer. */
  75. state->ov.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  76. /* Create a (currently unused) handle to record exceptions. */
  77. state->except_event = CreateEvent (0, TRUE, FALSE, 0);
  78. return 0;
  79. }
  80. /* Wait for the output to drain away, as opposed to flushing (discarding)
  81. it. */
  82. static int
  83. ser_windows_drain_output (struct serial *scb)
  84. {
  85. HANDLE h = (HANDLE) _get_osfhandle (scb->fd);
  86. return (FlushFileBuffers (h) != 0) ? 0 : -1;
  87. }
  88. static int
  89. ser_windows_flush_output (struct serial *scb)
  90. {
  91. HANDLE h = (HANDLE) _get_osfhandle (scb->fd);
  92. return (PurgeComm (h, PURGE_TXCLEAR) != 0) ? 0 : -1;
  93. }
  94. static int
  95. ser_windows_flush_input (struct serial *scb)
  96. {
  97. HANDLE h = (HANDLE) _get_osfhandle (scb->fd);
  98. return (PurgeComm (h, PURGE_RXCLEAR) != 0) ? 0 : -1;
  99. }
  100. static int
  101. ser_windows_send_break (struct serial *scb)
  102. {
  103. HANDLE h = (HANDLE) _get_osfhandle (scb->fd);
  104. if (SetCommBreak (h) == 0)
  105. return -1;
  106. /* Delay for 250 milliseconds. */
  107. Sleep (250);
  108. if (ClearCommBreak (h))
  109. return -1;
  110. return 0;
  111. }
  112. static void
  113. ser_windows_raw (struct serial *scb)
  114. {
  115. HANDLE h = (HANDLE) _get_osfhandle (scb->fd);
  116. DCB state;
  117. if (GetCommState (h, &state) == 0)
  118. return;
  119. state.fOutxCtsFlow = FALSE;
  120. state.fOutxDsrFlow = FALSE;
  121. state.fDtrControl = DTR_CONTROL_ENABLE;
  122. state.fDsrSensitivity = FALSE;
  123. state.fOutX = FALSE;
  124. state.fInX = FALSE;
  125. state.fNull = FALSE;
  126. state.fAbortOnError = FALSE;
  127. state.ByteSize = 8;
  128. if (SetCommState (h, &state) == 0)
  129. warning (_("SetCommState failed"));
  130. }
  131. static int
  132. ser_windows_setstopbits (struct serial *scb, int num)
  133. {
  134. HANDLE h = (HANDLE) _get_osfhandle (scb->fd);
  135. DCB state;
  136. if (GetCommState (h, &state) == 0)
  137. return -1;
  138. switch (num)
  139. {
  140. case SERIAL_1_STOPBITS:
  141. state.StopBits = ONESTOPBIT;
  142. break;
  143. case SERIAL_1_AND_A_HALF_STOPBITS:
  144. state.StopBits = ONE5STOPBITS;
  145. break;
  146. case SERIAL_2_STOPBITS:
  147. state.StopBits = TWOSTOPBITS;
  148. break;
  149. default:
  150. return 1;
  151. }
  152. return (SetCommState (h, &state) != 0) ? 0 : -1;
  153. }
  154. /* Implement the "setparity" serial_ops callback. */
  155. static int
  156. ser_windows_setparity (struct serial *scb, int parity)
  157. {
  158. HANDLE h = (HANDLE) _get_osfhandle (scb->fd);
  159. DCB state;
  160. if (GetCommState (h, &state) == 0)
  161. return -1;
  162. switch (parity)
  163. {
  164. case GDBPARITY_NONE:
  165. state.Parity = NOPARITY;
  166. state.fParity = FALSE;
  167. break;
  168. case GDBPARITY_ODD:
  169. state.Parity = ODDPARITY;
  170. state.fParity = TRUE;
  171. break;
  172. case GDBPARITY_EVEN:
  173. state.Parity = EVENPARITY;
  174. state.fParity = TRUE;
  175. break;
  176. default:
  177. internal_warning (__FILE__, __LINE__,
  178. "Incorrect parity value: %d", parity);
  179. return -1;
  180. }
  181. return (SetCommState (h, &state) != 0) ? 0 : -1;
  182. }
  183. static int
  184. ser_windows_setbaudrate (struct serial *scb, int rate)
  185. {
  186. HANDLE h = (HANDLE) _get_osfhandle (scb->fd);
  187. DCB state;
  188. if (GetCommState (h, &state) == 0)
  189. return -1;
  190. state.BaudRate = rate;
  191. return (SetCommState (h, &state) != 0) ? 0 : -1;
  192. }
  193. static void
  194. ser_windows_close (struct serial *scb)
  195. {
  196. struct ser_windows_state *state;
  197. /* Stop any pending selects. On Windows 95 OS, CancelIo function does
  198. not exist. In that case, it can be replaced by a call to CloseHandle,
  199. but this is not necessary here as we do close the Windows handle
  200. by calling close (scb->fd) below. */
  201. if (CancelIo)
  202. CancelIo ((HANDLE) _get_osfhandle (scb->fd));
  203. state = (struct ser_windows_state *) scb->state;
  204. CloseHandle (state->ov.hEvent);
  205. CloseHandle (state->except_event);
  206. if (scb->fd < 0)
  207. return;
  208. close (scb->fd);
  209. scb->fd = -1;
  210. xfree (scb->state);
  211. }
  212. static void
  213. ser_windows_wait_handle (struct serial *scb, HANDLE *read, HANDLE *except)
  214. {
  215. struct ser_windows_state *state;
  216. COMSTAT status;
  217. DWORD errors;
  218. HANDLE h = (HANDLE) _get_osfhandle (scb->fd);
  219. state = (struct ser_windows_state *) scb->state;
  220. *except = state->except_event;
  221. *read = state->ov.hEvent;
  222. if (state->in_progress)
  223. return;
  224. /* Reset the mask - we are only interested in any characters which
  225. arrive after this point, not characters which might have arrived
  226. and already been read. */
  227. /* This really, really shouldn't be necessary - just the second one.
  228. But otherwise an internal flag for EV_RXCHAR does not get
  229. cleared, and we get a duplicated event, if the last batch
  230. of characters included at least two arriving close together. */
  231. if (!SetCommMask (h, 0))
  232. warning (_("ser_windows_wait_handle: reseting mask failed"));
  233. if (!SetCommMask (h, EV_RXCHAR))
  234. warning (_("ser_windows_wait_handle: reseting mask failed (2)"));
  235. /* There's a potential race condition here; we must check cbInQue
  236. and not wait if that's nonzero. */
  237. ClearCommError (h, &errors, &status);
  238. if (status.cbInQue > 0)
  239. {
  240. SetEvent (state->ov.hEvent);
  241. return;
  242. }
  243. state->in_progress = 1;
  244. ResetEvent (state->ov.hEvent);
  245. state->lastCommMask = -2;
  246. if (WaitCommEvent (h, &state->lastCommMask, &state->ov))
  247. {
  248. gdb_assert (state->lastCommMask & EV_RXCHAR);
  249. SetEvent (state->ov.hEvent);
  250. }
  251. else
  252. gdb_assert (GetLastError () == ERROR_IO_PENDING);
  253. }
  254. static int
  255. ser_windows_read_prim (struct serial *scb, size_t count)
  256. {
  257. struct ser_windows_state *state;
  258. OVERLAPPED ov;
  259. DWORD bytes_read;
  260. HANDLE h;
  261. state = (struct ser_windows_state *) scb->state;
  262. if (state->in_progress)
  263. {
  264. WaitForSingleObject (state->ov.hEvent, INFINITE);
  265. state->in_progress = 0;
  266. ResetEvent (state->ov.hEvent);
  267. }
  268. memset (&ov, 0, sizeof (OVERLAPPED));
  269. ov.hEvent = CreateEvent (0, FALSE, FALSE, 0);
  270. h = (HANDLE) _get_osfhandle (scb->fd);
  271. if (!ReadFile (h, scb->buf, /* count */ 1, &bytes_read, &ov))
  272. {
  273. if (GetLastError () != ERROR_IO_PENDING
  274. || !GetOverlappedResult (h, &ov, &bytes_read, TRUE))
  275. bytes_read = -1;
  276. }
  277. CloseHandle (ov.hEvent);
  278. return bytes_read;
  279. }
  280. static int
  281. ser_windows_write_prim (struct serial *scb, const void *buf, size_t len)
  282. {
  283. OVERLAPPED ov;
  284. DWORD bytes_written;
  285. HANDLE h;
  286. memset (&ov, 0, sizeof (OVERLAPPED));
  287. ov.hEvent = CreateEvent (0, FALSE, FALSE, 0);
  288. h = (HANDLE) _get_osfhandle (scb->fd);
  289. if (!WriteFile (h, buf, len, &bytes_written, &ov))
  290. {
  291. if (GetLastError () != ERROR_IO_PENDING
  292. || !GetOverlappedResult (h, &ov, &bytes_written, TRUE))
  293. bytes_written = -1;
  294. }
  295. CloseHandle (ov.hEvent);
  296. return bytes_written;
  297. }
  298. /* On Windows, gdb_select is implemented using WaitForMulpleObjects.
  299. A "select thread" is created for each file descriptor. These
  300. threads looks for activity on the corresponding descriptor, using
  301. whatever techniques are appropriate for the descriptor type. When
  302. that activity occurs, the thread signals an appropriate event,
  303. which wakes up WaitForMultipleObjects.
  304. Each select thread is in one of two states: stopped or started.
  305. Select threads begin in the stopped state. When gdb_select is
  306. called, threads corresponding to the descriptors of interest are
  307. started by calling a wait_handle function. Each thread that
  308. notices activity signals the appropriate event and then reenters
  309. the stopped state. Before gdb_select returns it calls the
  310. wait_handle_done functions, which return the threads to the stopped
  311. state. */
  312. enum select_thread_state {
  313. STS_STARTED,
  314. STS_STOPPED
  315. };
  316. struct ser_console_state
  317. {
  318. /* Signaled by the select thread to indicate that data is available
  319. on the file descriptor. */
  320. HANDLE read_event;
  321. /* Signaled by the select thread to indicate that an exception has
  322. occurred on the file descriptor. */
  323. HANDLE except_event;
  324. /* Signaled by the select thread to indicate that it has entered the
  325. started state. HAVE_STARTED and HAVE_STOPPED are never signaled
  326. simultaneously. */
  327. HANDLE have_started;
  328. /* Signaled by the select thread to indicate that it has stopped,
  329. either because data is available (and READ_EVENT is signaled),
  330. because an exception has occurred (and EXCEPT_EVENT is signaled),
  331. or because STOP_SELECT was signaled. */
  332. HANDLE have_stopped;
  333. /* Signaled by the main program to tell the select thread to enter
  334. the started state. */
  335. HANDLE start_select;
  336. /* Signaled by the main program to tell the select thread to enter
  337. the stopped state. */
  338. HANDLE stop_select;
  339. /* Signaled by the main program to tell the select thread to
  340. exit. */
  341. HANDLE exit_select;
  342. /* The handle for the select thread. */
  343. HANDLE thread;
  344. /* The state of the select thread. This field is only accessed in
  345. the main program, never by the select thread itself. */
  346. enum select_thread_state thread_state;
  347. };
  348. /* Called by a select thread to enter the stopped state. This
  349. function does not return until the thread has re-entered the
  350. started state. */
  351. static void
  352. select_thread_wait (struct ser_console_state *state)
  353. {
  354. HANDLE wait_events[2];
  355. /* There are two things that can wake us up: a request that we enter
  356. the started state, or that we exit this thread. */
  357. wait_events[0] = state->start_select;
  358. wait_events[1] = state->exit_select;
  359. if (WaitForMultipleObjects (2, wait_events, FALSE, INFINITE)
  360. != WAIT_OBJECT_0)
  361. /* Either the EXIT_SELECT event was signaled (requesting that the
  362. thread exit) or an error has occurred. In either case, we exit
  363. the thread. */
  364. ExitThread (0);
  365. /* We are now in the started state. */
  366. SetEvent (state->have_started);
  367. }
  368. typedef DWORD WINAPI (*thread_fn_type)(void *);
  369. /* Create a new select thread for SCB executing THREAD_FN. The STATE
  370. will be filled in by this function before return. */
  371. static void
  372. create_select_thread (thread_fn_type thread_fn,
  373. struct serial *scb,
  374. struct ser_console_state *state)
  375. {
  376. DWORD threadId;
  377. /* Create all of the events. These are all auto-reset events. */
  378. state->read_event = CreateEvent (NULL, FALSE, FALSE, NULL);
  379. state->except_event = CreateEvent (NULL, FALSE, FALSE, NULL);
  380. state->have_started = CreateEvent (NULL, FALSE, FALSE, NULL);
  381. state->have_stopped = CreateEvent (NULL, FALSE, FALSE, NULL);
  382. state->start_select = CreateEvent (NULL, FALSE, FALSE, NULL);
  383. state->stop_select = CreateEvent (NULL, FALSE, FALSE, NULL);
  384. state->exit_select = CreateEvent (NULL, FALSE, FALSE, NULL);
  385. state->thread = CreateThread (NULL, 0, thread_fn, scb, 0, &threadId);
  386. /* The thread begins in the stopped state. */
  387. state->thread_state = STS_STOPPED;
  388. }
  389. /* Destroy the select thread indicated by STATE. */
  390. static void
  391. destroy_select_thread (struct ser_console_state *state)
  392. {
  393. /* Ask the thread to exit. */
  394. SetEvent (state->exit_select);
  395. /* Wait until it does. */
  396. WaitForSingleObject (state->thread, INFINITE);
  397. /* Destroy the events. */
  398. CloseHandle (state->read_event);
  399. CloseHandle (state->except_event);
  400. CloseHandle (state->have_started);
  401. CloseHandle (state->have_stopped);
  402. CloseHandle (state->start_select);
  403. CloseHandle (state->stop_select);
  404. CloseHandle (state->exit_select);
  405. }
  406. /* Called by gdb_select to start the select thread indicated by STATE.
  407. This function does not return until the thread has started. */
  408. static void
  409. start_select_thread (struct ser_console_state *state)
  410. {
  411. /* Ask the thread to start. */
  412. SetEvent (state->start_select);
  413. /* Wait until it does. */
  414. WaitForSingleObject (state->have_started, INFINITE);
  415. /* The thread is now started. */
  416. state->thread_state = STS_STARTED;
  417. }
  418. /* Called by gdb_select to stop the select thread indicated by STATE.
  419. This function does not return until the thread has stopped. */
  420. static void
  421. stop_select_thread (struct ser_console_state *state)
  422. {
  423. /* If the thread is already in the stopped state, we have nothing to
  424. do. Some of the wait_handle functions avoid calling
  425. start_select_thread if they notice activity on the relevant file
  426. descriptors. The wait_handle_done functions still call
  427. stop_select_thread -- but it is already stopped. */
  428. if (state->thread_state != STS_STARTED)
  429. return;
  430. /* Ask the thread to stop. */
  431. SetEvent (state->stop_select);
  432. /* Wait until it does. */
  433. WaitForSingleObject (state->have_stopped, INFINITE);
  434. /* The thread is now stopped. */
  435. state->thread_state = STS_STOPPED;
  436. }
  437. static DWORD WINAPI
  438. console_select_thread (void *arg)
  439. {
  440. struct serial *scb = (struct serial *) arg;
  441. struct ser_console_state *state;
  442. int event_index;
  443. HANDLE h;
  444. state = (struct ser_console_state *) scb->state;
  445. h = (HANDLE) _get_osfhandle (scb->fd);
  446. while (1)
  447. {
  448. HANDLE wait_events[2];
  449. INPUT_RECORD record;
  450. DWORD n_records;
  451. select_thread_wait (state);
  452. while (1)
  453. {
  454. wait_events[0] = state->stop_select;
  455. wait_events[1] = h;
  456. event_index = WaitForMultipleObjects (2, wait_events,
  457. FALSE, INFINITE);
  458. if (event_index == WAIT_OBJECT_0
  459. || WaitForSingleObject (state->stop_select, 0) == WAIT_OBJECT_0)
  460. break;
  461. if (event_index != WAIT_OBJECT_0 + 1)
  462. {
  463. /* Wait must have failed; assume an error has occured, e.g.
  464. the handle has been closed. */
  465. SetEvent (state->except_event);
  466. break;
  467. }
  468. /* We've got a pending event on the console. See if it's
  469. of interest. */
  470. if (!PeekConsoleInput (h, &record, 1, &n_records) || n_records != 1)
  471. {
  472. /* Something went wrong. Maybe the console is gone. */
  473. SetEvent (state->except_event);
  474. break;
  475. }
  476. if (record.EventType == KEY_EVENT && record.Event.KeyEvent.bKeyDown)
  477. {
  478. WORD keycode = record.Event.KeyEvent.wVirtualKeyCode;
  479. /* Ignore events containing only control keys. We must
  480. recognize "enhanced" keys which we are interested in
  481. reading via getch, if they do not map to ASCII. But we
  482. do not want to report input available for e.g. the
  483. control key alone. */
  484. if (record.Event.KeyEvent.uChar.AsciiChar != 0
  485. || keycode == VK_PRIOR
  486. || keycode == VK_NEXT
  487. || keycode == VK_END
  488. || keycode == VK_HOME
  489. || keycode == VK_LEFT
  490. || keycode == VK_UP
  491. || keycode == VK_RIGHT
  492. || keycode == VK_DOWN
  493. || keycode == VK_INSERT
  494. || keycode == VK_DELETE)
  495. {
  496. /* This is really a keypress. */
  497. SetEvent (state->read_event);
  498. break;
  499. }
  500. }
  501. else if (record.EventType == MOUSE_EVENT)
  502. {
  503. SetEvent (state->read_event);
  504. break;
  505. }
  506. /* Otherwise discard it and wait again. */
  507. ReadConsoleInput (h, &record, 1, &n_records);
  508. }
  509. SetEvent(state->have_stopped);
  510. }
  511. return 0;
  512. }
  513. static int
  514. fd_is_pipe (int fd)
  515. {
  516. if (PeekNamedPipe ((HANDLE) _get_osfhandle (fd), NULL, 0, NULL, NULL, NULL))
  517. return 1;
  518. else
  519. return 0;
  520. }
  521. static int
  522. fd_is_file (int fd)
  523. {
  524. if (GetFileType ((HANDLE) _get_osfhandle (fd)) == FILE_TYPE_DISK)
  525. return 1;
  526. else
  527. return 0;
  528. }
  529. static DWORD WINAPI
  530. pipe_select_thread (void *arg)
  531. {
  532. struct serial *scb = (struct serial *) arg;
  533. struct ser_console_state *state;
  534. HANDLE h;
  535. state = (struct ser_console_state *) scb->state;
  536. h = (HANDLE) _get_osfhandle (scb->fd);
  537. while (1)
  538. {
  539. DWORD n_avail;
  540. select_thread_wait (state);
  541. /* Wait for something to happen on the pipe. */
  542. while (1)
  543. {
  544. if (!PeekNamedPipe (h, NULL, 0, NULL, &n_avail, NULL))
  545. {
  546. SetEvent (state->except_event);
  547. break;
  548. }
  549. if (n_avail > 0)
  550. {
  551. SetEvent (state->read_event);
  552. break;
  553. }
  554. /* Delay 10ms before checking again, but allow the stop
  555. event to wake us. */
  556. if (WaitForSingleObject (state->stop_select, 10) == WAIT_OBJECT_0)
  557. break;
  558. }
  559. SetEvent (state->have_stopped);
  560. }
  561. return 0;
  562. }
  563. static DWORD WINAPI
  564. file_select_thread (void *arg)
  565. {
  566. struct serial *scb = (struct serial *) arg;
  567. struct ser_console_state *state;
  568. HANDLE h;
  569. state = (struct ser_console_state *) scb->state;
  570. h = (HANDLE) _get_osfhandle (scb->fd);
  571. while (1)
  572. {
  573. select_thread_wait (state);
  574. if (SetFilePointer (h, 0, NULL, FILE_CURRENT)
  575. == INVALID_SET_FILE_POINTER)
  576. SetEvent (state->except_event);
  577. else
  578. SetEvent (state->read_event);
  579. SetEvent (state->have_stopped);
  580. }
  581. return 0;
  582. }
  583. static void
  584. ser_console_wait_handle (struct serial *scb, HANDLE *read, HANDLE *except)
  585. {
  586. struct ser_console_state *state = (struct ser_console_state *) scb->state;
  587. if (state == NULL)
  588. {
  589. thread_fn_type thread_fn;
  590. int is_tty;
  591. is_tty = isatty (scb->fd);
  592. if (!is_tty && !fd_is_file (scb->fd) && !fd_is_pipe (scb->fd))
  593. {
  594. *read = NULL;
  595. *except = NULL;
  596. return;
  597. }
  598. state = XCNEW (struct ser_console_state);
  599. scb->state = state;
  600. if (is_tty)
  601. thread_fn = console_select_thread;
  602. else if (fd_is_pipe (scb->fd))
  603. thread_fn = pipe_select_thread;
  604. else
  605. thread_fn = file_select_thread;
  606. create_select_thread (thread_fn, scb, state);
  607. }
  608. *read = state->read_event;
  609. *except = state->except_event;
  610. /* Start from a blank state. */
  611. ResetEvent (state->read_event);
  612. ResetEvent (state->except_event);
  613. ResetEvent (state->stop_select);
  614. /* First check for a key already in the buffer. If there is one,
  615. we don't need a thread. This also catches the second key of
  616. multi-character returns from getch, for instance for arrow
  617. keys. The second half is in a C library internal buffer,
  618. and PeekConsoleInput will not find it. */
  619. if (_kbhit ())
  620. {
  621. SetEvent (state->read_event);
  622. return;
  623. }
  624. /* Otherwise, start the select thread. */
  625. start_select_thread (state);
  626. }
  627. static void
  628. ser_console_done_wait_handle (struct serial *scb)
  629. {
  630. struct ser_console_state *state = (struct ser_console_state *) scb->state;
  631. if (state == NULL)
  632. return;
  633. stop_select_thread (state);
  634. }
  635. static void
  636. ser_console_close (struct serial *scb)
  637. {
  638. struct ser_console_state *state = (struct ser_console_state *) scb->state;
  639. if (scb->state)
  640. {
  641. destroy_select_thread (state);
  642. xfree (scb->state);
  643. }
  644. }
  645. struct ser_console_ttystate
  646. {
  647. int is_a_tty;
  648. };
  649. static serial_ttystate
  650. ser_console_get_tty_state (struct serial *scb)
  651. {
  652. if (isatty (scb->fd))
  653. {
  654. struct ser_console_ttystate *state;
  655. state = XNEW (struct ser_console_ttystate);
  656. state->is_a_tty = 1;
  657. return state;
  658. }
  659. else
  660. return NULL;
  661. }
  662. struct pipe_state
  663. {
  664. /* Since we use the pipe_select_thread for our select emulation,
  665. we need to place the state structure it requires at the front
  666. of our state. */
  667. struct ser_console_state wait;
  668. /* The pex obj for our (one-stage) pipeline. */
  669. struct pex_obj *pex;
  670. /* Streams for the pipeline's input and output. */
  671. FILE *input, *output;
  672. };
  673. static struct pipe_state *
  674. make_pipe_state (void)
  675. {
  676. struct pipe_state *ps = XCNEW (struct pipe_state);
  677. ps->wait.read_event = INVALID_HANDLE_VALUE;
  678. ps->wait.except_event = INVALID_HANDLE_VALUE;
  679. ps->wait.start_select = INVALID_HANDLE_VALUE;
  680. ps->wait.stop_select = INVALID_HANDLE_VALUE;
  681. return ps;
  682. }
  683. static void
  684. free_pipe_state (struct pipe_state *ps)
  685. {
  686. int saved_errno = errno;
  687. if (ps->wait.read_event != INVALID_HANDLE_VALUE)
  688. destroy_select_thread (&ps->wait);
  689. /* Close the pipe to the child. We must close the pipe before
  690. calling pex_free because pex_free will wait for the child to exit
  691. and the child will not exit until the pipe is closed. */
  692. if (ps->input)
  693. fclose (ps->input);
  694. if (ps->pex)
  695. {
  696. pex_free (ps->pex);
  697. /* pex_free closes ps->output. */
  698. }
  699. else if (ps->output)
  700. fclose (ps->output);
  701. xfree (ps);
  702. errno = saved_errno;
  703. }
  704. struct pipe_state_destroyer
  705. {
  706. void operator() (pipe_state *ps) const
  707. {
  708. free_pipe_state (ps);
  709. }
  710. };
  711. typedef std::unique_ptr<pipe_state, pipe_state_destroyer> pipe_state_up;
  712. static int
  713. pipe_windows_open (struct serial *scb, const char *name)
  714. {
  715. FILE *pex_stderr;
  716. if (name == NULL)
  717. error_no_arg (_("child command"));
  718. gdb_argv argv (name);
  719. if (! argv[0] || argv[0][0] == '\0')
  720. error (_("missing child command"));
  721. pipe_state_up ps (make_pipe_state ());
  722. ps->pex = pex_init (PEX_USE_PIPES, "target remote pipe", NULL);
  723. if (! ps->pex)
  724. return -1;
  725. ps->input = pex_input_pipe (ps->pex, 1);
  726. if (! ps->input)
  727. return -1;
  728. {
  729. int err;
  730. const char *err_msg
  731. = pex_run (ps->pex, PEX_SEARCH | PEX_BINARY_INPUT | PEX_BINARY_OUTPUT
  732. | PEX_STDERR_TO_PIPE,
  733. argv[0], argv.get (), NULL, NULL,
  734. &err);
  735. if (err_msg)
  736. {
  737. /* Our caller expects us to return -1, but all they'll do with
  738. it generally is print the message based on errno. We have
  739. all the same information here, plus err_msg provided by
  740. pex_run, so we just raise the error here. */
  741. if (err)
  742. error (_("error starting child process '%s': %s: %s"),
  743. name, err_msg, safe_strerror (err));
  744. else
  745. error (_("error starting child process '%s': %s"),
  746. name, err_msg);
  747. }
  748. }
  749. ps->output = pex_read_output (ps->pex, 1);
  750. if (! ps->output)
  751. return -1;
  752. scb->fd = fileno (ps->output);
  753. pex_stderr = pex_read_err (ps->pex, 1);
  754. if (! pex_stderr)
  755. return -1;
  756. scb->error_fd = fileno (pex_stderr);
  757. scb->state = ps.release ();
  758. return 0;
  759. }
  760. static int
  761. pipe_windows_fdopen (struct serial *scb, int fd)
  762. {
  763. struct pipe_state *ps;
  764. ps = make_pipe_state ();
  765. ps->input = fdopen (fd, "r+");
  766. if (! ps->input)
  767. goto fail;
  768. ps->output = fdopen (fd, "r+");
  769. if (! ps->output)
  770. goto fail;
  771. scb->fd = fd;
  772. scb->state = (void *) ps;
  773. return 0;
  774. fail:
  775. free_pipe_state (ps);
  776. return -1;
  777. }
  778. static void
  779. pipe_windows_close (struct serial *scb)
  780. {
  781. struct pipe_state *ps = (struct pipe_state *) scb->state;
  782. /* In theory, we should try to kill the subprocess here, but the pex
  783. interface doesn't give us enough information to do that. Usually
  784. closing the input pipe will get the message across. */
  785. free_pipe_state (ps);
  786. }
  787. static int
  788. pipe_windows_read (struct serial *scb, size_t count)
  789. {
  790. HANDLE pipeline_out = (HANDLE) _get_osfhandle (scb->fd);
  791. DWORD available;
  792. DWORD bytes_read;
  793. if (pipeline_out == INVALID_HANDLE_VALUE)
  794. return -1;
  795. if (! PeekNamedPipe (pipeline_out, NULL, 0, NULL, &available, NULL))
  796. return -1;
  797. if (count > available)
  798. count = available;
  799. if (! ReadFile (pipeline_out, scb->buf, count, &bytes_read, NULL))
  800. return -1;
  801. return bytes_read;
  802. }
  803. static int
  804. pipe_windows_write (struct serial *scb, const void *buf, size_t count)
  805. {
  806. struct pipe_state *ps = (struct pipe_state *) scb->state;
  807. HANDLE pipeline_in;
  808. DWORD written;
  809. int pipeline_in_fd = fileno (ps->input);
  810. if (pipeline_in_fd < 0)
  811. return -1;
  812. pipeline_in = (HANDLE) _get_osfhandle (pipeline_in_fd);
  813. if (pipeline_in == INVALID_HANDLE_VALUE)
  814. return -1;
  815. if (! WriteFile (pipeline_in, buf, count, &written, NULL))
  816. return -1;
  817. return written;
  818. }
  819. static void
  820. pipe_wait_handle (struct serial *scb, HANDLE *read, HANDLE *except)
  821. {
  822. struct pipe_state *ps = (struct pipe_state *) scb->state;
  823. /* Have we allocated our events yet? */
  824. if (ps->wait.read_event == INVALID_HANDLE_VALUE)
  825. /* Start the thread. */
  826. create_select_thread (pipe_select_thread, scb, &ps->wait);
  827. *read = ps->wait.read_event;
  828. *except = ps->wait.except_event;
  829. /* Start from a blank state. */
  830. ResetEvent (ps->wait.read_event);
  831. ResetEvent (ps->wait.except_event);
  832. ResetEvent (ps->wait.stop_select);
  833. start_select_thread (&ps->wait);
  834. }
  835. static void
  836. pipe_done_wait_handle (struct serial *scb)
  837. {
  838. struct pipe_state *ps = (struct pipe_state *) scb->state;
  839. /* Have we allocated our events yet? */
  840. if (ps->wait.read_event == INVALID_HANDLE_VALUE)
  841. return;
  842. stop_select_thread (&ps->wait);
  843. }
  844. static int
  845. pipe_avail (struct serial *scb, int fd)
  846. {
  847. HANDLE h = (HANDLE) _get_osfhandle (fd);
  848. DWORD numBytes;
  849. BOOL r = PeekNamedPipe (h, NULL, 0, NULL, &numBytes, NULL);
  850. if (r == FALSE)
  851. numBytes = 0;
  852. return numBytes;
  853. }
  854. int
  855. gdb_pipe (int pdes[2])
  856. {
  857. if (_pipe (pdes, 512, _O_BINARY | _O_NOINHERIT) == -1)
  858. return -1;
  859. return 0;
  860. }
  861. struct net_windows_state
  862. {
  863. struct ser_console_state base;
  864. HANDLE sock_event;
  865. };
  866. /* Check whether the socket has any pending data to be read. If so,
  867. set the select thread's read event. On error, set the select
  868. thread's except event. If any event was set, return true,
  869. otherwise return false. */
  870. static int
  871. net_windows_socket_check_pending (struct serial *scb)
  872. {
  873. struct net_windows_state *state = (struct net_windows_state *) scb->state;
  874. unsigned long available;
  875. if (ioctlsocket (scb->fd, FIONREAD, &available) != 0)
  876. {
  877. /* The socket closed, or some other error. */
  878. SetEvent (state->base.except_event);
  879. return 1;
  880. }
  881. else if (available > 0)
  882. {
  883. SetEvent (state->base.read_event);
  884. return 1;
  885. }
  886. return 0;
  887. }
  888. static DWORD WINAPI
  889. net_windows_select_thread (void *arg)
  890. {
  891. struct serial *scb = (struct serial *) arg;
  892. struct net_windows_state *state;
  893. int event_index;
  894. state = (struct net_windows_state *) scb->state;
  895. while (1)
  896. {
  897. HANDLE wait_events[2];
  898. WSANETWORKEVENTS events;
  899. select_thread_wait (&state->base);
  900. wait_events[0] = state->base.stop_select;
  901. wait_events[1] = state->sock_event;
  902. /* Wait for something to happen on the socket. */
  903. while (1)
  904. {
  905. event_index = WaitForMultipleObjects (2, wait_events, FALSE, INFINITE);
  906. if (event_index == WAIT_OBJECT_0
  907. || WaitForSingleObject (state->base.stop_select, 0) == WAIT_OBJECT_0)
  908. {
  909. /* We have been requested to stop. */
  910. break;
  911. }
  912. if (event_index != WAIT_OBJECT_0 + 1)
  913. {
  914. /* Some error has occured. Assume that this is an error
  915. condition. */
  916. SetEvent (state->base.except_event);
  917. break;
  918. }
  919. /* Enumerate the internal network events, and reset the
  920. object that signalled us to catch the next event. */
  921. if (WSAEnumNetworkEvents (scb->fd, state->sock_event, &events) != 0)
  922. {
  923. /* Something went wrong. Maybe the socket is gone. */
  924. SetEvent (state->base.except_event);
  925. break;
  926. }
  927. if (events.lNetworkEvents & FD_READ)
  928. {
  929. if (net_windows_socket_check_pending (scb))
  930. break;
  931. /* Spurious wakeup. That is, the socket's event was
  932. signalled before we last called recv. */
  933. }
  934. if (events.lNetworkEvents & FD_CLOSE)
  935. {
  936. SetEvent (state->base.except_event);
  937. break;
  938. }
  939. }
  940. SetEvent (state->base.have_stopped);
  941. }
  942. return 0;
  943. }
  944. static void
  945. net_windows_wait_handle (struct serial *scb, HANDLE *read, HANDLE *except)
  946. {
  947. struct net_windows_state *state = (struct net_windows_state *) scb->state;
  948. /* Start from a clean slate. */
  949. ResetEvent (state->base.read_event);
  950. ResetEvent (state->base.except_event);
  951. ResetEvent (state->base.stop_select);
  952. *read = state->base.read_event;
  953. *except = state->base.except_event;
  954. /* Check any pending events. Otherwise, start the select
  955. thread. */
  956. if (!net_windows_socket_check_pending (scb))
  957. start_select_thread (&state->base);
  958. }
  959. static void
  960. net_windows_done_wait_handle (struct serial *scb)
  961. {
  962. struct net_windows_state *state = (struct net_windows_state *) scb->state;
  963. stop_select_thread (&state->base);
  964. }
  965. static int
  966. net_windows_open (struct serial *scb, const char *name)
  967. {
  968. struct net_windows_state *state;
  969. int ret;
  970. ret = net_open (scb, name);
  971. if (ret != 0)
  972. return ret;
  973. state = XCNEW (struct net_windows_state);
  974. scb->state = state;
  975. /* Associate an event with the socket. */
  976. state->sock_event = CreateEvent (0, TRUE, FALSE, 0);
  977. WSAEventSelect (scb->fd, state->sock_event, FD_READ | FD_CLOSE);
  978. /* Start the thread. */
  979. create_select_thread (net_windows_select_thread, scb, &state->base);
  980. return 0;
  981. }
  982. static void
  983. net_windows_close (struct serial *scb)
  984. {
  985. struct net_windows_state *state = (struct net_windows_state *) scb->state;
  986. destroy_select_thread (&state->base);
  987. CloseHandle (state->sock_event);
  988. xfree (scb->state);
  989. net_close (scb);
  990. }
  991. /* The serial port driver. */
  992. static const struct serial_ops hardwire_ops =
  993. {
  994. "hardwire",
  995. ser_windows_open,
  996. ser_windows_close,
  997. NULL,
  998. ser_base_readchar,
  999. ser_base_write,
  1000. ser_windows_flush_output,
  1001. ser_windows_flush_input,
  1002. ser_windows_send_break,
  1003. ser_windows_raw,
  1004. /* These are only used for stdin; we do not need them for serial
  1005. ports, so supply the standard dummies. */
  1006. ser_base_get_tty_state,
  1007. ser_base_copy_tty_state,
  1008. ser_base_set_tty_state,
  1009. ser_base_print_tty_state,
  1010. ser_windows_setbaudrate,
  1011. ser_windows_setstopbits,
  1012. ser_windows_setparity,
  1013. ser_windows_drain_output,
  1014. ser_base_async,
  1015. ser_windows_read_prim,
  1016. ser_windows_write_prim,
  1017. NULL,
  1018. ser_windows_wait_handle
  1019. };
  1020. /* The dummy serial driver used for terminals. We only provide the
  1021. TTY-related methods. */
  1022. static const struct serial_ops tty_ops =
  1023. {
  1024. "terminal",
  1025. NULL,
  1026. ser_console_close,
  1027. NULL,
  1028. NULL,
  1029. NULL,
  1030. NULL,
  1031. NULL,
  1032. NULL,
  1033. NULL,
  1034. ser_console_get_tty_state,
  1035. ser_base_copy_tty_state,
  1036. ser_base_set_tty_state,
  1037. ser_base_print_tty_state,
  1038. NULL,
  1039. NULL,
  1040. NULL,
  1041. ser_base_drain_output,
  1042. NULL,
  1043. NULL,
  1044. NULL,
  1045. NULL,
  1046. ser_console_wait_handle,
  1047. ser_console_done_wait_handle
  1048. };
  1049. /* The pipe interface. */
  1050. static const struct serial_ops pipe_ops =
  1051. {
  1052. "pipe",
  1053. pipe_windows_open,
  1054. pipe_windows_close,
  1055. pipe_windows_fdopen,
  1056. ser_base_readchar,
  1057. ser_base_write,
  1058. ser_base_flush_output,
  1059. ser_base_flush_input,
  1060. ser_base_send_break,
  1061. ser_base_raw,
  1062. ser_base_get_tty_state,
  1063. ser_base_copy_tty_state,
  1064. ser_base_set_tty_state,
  1065. ser_base_print_tty_state,
  1066. ser_base_setbaudrate,
  1067. ser_base_setstopbits,
  1068. ser_base_setparity,
  1069. ser_base_drain_output,
  1070. ser_base_async,
  1071. pipe_windows_read,
  1072. pipe_windows_write,
  1073. pipe_avail,
  1074. pipe_wait_handle,
  1075. pipe_done_wait_handle
  1076. };
  1077. /* The TCP/UDP socket driver. */
  1078. static const struct serial_ops tcp_ops =
  1079. {
  1080. "tcp",
  1081. net_windows_open,
  1082. net_windows_close,
  1083. NULL,
  1084. ser_base_readchar,
  1085. ser_base_write,
  1086. ser_base_flush_output,
  1087. ser_base_flush_input,
  1088. ser_tcp_send_break,
  1089. ser_base_raw,
  1090. ser_base_get_tty_state,
  1091. ser_base_copy_tty_state,
  1092. ser_base_set_tty_state,
  1093. ser_base_print_tty_state,
  1094. ser_base_setbaudrate,
  1095. ser_base_setstopbits,
  1096. ser_base_setparity,
  1097. ser_base_drain_output,
  1098. ser_base_async,
  1099. net_read_prim,
  1100. net_write_prim,
  1101. NULL,
  1102. net_windows_wait_handle,
  1103. net_windows_done_wait_handle
  1104. };
  1105. void _initialize_ser_windows ();
  1106. void
  1107. _initialize_ser_windows ()
  1108. {
  1109. WSADATA wsa_data;
  1110. HMODULE hm = NULL;
  1111. /* First find out if kernel32 exports CancelIo function. */
  1112. hm = LoadLibrary ("kernel32.dll");
  1113. if (hm)
  1114. {
  1115. CancelIo = (CancelIo_ftype *) GetProcAddress (hm, "CancelIo");
  1116. FreeLibrary (hm);
  1117. }
  1118. else
  1119. CancelIo = NULL;
  1120. serial_add_interface (&hardwire_ops);
  1121. serial_add_interface (&tty_ops);
  1122. serial_add_interface (&pipe_ops);
  1123. /* If WinSock works, register the TCP/UDP socket driver. */
  1124. if (WSAStartup (MAKEWORD (1, 0), &wsa_data) != 0)
  1125. /* WinSock is unavailable. */
  1126. return;
  1127. serial_add_interface (&tcp_ops);
  1128. }