+
+ RETURN_OK();
+}
+#endif
+
+SP_API enum sp_return sp_open(struct sp_port *port, enum sp_mode flags)
+{
+ struct port_data data;
+ struct sp_port_config config;
+ enum sp_return ret;
+
+ TRACE("%p, 0x%x", port, flags);
+
+ CHECK_PORT();
+
+ if (flags > SP_MODE_READ_WRITE)
+ RETURN_ERROR(SP_ERR_ARG, "Invalid flags");
+
+ DEBUG_FMT("Opening port %s", port->name);
+
+#ifdef _WIN32
+ DWORD desired_access = 0, flags_and_attributes = 0, errors;
+ char *escaped_port_name;
+ COMSTAT status;
+
+ /* Prefix port name with '\\.\' to work with ports above COM9. */
+ if (!(escaped_port_name = malloc(strlen(port->name) + 5)))
+ RETURN_ERROR(SP_ERR_MEM, "Escaped port name malloc failed");
+ sprintf(escaped_port_name, "\\\\.\\%s", port->name);
+
+ /* Map 'flags' to the OS-specific settings. */
+ flags_and_attributes = FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED;
+ if (flags & SP_MODE_READ)
+ desired_access |= GENERIC_READ;
+ if (flags & SP_MODE_WRITE)
+ desired_access |= GENERIC_WRITE;
+
+ port->hdl = CreateFile(escaped_port_name, desired_access, 0, 0,
+ OPEN_EXISTING, flags_and_attributes, 0);
+
+ free(escaped_port_name);
+
+ if (port->hdl == INVALID_HANDLE_VALUE)
+ RETURN_FAIL("Port CreateFile() failed");
+
+ /* All timeouts initially disabled. */
+ port->timeouts.ReadIntervalTimeout = 0;
+ port->timeouts.ReadTotalTimeoutMultiplier = 0;
+ port->timeouts.ReadTotalTimeoutConstant = 0;
+ port->timeouts.WriteTotalTimeoutMultiplier = 0;
+ port->timeouts.WriteTotalTimeoutConstant = 0;
+
+ if (SetCommTimeouts(port->hdl, &port->timeouts) == 0) {
+ sp_close(port);
+ RETURN_FAIL("SetCommTimeouts() failed");
+ }
+
+ /* Prepare OVERLAPPED structures. */
+#define INIT_OVERLAPPED(ovl) do { \
+ memset(&port->ovl, 0, sizeof(port->ovl)); \
+ port->ovl.hEvent = INVALID_HANDLE_VALUE; \
+ if ((port->ovl.hEvent = CreateEvent(NULL, TRUE, TRUE, NULL)) \
+ == INVALID_HANDLE_VALUE) { \
+ sp_close(port); \
+ RETURN_FAIL(#ovl "CreateEvent() failed"); \
+ } \
+} while (0)
+
+ INIT_OVERLAPPED(read_ovl);
+ INIT_OVERLAPPED(write_ovl);
+ INIT_OVERLAPPED(wait_ovl);
+
+ /* Set event mask for RX and error events. */
+ if (SetCommMask(port->hdl, EV_RXCHAR | EV_ERR) == 0) {
+ sp_close(port);
+ RETURN_FAIL("SetCommMask() failed");
+ }
+
+ port->writing = FALSE;
+ port->wait_running = FALSE;
+
+ ret = restart_wait(port);
+
+ if (ret < 0) {
+ sp_close(port);
+ RETURN_CODEVAL(ret);