+ int fd;
+
+ if ((fd = open(pathname, flags)) < 0) {
+ /*
+ * Should be sr_err(), but since some drivers try to open all
+ * ports on a system and see if they succeed, this would
+ * yield ugly output for e.g. "sigrok-cli -D".
+ */
+ sr_dbg("Error opening serial port '%s': %s.", pathname,
+ strerror(errno));
+ } else {
+ sr_dbg("Opened serial port '%s' as FD %d.", pathname, fd);
+ }
+
+ return fd;
+#endif
+}
+
+/**
+ * Close the specified serial port.
+ *
+ * @param fd File descriptor of the serial port.
+ *
+ * @return 0 upon success, -1 upon failure.
+ */
+SR_PRIV int serial_close(int fd)
+{
+ sr_dbg("FD %d: Closing serial port.", fd);
+
+#ifdef _WIN32
+ /* Returns non-zero upon success, 0 upon failure. */
+ return (CloseHandle(hdl) == 0) ? -1 : 0;
+#else
+ int ret;
+
+ /* Returns 0 upon success, -1 upon failure. */
+ if ((ret = close(fd)) < 0) {
+ sr_dbg("FD %d: Error closing serial port: %s.",
+ fd, strerror(errno));
+ }
+
+ return ret;
+#endif
+}
+
+/**
+ * Flush serial port buffers (if any).
+ *
+ * @param fd File descriptor of the serial port.
+ *
+ * @return 0 upon success, -1 upon failure.
+ */
+SR_PRIV int serial_flush(int fd)
+{
+ sr_dbg("FD %d: Flushing serial port.", fd);
+
+#ifdef _WIN32
+ /* Returns non-zero upon success, 0 upon failure. */
+ return (PurgeComm(hdl, PURGE_RXCLEAR | PURGE_TXCLEAR) == 0) ? -1 : 0;
+#else
+ int ret;
+
+ /* Returns 0 upon success, -1 upon failure. */
+ if ((ret = tcflush(fd, TCIOFLUSH)) < 0)
+ sr_err("Error flushing serial port: %s.", strerror(errno));
+
+ return ret;
+#endif
+}
+
+/**
+ * Write a number of bytes to the specified serial port.
+ *
+ * @param fd File descriptor of the serial port.
+ * @param buf Buffer containing the bytes to write.
+ * @param count Number of bytes to write.
+ *
+ * @return The number of bytes written, or -1 upon failure.
+ */
+SR_PRIV int serial_write(int fd, const void *buf, size_t count)
+{
+ sr_spew("FD %d: Writing %d bytes.", fd, count);
+
+#ifdef _WIN32
+ DWORD tmp = 0;
+
+ /* FIXME */
+ /* Returns non-zero upon success, 0 upon failure. */
+ WriteFile(hdl, buf, count, &tmp, NULL);
+#else
+ ssize_t ret;
+
+ /* Returns the number of bytes written, or -1 upon failure. */
+ ret = write(fd, buf, count);
+ if (ret < 0)
+ sr_err("FD %d: Write error: %s.", fd, strerror(errno));
+ else if ((size_t)ret != count)
+ sr_spew("FD %d: Only wrote %d/%d bytes.", fd, ret, count);
+
+ return ret;