1/* Event pipe for GDB, the GNU debugger.
2
3   Copyright (C) 2021-2023 Free Software Foundation, Inc.
4
5   This file is part of GDB.
6
7   This program is free software; you can redistribute it and/or modify
8   it under the terms of the GNU General Public License as published by
9   the Free Software Foundation; either version 3 of the License, or
10   (at your option) any later version.
11
12   This program is distributed in the hope that it will be useful,
13   but WITHOUT ANY WARRANTY; without even the implied warranty of
14   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15   GNU General Public License for more details.
16
17   You should have received a copy of the GNU General Public License
18   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
19
20#include "gdbsupport/common-defs.h"
21#include "gdbsupport/event-pipe.h"
22#include "gdbsupport/filestuff.h"
23
24#include <errno.h>
25#include <fcntl.h>
26#include <unistd.h>
27
28event_pipe::~event_pipe ()
29{
30  if (is_open ())
31    close_pipe ();
32}
33
34/* See event-pipe.h.  */
35
36bool
37event_pipe::open_pipe ()
38{
39  if (is_open ())
40    return false;
41
42  if (gdb_pipe_cloexec (m_fds) == -1)
43    return false;
44
45  if (fcntl (m_fds[0], F_SETFL, O_NONBLOCK) == -1
46      || fcntl (m_fds[1], F_SETFL, O_NONBLOCK) == -1)
47    {
48      close_pipe ();
49      return false;
50    }
51
52  return true;
53}
54
55/* See event-pipe.h.  */
56
57void
58event_pipe::close_pipe ()
59{
60  ::close (m_fds[0]);
61  ::close (m_fds[1]);
62  m_fds[0] = -1;
63  m_fds[1] = -1;
64}
65
66/* See event-pipe.h.  */
67
68void
69event_pipe::flush ()
70{
71  int ret;
72  char buf;
73
74  do
75    {
76      ret = read (m_fds[0], &buf, 1);
77    }
78  while (ret >= 0 || (ret == -1 && errno == EINTR));
79}
80
81/* See event-pipe.h.  */
82
83void
84event_pipe::mark ()
85{
86  int ret;
87
88  /* It doesn't really matter what the pipe contains, as long we end
89     up with something in it.  Might as well flush the previous
90     left-overs.  */
91  flush ();
92
93  do
94    {
95      ret = write (m_fds[1], "+", 1);
96    }
97  while (ret == -1 && errno == EINTR);
98
99  /* Ignore EAGAIN.  If the pipe is full, the event loop will already
100     be awakened anyway.  */
101}
102