+/* File handle for target file operations. */
+
+typedef struct
+{
+ /* The target on which this file is open. */
+ struct target_ops *t;
+
+ /* The file descriptor on the target. */
+ int fd;
+} fileio_fh_t;
+
+DEF_VEC_O (fileio_fh_t);
+
+/* Vector of currently open file handles. The value returned by
+ target_fileio_open and passed as the FD argument to other
+ target_fileio_* functions is an index into this vector. This
+ vector's entries are never freed; instead, files are marked as
+ closed, and the handle becomes available for reuse. */
+static VEC (fileio_fh_t) *fileio_fhandles;
+
+/* Macro to check whether a fileio_fh_t represents a closed file. */
+#define is_closed_fileio_fh(fd) ((fd) < 0)
+
+/* Index into fileio_fhandles of the lowest handle that might be
+ closed. This permits handle reuse without searching the whole
+ list each time a new file is opened. */
+static int lowest_closed_fd;
+
+/* Acquire a target fileio file descriptor. */
+
+static int
+acquire_fileio_fd (struct target_ops *t, int fd)
+{
+ fileio_fh_t *fh, buf;
+
+ gdb_assert (!is_closed_fileio_fh (fd));
+
+ /* Search for closed handles to reuse. */
+ for (;
+ VEC_iterate (fileio_fh_t, fileio_fhandles,
+ lowest_closed_fd, fh);
+ lowest_closed_fd++)
+ if (is_closed_fileio_fh (fh->fd))
+ break;
+
+ /* Push a new handle if no closed handles were found. */
+ if (lowest_closed_fd == VEC_length (fileio_fh_t, fileio_fhandles))
+ fh = VEC_safe_push (fileio_fh_t, fileio_fhandles, NULL);
+
+ /* Fill in the handle. */
+ fh->t = t;
+ fh->fd = fd;
+
+ /* Return its index, and start the next lookup at
+ the next index. */
+ return lowest_closed_fd++;
+}
+
+/* Release a target fileio file descriptor. */
+
+static void
+release_fileio_fd (int fd, fileio_fh_t *fh)
+{
+ fh->fd = -1;
+ lowest_closed_fd = min (lowest_closed_fd, fd);
+}
+
+/* Return a pointer to the fileio_fhandle_t corresponding to FD. */
+
+#define fileio_fd_to_fh(fd) \
+ VEC_index (fileio_fh_t, fileio_fhandles, (fd))
+
+/* Helper for target_fileio_open and
+ target_fileio_open_warn_if_slow. */
+
+static int
+target_fileio_open_1 (struct inferior *inf, const char *filename,
+ int flags, int mode, int warn_if_slow,
+ int *target_errno)