Beispiel #1
0
int diag_tty_break(struct diag_l0_device *dl0d, const int ms)
{
	HANDLE hd;
	long h;

	/*
	 * I'm going through this convoluted two-step conversion
	 * to avoid compiler warnings:
	 */

	h = get_osfhandle(dl0d->fd);
	hd = (HANDLE)h;

	if (tcdrain(dl0d->fd)) {
			fprintf(stderr, FLFMT "tcdrain returned %s.\n",
				FL, strerror(errno));
			return diag_iseterr(DIAG_ERR_GENERAL);
		}

	SetCommBreak(hd);
	diag_os_millisleep(ms);
	ClearCommBreak(hd);

	return 0;
}
Beispiel #2
0
serial_source open_serial_source(const char *device, int baud_rate,	int non_blocking, void (*message)(serial_source_msg problem))
	/* Effects: opens serial port device at specified baud_rate. If non_blocking
	   is true, read_serial_packet calls will be non-blocking (writes are
	   always blocking, for now at least)
	   Returns: descriptor for serial forwarder at host:port, or
	   NULL for failure (bad device or bad baud rate)
	   */
{
	struct termios newtio;
	int fd;
	tcflag_t baudflag = parse_baudrate(baud_rate);

	if (!baudflag)
		return NULL;

	fd = open(device, O_RDWR | O_NOCTTY | O_NONBLOCK);
	if (fd < 0)
		return NULL;

#ifdef __CYGWIN__
	/* For some very mysterious reason, this incantation is necessary to make
	   the serial port work under some windows machines */
	HANDLE handle = (HANDLE)get_osfhandle(fd);
	DCB dcb;
	if (!(GetCommState(handle, &dcb) && SetCommState(handle, &dcb)))
	{
		close(fd);
		return NULL;
	}
#endif
	/* Serial port setting */
	memset(&newtio, 0, sizeof(newtio));
	newtio.c_cflag = CS8 | CLOCAL | CREAD;
	newtio.c_iflag = IGNPAR | IGNBRK;
	cfsetispeed(&newtio, baudflag);
	cfsetospeed(&newtio, baudflag);

	/* Raw output_file */
	newtio.c_oflag = 0;
	if (tcflush(fd, TCIFLUSH) >= 0 && tcsetattr(fd, TCSANOW, &newtio) >= 0) {
		serial_source src = malloc(sizeof *src);

		if (src) {
			memset(src, 0, sizeof src);
			src->fd = fd;
			src->non_blocking = non_blocking;
			src->message = message;
			src->send.seqno = 37;

			return src;
		}
	}
	close(fd);

	return NULL;
}
Beispiel #3
0
/*  Start a new overlapped I/O read from the command stream  */
void start_read_command(
    struct command_buffer_t *buffer)
{
    HANDLE command_stream =
        (HANDLE)get_osfhandle(buffer->command_stream);
    int space_remaining = 
        COMMAND_BUFFER_SIZE - buffer->incoming_read_position - 1;
    int err;

    /*  If a read is already active, or the pipe is closed, do nothing  */
    if (!buffer->platform.pipe_open || buffer->platform.read_active) {
        return;
    }

    memset(&buffer->platform.overlapped, 0, sizeof(OVERLAPPED));
    buffer->platform.overlapped.hEvent = (HANDLE)buffer;

    if (!ReadFileEx(
        command_stream, buffer->platform.overlapped_buffer, space_remaining,
        &buffer->platform.overlapped, finish_read_command)) {

        err = GetLastError();

        if (err == ERROR_BROKEN_PIPE) {
            /*  If the command stream has been closed, we need to wake from
                the next altertable wait to exit the main loop  */
            buffer->platform.pipe_open = false;
            queue_empty_apc();

            return;
        } else if (err != WAIT_IO_COMPLETION) {
            fprintf(
                stderr, "Unexpected ReadFileEx failure %d\n", GetLastError());
            exit(EXIT_FAILURE);
        }
    }

    /*  Remember that we have started an overlapped read already  */
    buffer->platform.read_active = true;
}
Beispiel #4
0
/* We are using Windows-specific API's to map files */
static void *mmapPerform(int fd, unsigned long offset,
						 unsigned long len, unsigned long end)
{
	HANDLE osHandle;
	HANDLE mapHandle;
	void *mapAddress;

	/* Get the underlying OS handle for the fd */
#ifdef IL_WIN32_CYGWIN
	osHandle = (HANDLE)get_osfhandle(fd);
#else
	osHandle = (HANDLE)_get_osfhandle(fd);
#endif
	if(osHandle == (HANDLE)INVALID_HANDLE_VALUE)
	{
		return 0;
	}

	/* Under Windows, we cannot map bytes beyond the end of the file,
	   so we need to clamp the length to stay within the file's extent */
	if((offset + len) > end)
	{
		len = end - offset;
	}

	/* Attempt to map the file */
	mapHandle = CreateFileMapping(osHandle, NULL, PAGE_READONLY,
								  0, 0, NULL);
	if(mapHandle == (HANDLE)NULL)
	{
		return 0;
	}
	mapAddress = MapViewOfFile(mapHandle, FILE_MAP_READ, 0, offset, len);

	/* Close the mapping object, which we no longer require */
	CloseHandle(mapHandle);

	/* Return the memory pointer to the caller */
	return mapAddress;
}
Beispiel #5
0
/**
 * Opens up a stream to the serial port.
 * 
 * @return    Handle to the serial port as an integer.
 * @author    Martin Turon
 * @version   2004/3/10       mturon      Intial revision
 * @n         2004/3/11       mturon      Fixed cygwin reset problem
 * @n         2004/3/12       mturon      Added improved cygwin fix by dgay
 */
int xserial_port_open() 
{
    /* open serline for read/write */ 
    int serline;
    const char *name = g_device;
    unsigned long baudrate = g_baudrate;
    
    serline = open(name, O_RDWR | O_NOCTTY);
    if (serline == -1) {
        fprintf(stderr, "Failed to open %s\n", name);
        perror("");
        fprintf(stderr, "Verify that user has permission to open device.\n");
        exit(2);
    }
    if (xmain_get_verbose()) printf("%s input stream opened\n", name);

#ifdef __CYGWIN__
    /* Cygwin requires some specific initialization. */
    HANDLE handle = (HANDLE)get_osfhandle(serline);
    DCB dcb;
    if (!(GetCommState(handle, &dcb) &&
	  SetCommState(handle, &dcb))) {
	fprintf(stderr, "serial port initialisation problem\n");
	exit(2);
    }
#endif
    
    /* Serial port setting */
    struct termios newtio;
    bzero(&newtio, sizeof(newtio));
    newtio.c_cc[VMIN] = 1;
    newtio.c_cflag = CS8 | CLOCAL | CREAD;
    newtio.c_iflag = IGNBRK | IGNPAR;
    cfsetispeed(&newtio, baudrate);
    cfsetospeed(&newtio, baudrate);
    tcflush(serline, TCIFLUSH);
    tcsetattr(serline, TCSANOW, &newtio);

    return serline;
}
Beispiel #6
0
int ILSysIOLock(ILSysIOHandle handle, ILInt64 position, ILInt64 length)
{
#if defined(IL_WIN32_PLATFORM)
	/* Bypass the system library and call LockFile directly under Win32 */
#ifdef IL_WIN32_CYGWIN
	HANDLE osHandle = (HANDLE)get_osfhandle((int)(ILNativeInt)handle);
#else
	HANDLE osHandle = (HANDLE)_get_osfhandle((int)(ILNativeInt)handle);
#endif
	if(osHandle == (HANDLE)INVALID_HANDLE_VALUE)
	{
		ILSysIOSetErrno(IL_ERRNO_EBADF);
		return 0;
	}
	if(LockFile(osHandle,
				(DWORD)(position & IL_MAX_UINT32),
			 	(DWORD)((position >> 32) & IL_MAX_UINT32),
			 	(DWORD)(length & IL_MAX_UINT32),
			 	(DWORD)((length >> 32) & IL_MAX_UINT32)))
	{
		return 1;
	}
	else
	{
Beispiel #7
0
int
w32fcntl(int fd, int flag, void *argp)
{
   HANDLE h = LongToHandle(get_osfhandle(fd));

   int r = 0, err = 0;

   struct flock *fl;

   switch (flag)
   {
   case F_SETLK:
   case F_SETLKW:
#if 0
   default:
      return fcntl(fd, flag, argp);
#else
      fl = (struct flock *) argp;
      switch (fl->l_type)
      {
      case F_RDLCK:
      case F_WRLCK:
	 r = LockFile(h, fl->l_start, 0, fl->l_len, 0);
	 break;
      case F_UNLCK:
	 r = UnlockFile(h, fl->l_start, 0, fl->l_len, 0);
	 break;
      }
      if (!r)
	 err = GetLastError();
      return !r;
#endif
   case F_GETLK:
#if 0
      fl = (struct flock *) argp;
      fl->l_type = F_WRLCK;
      if (!fcntl(fd, F_SETLK, fl))
      {
	 fl->l_type = F_UNLCK;
	 fcntl(fd, F_SETLK, fl);
	 fl->l_type = F_SETLK;
      }
      else
	 fl->l_type = F_UNLCK;
      return 0;
#else
      fl = (struct flock *) argp;
      if (LockFile(h, fl->l_start, 0, fl->l_len, 0))
      {
	 fl->l_type = F_UNLCK;
	 UnlockFile(h, fl->l_start, 0, fl->l_len, 0);
      }
      else
      {
	 fl->l_type = F_WRLCK;
      }
#endif
      return 0;
   }
   return -1;
}
Beispiel #8
0
serial_source open_serial_source(const char *device, int baud_rate,
				 int non_blocking,
				 void (*message)(serial_source_msg problem))
/* Effects: opens serial port device at specified baud_rate. If non_blocking
     is true, read_serial_packet calls will be non-blocking (writes are
     always blocking, for now at least)
   Returns: descriptor for serial forwarder at host:port, or
     NULL for failure (bad device or bad baud rate)
 */
{
#ifndef LOSE32
  struct termios newtio;
  int fd;
  tcflag_t baudflag = parse_baudrate(baud_rate);

  if (!baudflag)
    return NULL;

  fd = open(device, O_RDWR | O_NOCTTY | O_NONBLOCK);
  if (fd < 0)
    return NULL;

#ifdef __CYGWIN__
  /* For some very mysterious reason, this incantation is necessary to make
     the serial port work under some windows machines */
  HANDLE handle = (HANDLE)get_osfhandle(fd);
  DCB dcb;
  if (!(GetCommState(handle, &dcb) && SetCommState(handle, &dcb)))
    {
      close(fd);
      return NULL;
    }
#endif
  /* Serial port setting */
  memset(&newtio, 0, sizeof(newtio));
  newtio.c_cflag = CS8 | CLOCAL | CREAD;
  newtio.c_iflag = IGNPAR | IGNBRK;
  cfsetispeed(&newtio, baudflag);
  cfsetospeed(&newtio, baudflag);

  /* Raw output_file */
  newtio.c_oflag = 0;

  if (tcflush(fd, TCIFLUSH) >= 0 &&
      tcsetattr(fd, TCSANOW, &newtio) >= 0)
    {
      serial_source src = malloc(sizeof *src);

      if (src)
	{
	  memset(src, 0, sizeof *src);
	  src->fd = fd;
	  src->non_blocking = non_blocking;
	  src->message = message;
	  src->send.seqno = 37;

	  return src;
	}
    }
  close(fd);

  return NULL;
#else // LOSE32
	LPCTSTR       ComName = (LPCTSTR)device;
    HANDLE        hComm;
	DCB           dcb;
    serial_source src;

	int buflen = MultiByteToWideChar(CP_ACP,0,(PCSTR)device,-1,(LPWSTR)ComName,0);
	MultiByteToWideChar(CP_ACP,0,(PCSTR)device,-1,(LPWSTR)ComName,buflen);
	
	//syncronize
	hComm = CreateFile(ComName,  GENERIC_READ | GENERIC_WRITE,  0,  NULL,  OPEN_EXISTING,
					FILE_ATTRIBUTE_NORMAL, NULL);

    if (hComm == INVALID_HANDLE_VALUE) {
        return NULL;
    }

    PurgeComm(hComm, PURGE_RXCLEAR);

	GetCommState(hComm, &dcb); 
	dcb.BaudRate = baud_rate;
	dcb.ByteSize = 8;
	dcb.Parity = NOPARITY;
	dcb.fParity = FALSE;
	dcb.StopBits = ONESTOPBIT;
    if (SetCommState(hComm, &dcb) == 0) {
        return NULL;
    }

    src = malloc(sizeof *src);

    if (src) {
	  memset(src, 0, sizeof *src);
	  src->hComm = hComm;
	  src->non_blocking = non_blocking;
	  src->message = message;
	  src->send.seqno = 37;

	}

	return src;

#endif // LOSE32
}
Beispiel #9
0
int fb_hFileUnlock( FILE *f, fb_off_t inipos, fb_off_t size )
{
	return fb_ErrorSetNum( UnlockFile( (HANDLE)get_osfhandle( fileno( f ) ), inipos, 0, size, 0 ) == TRUE ?
	                       FB_RTERROR_OK : FB_RTERROR_FILEIO );
}
static int start_process(Channel * c, char ** envp, char * dir, char * exe, char ** args, int attach,
                int * pid, int * selfattach, ChildProcess ** prs) {
    typedef struct _SYSTEM_HANDLE_INFORMATION {
        ULONG Count;
        struct HANDLE_INFORMATION {
            USHORT ProcessId;
            USHORT CreatorBackTraceIndex;
            UCHAR ObjectTypeNumber;
            UCHAR Flags;
            USHORT Handle;
            PVOID Object;
            ACCESS_MASK GrantedAccess;
        } Handles[1];
    } SYSTEM_HANDLE_INFORMATION;
    FARPROC QuerySystemInformationProc = GetProcAddress(GetModuleHandle("NTDLL.DLL"), "NtQuerySystemInformation");
    DWORD size;
    NTSTATUS status;
    SYSTEM_HANDLE_INFORMATION * hi = NULL;
    int fpipes[3][2];
    HANDLE hpipes[3][2];
    char * cmd = NULL;
    int err = 0;
    int i;

    if (args != NULL) {
        int i = 0;
        int cmd_size = 0;
        int cmd_pos = 0;
#           define cmd_append(ch) { \
            if (!cmd) { \
                cmd_size = 0x1000; \
                cmd = (char *)loc_alloc(cmd_size); \
            } \
            else if (cmd_pos >= cmd_size) { \
                char * tmp = (char *)loc_alloc(cmd_size * 2); \
                memcpy(tmp, cmd, cmd_pos); \
                loc_free(cmd); \
                cmd = tmp; \
                cmd_size *= 2; \
            }; \
            cmd[cmd_pos++] = (ch); \
        }
        while (args[i] != NULL) {
            char * p = args[i++];
            if (cmd_pos > 0) cmd_append(' ');
            cmd_append('"');
            while (*p) {
                if (*p == '"') cmd_append('\\');
                cmd_append(*p);
                p++;
            }
            cmd_append('"');
        }
        cmd_append(0);
#       undef cmd_append
    }

    size = sizeof(SYSTEM_HANDLE_INFORMATION) * 16;
    hi = loc_alloc(size);
    for (;;) {
        status = QuerySystemInformationProc(SystemHandleInformation, hi, size, &size);
        if (status != STATUS_INFO_LENGTH_MISMATCH) break;
        hi = loc_realloc(hi, size);
    }
    if (status == 0) {
        ULONG i;
        DWORD id = GetCurrentProcessId();
        for (i = 0; i < hi->Count; i++) {
            if (hi->Handles[i].ProcessId != id) continue;
            SetHandleInformation((HANDLE)(int)hi->Handles[i].Handle, HANDLE_FLAG_INHERIT, FALSE);
        }
    }
    else {
        err = set_win32_errno(status);
        trace(LOG_ALWAYS, "Can't start process '%s': %s", exe, errno_to_str(err));
    }
    loc_free(hi);

    memset(hpipes, 0, sizeof(hpipes));
    for (i = 0; i < 3; i++) fpipes[i][0] = fpipes[i][1] = -1;
    if (!err) {
#if defined(__CYGWIN__)
        for (i = 0; i < 3; i++) {
            if (pipe(fpipes[i]) < 0) {
                err = errno;
                break;
            }
            hpipes[i][0] = (HANDLE)get_osfhandle(fpipes[i][0]);
            hpipes[i][1] = (HANDLE)get_osfhandle(fpipes[i][1]);
        }
#else
        for (i = 0; i < 3; i++) {
            if (!CreatePipe(&hpipes[i][0], &hpipes[i][1], NULL, PIPE_SIZE)) {
                err = set_win32_errno(GetLastError());
                break;
            }
            fpipes[i][0] = _open_osfhandle((intptr_t)hpipes[i][0], O_TEXT);
            fpipes[i][1] = _open_osfhandle((intptr_t)hpipes[i][1], O_TEXT);
        }
#endif
    }
    if (!err) {
        STARTUPINFO si;
        PROCESS_INFORMATION prs_info;
        SetHandleInformation(hpipes[0][0], HANDLE_FLAG_INHERIT, TRUE);
        SetHandleInformation(hpipes[1][1], HANDLE_FLAG_INHERIT, TRUE);
        SetHandleInformation(hpipes[2][1], HANDLE_FLAG_INHERIT, TRUE);
        memset(&si, 0, sizeof(si));
        memset(&prs_info, 0, sizeof(prs_info));
        si.cb = sizeof(si);
        si.dwFlags |= STARTF_USESTDHANDLES;
        si.hStdInput  = hpipes[0][0];
        si.hStdOutput = hpipes[1][1];
        si.hStdError  = hpipes[2][1];
        if (CreateProcess(exe, cmd, NULL, NULL, TRUE, (attach ? CREATE_SUSPENDED : 0),
                (envp ? envp[0] : NULL), (dir[0] ? dir : NULL), &si, &prs_info) == 0)
        {
            err = set_win32_errno(GetLastError());
        }
        else {
            *pid = prs_info.dwProcessId;
            CloseHandle(prs_info.hThread);
            CloseHandle(prs_info.hProcess);
        }
    }
    close(fpipes[0][0]);
    close(fpipes[1][1]);
    close(fpipes[2][1]);
    if (!err) {
        *prs = loc_alloc_zero(sizeof(ChildProcess));
        (*prs)->inp = fpipes[0][1];
        (*prs)->out = fpipes[1][0];
        (*prs)->err = fpipes[2][0];
        (*prs)->pid = *pid;
        (*prs)->bcg = c->bcg;
        list_add_first(&(*prs)->link, &prs_list);
    }
    else {
        close(fpipes[0][1]);
        close(fpipes[1][0]);
        close(fpipes[2][0]);
    }
    loc_free(cmd);
    if (!err) return 0;
    trace(LOG_ALWAYS, "Can't start process '%s': %s", exe, errno_to_str(err));
    errno = err;
    return -1;
}