Ejemplo n.º 1
0
Archivo: file.c Proyecto: NativeAPI/dmd
int File::read()
{
    if (len)
        return 0;               // already read the file
#if POSIX
    size_t size;
    ssize_t numread;
    int fd;
    struct stat buf;
    int result = 0;
    char *name;

    name = this->name->toChars();
    //printf("File::read('%s')\n",name);
    fd = open(name, O_RDONLY);
    if (fd == -1)
    {
        //printf("\topen error, errno = %d\n",errno);
        goto err1;
    }

    if (!ref)
        ::free(buffer);
    ref = 0;       // we own the buffer now

    //printf("\tfile opened\n");
    if (fstat(fd, &buf))
    {
        printf("\tfstat error, errno = %d\n",errno);
        goto err2;
    }
    size = (size_t)buf.st_size;
    buffer = (unsigned char *) ::malloc(size + 2);
    if (!buffer)
    {
        printf("\tmalloc error, errno = %d\n",errno);
        goto err2;
    }

    numread = ::read(fd, buffer, size);
    if (numread != size)
    {
        printf("\tread error, errno = %d\n",errno);
        goto err2;
    }

    if (touchtime)
        memcpy(touchtime, &buf, sizeof(buf));

    if (close(fd) == -1)
    {
        printf("\tclose error, errno = %d\n",errno);
        goto err;
    }

    len = size;

    // Always store a wchar ^Z past end of buffer so scanner has a sentinel
    buffer[size] = 0;           // ^Z is obsolete, use 0
    buffer[size + 1] = 0;
    return 0;

err2:
    close(fd);
err:
    ::free(buffer);
    buffer = NULL;
    len = 0;

err1:
    result = 1;
    return result;
#elif _WIN32
    DWORD size;
    DWORD numread;
    HANDLE h;
    int result = 0;
    char *name;

    name = this->name->toChars();
    h = CreateFileA(name,GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_EXISTING,
        FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN,NULL);
    if (h == INVALID_HANDLE_VALUE)
        goto err1;

    if (!ref)
        ::free(buffer);
    ref = 0;

    size = GetFileSize(h,NULL);
    buffer = (unsigned char *) ::malloc(size + 2);
    if (!buffer)
        goto err2;

    if (ReadFile(h,buffer,size,&numread,NULL) != TRUE)
        goto err2;

    if (numread != size)
        goto err2;

    if (touchtime)
    {
        if (!GetFileTime(h, NULL, NULL, &((WIN32_FIND_DATAA *)touchtime)->ftLastWriteTime))
            goto err2;
    }

    if (!CloseHandle(h))
        goto err;

    len = size;

    // Always store a wchar ^Z past end of buffer so scanner has a sentinel
    buffer[size] = 0;           // ^Z is obsolete, use 0
    buffer[size + 1] = 0;
    return 0;

err2:
    CloseHandle(h);
err:
    ::free(buffer);
    buffer = NULL;
    len = 0;

err1:
    result = 1;
    return result;
#else
    assert(0);
#endif
}
void
TeDecoderFile::init()
{
	clear();

	// First open the file
	m_hFile = CreateFileA(
		params_.fileName_.c_str(),	// File name
		GENERIC_READ | GENERIC_WRITE,	// Read-write
		FILE_SHARE_READ
		| FILE_SHARE_WRITE,		// Allow sharing-- we're only doing a quick scan
		NULL,					// No security attributes
		OPEN_EXISTING,			// Only open an existing file
		0,						// Ignore file attributes
		NULL);					// Ignore hTemplateFile

	if (m_hFile == INVALID_HANDLE_VALUE) 
			return ;		// could not open file

// Get the file's size
	m_dwSize = GetFileSize(m_hFile, NULL);
	if (m_dwSize == 0xffffffff)
	{
		m_hFile = NULL;
		return ;
	}

// Allocate buffer to get raster line from file

	long mBufferSize = params_.ncols_;
	if (params_.interleaving_ == TeRasterParams::TePerPixel)
		mBufferSize *= params_.nBands();

	switch (params_.dataType_[0]) {
	case (TeUNSIGNEDCHAR):
		m_buffer = new unsigned char[mBufferSize];
		break;
	case (TeCHAR) :
		m_buffer = new char[mBufferSize];
		break;
	case (TeUNSIGNEDSHORT):
		m_buffer = new unsigned short[mBufferSize];
		break;
	case (TeSHORT):
		m_buffer = new short[mBufferSize];
		break;
	case (TeUNSIGNEDLONG):
		m_buffer = new unsigned long[mBufferSize];
		break;
	case (TeLONG):
		m_buffer = new long[mBufferSize];
		break;
	case (TeFLOAT):
		m_buffer = new float[mBufferSize];
		break;
	case (TeDOUBLE):
		m_buffer = new double[mBufferSize];
		break;

    default:
        break;
	}
	if ( m_buffer == NULL )
		return ;
	else
		return ;
		
}
Ejemplo n.º 3
0
BOOL SetFile(PCHAR pszPath)
{
    BOOL bGood = TRUE;
    HANDLE hOld = INVALID_HANDLE_VALUE;
    HANDLE hNew = INVALID_HANDLE_VALUE;
    PDETOUR_BINARY pBinary = NULL;

    CHAR szOrg[MAX_PATH];
    CHAR szNew[MAX_PATH];
    CHAR szOld[MAX_PATH];

    szOld[0] = '\0';
    szNew[0] = '\0';

    StringCchCopyA(szOrg, sizeof(szOrg), pszPath);
    StringCchCopyA(szNew, sizeof(szNew), szOrg);
    StringCchCatA(szNew, sizeof(szNew), "#");
    StringCchCopyA(szOld, sizeof(szOld), szOrg);
    StringCchCatA(szOld, sizeof(szOld), "~");
    printf("  %s:\n", pszPath);

    hOld = CreateFileA(szOrg,
                       GENERIC_READ,
                       FILE_SHARE_READ,
                       NULL,
                       OPEN_EXISTING,
                       FILE_ATTRIBUTE_NORMAL,
                       NULL);

    if (hOld == INVALID_HANDLE_VALUE) {
        printf("Couldn't open input file: %s, error: %d\n",
               szOrg, GetLastError());
        bGood = FALSE;
        goto end;
    }

    hNew = CreateFileA(szNew,
                       GENERIC_WRITE | GENERIC_READ, 0, NULL, CREATE_ALWAYS,
                       FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, NULL);
    if (hNew == INVALID_HANDLE_VALUE) {
        printf("Couldn't open output file: %s, error: %d\n",
               szNew, GetLastError());
        bGood = FALSE;
        goto end;
    }

    if ((pBinary = DetourBinaryOpen(hOld)) == NULL) {
        printf("DetourBinaryOpen failed: %d\n", GetLastError());
        goto end;
    }

    if (hOld != INVALID_HANDLE_VALUE) {
        CloseHandle(hOld);
        hOld = INVALID_HANDLE_VALUE;
    }

    {
        BOOL bAddedDll = FALSE;

        DetourBinaryResetImports(pBinary);

        if (!s_fRemove) {
            if (!DetourBinaryEditImports(pBinary,
                                         &bAddedDll,
                                         AddBywayCallback, NULL, NULL, NULL)) {
                printf("DetourBinaryEditImports failed: %d\n", GetLastError());
            }
        }

        if (!DetourBinaryEditImports(pBinary, NULL,
                                     ListBywayCallback, ListFileCallback,
                                     NULL, NULL)) {

            printf("DetourBinaryEditImports failed: %d\n", GetLastError());
        }

        if (!DetourBinaryWrite(pBinary, hNew)) {
            printf("DetourBinaryWrite failed: %d\n", GetLastError());
            bGood = FALSE;
        }

        DetourBinaryClose(pBinary);
        pBinary = NULL;

        if (hNew != INVALID_HANDLE_VALUE) {
            CloseHandle(hNew);
            hNew = INVALID_HANDLE_VALUE;
        }

        if (bGood) {
            if (!DeleteFileA(szOld)) {
                DWORD dwError = GetLastError();
                if (dwError != ERROR_FILE_NOT_FOUND) {
                    printf("Warning: Couldn't delete %s: %d\n", szOld, dwError);
                    bGood = FALSE;
                }
            }
            if (!MoveFileA(szOrg, szOld)) {
                printf("Error: Couldn't back up %s to %s: %d\n",
                       szOrg, szOld, GetLastError());
                bGood = FALSE;
            }
            if (!MoveFileA(szNew, szOrg)) {
                printf("Error: Couldn't install %s as %s: %d\n",
                       szNew, szOrg, GetLastError());
                bGood = FALSE;
            }
        }

        DeleteFileA(szNew);
    }


  end:
    if (pBinary) {
        DetourBinaryClose(pBinary);
        pBinary = NULL;
    }
    if (hNew != INVALID_HANDLE_VALUE) {
        CloseHandle(hNew);
        hNew = INVALID_HANDLE_VALUE;
    }
    if (hOld != INVALID_HANDLE_VALUE) {
        CloseHandle(hOld);
        hOld = INVALID_HANDLE_VALUE;
    }
    return bGood;
}
Ejemplo n.º 4
0
template <typename PointT> int
pcl::PCDWriter::writeBinaryCompressed (const std::string &file_name, 
                                       const pcl::PointCloud<PointT> &cloud)
{
  if (cloud.points.empty ())
  {
    throw pcl::IOException ("[pcl::PCDWriter::writeBinaryCompressed] Input point cloud has no data!");
    return (-1);
  }
  int data_idx = 0;
  std::ostringstream oss;
  oss << generateHeader<PointT> (cloud) << "DATA binary_compressed\n";
  oss.flush ();
  data_idx = static_cast<int> (oss.tellp ());

#if _WIN32
  HANDLE h_native_file = CreateFileA (file_name.c_str (), GENERIC_READ | GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
  if (h_native_file == INVALID_HANDLE_VALUE)
  {
    throw pcl::IOException ("[pcl::PCDWriter::writeBinaryCompressed] Error during CreateFile!");
    return (-1);
  }
#else
  int fd = pcl_open (file_name.c_str (), O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
  if (fd < 0)
  {
    throw pcl::IOException ("[pcl::PCDWriter::writeBinaryCompressed] Error during open!");
    return (-1);
  }
#endif

  // Mandatory lock file
  boost::interprocess::file_lock file_lock;
  setLockingPermissions (file_name, file_lock);

  std::vector<pcl::PCLPointField> fields;
  size_t fsize = 0;
  size_t data_size = 0;
  size_t nri = 0;
  pcl::getFields (cloud, fields);
  std::vector<int> fields_sizes (fields.size ());
  // Compute the total size of the fields
  for (size_t i = 0; i < fields.size (); ++i)
  {
    if (fields[i].name == "_")
      continue;
    
    fields_sizes[nri] = fields[i].count * pcl::getFieldSize (fields[i].datatype);
    fsize += fields_sizes[nri];
    fields[nri] = fields[i];
    ++nri;
  }
  fields_sizes.resize (nri);
  fields.resize (nri);
 
  // Compute the size of data
  data_size = cloud.points.size () * fsize;

  //////////////////////////////////////////////////////////////////////
  // Empty array holding only the valid data
  // data_size = nr_points * point_size 
  //           = nr_points * (sizeof_field_1 + sizeof_field_2 + ... sizeof_field_n)
  //           = sizeof_field_1 * nr_points + sizeof_field_2 * nr_points + ... sizeof_field_n * nr_points
  char *only_valid_data = static_cast<char*> (malloc (data_size));

  // Convert the XYZRGBXYZRGB structure to XXYYZZRGBRGB to aid compression. For
  // this, we need a vector of fields.size () (4 in this case), which points to
  // each individual plane:
  //   pters[0] = &only_valid_data[offset_of_plane_x];
  //   pters[1] = &only_valid_data[offset_of_plane_y];
  //   pters[2] = &only_valid_data[offset_of_plane_z];
  //   pters[3] = &only_valid_data[offset_of_plane_RGB];
  //
  std::vector<char*> pters (fields.size ());
  int toff = 0;
  for (size_t i = 0; i < pters.size (); ++i)
  {
    pters[i] = &only_valid_data[toff];
    toff += fields_sizes[i] * static_cast<int> (cloud.points.size ());
  }
  
  // Go over all the points, and copy the data in the appropriate places
  for (size_t i = 0; i < cloud.points.size (); ++i)
  {
    for (size_t j = 0; j < fields.size (); ++j)
    {
      memcpy (pters[j], reinterpret_cast<const char*> (&cloud.points[i]) + fields[j].offset, fields_sizes[j]);
      // Increment the pointer
      pters[j] += fields_sizes[j];
    }
  }

  char* temp_buf = static_cast<char*> (malloc (static_cast<size_t> (static_cast<float> (data_size) * 1.5f + 8.0f)));
  // Compress the valid data
  unsigned int compressed_size = pcl::lzfCompress (only_valid_data, 
                                                   static_cast<uint32_t> (data_size), 
                                                   &temp_buf[8], 
                                                   static_cast<uint32_t> (static_cast<float>(data_size) * 1.5f));
  unsigned int compressed_final_size = 0;
  // Was the compression successful?
  if (compressed_size)
  {
    char *header = &temp_buf[0];
    memcpy (&header[0], &compressed_size, sizeof (unsigned int));
    memcpy (&header[4], &data_size, sizeof (unsigned int));
    data_size = compressed_size + 8;
    compressed_final_size = static_cast<uint32_t> (data_size) + data_idx;
  }
  else
  {
#if !_WIN32
    pcl_close (fd);
#endif
    resetLockingPermissions (file_name, file_lock);
    throw pcl::IOException ("[pcl::PCDWriter::writeBinaryCompressed] Error during compression!");
    return (-1);
  }

#if !_WIN32
  // Stretch the file size to the size of the data
  off_t result = pcl_lseek (fd, getpagesize () + data_size - 1, SEEK_SET);
  if (result < 0)
  {
    pcl_close (fd);
    resetLockingPermissions (file_name, file_lock);
    PCL_ERROR ("[pcl::PCDWriter::writeBinary] lseek errno: %d strerror: %s\n", errno, strerror (errno));
    
    throw pcl::IOException ("[pcl::PCDWriter::writeBinaryCompressed] Error during lseek ()!");
    return (-1);
  }
  // Write a bogus entry so that the new file size comes in effect
  result = static_cast<int> (::write (fd, "", 1));
  if (result != 1)
  {
    pcl_close (fd);
    resetLockingPermissions (file_name, file_lock);
    throw pcl::IOException ("[pcl::PCDWriter::writeBinaryCompressed] Error during write ()!");
    return (-1);
  }
#endif

  // Prepare the map
#if _WIN32
  HANDLE fm = CreateFileMapping (h_native_file, NULL, PAGE_READWRITE, 0, compressed_final_size, NULL);
  char *map = static_cast<char*>(MapViewOfFile (fm, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, compressed_final_size));
  CloseHandle (fm);

#else
  char *map = static_cast<char*> (mmap (0, compressed_final_size, PROT_WRITE, MAP_SHARED, fd, 0));
  if (map == reinterpret_cast<char*> (-1)) //MAP_FAILED)
  {
    pcl_close (fd);
    resetLockingPermissions (file_name, file_lock);
    throw pcl::IOException ("[pcl::PCDWriter::writeBinaryCompressed] Error during mmap ()!");
    return (-1);
  }
#endif

  // Copy the header
  memcpy (&map[0], oss.str ().c_str (), data_idx);
  // Copy the compressed data
  memcpy (&map[data_idx], temp_buf, data_size);

#if !_WIN32
  // If the user set the synchronization flag on, call msync
  if (map_synchronization_)
    msync (map, compressed_final_size, MS_SYNC);
#endif

  // Unmap the pages of memory
#if _WIN32
    UnmapViewOfFile (map);
#else
  if (munmap (map, (compressed_final_size)) == -1)
  {
    pcl_close (fd);
    resetLockingPermissions (file_name, file_lock);
    throw pcl::IOException ("[pcl::PCDWriter::writeBinaryCompressed] Error during munmap ()!");
    return (-1);
  }
#endif

  // Close file
#if _WIN32
  CloseHandle (h_native_file);
#else
  pcl_close (fd);
#endif
  resetLockingPermissions (file_name, file_lock);

  free (only_valid_data);
  free (temp_buf);
  return (0);
}
Ejemplo n.º 5
0
int main (int argc, char *argv[])
{
  if (argc != 5) {
    fputs("Usage: lab1 [enc|dec] <input file> <output file> <key>", stderr);
    return -1;
  }

  enum mode mod;
  if (strncmp(argv[1], "enc", 3) == 0) {
    mod = ENC;
  } else if (strncmp(argv[1], "dec", 3) == 0) {
    mod = DEC;
  } else {
    fprintf(stderr, "Wrong encryption mode: \"%s\".", argv[1]);
    return -1;
  }

  HANDLE inf = 0;
  HANDLE inmmf = 0;
  PBYTE indata = NULL;
  HANDLE outf = 0;
  HANDLE outmmf = 0;
  PBYTE outdata = NULL;
  LARGE_INTEGER insz = {.QuadPart = 0};
  LARGE_INTEGER outsz = {.QuadPart = 0};
  unsigned char err = 1;


  inf = CreateFileA(argv[2], GENERIC_READ, 0, NULL, OPEN_EXISTING,
                    FILE_ATTRIBUTE_NORMAL, NULL);
  //printf("%0.16lx || %lu %s\n", inf, GetLastError(), argv[2]);
  inmmf = CreateFileMappingA(inf, NULL, PAGE_READONLY, 0, 0, NULL);
  if (inmmf == NULL) {
    fprintf(stderr, "Can't open memory mapped file. Error code: %lu\n",
            GetLastError());
    goto err;
  }
  indata = (PBYTE)MapViewOfFile(inmmf, FILE_MAP_READ, 0, 0, 0);
  if (indata == NULL) {
    fprintf(stderr, "Can't map view of file. Error code: %lu\n", GetLastError());
    goto err;
  }

  GetFileSizeEx(inf, &insz);
  outsz.QuadPart = (insz.QuadPart / 8 + 2) * 8;

  outf = CreateFileA(argv[3], GENERIC_READ | GENERIC_WRITE, 0, NULL,
                     CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
  outmmf = CreateFileMappingA(outf, NULL, PAGE_READWRITE,
                              outsz.HighPart, outsz.LowPart, NULL);
  if (outmmf == NULL) {
    fprintf(stderr, "Can't open memory mapped file. Error code: %lu\n",
            GetLastError());
    goto err;
  }

  outdata = (PBYTE)MapViewOfFile(outmmf, FILE_MAP_WRITE, 0, 0, 0);
  if (outdata == NULL) {
    fprintf(stderr, "Can't map view of file. Error code: %lu\n", GetLastError());
    goto err;
  }

  // Crypto stuff
  BOOL res;
  HCRYPTPROV prov;

  if (!CryptAcquireContext(&prov, 0, MS_ENHANCED_PROV, PROV_RSA_FULL,
                           CRYPT_VERIFYCONTEXT)) {
    fputs("Cannot acquire crypt context.", stderr);
    goto err;
  }

  HCRYPTKEY key = generateKey(prov, CALG_3DES, argv[4]);
  crash_if(key == 0, "Cannot make a key.");

  for (LARGE_INTEGER i = {.QuadPart = 0}; i.QuadPart < insz.QuadPart;
       (i.QuadPart) += buf_size) {

    unsigned char buf[buf_size + block_size];
    DWORD len = buf_size;
    void *inp = indata + i.QuadPart,
         *outp = outdata + i.QuadPart;
    BOOL final = insz.QuadPart - i.QuadPart <= buf_size;

    if (final) {
      len = insz.QuadPart - i.QuadPart;
    }

    memcpy(buf, inp, len);
    if (mod == ENC) {
      res = CryptEncrypt(key, 0, final, 0, buf, &len, buf_size + block_size);
    } else {
      res = CryptDecrypt(key, 0, final, 0, buf, &len);
    }

    if (res) {
      memcpy(outp, buf, len);
      if (final) {
        outsz.QuadPart = i.QuadPart + len;
      }
    } else {
      fprintf(stderr, "Can't crypt the block 0x%lx. Error code: %lu\n",
              i.QuadPart, GetLastError());
      goto err;
    }
  }

  CryptDestroyKey(key);
  CryptReleaseContext(prov,0);

  err = 0;

err:
  // Freeing resources.
  apply_not_null(indata, UnmapViewOfFile);
  apply_not_null(inmmf, CloseHandle);
  apply_not_null(inf, CloseHandle);

  apply_not_null(outdata, UnmapViewOfFile);
  apply_not_null(outmmf, CloseHandle);

  if (outf) {
    SetFilePointer(outf, outsz.LowPart, &(outsz.HighPart), FILE_BEGIN);
    SetEndOfFile(outf);
  }

  apply_not_null(outf, CloseHandle);

  if (err)
    return -1;
  else
    return 0;
}
Ejemplo n.º 6
0
/*-----------------------------------------------------------------------------
*  Schnittstelle öffnen
*/
int SioOpen(const char *pPortName,
            TSioBaud baud,
            TSioDataBits dataBits,
            TSioParity parity,
            TSioStopBits stopBits,
            TSioMode mode
            ) {
   HANDLE       hCom;
   DCB          dcb;
   bool         fSuccess;
   COMMTIMEOUTS timeouts;
   int          i;

   // freien descriptor suchen
   for (i = 0; (i < MAX_NUM_SIO) && (sSio[i].used == true); i++);

   if (i == MAX_NUM_SIO) {
      // kein Platz
      printf("no handle for %s\r\n", pPortName);
      return -1;
   }

   hCom = CreateFileA(pPortName, GENERIC_WRITE | GENERIC_READ,
                          0, NULL, OPEN_EXISTING, 0, NULL );

   if (hCom == INVALID_HANDLE_VALUE) {
      return -1;
   }

   sSio[i].used = true;
   sSio[i].hCom = hCom;
   sSio[i].unRead.bufIdxWr = 0;
   sSio[i].unRead.bufIdxRd = 0;

   fSuccess = GetCommState(hCom, &dcb);
   if (!fSuccess) {
      printf("GetCommState failed\r\n");
      return -1;
   }

   switch (baud) {
      case eSioBaud9600:
         dcb.BaudRate = 9600;
         break;
      default:
         dcb.BaudRate = 9600;
         break;
   }

   switch (dataBits) {
      case eSioDataBits8:
         dcb.ByteSize = DATABITS_8;
         break;
      default:
         dcb.ByteSize = DATABITS_8;
         break;
   }

   switch (parity) {
      case eSioParityNo:
         dcb.Parity = NOPARITY;
         break;
      case eSioParityEven:
         dcb.Parity = EVENPARITY;
         break;
      default:
         dcb.Parity = NOPARITY;
         break;
   }

   switch (stopBits) {
      case eSioStopBits1:
         dcb.StopBits = ONESTOPBIT;
         break;
      default:
         dcb.StopBits = ONESTOPBIT;
         break;
   }

   fSuccess = SetCommState(hCom, &dcb);
   if (!fSuccess) {
      printf("SetCommState failed\r\n");
      return -1;
   }


  fSuccess = GetCommTimeouts(hCom, &timeouts);


  /* Set timeout to 0 to force that:
     If a character is in the buffer, the character is read,
     If no character is in the buffer, the function do not wait and returns immediatly
  */
   timeouts.ReadIntervalTimeout = MAXDWORD;
   timeouts.ReadTotalTimeoutMultiplier = 0;
   timeouts.ReadTotalTimeoutConstant = 0;

   fSuccess = SetCommTimeouts(hCom, &timeouts);

//   SetCommMask(hCom, EV_RXCHAR);

   return i;
}
Ejemplo n.º 7
0
int RS232_OpenComport(int comport_number, int baudrate)
{
  if((comport_number>15)||(comport_number<0))
  {
    printf("illegal comport number\n");
    return(1);
  }

  switch(baudrate)
  {
    case     110 : strcpy(baudr, "baud=110 data=8 parity=N stop=1 dtr=on rts=on");
                   break;
    case     300 : strcpy(baudr, "baud=300 data=8 parity=N stop=1 dtr=on rts=on");
                   break;
    case     600 : strcpy(baudr, "baud=600 data=8 parity=N stop=1 dtr=on rts=on");
                   break;
    case    1200 : strcpy(baudr, "baud=1200 data=8 parity=N stop=1 dtr=on rts=on");
                   break;
    case    2400 : strcpy(baudr, "baud=2400 data=8 parity=N stop=1 dtr=on rts=on");
                   break;
    case    4800 : strcpy(baudr, "baud=4800 data=8 parity=N stop=1 dtr=on rts=on");
                   break;
    case    9600 : strcpy(baudr, "baud=9600 data=8 parity=N stop=1 dtr=on rts=on");
                   break;
    case   19200 : strcpy(baudr, "baud=19200 data=8 parity=N stop=1 dtr=on rts=on");
                   break;
    case   38400 : strcpy(baudr, "baud=38400 data=8 parity=N stop=1 dtr=on rts=on");
                   break;
    case   57600 : strcpy(baudr, "baud=57600 data=8 parity=N stop=1 dtr=on rts=on");
                   break;
    case  115200 : strcpy(baudr, "baud=115200 data=8 parity=N stop=1 dtr=on rts=on");
                   break;
    case  128000 : strcpy(baudr, "baud=128000 data=8 parity=N stop=1 dtr=on rts=on");
                   break;
    case  256000 : strcpy(baudr, "baud=256000 data=8 parity=N stop=1 dtr=on rts=on");
                   break;
    case  500000 : strcpy(baudr, "baud=500000 data=8 parity=N stop=1 dtr=on rts=on");
                   break;
    case 1000000 : strcpy(baudr, "baud=1000000 data=8 parity=N stop=1 dtr=on rts=on");
                   break;
    default      : printf("invalid baudrate\n");
                   return(1);
                   break;
  }

  Cport[comport_number] = CreateFileA(comports[comport_number],
                      GENERIC_READ|GENERIC_WRITE,
                      0,                          /* no share  */
                      NULL,                       /* no security */
                      OPEN_EXISTING,
                      0,                          /* no threads */
                      NULL);                      /* no templates */

  if(Cport[comport_number]==INVALID_HANDLE_VALUE)
  {
    printf("unable to open comport\n");
    return(1);
  }

  DCB port_settings;
  memset(&port_settings, 0, sizeof(port_settings));  /* clear the new struct  */
  port_settings.DCBlength = sizeof(port_settings);

  if(!BuildCommDCBA(baudr, &port_settings))
  {
    printf("unable to set comport dcb settings\n");
    CloseHandle(Cport[comport_number]);
    return(1);
  }

  if(!SetCommState(Cport[comport_number], &port_settings))
  {
    printf("unable to set comport cfg settings\n");
    CloseHandle(Cport[comport_number]);
    return(1);
  }

  COMMTIMEOUTS Cptimeouts;

  Cptimeouts.ReadIntervalTimeout         = MAXDWORD;
  Cptimeouts.ReadTotalTimeoutMultiplier  = 0;
  Cptimeouts.ReadTotalTimeoutConstant    = 0;
  Cptimeouts.WriteTotalTimeoutMultiplier = 0;
  Cptimeouts.WriteTotalTimeoutConstant   = 0;

  if(!SetCommTimeouts(Cport[comport_number], &Cptimeouts))
  {
    printf("unable to set comport time-out settings\n");
    CloseHandle(Cport[comport_number]);
    return(1);
  }

  return(0);
}
Ejemplo n.º 8
0
/**
 * 
 *  rct2: 0x00408060
 */
HANDLE osinterface_file_open(const char* filename)
{
	return CreateFileA(filename, GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_FLAG_RANDOM_ACCESS | FILE_ATTRIBUTE_NORMAL, 0);
}
Ejemplo n.º 9
0
/**
 * 
 *  rct2: 0x0040807D
 */
HANDLE osinterface_file_create(const char* filename)
{
	return CreateFileA(filename, GENERIC_WRITE, FILE_SHARE_READ, 0, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
}
Ejemplo n.º 10
0
int RS232_OpenComport(int comport_number, int baudrate, const char *mode)
{
  if((comport_number>15)||(comport_number<0))
  {
    printf("illegal comport number\n");
    return(1);
  }

  switch(baudrate)
  {
    case     110 : strcpy(mode_str, "baud=110");
                   break;
    case     300 : strcpy(mode_str, "baud=300");
                   break;
    case     600 : strcpy(mode_str, "baud=600");
                   break;
    case    1200 : strcpy(mode_str, "baud=1200");
                   break;
    case    2400 : strcpy(mode_str, "baud=2400");
                   break;
    case    4800 : strcpy(mode_str, "baud=4800");
                   break;
    case    9600 : strcpy(mode_str, "baud=9600");
                   break;
    case   19200 : strcpy(mode_str, "baud=19200");
                   break;
    case   38400 : strcpy(mode_str, "baud=38400");
                   break;
    case   57600 : strcpy(mode_str, "baud=57600");
                   break;
    case  115200 : strcpy(mode_str, "baud=115200");
                   break;
    case  128000 : strcpy(mode_str, "baud=128000");
                   break;
    case  256000 : strcpy(mode_str, "baud=256000");
                   break;
    case  500000 : strcpy(mode_str, "baud=500000");
                   break;
    case 1000000 : strcpy(mode_str, "baud=1000000");
                   break;
    default      : printf("invalid baudrate\n");
                   return(1);
                   break;
  }

  if(strlen(mode) != 3)
  {
    printf("invalid mode \"%s\"\n", mode);
    return(1);
  }

  switch(mode[0])
  {
    case '8': strcat(mode_str, " data=8");
              break;
    case '7': strcat(mode_str, " data=7");
              break;
    case '6': strcat(mode_str, " data=6");
              break;
    case '5': strcat(mode_str, " data=5");
              break;
    default : printf("invalid number of data-bits '%c'\n", mode[0]);
              return(1);
              break;
  }

  switch(mode[1])
  {
    case 'N':
    case 'n': strcat(mode_str, " parity=n");
              break;
    case 'E':
    case 'e': strcat(mode_str, " parity=e");
              break;
    case 'O':
    case 'o': strcat(mode_str, " parity=o");
              break;
    default : printf("invalid parity '%c'\n", mode[1]);
              return(1);
              break;
  }

  switch(mode[2])
  {
    case '1': strcat(mode_str, " stop=1");
              break;
    case '2': strcat(mode_str, " stop=2");
              break;
    default : printf("invalid number of stop bits '%c'\n", mode[2]);
              return(1);
              break;
  }

  strcat(mode_str, " dtr=on rts=on");

/*
http://msdn.microsoft.com/en-us/library/windows/desktop/aa363145%28v=vs.85%29.aspx

http://technet.microsoft.com/en-us/library/cc732236.aspx
*/

  Cport[comport_number] = CreateFileA(comports[comport_number],
                      GENERIC_READ|GENERIC_WRITE,
                      0,                          /* no share  */
                      NULL,                       /* no security */
                      OPEN_EXISTING,
                      0,                          /* no threads */
                      NULL);                      /* no templates */

  if(Cport[comport_number]==INVALID_HANDLE_VALUE)
  {
    printf("unable to open comport\n");
    return(1);
  }

  DCB port_settings;
  memset(&port_settings, 0, sizeof(port_settings));  /* clear the new struct  */
  port_settings.DCBlength = sizeof(port_settings);

  if(!BuildCommDCBA(mode_str, &port_settings))
  {
    printf("unable to set comport dcb settings\n");
    CloseHandle(Cport[comport_number]);
    return(1);
  }

  if(!SetCommState(Cport[comport_number], &port_settings))
  {
    printf("unable to set comport cfg settings\n");
    CloseHandle(Cport[comport_number]);
    return(1);
  }

  COMMTIMEOUTS Cptimeouts;

  Cptimeouts.ReadIntervalTimeout         = MAXDWORD;
  Cptimeouts.ReadTotalTimeoutMultiplier  = 0;
  Cptimeouts.ReadTotalTimeoutConstant    = 0;
  Cptimeouts.WriteTotalTimeoutMultiplier = 0;
  Cptimeouts.WriteTotalTimeoutConstant   = 0;

  if(!SetCommTimeouts(Cport[comport_number], &Cptimeouts))
  {
    printf("unable to set comport time-out settings\n");
    CloseHandle(Cport[comport_number]);
    return(1);
  }

  return(0);
}
Ejemplo n.º 11
0
int __cdecl main(int argc, char *argv[])

{



    BOOL testPass = TRUE;

    BOOL bRc = TRUE;

    HANDLE hFile; 



    const char* sBadFilePath = "bad/badPath.tmp";

    const char* sBadFileName = "badName.tmp";

    const char* sDest = "dest.tmp";

    const WCHAR wBadFilePath[] = 

        {'w','b','a','d','/','b','a',

        'd','.','t','m','p','\0'};

    const WCHAR wBadFileName[] = 

        {'w','B','a','d','.','t','m','p','\0'};

    const WCHAR wDest[] = 

        {'w','d','e','s','t','.','t','m','p','\0'};





    if (0 != PAL_Initialize(argc,argv))

    {

        return FAIL;

    }



    /*...................Test CopyFileW.............................*/



    /* test with an invalid path */

    bRc = CopyFileW(wBadFilePath,wDest,TRUE);

    if(!bRc)

    {

        if(GetLastError()!= ERROR_PATH_NOT_FOUND)

        {

            Trace("CopyFileW: calling GetLastError() after copying a file"

                " with wrong path returned [%u] while it should return [%u]\n"

                ,GetLastError(), ERROR_PATH_NOT_FOUND);

            testPass = FALSE;

        }

    }

    else

    {

        testPass = FALSE; 

    }



    /* test with invalid file name */

    bRc = CopyFileW(wBadFileName,wDest,TRUE);

    if(!bRc)

    { 

        if(GetLastError()!= ERROR_FILE_NOT_FOUND)

        {

            Trace("CopyFileW: calling GetLastError() after copying a file"

                " with wrong name returned [%u] while it should return [%u]\n"

                ,GetLastError(), ERROR_FILE_NOT_FOUND);

            testPass = FALSE;

        }



    }

    else

    {

        Trace("CopyFileW: managed to copy a file with wrong name\n");     

        testPass = FALSE;

    }



  



    /*..................CopyFileA...................................*/



    /* test with an invalid path */

    bRc = CopyFileA(sBadFilePath,sDest,TRUE);

    if(! bRc)

    {

        if(GetLastError()!= ERROR_PATH_NOT_FOUND)

        {

            Trace("CopyFileA: calling GetLastError() after copying a file"

                " with wrong path returned [%u] while it should return [%u]\n"

                ,GetLastError(), ERROR_PATH_NOT_FOUND);

            testPass = FALSE;

        }

    }

    else

    {

        Trace("CopyFileA: managed to copy a file with wrong path\n");     

        testPass = FALSE;

    }



    /* test with an invalid file name */

    bRc = CopyFileA(sBadFileName,sDest,TRUE);

    if(! bRc)

    { 

        if(GetLastError()!= ERROR_FILE_NOT_FOUND)

        {

            Trace("CopyFileA: calling GetLastError() after copying a file"

                " with wrong name returned [%u] while it should return [%u]\n"

                ,GetLastError(), ERROR_FILE_NOT_FOUND);

            testPass = FALSE;

        }

    }

    else

    {

        Trace("CopyFileA: managed to copy a file with wrong name\n"); 

        testPass = FALSE;

    }



    



    /*............. Test CreateFileA..................................*/



    /* test with an invalid file name */

    hFile = CreateFileA(sBadFileName,          

        GENERIC_READ,              /* open for reading */

        FILE_SHARE_READ,           /* share for reading */

        NULL,                      /* no security */

        OPEN_EXISTING,             /* existing file only */

        FILE_ATTRIBUTE_NORMAL,     /* normal file */ 

        NULL);                     /* no attr. template */



    if (hFile == INVALID_HANDLE_VALUE) 

    { 

        if(GetLastError() != ERROR_FILE_NOT_FOUND)

        {

            Trace("CreateFileA: calling GetLastError() returned [%u] "

                "while it should return [%u] for a bad File Name\n",

                GetLastError(),ERROR_FILE_NOT_FOUND);   

            testPass = FALSE;

        }   



    } 

    else

    {

        Trace("CreateFileA: managed to create a file with an incorrect "

              "filename\n");   

        testPass = FALSE;



        if(!CloseHandle(hFile))

        {

            Trace("CreateFileA: Call to CloseHandle failed with ErrorCode "

                "[%u]\n", GetLastError());



        }

        if(!DeleteFile(sBadFileName))

        {

            Trace("CreateFileA: Call to DeleteFile failed with ErrorCode "

                "[%u]\n", GetLastError());

        }

    }



    /* test with an invalid path */

    hFile = CreateFileA(sBadFilePath,          

        GENERIC_READ,              /* open for reading */

        FILE_SHARE_READ,           /* share for reading */

        NULL,                      /* no security */

        OPEN_EXISTING,             /* existing file only */

        FILE_ATTRIBUTE_NORMAL,     /* normal file */ 

        NULL);                     /* no attr. template */



    if (hFile == INVALID_HANDLE_VALUE) 

    { 

        if(GetLastError() != ERROR_PATH_NOT_FOUND)

        {

            Trace("CreateFileA: calling GetLastError() returned [%u] "

                "while it should return [%u] for a bad file path name\n",

                GetLastError(), ERROR_PATH_NOT_FOUND);   

            testPass = FALSE;

        }   



    } 

    else

    {

        Trace("CreateFileA: managed to create a file with an incorrect "

              "filename\n");   

        testPass = FALSE;

        /*this should not happen*/

        if(!CloseHandle(hFile))

        {

            Trace("CreateFileA: Call to CloseHandle Failed with ErrorCode "

                "[%u]\n", GetLastError());



        }

        if(!DeleteFile(sBadFilePath))

        {

            Trace("CreateFileA: Call to DeleteFile Failed with ErrorCode "

                "[%u]\n", GetLastError());

        }

    }





    



    /*............. Test CreateFileW..................................*/



    /* test with an invalid file name */

    hFile = CreateFileW(wBadFileName,          

        GENERIC_READ,              /* open for reading */

        FILE_SHARE_READ,           /* share for reading */

        NULL,                      /* no security */

        OPEN_EXISTING,             /* existing file only */

        FILE_ATTRIBUTE_NORMAL,     /* normal file */ 

        NULL);                     /* no attr. template */



    if (hFile == INVALID_HANDLE_VALUE) 

    { 

        if(GetLastError() != ERROR_FILE_NOT_FOUND)

        {

            Trace("CreateFileW: calling GetLastError() returned [%u] "

                "while it should return [%u] for a bad filename\n",

                GetLastError(), ERROR_FILE_NOT_FOUND);   

            testPass = FALSE;

        }   



    } 

    else

    {

        Trace("CreateFileW: managed to create a file with an incorrect "

              "filename\n");   

        testPass = FALSE;



        if(!CloseHandle(hFile))

        {

            Trace("CreateFileW: Call to CloseHandle Failed with ErrorCode "

                "[%u]\n", GetLastError());



        }



        if(!DeleteFileW(wBadFileName))

        {

            Trace("CreateFileW: Call to DeleteFile Failed with ErrorCode "

                "[%u]\n", GetLastError());

        }

    }







    /* test with an invalid path */

    hFile = CreateFileW(wBadFilePath,          

        GENERIC_READ,              /* open for reading */

        FILE_SHARE_READ,           /* share for reading */

        NULL,                      /* no security */

        OPEN_EXISTING,             /* existing file only */

        FILE_ATTRIBUTE_NORMAL,     /* normal file */ 

        NULL);                     /* no attr. template */



    if (hFile == INVALID_HANDLE_VALUE) 

    { 



        if(GetLastError() != ERROR_PATH_NOT_FOUND)

        {

            Trace("CreateFileW: calling GetLastError() returned [%u] "

                "while it should return [%u] for a bad file path \n",

                GetLastError(), ERROR_FILE_NOT_FOUND);   

            testPass = FALSE;

        }   



    } 

    else

    {

        Trace("CreateFileW: managed to create a file with an incorrect "

              "filename\n");   

        testPass = FALSE;



        if(!CloseHandle(hFile))

        {

            Trace("CreateFileW: Call to CloseHandle Failed with ErrorCode "

                "[%u]\n", GetLastError());



        }

        if(!DeleteFileW(wBadFilePath))

        {

            Trace("CreateFileW: Call to DeleteFile Failed with ErrorCode "

                "[%u]\n", GetLastError());

        }

    }





    

    /* .............  DeleteFileW..................................*/



    /* test with an invalid path */

    if(DeleteFileW(wBadFilePath))

    {

        Trace("DeleteFileW: Call to DeleteFileW to delete a file"

            " that does not exist succeeded\n");

        testPass = FALSE;



    }

    else

    {

        if(GetLastError() != ERROR_PATH_NOT_FOUND)

        {

            Trace("DeleteFileW: Call GetLastError()returned "

                "[%u] while it should return ERROR_PATH_NOT_FOUND [%u]\n",

                GetLastError(),ERROR_FILE_NOT_FOUND);

            testPass = FALSE;



        }



    }



    /* test with an invalid file name */

    if(DeleteFileW(wBadFileName))

    {

        Trace("DeleteFileW: Call to DeleteFileW to delete a file"

            " that does not exist succeeded\n");

        testPass = FALSE;



    }

    else

    {

        if(GetLastError() != ERROR_FILE_NOT_FOUND)

        {

            Trace("DeleteFileW: Call GetLastError()returned [%u]"

                " while it should return ERROR_FILE_NOT_FOUND [%u]\n",

                GetLastError(),ERROR_FILE_NOT_FOUND);

            testPass = FALSE;



        }



    }





    /* .............  DeleteFileA..................................*/



    /* test with an invalid path */

    if(DeleteFileA(sBadFilePath))

    {

        Trace("DeleteFileA: Call to DeleteFileA to delete a file"

            " that does not exist succeeded\n");

        testPass = FALSE;



    }

    else

    {

        if(GetLastError() != ERROR_PATH_NOT_FOUND)

        {

            Trace("DeleteFileA: Call GetLastError() returned [%u]"

                " while it should return ERROR_PATH_NOT_FOUND [%u]\n",

                GetLastError(),ERROR_FILE_NOT_FOUND);

            testPass = FALSE;



        }



    }



    /* test with an invalid file name */

    if(DeleteFileA(sBadFileName))

    {

        Trace("DeleteFileA: Call to DeleteFileA to delete a file"

            " that does not exist succeeded\n");

        testPass = FALSE;



    }

    else

    {

        if(GetLastError() != ERROR_FILE_NOT_FOUND)

        {

            Trace("DeleteFileA: Call GetLastError() returned [%u]"

                " while it should return ERROR_FILE_NOT_FOUND [%u]\n",

                GetLastError(),ERROR_FILE_NOT_FOUND);

            testPass = FALSE;



        }



    }



  



    if(! testPass)

    {

        Fail("");

    }

    PAL_Terminate();

    return PASS;

}
Ejemplo n.º 12
0
/*** IDirectXFile methods ***/
static HRESULT WINAPI IDirectXFileImpl_CreateEnumObject(IDirectXFile* iface, LPVOID pvSource, DXFILELOADOPTIONS dwLoadOptions, LPDIRECTXFILEENUMOBJECT* ppEnumObj)
{
  IDirectXFileImpl *This = impl_from_IDirectXFile(iface);
  IDirectXFileEnumObjectImpl* object;
  HRESULT hr;
  LPBYTE file_buffer;
  DWORD file_size;
  DWORD bytes_written;

  TRACE("(%p/%p)->(%p,%x,%p)\n", This, iface, pvSource, dwLoadOptions, ppEnumObj);

  if (!ppEnumObj)
    return DXFILEERR_BADVALUE;

  /* Only lowest 4 bits are relevant in DXFILELOADOPTIONS */
  dwLoadOptions &= 0xF;

  hr = IDirectXFileEnumObjectImpl_Create(&object);
  if (FAILED(hr))
    return hr;

  if (dwLoadOptions == DXFILELOAD_FROMFILE)
  {
    HANDLE hFile, file_mapping;

    TRACE("Open source file '%s'\n", (char*)pvSource);

    hFile = CreateFileA(pvSource, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
    if (hFile == INVALID_HANDLE_VALUE)
    {
      TRACE("File '%s' not found\n", (char*)pvSource);
      return DXFILEERR_FILENOTFOUND;
    }

    file_size = GetFileSize(hFile, NULL);

    file_mapping = CreateFileMappingA(hFile, NULL, PAGE_READONLY, 0, 0, NULL);
    CloseHandle(hFile);
    if (!file_mapping)
    {
      hr = DXFILEERR_BADFILETYPE;
      goto error;
    }

    object->mapped_memory = MapViewOfFile(file_mapping, FILE_MAP_READ, 0, 0, 0);
    CloseHandle(file_mapping);
    if (!object->mapped_memory)
    {
      hr = DXFILEERR_BADFILETYPE;
      goto error;
    }
    file_buffer = object->mapped_memory;
  }
  else if (dwLoadOptions == DXFILELOAD_FROMRESOURCE)
  {
    HRSRC resource_info;
    HGLOBAL resource_data;
    LPDXFILELOADRESOURCE lpdxflr = pvSource;

    TRACE("Source in resource (module = %p, name = %s, type = %s)\n", lpdxflr->hModule, debugstr_a(lpdxflr->lpName), debugstr_a(lpdxflr->lpType));

    resource_info = FindResourceA(lpdxflr->hModule, lpdxflr->lpName, lpdxflr->lpType);
    if (!resource_info)
    {
      hr = DXFILEERR_RESOURCENOTFOUND;
      goto error;
    }

    file_size = SizeofResource(lpdxflr->hModule, resource_info);

    resource_data = LoadResource(lpdxflr->hModule, resource_info);
    if (!resource_data)
    {
      hr = DXFILEERR_BADRESOURCE;
      goto error;
    }

    file_buffer = LockResource(resource_data);
    if (!file_buffer)
    {
      hr = DXFILEERR_BADRESOURCE;
      goto error;
    }
  }
  else if (dwLoadOptions == DXFILELOAD_FROMMEMORY)
  {
    LPDXFILELOADMEMORY lpdxflm = pvSource;

    TRACE("Source in memory at %p with size %d\n", lpdxflm->lpMemory, lpdxflm->dSize);

    file_buffer = lpdxflm->lpMemory;
    file_size = lpdxflm->dSize;
  }
  else
  {
    FIXME("Source type %d is not handled yet\n", dwLoadOptions);
    hr = DXFILEERR_NOTDONEYET;
    goto error;
  }

  TRACE("File size is %d bytes\n", file_size);

  if (TRACE_ON(d3dxof_dump))
  {
    static USHORT num;
    char tmp[12];
    HANDLE file;
    sprintf(tmp, "file%05u.x", num++);

    file = CreateFileA(tmp, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, 0, NULL);
    if (file != INVALID_HANDLE_VALUE)
    {
      WriteFile(file, file_buffer, file_size, &bytes_written, NULL);
      CloseHandle(file);
    }
  }

  object->pDirectXFile = This;

  object->buf.pdxf = This;
  object->buf.token_present = FALSE;
  object->buf.buffer = file_buffer;
  object->buf.rem_bytes = file_size;
  hr = parse_header(&object->buf, &object->decomp_buffer);
  if (FAILED(hr))
    goto error;

  /* Check if there are templates defined before the object */
  if (!parse_templates(&object->buf, TRUE))
  {
    hr = DXFILEERR_PARSEERROR;
    goto error;
  }

  if (TRACE_ON(d3dxof))
  {
    ULONG i;
    TRACE("Registered templates (%d):\n", This->nb_xtemplates);
    for (i = 1; i < This->nb_xtemplates; i++)
      DPRINTF("%s - %s\n", This->xtemplates[i].name, debugstr_guid(&This->xtemplates[i].class_id));
  }

  *ppEnumObj = &object->IDirectXFileEnumObject_iface;

  return DXFILE_OK;

error:
  IDirectXFileEnumObject_Release(&object->IDirectXFileEnumObject_iface);
  *ppEnumObj = NULL;

  return hr;
}
Ejemplo n.º 13
0
// TODO: allow commandline options (v2)
// TODO: remove existing infs for similar devices (v2)
int __cdecl main(int argc_ansi, char** argv_ansi)
{
	DWORD r;
	BOOL b;
	int i, ret, argc = argc_ansi, si=0;
	char** argv = argv_ansi;
	wchar_t **wenv, **wargv;
	char* hardware_id = NULL;
	char* device_id = NULL;
	char* user_sid = NULL;
	char* inf_name = NULL;
	char path[MAX_PATH_LENGTH];
	char destname[MAX_PATH_LENGTH];
	uintptr_t syslog_reader_thid = -1L;

	// Connect to the messaging pipe
	pipe_handle = CreateFileA(INSTALLER_PIPE_NAME, GENERIC_READ|GENERIC_WRITE, 0, NULL, OPEN_EXISTING,
		FILE_ATTRIBUTE_NORMAL|FILE_FLAG_OVERLAPPED, NULL);
	if (pipe_handle == INVALID_HANDLE_VALUE) {
		// If we can't connect to the pipe, someone is probably trying to run us standalone
		printf("This application can not be run from the command line.\n");
		printf("Please use your initial installer application if you want to install the driver.\n");
		return WDI_ERROR_NOT_SUPPORTED;
	}

	if (init_dlls()) {
		plog("could not init DLLs");
		ret = WDI_ERROR_RESOURCE;
		goto out;
	}

	// Initialize COM for Restore Point disabling
	IGNORE_RETVAL(CoInitializeEx(NULL, COINIT_APARTMENTTHREADED));

	// libwdi provides the arguments as UTF-16 => read them and convert to UTF-8
	if (__wgetmainargs != NULL) {
		__wgetmainargs(&argc, &wargv, &wenv, 1, &si);
		argv = calloc(argc, sizeof(char*));
		for (i=0; i<argc; i++) {
			argv[i] = wchar_to_utf8(wargv[i]);
		}
	} else {
		plog("unable to access UTF-16 args - trying ANSI");
	}

	if (argc < 2) {
		printf("usage: %s <inf_name>\n", argv[0]);
		plog("missing inf_name parameter");
	}

	inf_name = argv[1];
	plog("got parameter %s", argv[1]);
	r = GetFullPathNameU(".", MAX_PATH_LENGTH, path, NULL);
	if ((r == 0) || (r > MAX_PATH_LENGTH)) {
		plog("could not retrieve absolute path of working directory");
		ret = WDI_ERROR_ACCESS;
		goto out;
	}
	safe_strcat(path, MAX_PATH_LENGTH, "\\");
	safe_strcat(path, MAX_PATH_LENGTH, inf_name);

	device_id = req_id(IC_GET_DEVICE_ID);
	hardware_id = req_id(IC_GET_HARDWARE_ID);
	// Will be used if we ever need to create a file, as the original user, from this app
	user_sid = req_id(IC_GET_USER_SID);
	ConvertStringSidToSidA(user_sid, &user_psid);

	// Setup the syslog reader thread
	syslog_ready_event = CreateEvent(NULL, TRUE, FALSE, NULL);
	syslog_terminate_event = CreateEvent(NULL, TRUE, FALSE, NULL);
	syslog_reader_thid = _beginthread(syslog_reader_thread, 0, 0);
	if ( (syslog_reader_thid == -1L)
	  || (WaitForSingleObject(syslog_ready_event, 2000) != WAIT_OBJECT_0) )	{
		plog("Unable to create syslog reader thread");
		SetEvent(syslog_terminate_event);
		// NB: if you try to close the syslog reader thread handle, you get a
		// "more recent driver was found" error from UpdateForPnP. Weird...
	}

	// Disable the creation of a restore point
	disable_system_restore(TRUE);

	// Find if the device is plugged in
	send_status(IC_SET_TIMEOUT_INFINITE);
	if (hardware_id != NULL) {
		plog("Installing driver for %s - please wait...", hardware_id);
		b = UpdateDriverForPlugAndPlayDevicesU(NULL, hardware_id, path, INSTALLFLAG_FORCE, NULL);
		send_status(IC_SET_TIMEOUT_DEFAULT);
		if (b == TRUE) {
			// Success
			plog("driver update completed");
			enumerate_device(device_id);
			ret = WDI_SUCCESS;
			goto out;
		}

		ret = process_error(GetLastError(), path);
		if (ret != WDI_SUCCESS) {
			goto out;
		}
	}

	// TODO: try URL for OEMSourceMediaLocation (v2)
	plog("Copying inf file (for the next time device is plugged) - please wait...");
	send_status(IC_SET_TIMEOUT_INFINITE);
	b = SetupCopyOEMInfU(path, NULL, SPOST_PATH, 0, destname, MAX_PATH_LENGTH, NULL, NULL);
	send_status(IC_SET_TIMEOUT_DEFAULT);
	if (b) {
		plog("copied inf to %s", destname);
		ret = WDI_SUCCESS;
		enumerate_device(device_id);
		goto out;
	}

	ret = process_error(GetLastError(), path);
	if (ret != WDI_SUCCESS) {
		goto out;
	}

	// If needed, flag removed devices for reinstallation. see:
	// http://msdn.microsoft.com/en-us/library/aa906206.aspx
	check_removed(hardware_id);

out:
	// Report any error status code and wait for target app to read it
	send_status(IC_INSTALLER_COMPLETED);
	pstat(ret);
	// Restore the system restore point creation original settings
	disable_system_restore(FALSE);
	// TODO: have libwi send an ACK?
	Sleep(1000);
	SetEvent(syslog_terminate_event);
	if (argv != argv_ansi) {
		for (i=0; i<argc; i++) {
			safe_free(argv[i]);
		}
		safe_free(argv);
	}
	CloseHandle(syslog_ready_event);
	CloseHandle(syslog_terminate_event);
	CloseHandle((HANDLE)syslog_reader_thid);
	CloseHandle(pipe_handle);
	return ret;
}
Ejemplo n.º 14
0
/*
 * Read from the driver installation syslog in real-time
 */
void __cdecl syslog_reader_thread(void* param)
{
#define NB_SYSLOGS 3
	char* syslog_name[NB_SYSLOGS] = { "\\inf\\setupapi.dev.log", "\\setupapi.log", "\\setupact.log" };
	HANDLE log_handle;
	DWORD last_offset, size, read_size, processed_size;
	char *buffer = NULL;
	char log_path[MAX_PATH_LENGTH];
	DWORD duration = 0;
	int i;

	// Try the various driver installation logs
	for (i=0; i<NB_SYSLOGS; i++) {
		safe_strcpy(log_path, MAX_PATH_LENGTH, getenv("WINDIR"));	// Use %WINDIR% env variable
		safe_strcat(log_path, MAX_PATH_LENGTH, syslog_name[i]);
		log_handle = CreateFileA(log_path, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_WRITE,
			NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);

		if (log_handle != INVALID_HANDLE_VALUE) {
			plog("using syslog '%s'", log_path);
			break;
		}
	}
	if (i == NB_SYSLOGS) {
		plog("Could not open any syslog");
		goto out;
	}

	// We assert that the log file is never gonna be bigger than 2 GB
	// TODO: special case of setupapi.dev.log's last offset not being the end (v2)
	last_offset = SetFilePointer(log_handle, 0, NULL, FILE_END);
	if (last_offset == INVALID_SET_FILE_POINTER) {
		plog("Could not set syslog offset");
		goto out;
	}

	plog("sylog reader thread started");
	SetEvent(syslog_ready_event);
	processed_size = 0;

	while(WaitForSingleObject(syslog_terminate_event, 0) != WAIT_OBJECT_0) {
		// Find out if file size has increased since last time
		size = GetFileSize(log_handle, NULL);
		if (size == INVALID_FILE_SIZE) {
			plog("could not read syslog file size");
			goto out;
		}
		size -= last_offset;

		if (size != 0) {
			// Read from file and add a zero terminator
			buffer = malloc(size+1);
			if (buffer == NULL) {
				plog("could not allocate buffer to read syslog");
				goto out;
			}
			// Keep an extra spare byte at the beginning
			if (!ReadFile(log_handle, buffer, size, &read_size, NULL)) {
				plog("failed to read syslog");
				goto out;
			}
			buffer[read_size] = 0;

			// Send all the complete lines through the pipe
			processed_size = process_syslog(buffer, read_size);
			safe_free(buffer);
			last_offset += processed_size;

			// Reposition at start of last line if needed
			if (processed_size != read_size) {
				last_offset = SetFilePointer(log_handle, processed_size-read_size, NULL, FILE_CURRENT);
				if (last_offset == INVALID_SET_FILE_POINTER) {
					plog("Could not set syslog offset");
					goto out;
				}
			}

			// Reset adaptive sleep duration if we did send data out
			if (processed_size !=0) {
				duration = 0;
			}
		}

		// Compute adaptive sleep duration
		if (((size == 0) || (processed_size == 0)) && (duration < 500)) {
			duration += 100;	// read log more frequently on recent update
		}
		Sleep(duration);
	}

out:
	plog("syslog reader thread terminating");
	safe_free(buffer);
	CloseHandle(log_handle);
	_endthread();
}
Ejemplo n.º 15
0
int process_start(char *name, char *part, process_info_t *p, int is_helper) {
  HANDLE file = INVALID_HANDLE_VALUE;
  HANDLE nul = INVALID_HANDLE_VALUE;
  WCHAR path[MAX_PATH], filename[MAX_PATH];
  WCHAR image[MAX_PATH + 1];
  WCHAR args[MAX_PATH * 2];
  STARTUPINFOW si;
  PROCESS_INFORMATION pi;
  DWORD result;

  if (GetTempPathW(sizeof(path) / sizeof(WCHAR), (WCHAR*)&path) == 0)
    goto error;
  if (GetTempFileNameW((WCHAR*)&path, L"uv", 0, (WCHAR*)&filename) == 0)
    goto error;

  file = CreateFileW((WCHAR*)filename,
                     GENERIC_READ | GENERIC_WRITE,
                     0,
                     NULL,
                     CREATE_ALWAYS,
                     FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_DELETE_ON_CLOSE,
                     NULL);
  if (file == INVALID_HANDLE_VALUE)
    goto error;

  if (!SetHandleInformation(file, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT))
    goto error;

  nul = CreateFileA("nul",
                    GENERIC_READ,
                    FILE_SHARE_READ | FILE_SHARE_WRITE,
                    NULL,
                    OPEN_EXISTING,
                    FILE_ATTRIBUTE_NORMAL,
                    NULL);
  if (nul == INVALID_HANDLE_VALUE)
    goto error;

  if (!SetHandleInformation(nul, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT))
    goto error;

  result = GetModuleFileNameW(NULL,
                              (WCHAR*) &image,
                              sizeof(image) / sizeof(WCHAR));
  if (result == 0 || result == sizeof(image))
    goto error;

  if (part) {
    if (_snwprintf((WCHAR*)args,
                   sizeof(args) / sizeof(WCHAR),
                   L"\"%s\" %S %S",
                   image,
                   name,
                   part) < 0) {
      goto error;
    }
  } else {
    if (_snwprintf((WCHAR*)args,
                   sizeof(args) / sizeof(WCHAR),
                   L"\"%s\" %S",
                   image,
                   name) < 0) {
      goto error;
    }
  }

  memset((void*)&si, 0, sizeof(si));
  si.cb = sizeof(si);
  si.dwFlags = STARTF_USESTDHANDLES;
  si.hStdInput = nul;
  si.hStdOutput = file;
  si.hStdError = file;

  if (!CreateProcessW(image, args, NULL, NULL, TRUE,
                      0, NULL, NULL, &si, &pi))
    goto error;

  CloseHandle(pi.hThread);

  SetHandleInformation(nul, HANDLE_FLAG_INHERIT, 0);
  SetHandleInformation(file, HANDLE_FLAG_INHERIT, 0);

  p->stdio_in = nul;
  p->stdio_out = file;
  p->process = pi.hProcess;
  p->name = part;

  return 0;

error:
  if (file != INVALID_HANDLE_VALUE)
    CloseHandle(file);
  if (nul != INVALID_HANDLE_VALUE)
    CloseHandle(nul);

  return -1;
}
Ejemplo n.º 16
0
static int Launch()
{
  Log(L"Launching browser...");

  DWORD processID;

  // The interface that allows us to activate the browser
  CComPtr<IApplicationActivationManager> activateMgr;
  if (FAILED(CoCreateInstance(CLSID_ApplicationActivationManager, nullptr,
                              CLSCTX_LOCAL_SERVER,
                              IID_IApplicationActivationManager,
                              (void**)&activateMgr))) {
    Fail(false, L"CoCreateInstance CLSID_ApplicationActivationManager failed.");
    return FAILURE;
  }
  
  HRESULT hr;
  WCHAR appModelID[256];
  // Activation is based on the browser's registered app model id
  if (!GetDefaultBrowserAppModelID(appModelID, (sizeof(appModelID)/sizeof(WCHAR)))) {
    Fail(false, L"GetDefaultBrowserAppModelID failed.");
    return FAILURE;
  }
  Log(L"App model id='%s'", appModelID);

  // Hand off focus rights if the terminal has focus to the out-of-process
  // activation server (explorer.exe). Without this the metro interface
  // won't launch.
  hr = CoAllowSetForegroundWindow(activateMgr, nullptr);
  if (FAILED(hr)) {
    // Log but don't fail. This has happened on vms with certain terminals run by
    // QA during mozmill testing.
    Log(L"Windows focus rights hand off failed (HRESULT=0x%X). Ignoring.", hr);
  }

  Log(L"Harness process id: %d", GetCurrentProcessId());

  // If provided, validate the firefox path passed in.
  int binLen = wcslen(kFirefoxExe);
  if (sFirefoxPath.GetLength() && sFirefoxPath.Right(binLen) != kFirefoxExe) {
    Log(L"firefoxpath is missing a valid bin name! Assuming '%s'.", kFirefoxExe);
    if (sFirefoxPath.Right(1) != L"\\") {
      sFirefoxPath += L"\\";
    }
    sFirefoxPath += kFirefoxExe;
  }

  // Because we can't pass command line args, we store params in a
  // tests.ini file in dist/bin which the browser picks up on launch.
  CStringA testFilePath;
  if (sFirefoxPath.GetLength()) {
    // Use the firefoxpath passed to us by the test harness
    int index = sFirefoxPath.ReverseFind('\\');
    if (index == -1) {
      Fail(false, L"Bad firefoxpath path");
      return FAILURE;
    }
    testFilePath = sFirefoxPath.Mid(0, index);
    testFilePath += "\\";
    testFilePath += kMetroTestFile;
  } else {
    // Use the module path
    char path[MAX_PATH];
    if (!GetModuleFileNameA(nullptr, path, MAX_PATH)) {
      Fail(false, L"GetModuleFileNameA errorno=%d", GetLastError());
      return FAILURE;
    }
    char* slash = strrchr(path, '\\');
    if (!slash)
      return FAILURE;
    *slash = '\0'; // no trailing slash
    testFilePath = path;
    testFilePath += "\\";
    sFirefoxPath = testFilePath;
    sFirefoxPath += kFirefoxExe;
    testFilePath += kMetroTestFile;
  }

  // Make sure the firefox bin exists
  if (GetFileAttributesW(sFirefoxPath) == INVALID_FILE_ATTRIBUTES) {
    Fail(false, L"Invalid bin path: '%s'", sFirefoxPath);
    return FAILURE;
  }

  Log(L"Using bin path: '%s'", sFirefoxPath);

  Log(L"Writing out tests.ini to: '%s'", CStringW(testFilePath));
  HANDLE hTestFile = CreateFileA(testFilePath, GENERIC_WRITE,
                                 0, nullptr, CREATE_ALWAYS,
                                 FILE_ATTRIBUTE_NORMAL,
                                 nullptr);
  if (hTestFile == INVALID_HANDLE_VALUE) {
    Fail(false, L"CreateFileA errorno=%d", GetLastError());
    return FAILURE;
  }

  DeleteTestFileHelper dtf(testFilePath);

  // nsAppRunner expects the first param to be the bin path, just like a
  // normal startup. So prepend our bin path to our param string we write.
  CStringA asciiParams = sFirefoxPath;
  asciiParams += " ";
  asciiParams += sAppParams;
  asciiParams.Trim();
  Log(L"Browser command line args: '%s'", CString(asciiParams));
  if (!WriteFile(hTestFile, asciiParams, asciiParams.GetLength(),
                 nullptr, 0)) {
    CloseHandle(hTestFile);
    Fail(false, L"WriteFile errorno=%d", GetLastError());
    return FAILURE;
  }
  FlushFileBuffers(hTestFile);
  CloseHandle(hTestFile);

  // Create a named stdout pipe for the browser
  if (!SetupTestOutputPipe()) {
    Fail(false, L"SetupTestOutputPipe failed (errno=%d)", GetLastError());
    return FAILURE;
  }

  // Launch firefox
  hr = activateMgr->ActivateApplication(appModelID, L"", AO_NOERRORUI, &processID);
  if (FAILED(hr)) {
    Fail(true, L"ActivateApplication result %X", hr);
    return RETRY;
  }

  Log(L"Activation succeeded.");

  // automation.py picks up on this, don't mess with it.
  Log(L"METRO_BROWSER_PROCESS=%d", processID);

  HANDLE child = OpenProcess(SYNCHRONIZE, FALSE, processID);
  if (!child) {
    Fail(false, L"Couldn't find child process. (%d)", GetLastError());
    return FAILURE;
  }

  Log(L"Waiting on child process...");

  MSG msg;
  DWORD waitResult = WAIT_TIMEOUT;
  HANDLE handles[2] = { child, gTestOutputPipe };
  while ((waitResult = MsgWaitForMultipleObjects(2, handles, FALSE, INFINITE, QS_ALLINPUT)) != WAIT_OBJECT_0) {
    if (waitResult == WAIT_FAILED) {
      Log(L"Wait failed (errno=%d)", GetLastError());
      break;
    } else if (waitResult == WAIT_OBJECT_0 + 1) {
      ReadPipe();
    } else if (waitResult == WAIT_OBJECT_0 + 2 &&
               PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE)) {
      TranslateMessage(&msg);
      DispatchMessage(&msg);
    }
  }

  ReadPipe();
  CloseHandle(gTestOutputPipe);
  CloseHandle(child);

  Log(L"Exiting.");
  return SUCCESS;
}
Ejemplo n.º 17
0
CPipe::CPipe(char *szName, DWORD dWait){
	int	iTemp;
	int	iFlag = 1;
	WCHAR	wbuffer[MAX_PATH+1];
	dTHX;
	
	hPipe = 0;                 
	dBufferSize = BUFFER_SIZE;
	dBytes = 0;
			              	
	char szPipeName[PIPE_NAME_SIZE + 1];				
	dwOpenMode = PIPE_ACCESS_DUPLEX;		
	dwPipeMode = 	PIPE_TYPE_BYTE	 |      
					PIPE_READMODE_BYTE	 |  
					PIPE_WAIT;				
	nMaxInstances =	PIPE_UNLIMITED_INSTANCES;
	nOutBufferSize = dBufferSize;			
	nInBufferSize  = dBufferSize;
	nDefaultTimeOut = PIPE_TIMEOUT;			
	lpSecurityAttributes= NULL; 
	iError = 0;
	strcpy((char *)szError, "");
	
	cBuffer = new char [dBufferSize];
	if (! cBuffer){
		dBufferSize = 0;
	}

	memset((void *)szError, 0, ERROR_TEXT_SIZE);
	memset((void *)szPipeName, 0, PIPE_NAME_SIZE + 1);
	if (strncmp((char *)szName, "\\\\", 2) == 0){
		iPipeType = CLIENT;
		iTemp = 0;
	}else{
		iPipeType = SERVER;
		strcpy(szPipeName, PIPE_NAME_PREFIX);
		iTemp = strlen(PIPE_NAME_PREFIX);
	}
	strncat(szPipeName, szName, PIPE_NAME_SIZE - iTemp);
	if (USING_WIDE()) {
	    A2WHELPER(szPipeName, wbuffer, sizeof(wbuffer));
	}
	if(iPipeType == SERVER){
	    if (USING_WIDE()) {
		hPipe = CreateNamedPipeW(wbuffer,
					dwOpenMode, 
					dwPipeMode, 
					nMaxInstances, 
					nOutBufferSize, 
					nInBufferSize, 
					nDefaultTimeOut,
					lpSecurityAttributes);
	    }
	    else {
		hPipe = CreateNamedPipeA(szPipeName,
					dwOpenMode, 
					dwPipeMode, 
					nMaxInstances, 
					nOutBufferSize, 
					nInBufferSize, 
					nDefaultTimeOut,
					lpSecurityAttributes);
	    }
	}else{
		while(iFlag){
		    if (USING_WIDE()) {
			hPipe = CreateFileW(wbuffer,
					    GENERIC_READ | GENERIC_WRITE, 
					    FILE_SHARE_READ	| FILE_SHARE_WRITE,
					    NULL,
					    OPEN_EXISTING,
					    FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH,
					    NULL);
		    }
		    else {
			hPipe = CreateFileA(szPipeName,
					    GENERIC_READ | GENERIC_WRITE, 
					    FILE_SHARE_READ	| FILE_SHARE_WRITE,
					    NULL,
					    OPEN_EXISTING,
					    FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH,
					    NULL);
		    }

		    if (GetLastError() == ERROR_PIPE_BUSY){
			if (USING_WIDE())
			    iFlag = WaitNamedPipeW(wbuffer, dWait);
			else
			    iFlag = WaitNamedPipeA(szPipeName, dWait);
		    }else{
			    iFlag = 0;
		    }
		}
	}
	if (cBuffer == 0){
		iError = 998;
		strcpy((char *)szError, "Could not allocate a buffer for the pipe connection");
	}
	if (hPipe == INVALID_HANDLE_VALUE){
		iError = 999;
		strcpy((char *)szError, "Could not connect");
		delete this;
	}
}									  
Ejemplo n.º 18
0
/* Sets up a serial port for RTU communications */
static int _modbus_rtu_connect(modbus_t *ctx)
{
#if defined(_WIN32)
    DCB dcb;
#else
    struct termios tios;
    speed_t speed;
    int flags;
#endif
    modbus_rtu_t *ctx_rtu = ctx->backend_data;

    if (ctx->debug) {
        printf("Opening %s at %d bauds (%c, %d, %d)\n",
               ctx_rtu->device, ctx_rtu->baud, ctx_rtu->parity,
               ctx_rtu->data_bit, ctx_rtu->stop_bit);
    }

#if defined(_WIN32)
    /* Some references here:
     * http://msdn.microsoft.com/en-us/library/aa450602.aspx
     */
    win32_ser_init(&ctx_rtu->w_ser);

    /* ctx_rtu->device should contain a string like "COMxx:" xx being a decimal
     * number */
    ctx_rtu->w_ser.fd = CreateFileA(ctx_rtu->device,
                                    GENERIC_READ | GENERIC_WRITE,
                                    0,
                                    NULL,
                                    OPEN_EXISTING,
                                    0,
                                    NULL);

    /* Error checking */
    if (ctx_rtu->w_ser.fd == INVALID_HANDLE_VALUE) {
        if (ctx->debug) {
            fprintf(stderr, "ERROR Can't open the device %s (LastError %d)\n",
                    ctx_rtu->device, (int)GetLastError());
        }
        return -1;
    }

    /* Save params */
    ctx_rtu->old_dcb.DCBlength = sizeof(DCB);
    if (!GetCommState(ctx_rtu->w_ser.fd, &ctx_rtu->old_dcb)) {
        if (ctx->debug) {
            fprintf(stderr, "ERROR Error getting configuration (LastError %d)\n",
                    (int)GetLastError());
        }
        CloseHandle(ctx_rtu->w_ser.fd);
        ctx_rtu->w_ser.fd = INVALID_HANDLE_VALUE;
        return -1;
    }

    /* Build new configuration (starting from current settings) */
    dcb = ctx_rtu->old_dcb;

    /* Speed setting */
    switch (ctx_rtu->baud) {
    case 110:
        dcb.BaudRate = CBR_110;
        break;
    case 300:
        dcb.BaudRate = CBR_300;
        break;
    case 600:
        dcb.BaudRate = CBR_600;
        break;
    case 1200:
        dcb.BaudRate = CBR_1200;
        break;
    case 2400:
        dcb.BaudRate = CBR_2400;
        break;
    case 4800:
        dcb.BaudRate = CBR_4800;
        break;
    case 9600:
        dcb.BaudRate = CBR_9600;
        break;
    case 14400:
        dcb.BaudRate = CBR_14400;
        break;
    case 19200:
        dcb.BaudRate = CBR_19200;
        break;
    case 38400:
        dcb.BaudRate = CBR_38400;
        break;
    case 57600:
        dcb.BaudRate = CBR_57600;
        break;
    case 115200:
        dcb.BaudRate = CBR_115200;
        break;
    case 230400:
        /* CBR_230400 - not defined */
        dcb.BaudRate = 230400;
        break;
    case 250000:
        dcb.BaudRate = 250000;
        break;
    case 460800:
        dcb.BaudRate = 460800;
        break;
    case 500000:
        dcb.BaudRate = 500000;
        break;
    case 921600:
        dcb.BaudRate = 921600;
        break;
    case 1000000:
        dcb.BaudRate = 1000000;
        break;
    default:
        dcb.BaudRate = CBR_9600;
        if (ctx->debug) {
            fprintf(stderr, "WARNING Unknown baud rate %d for %s (B9600 used)\n",
                    ctx_rtu->baud, ctx_rtu->device);
        }
    }

    /* Data bits */
    switch (ctx_rtu->data_bit) {
    case 5:
        dcb.ByteSize = 5;
        break;
    case 6:
        dcb.ByteSize = 6;
        break;
    case 7:
        dcb.ByteSize = 7;
        break;
    case 8:
    default:
        dcb.ByteSize = 8;
        break;
    }

    /* Stop bits */
    if (ctx_rtu->stop_bit == 1)
        dcb.StopBits = ONESTOPBIT;
    else /* 2 */
        dcb.StopBits = TWOSTOPBITS;

    /* Parity */
    if (ctx_rtu->parity == 'N') {
        dcb.Parity = NOPARITY;
        dcb.fParity = FALSE;
    } else if (ctx_rtu->parity == 'E') {
        dcb.Parity = EVENPARITY;
        dcb.fParity = TRUE;
    } else {
        /* odd */
        dcb.Parity = ODDPARITY;
        dcb.fParity = TRUE;
    }

    /* Hardware handshaking left as default settings retrieved */

    /* No software handshaking */
    dcb.fTXContinueOnXoff = TRUE;
    dcb.fOutX = FALSE;
    dcb.fInX = FALSE;

    /* Binary mode (it's the only supported on Windows anyway) */
    dcb.fBinary = TRUE;

    /* Don't want errors to be blocking */
    dcb.fAbortOnError = FALSE;

	//***Not part of libmodbus - added for QModMaster***//
    dcb.fRtsControl = ctx_rtu->rts;
	
    /* Setup port */
    if (!SetCommState(ctx_rtu->w_ser.fd, &dcb)) {
        if (ctx->debug) {
            fprintf(stderr, "ERROR Error setting new configuration (LastError %d)\n",
                    (int)GetLastError());
        }
        CloseHandle(ctx_rtu->w_ser.fd);
        ctx_rtu->w_ser.fd = INVALID_HANDLE_VALUE;
        return -1;
    }
#else
    /* The O_NOCTTY flag tells UNIX that this program doesn't want
       to be the "controlling terminal" for that port. If you
       don't specify this then any input (such as keyboard abort
       signals and so forth) will affect your process

       Timeouts are ignored in canonical input mode or when the
       NDELAY option is set on the file via open or fcntl */
    flags = O_RDWR | O_NOCTTY | O_NDELAY | O_EXCL;
#ifdef O_CLOEXEC
    flags |= O_CLOEXEC;
#endif

    ctx->s = open(ctx_rtu->device, flags);
    if (ctx->s == -1) {
        if (ctx->debug) {
            fprintf(stderr, "ERROR Can't open the device %s (%s)\n",
                    ctx_rtu->device, strerror(errno));
        }
        return -1;
    }

    /* Save */
    tcgetattr(ctx->s, &ctx_rtu->old_tios);

    memset(&tios, 0, sizeof(struct termios));

    /* C_ISPEED     Input baud (new interface)
       C_OSPEED     Output baud (new interface)
    */
    switch (ctx_rtu->baud) {
    case 110:
        speed = B110;
        break;
    case 300:
        speed = B300;
        break;
    case 600:
        speed = B600;
        break;
    case 1200:
        speed = B1200;
        break;
    case 2400:
        speed = B2400;
        break;
    case 4800:
        speed = B4800;
        break;
    case 9600:
        speed = B9600;
        break;
    case 19200:
        speed = B19200;
        break;
    case 38400:
        speed = B38400;
        break;
#ifdef B57600
    case 57600:
        speed = B57600;
        break;
#endif
#ifdef B115200
    case 115200:
        speed = B115200;
        break;
#endif
#ifdef B230400
    case 230400:
        speed = B230400;
        break;
#endif
#ifdef B460800
    case 460800:
        speed = B460800;
        break;
#endif
#ifdef B500000
    case 500000:
        speed = B500000;
        break;
#endif
#ifdef B576000
    case 576000:
        speed = B576000;
        break;
#endif
#ifdef B921600
    case 921600:
        speed = B921600;
        break;
#endif
#ifdef B1000000
    case 1000000:
        speed = B1000000;
        break;
#endif
#ifdef B1152000
   case 1152000:
        speed = B1152000;
        break;
#endif
#ifdef B1500000
    case 1500000:
        speed = B1500000;
        break;
#endif
#ifdef B2500000
    case 2500000:
        speed = B2500000;
        break;
#endif
#ifdef B3000000
    case 3000000:
        speed = B3000000;
        break;
#endif
#ifdef B3500000
    case 3500000:
        speed = B3500000;
        break;
#endif
#ifdef B4000000
    case 4000000:
        speed = B4000000;
        break;
#endif
    default:
        speed = B9600;
        if (ctx->debug) {
            fprintf(stderr,
                    "WARNING Unknown baud rate %d for %s (B9600 used)\n",
                    ctx_rtu->baud, ctx_rtu->device);
        }
    }

    /* Set the baud rate */
    if ((cfsetispeed(&tios, speed) < 0) ||
        (cfsetospeed(&tios, speed) < 0)) {
        close(ctx->s);
        ctx->s = -1;
        return -1;
    }

    /* C_CFLAG      Control options
       CLOCAL       Local line - do not change "owner" of port
       CREAD        Enable receiver
    */
    tios.c_cflag |= (CREAD | CLOCAL);
    /* CSIZE, HUPCL, CRTSCTS (hardware flow control) */

    /* Set data bits (5, 6, 7, 8 bits)
       CSIZE        Bit mask for data bits
    */
    tios.c_cflag &= ~CSIZE;
    switch (ctx_rtu->data_bit) {
    case 5:
        tios.c_cflag |= CS5;
        break;
    case 6:
        tios.c_cflag |= CS6;
        break;
    case 7:
        tios.c_cflag |= CS7;
        break;
    case 8:
    default:
        tios.c_cflag |= CS8;
        break;
    }

    /* Stop bit (1 or 2) */
    if (ctx_rtu->stop_bit == 1)
        tios.c_cflag &=~ CSTOPB;
    else /* 2 */
        tios.c_cflag |= CSTOPB;

    /* PARENB       Enable parity bit
       PARODD       Use odd parity instead of even */
    if (ctx_rtu->parity == 'N') {
        /* None */
        tios.c_cflag &=~ PARENB;
    } else if (ctx_rtu->parity == 'E') {
        /* Even */
        tios.c_cflag |= PARENB;
        tios.c_cflag &=~ PARODD;
    } else {
        /* Odd */
        tios.c_cflag |= PARENB;
        tios.c_cflag |= PARODD;
    }

    /* Read the man page of termios if you need more information. */

    /* This field isn't used on POSIX systems
       tios.c_line = 0;
    */

    /* C_LFLAG      Line options

       ISIG Enable SIGINTR, SIGSUSP, SIGDSUSP, and SIGQUIT signals
       ICANON       Enable canonical input (else raw)
       XCASE        Map uppercase \lowercase (obsolete)
       ECHO Enable echoing of input characters
       ECHOE        Echo erase character as BS-SP-BS
       ECHOK        Echo NL after kill character
       ECHONL       Echo NL
       NOFLSH       Disable flushing of input buffers after
       interrupt or quit characters
       IEXTEN       Enable extended functions
       ECHOCTL      Echo control characters as ^char and delete as ~?
       ECHOPRT      Echo erased character as character erased
       ECHOKE       BS-SP-BS entire line on line kill
       FLUSHO       Output being flushed
       PENDIN       Retype pending input at next read or input char
       TOSTOP       Send SIGTTOU for background output

       Canonical input is line-oriented. Input characters are put
       into a buffer which can be edited interactively by the user
       until a CR (carriage return) or LF (line feed) character is
       received.

       Raw input is unprocessed. Input characters are passed
       through exactly as they are received, when they are
       received. Generally you'll deselect the ICANON, ECHO,
       ECHOE, and ISIG options when using raw input
    */

    /* Raw input */
    tios.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);

    /* C_IFLAG      Input options

       Constant     Description
       INPCK        Enable parity check
       IGNPAR       Ignore parity errors
       PARMRK       Mark parity errors
       ISTRIP       Strip parity bits
       IXON Enable software flow control (outgoing)
       IXOFF        Enable software flow control (incoming)
       IXANY        Allow any character to start flow again
       IGNBRK       Ignore break condition
       BRKINT       Send a SIGINT when a break condition is detected
       INLCR        Map NL to CR
       IGNCR        Ignore CR
       ICRNL        Map CR to NL
       IUCLC        Map uppercase to lowercase
       IMAXBEL      Echo BEL on input line too long
    */
    if (ctx_rtu->parity == 'N') {
        /* None */
        tios.c_iflag &= ~INPCK;
    } else {
        tios.c_iflag |= INPCK;
    }

    /* Software flow control is disabled */
    tios.c_iflag &= ~(IXON | IXOFF | IXANY);

    /* C_OFLAG      Output options
       OPOST        Postprocess output (not set = raw output)
       ONLCR        Map NL to CR-NL

       ONCLR ant others needs OPOST to be enabled
    */

    /* Raw ouput */
    tios.c_oflag &=~ OPOST;

    /* C_CC         Control characters
       VMIN         Minimum number of characters to read
       VTIME        Time to wait for data (tenths of seconds)

       UNIX serial interface drivers provide the ability to
       specify character and packet timeouts. Two elements of the
       c_cc array are used for timeouts: VMIN and VTIME. Timeouts
       are ignored in canonical input mode or when the NDELAY
       option is set on the file via open or fcntl.

       VMIN specifies the minimum number of characters to read. If
       it is set to 0, then the VTIME value specifies the time to
       wait for every character read. Note that this does not mean
       that a read call for N bytes will wait for N characters to
       come in. Rather, the timeout will apply to the first
       character and the read call will return the number of
       characters immediately available (up to the number you
       request).

       If VMIN is non-zero, VTIME specifies the time to wait for
       the first character read. If a character is read within the
       time given, any read will block (wait) until all VMIN
       characters are read. That is, once the first character is
       read, the serial interface driver expects to receive an
       entire packet of characters (VMIN bytes total). If no
       character is read within the time allowed, then the call to
       read returns 0. This method allows you to tell the serial
       driver you need exactly N bytes and any read call will
       return 0 or N bytes. However, the timeout only applies to
       the first character read, so if for some reason the driver
       misses one character inside the N byte packet then the read
       call could block forever waiting for additional input
       characters.

       VTIME specifies the amount of time to wait for incoming
       characters in tenths of seconds. If VTIME is set to 0 (the
       default), reads will block (wait) indefinitely unless the
       NDELAY option is set on the port with open or fcntl.
    */
    /* Unused because we use open with the NDELAY option */
    tios.c_cc[VMIN] = 0;
    tios.c_cc[VTIME] = 0;

    if (tcsetattr(ctx->s, TCSANOW, &tios) < 0) {
        close(ctx->s);
        ctx->s = -1;
        return -1;
    }
#endif

    return 0;
}
Ejemplo n.º 19
0
int main(int argc, char** argv)
{
	time_t time_now = time(NULL);
	char* time_str = strdup(asctime(gmtime(&time_now)));
	time_str[24] = 0;

	printf("Time now is %d (%s)\n", time_now, time_str);

	char testfile[80];
	snprintf(testfile, sizeof(testfile), "test.%d", time_now);
	printf("Test file is: %s\n", testfile);

	_unlink(testfile);

	/*
	int fd = open(testfile, O_RDWR | O_CREAT | O_EXCL);
	if (fd < 0)
	{
		perror("open");
		exit(1);
	}
	close(fd);
	*/

	HANDLE fh = CreateFileA(testfile, FILE_READ_ATTRIBUTES,
		FILE_SHARE_READ | FILE_SHARE_DELETE, NULL, CREATE_ALWAYS, 
		FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_DELETE_ON_CLOSE, NULL);

	if (!fh)
	{
		fprintf(stderr, "Failed to open file '%s': error %d\n",
			testfile, GetLastError());
		exit(1);
	}

	BY_HANDLE_FILE_INFORMATION fi;

	if (!GetFileInformationByHandle(fh, &fi))
	{
		fprintf(stderr, "Failed to get file information for '%s': "
			"error %d\n", testfile, GetLastError());
		exit(1);
	}

	if (!CloseHandle(fh))
	{
		fprintf(stderr, "Failed to close file: error %d\n",
			GetLastError());
		exit(1);
	}

	time_t created_time = ConvertFileTimeToTime_t(&fi.ftCreationTime);
	time_str = strdup(asctime(gmtime(&created_time)));
	time_str[24] = 0;

	printf("File created time: %d (%s)\n", created_time, time_str);

	printf("Difference is: %d\n", created_time - time_now);

	if (abs(created_time - time_now) > 30)
	{
		fprintf(stderr, "Error: time difference too big: "
			"bug in emu.h?\n");
		exit(1);
	}

	/*
	sleep(1);

	if (_unlink(testfile) != 0)
	{
		perror("Failed to delete test file");
		exit(1);
	}
	*/

	exit(0);
}
Ejemplo n.º 20
0
/**
 * Logs the details of this crash and shows an error.
 * @param ex Pointer to exception data (PEXCEPTION_POINTERS on Windows, signal int on Unix)
 * @param err Exception message, if any.
 */
void crashDump(void *ex, const std::string &err)
{
	std::ostringstream error;
#ifdef _MSC_VER
	PEXCEPTION_POINTERS exception = (PEXCEPTION_POINTERS)ex;
	std::exception *cppException = 0;
	switch (exception->ExceptionRecord->ExceptionCode)
	{
	case EXCEPTION_CODE_CXX:
		cppException = (std::exception *)exception->ExceptionRecord->ExceptionInformation[1];
		error << cppException->what();
		break;
	case EXCEPTION_ACCESS_VIOLATION:
		error << "Memory access violation. This usually indicates something missing in a mod.";
		break;
	default:
		error << "code 0x" << std::hex << exception->ExceptionRecord->ExceptionCode;
		break;
	}
	Log(LOG_FATAL) << "A fatal error has occurred: " << error.str();
	stackTrace(exception->ContextRecord);
	std::string dumpName = Options::getUserFolder();
	dumpName += now() + ".dmp";
	HANDLE dumpFile = CreateFileA(dumpName.c_str(), GENERIC_READ | GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
	MINIDUMP_EXCEPTION_INFORMATION exceptionInformation;
	exceptionInformation.ThreadId = GetCurrentThreadId();
	exceptionInformation.ExceptionPointers = exception;
	exceptionInformation.ClientPointers = FALSE;
	if (MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), dumpFile, MiniDumpNormal, exception ? &exceptionInformation : NULL, NULL, NULL))
	{
		Log(LOG_FATAL) << "Crash dump generated at " << dumpName;
	}
	else
	{
		Log(LOG_FATAL) << "No crash dump generated: " << GetLastError();
	}
#else
	if (ex == 0)
	{
		error << err;
	}
	else
	{
		int signal = *((int*)ex);
		switch (signal)
		{
		case SIGSEGV:
			error << "Segmentation fault. This usually indicates something missing in a mod.";
			break;
		default:
			error << "signal " << signal;
			break;
		}
	}
	Log(LOG_FATAL) << "A fatal error has occurred: " << error.str();
	stackTrace(0);
#endif
	std::ostringstream msg;
	msg << "OpenXcom has crashed: " << error.str() << std::endl;
	msg << "Extra information has been saved to openxcom.log." << std::endl;
	msg << "If this error was unexpected, please report it to the developers.";
	showError(msg.str());
}
Ejemplo n.º 21
0
bool CSerial::Open(QString portName, DWORD dwInQueue, DWORD dwOutQueue, bool fOverlapped)
{
	// Reset error state
	m_lLastError = ERROR_SUCCESS;

	// Check if the port isn't already opened
	if (m_hFile)
		return true;

	// Open the device
	m_hFile = CreateFileA(portName.toAscii(),
						   GENERIC_READ|GENERIC_WRITE,
						   0,
						   0,
						   OPEN_EXISTING,
						   fOverlapped?FILE_FLAG_OVERLAPPED:0,
						   0);

	// Check if the opening was successful.
	if (m_hFile == INVALID_HANDLE_VALUE)
    {
		m_hFile = 0;
		return false;
	}

#ifndef SERIAL_NO_OVERLAPPED
	// We cannot have an event handle yet
	//_ASSERTE(m_hevtOverlapped == 0);

	// Create the event handle for internal overlapped operations (manual reset)
	if (fOverlapped)
	{
		m_hevtOverlapped = ::CreateEvent(0,true,false,0);
		if (m_hevtOverlapped == 0)
		{
			// Obtain the error information
			m_lLastError = ::GetLastError();
			qDebug() << ("CSerial::Open - Unable to create event\n");

			// Close the port
			CloseHandle(m_hFile);
			m_hFile = 0;

			// Return the error
			//return m_lLastError;
			return false;
		}
	}
#else

	// Overlapped flag shouldn't be specified
	//_ASSERTE(!fOverlapped);

#endif

	// Setup the COM-port
	if (dwInQueue || dwOutQueue)
	{
		// Make sure the queue-sizes are reasonable sized. Win9X systems crash
		// if the input queue-size is zero. Both queues need to be at least
		// 16 bytes large.
		//_ASSERTE(dwInQueue >= 16);
		//_ASSERTE(dwOutQueue >= 16);

		if (!SetupComm(m_hFile,dwInQueue,dwOutQueue))
		{
			// Display a warning
			long lLastError = ::GetLastError();
			qDebug() << ("CSerial::Open - Unable to setup the COM-port\n");

			// Close the port
			close();

			// Save last error from SetupComm
			m_lLastError = lLastError;
			//return m_lLastError;
			return false;
		}
	}

	// Setup the default communication mask
	SetMask();

	// Non-blocking reads is default
	SetupReadTimeouts(EReadTimeoutNonblocking);

//
//	// Setup the device for default settings
// 	COMMCONFIG commConfig = {0};
//	DWORD dwSize = sizeof(commConfig);
//	commConfig.dwSize = dwSize;
//	if (GetDefaultCommConfig(lpszDevice,&commConfig,&dwSize))
//	{
//		// Set the default communication configuration
//		if (!SetCommConfig(m_hFile,&commConfig,dwSize))
//		{
//			// Display a warning
//			qDebug() << ("CSerial::Open - Unable to set default communication configuration.\n");
//		}
//	}
//	else
//	{
//		// Display a warning
//		qDebug() << ("CSerial::Open - Unable to obtain default communication configuration.\n");
//	}

	// Return successful
	//return m_lLastError;
	return true;
}
Ejemplo n.º 22
0
/***********************************************************************
 *		wine_load_dos_exe (WINEDOS.@)
 *
 * Called from WineVDM when a new real-mode DOS process is started.
 * Loads DOS program into memory and executes the program.
 */
void WINAPI wine_load_dos_exe( LPCSTR filename, LPCSTR cmdline )
{
    char dos_cmdtail[126];
    int  dos_length = 0;

    HANDLE hFile = CreateFileA( filename, GENERIC_READ, FILE_SHARE_READ, 
                                NULL, OPEN_EXISTING, 0, 0 );
    if (hFile == INVALID_HANDLE_VALUE) return;
    DOSVM_isdosexe = TRUE;

    if(cmdline && *cmdline)
    {
        dos_length = strlen(cmdline);
        memmove( dos_cmdtail + 1, cmdline, 
                 (dos_length < 125) ? dos_length : 125 );

        /* Non-empty command tail always starts with at least one space. */
        dos_cmdtail[0] = ' ';
        dos_length++;

        /*
         * If command tail is longer than 126 characters,
         * set tail length to 127 and fill CMDLINE environment variable 
         * with full command line (this includes filename).
         */
        if (dos_length > 126)
        {
            char *cmd = HeapAlloc( GetProcessHeap(), 0, 
                                   dos_length + strlen(filename) + 4 );
            char *ptr = cmd;

            if (!cmd)
                return;

            /*
             * Append filename. If path includes spaces, quote the path.
             */
            if (strchr(filename, ' '))
            {
                *ptr++ = '\"';
                strcpy( ptr, filename );
                ptr += strlen(filename);                   
                *ptr++ = '\"';
            }
            else
            {
                strcpy( ptr, filename );
                ptr += strlen(filename);  
            }

            /*
             * Append command tail.
             */
            if (cmdline[0] != ' ')
                *ptr++ = ' ';
            strcpy( ptr, cmdline );

            /*
             * Set environment variable. This will be passed to
             * new DOS process.
             */
            if (!SetEnvironmentVariableA( "CMDLINE", cmd ))
            {
                HeapFree(GetProcessHeap(), 0, cmd );
                return;
            }

            HeapFree(GetProcessHeap(), 0, cmd );
            dos_length = 127;
        }
    }

    if (MZ_DoLoadImage( hFile, filename, NULL, 0 )) 
        MZ_Launch( dos_cmdtail, dos_length );
}
Ejemplo n.º 23
0
template <typename PointT> int
pcl::PCDWriter::writeBinary (const std::string &file_name, 
                             const pcl::PointCloud<PointT> &cloud, 
                             const std::vector<int> &indices)
{
  if (cloud.points.empty () || indices.empty ())
  {
    throw pcl::IOException ("[pcl::PCDWriter::writeBinary] Input point cloud has no data or empty indices given!");
    return (-1);
  }
  int data_idx = 0;
  std::ostringstream oss;
  oss << generateHeader<PointT> (cloud, static_cast<int> (indices.size ())) << "DATA binary\n";
  oss.flush ();
  data_idx = static_cast<int> (oss.tellp ());

#if _WIN32
  HANDLE h_native_file = CreateFileA (file_name.c_str (), GENERIC_READ | GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
  if (h_native_file == INVALID_HANDLE_VALUE)
  {
    throw pcl::IOException ("[pcl::PCDWriter::writeBinary] Error during CreateFile!");
    return (-1);
  }
#else
  int fd = pcl_open (file_name.c_str (), O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
  if (fd < 0)
  {
    throw pcl::IOException ("[pcl::PCDWriter::writeBinary] Error during open!");
    return (-1);
  }
#endif
  // Mandatory lock file
  boost::interprocess::file_lock file_lock;
  setLockingPermissions (file_name, file_lock);

  std::vector<pcl::PCLPointField> fields;
  std::vector<int> fields_sizes;
  size_t fsize = 0;
  size_t data_size = 0;
  size_t nri = 0;
  pcl::getFields (cloud, fields);
  // Compute the total size of the fields
  for (size_t i = 0; i < fields.size (); ++i)
  {
    if (fields[i].name == "_")
      continue;
    
    int fs = fields[i].count * getFieldSize (fields[i].datatype);
    fsize += fs;
    fields_sizes.push_back (fs);
    fields[nri++] = fields[i];
  }
  fields.resize (nri);
  
  data_size = indices.size () * fsize;

  // Prepare the map
#if _WIN32
  HANDLE fm = CreateFileMapping (h_native_file, NULL, PAGE_READWRITE, 0, data_idx + data_size, NULL);
  char *map = static_cast<char*>(MapViewOfFile (fm, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, data_idx + data_size));
  CloseHandle (fm);

#else
  // Stretch the file size to the size of the data
  off_t result = pcl_lseek (fd, getpagesize () + data_size - 1, SEEK_SET);
  if (result < 0)
  {
    pcl_close (fd);
    resetLockingPermissions (file_name, file_lock);
    PCL_ERROR ("[pcl::PCDWriter::writeBinary] lseek errno: %d strerror: %s\n", errno, strerror (errno));
    
    throw pcl::IOException ("[pcl::PCDWriter::writeBinary] Error during lseek ()!");
    return (-1);
  }
  // Write a bogus entry so that the new file size comes in effect
  result = static_cast<int> (::write (fd, "", 1));
  if (result != 1)
  {
    pcl_close (fd);
    resetLockingPermissions (file_name, file_lock);
    throw pcl::IOException ("[pcl::PCDWriter::writeBinary] Error during write ()!");
    return (-1);
  }

  char *map = static_cast<char*> (mmap (0, data_idx + data_size, PROT_WRITE, MAP_SHARED, fd, 0));
  if (map == reinterpret_cast<char*> (-1)) //MAP_FAILED)
  {
    pcl_close (fd);
    resetLockingPermissions (file_name, file_lock);
    throw pcl::IOException ("[pcl::PCDWriter::writeBinary] Error during mmap ()!");
    return (-1);
  }
#endif

  // Copy the header
  memcpy (&map[0], oss.str ().c_str (), data_idx);

  char *out = &map[0] + data_idx;
  // Copy the data
  for (size_t i = 0; i < indices.size (); ++i)
  {
    int nrj = 0;
    for (size_t j = 0; j < fields.size (); ++j)
    {
      memcpy (out, reinterpret_cast<const char*> (&cloud.points[indices[i]]) + fields[j].offset, fields_sizes[nrj]);
      out += fields_sizes[nrj++];
    }
  }

#if !_WIN32
  // If the user set the synchronization flag on, call msync
  if (map_synchronization_)
    msync (map, data_idx + data_size, MS_SYNC);
#endif

  // Unmap the pages of memory
#if _WIN32
    UnmapViewOfFile (map);
#else
  if (munmap (map, (data_idx + data_size)) == -1)
  {
    pcl_close (fd);
    resetLockingPermissions (file_name, file_lock);
    throw pcl::IOException ("[pcl::PCDWriter::writeBinary] Error during munmap ()!");
    return (-1);
  }
#endif
  // Close file
#if _WIN32
  CloseHandle(h_native_file);
#else
  pcl_close (fd);
#endif
  
  resetLockingPermissions (file_name, file_lock);
  return (0);
}
Ejemplo n.º 24
0
/***********************************************************************
 *		MZ_Exec
 *
 * this may only be called from existing DOS processes
 */
BOOL WINAPI MZ_Exec( CONTEXT86 *context, LPCSTR filename, BYTE func, LPVOID paramblk )
{
  DWORD binType;
  STARTUPINFOA st;
  PROCESS_INFORMATION pe;
  HANDLE hFile;

  BOOL ret = FALSE;

  if(!GetBinaryTypeA(filename, &binType))   /* determine what kind of binary this is */
  {
    return FALSE; /* binary is not an executable */
  }

  /* handle non-dos executables */
  if(binType != SCS_DOS_BINARY)
  {
    if(func == 0) /* load and execute */
    {
      LPSTR fullCmdLine;
      WORD fullCmdLength;
      LPBYTE psp_start = (LPBYTE)((DWORD)DOSVM_psp << 4);
      PDB16 *psp = (PDB16 *)psp_start;
      ExecBlock *blk = (ExecBlock *)paramblk;
      LPBYTE cmdline = PTR_REAL_TO_LIN(SELECTOROF(blk->cmdline),OFFSETOF(blk->cmdline));
      LPBYTE envblock = PTR_REAL_TO_LIN(psp->environment, 0);
      int    cmdLength = cmdline[0];

      /*
       * If cmdLength is 127, command tail is truncated and environment 
       * variable CMDLINE should contain full command line 
       * (this includes filename).
       */
      if (cmdLength == 127)
      {
          FIXME( "CMDLINE argument passing is unimplemented.\n" );
          cmdLength = 126; /* FIXME */
      }

      fullCmdLength = (strlen(filename) + 1) + cmdLength + 1; /* filename + space + cmdline + terminating null character */

      fullCmdLine = HeapAlloc(GetProcessHeap(), 0, fullCmdLength);
      if(!fullCmdLine) return FALSE; /* return false on memory alloc failure */

      /* build the full command line from the executable file and the command line being passed in */
      snprintf(fullCmdLine, fullCmdLength, "%s ", filename); /* start off with the executable filename and a space */
      memcpy(fullCmdLine + strlen(fullCmdLine), cmdline + 1, cmdLength); /* append cmdline onto the end */
      fullCmdLine[fullCmdLength - 1] = 0; /* null terminate string */

      ZeroMemory (&st, sizeof(STARTUPINFOA));
      st.cb = sizeof(STARTUPINFOA);
      ret = CreateProcessA (NULL, fullCmdLine, NULL, NULL, TRUE, 0, envblock, NULL, &st, &pe);

      /* wait for the app to finish and clean up PROCESS_INFORMATION handles */
      if(ret)
      {
        WaitForSingleObject(pe.hProcess, INFINITE);  /* wait here until the child process is complete */
        CloseHandle(pe.hProcess);
        CloseHandle(pe.hThread);
      }

      HeapFree(GetProcessHeap(), 0, fullCmdLine);  /* free the memory we allocated */
    }
    else
    {
      FIXME("EXEC type of %d not implemented for non-dos executables\n", func);
      ret = FALSE;
    }

    return ret;
  } /* if(binType != SCS_DOS_BINARY) */


  /* handle dos executables */

  hFile = CreateFileA( filename, GENERIC_READ, FILE_SHARE_READ,
			     NULL, OPEN_EXISTING, 0, 0);
  if (hFile == INVALID_HANDLE_VALUE) return FALSE;

  switch (func) {
  case 0: /* load and execute */
  case 1: /* load but don't execute */
    {
      /* save current process's return SS:SP now */
      LPBYTE psp_start = (LPBYTE)((DWORD)DOSVM_psp << 4);
      PDB16 *psp = (PDB16 *)psp_start;
      psp->saveStack = (DWORD)MAKESEGPTR(context->SegSs, LOWORD(context->Esp));
    }
    ret = MZ_DoLoadImage( hFile, filename, NULL, ((ExecBlock *)paramblk)->env_seg );
    if (ret) {
      /* MZ_LoadImage created a new PSP and loaded new values into it,
       * let's work on the new values now */
      LPBYTE psp_start = (LPBYTE)((DWORD)DOSVM_psp << 4);
      ExecBlock *blk = (ExecBlock *)paramblk;
      LPBYTE cmdline = PTR_REAL_TO_LIN(SELECTOROF(blk->cmdline),OFFSETOF(blk->cmdline));

      /* First character contains the length of the command line. */
      MZ_FillPSP(psp_start, (LPSTR)cmdline + 1, cmdline[0]);

      /* the lame MS-DOS engineers decided that the return address should be in int22 */
      DOSVM_SetRMHandler(0x22, (FARPROC16)MAKESEGPTR(context->SegCs, LOWORD(context->Eip)));
      if (func) {
	/* don't execute, just return startup state */
        /*
         * From Ralph Brown:
         *  For function 01h, the AX value to be passed to the child program 
         *  is put on top of the child's stack
         */
        LPBYTE stack;
        init_sp -= 2;
        stack = (LPBYTE) CTX_SEG_OFF_TO_LIN(context, init_ss, init_sp);
        /* FIXME: push AX correctly */
        stack[0] = 0x00;    /* push AL */
        stack[1] = 0x00;    /* push AH */
	
	blk->init_cs = init_cs;
	blk->init_ip = init_ip;
	blk->init_ss = init_ss;
	blk->init_sp = init_sp;
      } else {
	/* execute by making us return to new process */
	context->SegCs = init_cs;
	context->Eip   = init_ip;
	context->SegSs = init_ss;
	context->Esp   = init_sp;
	context->SegDs = DOSVM_psp;
	context->SegEs = DOSVM_psp;
	context->Eax   = 0;
      }
    }
    break;
  case 3: /* load overlay */
    {
      OverlayBlock *blk = (OverlayBlock *)paramblk;
      ret = MZ_DoLoadImage( hFile, filename, blk, 0);
    }
    break;
  default:
    FIXME("EXEC load type %d not implemented\n", func);
    SetLastError(ERROR_INVALID_FUNCTION);
    break;
  }
  CloseHandle(hFile);
  return ret;
}
Ejemplo n.º 25
0
bool
TeDecoderFile::create()
{
	m_hFile = CreateFileA(
		params_.fileName_.c_str(),	// File name
		GENERIC_READ | GENERIC_WRITE,	// Read-write
		FILE_SHARE_READ
		| FILE_SHARE_WRITE,		// Allow sharing-- we're only doing a quick scan
		NULL,					// No security attributes
		CREATE_NEW,			    // Open a new file
		0,						// Ignore file attributes
		NULL);					// Ignore hTemplateFile
  
	if ( m_hFile == INVALID_HANDLE_VALUE) 
		return false;		// could not open file

	char			lpBuffer[1024];
	unsigned long	nNumberOfBytesToWrite=(long)params_.nBands() * (long)params_.ncols_ * (long)params_.nlines_;    // number of bytes to write
	nNumberOfBytesToWrite *= (long)params_.nbitsperPixel_[0]/8;    // number of bytes to write
	unsigned long	nNumberOfBytesWritten;  // pointer to number of bytes written

	for (;nNumberOfBytesToWrite > 1024; nNumberOfBytesToWrite-=1024)
	{
		if ( !WriteFile(
			m_hFile,                // handle to file to write to
			lpBuffer,               // pointer to data to write to file
			1024,					// number of bytes to write
			&nNumberOfBytesWritten,  // pointer to number of bytes written
			NULL					// pointer to structure for overlapped I/O
			))
 			return false;			// could not write to file
	}

	if ( !WriteFile(
		m_hFile,                // handle to file to write to
		lpBuffer,               // pointer to data to write to file
		nNumberOfBytesToWrite,	// number of bytes to write
		&nNumberOfBytesWritten,  // pointer to number of bytes written
		NULL					// pointer to structure for overlapped I/O
		))
 		return false;			// could not write to file
	
	SetFilePointer (m_hFile, NULL, NULL, FILE_BEGIN);

// Allocate buffer to get raster line from file

	switch (params_.dataType_[0]) {
	case (TeUNSIGNEDCHAR):
		m_buffer = new unsigned char[params_.ncols_];
		break;
	case (TeCHAR) :
		m_buffer = new char[params_.ncols_];
		break;
	case (TeUNSIGNEDSHORT):
		m_buffer = new unsigned short[params_.ncols_];
		break;
	case (TeSHORT):
		m_buffer = new short[params_.ncols_];
		break;
	case (TeUNSIGNEDLONG):
		m_buffer = new unsigned long[params_.ncols_];
		break;
	case (TeLONG):
		m_buffer = new long[params_.ncols_];
		break;
	case (TeFLOAT):
		m_buffer = new float[params_.ncols_];
		break;
	case (TeDOUBLE):
		m_buffer = new double[params_.ncols_];
		break;
    default:
        break;
	}

	if ( m_buffer == NULL )
		return false;

	if (params_.dummy_[0])
	{
		for (int b=0; b<params_.nBands();b++)
			for (int l=0; l<params_.nlines_;l++)
				for (int c=0; c<params_.ncols_;c++)
					setElement ( c, l, params_.dummy_[0], b);
	}
	return true;
}
Ejemplo n.º 26
0
void CExceptionHandler::WriteExceptionReport()
#endif
{
	// Get the current time and date
	time_t t = time(NULL);
	const struct tm * tm = localtime(&t);

	// Get the 'crashinfo' directory path
	String strPath(SharedUtility::GetAbsolutePath("crashinfo"));

	// Create the 'crashinfo' directory if needed
	if(!SharedUtility::Exists(strPath))
		SharedUtility::CreateDirectory(strPath);

	// Append the client or server string to the path
#ifdef _SERVER
	strPath.Append("\\Server");
#else
	strPath.Append("\\Client");
#endif

	// Append the operating system string to the path
	strPath.Append("-" OS_STRING);

	// Append the version, date and time to the path
	strPath.AppendF("-" MOD_VERSION_STRING "-%04d.%02d.%02d-%02d.%02d.%02d", (tm->tm_year + 1900), (tm->tm_mon + 1), tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec);

	// Get the log file path
	String strLogPath("%s.log", strPath.Get());

	// Open the log file
	FILE * fFile = fopen(strLogPath, "w");

	// Did the log file open successfully?
	if(fFile)
	{
		String strReportData;

		// Write the unhandled exception report start notice to the log file
		fprintf(fFile, "-- Unhandled Exception Report Start --\n");

#ifdef WIN32
		// Write the exception code and exception code string to the log file
		strReportData.AppendF("Exception code: 0x%p (%s)\n", ExceptionInfo->ExceptionRecord->ExceptionCode, 
			ExceptionCodeToString(ExceptionInfo->ExceptionRecord->ExceptionCode));

		// Write the exception address to the log file
#ifndef _SERVER
		strReportData.AppendF("Exception address: 0x%p (Game base: 0x%p)\n", ExceptionInfo->ExceptionRecord->ExceptionAddress, CGame::GetBase());
		strReportData.AppendF("Exception real-add: 0x%p / 0x%p\n", ((int)ExceptionInfo->ExceptionRecord->ExceptionAddress-CGame::GetBase()), (CGame::GetBase()-(int)ExceptionInfo->ExceptionRecord->ExceptionAddress));
#else
		strReportData.AppendF("Exception address: 0x%p\n", ExceptionInfo->ExceptionRecord->ExceptionAddress);
#endif
		// Create a tool help 32 process snapshot
		HANDLE hModuleSnapShot = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, GetCurrentProcessId());

		if(hModuleSnapShot)
		{
			MODULEENTRY32 ModuleEntry;
			ModuleEntry.dwSize = sizeof(ModuleEntry);

			if(Module32First(hModuleSnapShot, &ModuleEntry))
			{
				// Enumerate through all modules
				while(Module32Next(hModuleSnapShot, &ModuleEntry))
				{
					// See if exception was within this module
					if((ExceptionInfo->ContextRecord->Eip >= (DWORD)ModuleEntry.modBaseAddr) && (ExceptionInfo->ContextRecord->Eip <= ((DWORD)ModuleEntry.modBaseAddr + ModuleEntry.modBaseSize)))
					{
						strReportData.AppendF("Exception module: %s (+0x%p)\n", ModuleEntry.szModule, (ExceptionInfo->ContextRecord->Eip - (DWORD)ModuleEntry.modBaseAddr));
						break;
					}
				}
			}
		}

		// Write the registers segment header
		strReportData.AppendF("Exception registers: \n");

		// If we have segments context information then write it to the log file
		if(ExceptionInfo->ContextRecord->ContextFlags & CONTEXT_SEGMENTS)
		{
			strReportData.AppendF("GS=0x%p FS=0x%p ES=0x%p DS=0x%p\n", ExceptionInfo->ContextRecord->SegGs, 
				ExceptionInfo->ContextRecord->SegFs, ExceptionInfo->ContextRecord->SegEs, 
				ExceptionInfo->ContextRecord->SegDs);
		}

		// If we have integer context information then write it to the log file
		if(ExceptionInfo->ContextRecord->ContextFlags & CONTEXT_INTEGER)
		{
			strReportData.AppendF("EDI=0x%p ESI=0x%p EBX=0x%p EDX=0x%p\n", ExceptionInfo->ContextRecord->Edi, 
				ExceptionInfo->ContextRecord->Esi, ExceptionInfo->ContextRecord->Ebx,
				ExceptionInfo->ContextRecord->Edx);
			strReportData.AppendF("ECX=0x%p EAX=0x%p\n", ExceptionInfo->ContextRecord->Ecx, 
				ExceptionInfo->ContextRecord->Eax);
		}

		// If we have control context information then write it to the log file
		if(ExceptionInfo->ContextRecord->ContextFlags & CONTEXT_CONTROL)
		{
			strReportData.AppendF("EBP=0x%p EIP=0x%p CS=0x%p EFLAGS=0x%p\n", ExceptionInfo->ContextRecord->Ebp, 
				ExceptionInfo->ContextRecord->Eip, ExceptionInfo->ContextRecord->SegCs, 
				ExceptionInfo->ContextRecord->EFlags);
			strReportData.AppendF("ESP=0x%p SS=0x%p\n", ExceptionInfo->ContextRecord->Esp, 
				ExceptionInfo->ContextRecord->SegSs);
		}
#else
		void * pArray[50];
		int iSize = backtrace(pArray, 50);
		char ** szMessages = backtrace_symbols(pArray, iSize);

		for(int i = 0; i < iSize && (szMessages[i] != NULL); i++)
			strReportData.AppendF("[Backtrace %d]: %s\n", i, szMessages[i]);
#endif

		// If we have a callback call it
		if(m_pfnCallback)
			m_pfnCallback(strReportData);

		// Print the report data to the log file
		fprintf(fFile, strReportData.Get());

		// Write the unhandled exception report end notice to the log file
		fprintf(fFile, "--Unhandled Exception Report End --\n");

		// Close the log file
		fclose(fFile);
	}
	else
		CLogFile::Printf("Failed to open the crash log file.");

#ifdef WIN32
	// Get the minidump file path
	String strMiniDumpPath("%s.dmp", strPath.Get());

	// Open the minidump file
	HANDLE hFile = CreateFileA(strMiniDumpPath, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL , NULL);

	// Did the minidump file open successfully?
	if(hFile)
	{
		// Create the minidump exception information
		MINIDUMP_EXCEPTION_INFORMATION exceptionInfo;
		exceptionInfo.ThreadId = GetCurrentThreadId();
		exceptionInfo.ExceptionPointers = ExceptionInfo;
		exceptionInfo.ClientPointers = FALSE;

		// Write the minidump to the minidump file
		if(!MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), hFile, MiniDumpNormal, &exceptionInfo, NULL, NULL))
			CLogFile::Printf("Failed to write the minidump file.");

		// Close the minidump file
		CloseHandle(hFile);
	}
	else
		CLogFile::Printf("Failed to open the minidump file.");
#endif

	// Print a message in the log file
	CLogFile::Printf("IV:MP has crashed. Please see %s for more information.", strLogPath.Get());
}
Ejemplo n.º 27
0
BOOL CALLBACK EV_DlgMain(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    switch(uMsg)
    {
    case WM_INITDIALOG:
    {
        EV_shared=hwndDlg;
        EV_list_hwnd=GetDlgItem(hwndDlg, IDC_LIST);
    }
    return TRUE;

    case WM_CLOSE:
    {
        EndDialog(hwndDlg, 0);
    }
    return TRUE;

    case WM_BROWSE:
    {
        SendMessageA(EV_list_hwnd, LB_RESETCONTENT, 0, 0);
        strcpy(EV_szFileName, (const char*)wParam);
        strcpy(EV_program_dir, EV_szFileName);
        int i=strlen(EV_program_dir);
        while(EV_program_dir[i]!='\\')
            i--;
        EV_program_dir[i]=0;
        CreateThread(0, 0, EV_DebugThread, 0, 0, 0);
    }
    return TRUE;

    case WM_DROPFILES:
    {
        SendMessageA(EV_list_hwnd, LB_RESETCONTENT, 0, 0);
        DragQueryFileA((HDROP)wParam, 0, EV_szFileName, MAX_PATH);
        strcpy(EV_program_dir, EV_szFileName);
        int i=strlen(EV_program_dir);
        while(EV_program_dir[i]!='\\')
            i--;
        EV_program_dir[i]=0;
        CreateThread(0, 0, EV_DebugThread, 0, 0, 0);
    }
    return TRUE;

    case WM_CONTEXTMENU:
    {
        if(GetDlgCtrlID((HWND)wParam)==IDC_LIST)
        {
            LeftClick();
            LeftClick();
        }
    }
    return TRUE;

    case WM_HELP:
    {
        char id[10]="";
        sprintf(id, "%d", IDS_HELPEVLOG);
        SetEnvironmentVariableA("HELPID", id);
        SetEnvironmentVariableA("HELPTITLE", "EVLog Help");
        DialogBox(hInst, MAKEINTRESOURCE(DLG_HELP), hwndDlg, DlgHelp);
    }
    return TRUE;

    case WM_COMMAND:
    {
        switch(LOWORD(wParam))
        {
        case IDC_LIST:
        {
            switch(HIWORD(wParam))
            {
            case LBN_DBLCLK:
            {
                int cursel=SendMessageA(EV_list_hwnd, LB_GETCURSEL, 0, 0);
                int count=SendMessageA(EV_list_hwnd, LB_GETCOUNT, 0, 0);
                if(!count)
                    return TRUE;
                char line_text[1024]="";
                char var_name[512]="";
                char var_value[512]="";
                SendMessageA(EV_list_hwnd, LB_GETTEXT, cursel, (LPARAM)line_text);
                int len=strlen(line_text);
                for(int i=0,j=0,k=0,l=0; i<len; i++)
                {
                    if(line_text[i]=='=')
                    {
                        i++;
                        j=1;
                    }
                    if(!j)
                        k+=sprintf(var_name+k, "%c", line_text[i]);
                    else
                        l+=sprintf(var_value+l, "%c", line_text[i]);
                }
                HMENU myMenu=0;
                myMenu=CreatePopupMenu();
                AppendMenu(myMenu, MF_STRING, 1, "Copy Variable &Name");
                if(strcmp(var_value, "(0)"))
                    AppendMenu(myMenu, MF_STRING, 2, "Copy Variable &Value");
                AppendMenu(myMenu, MF_STRING, 3, "Copy &Line");
                POINT cursorPos;
                GetCursorPos(&cursorPos);
                SetForegroundWindow(hwndDlg);
                UINT MenuItemClicked=TrackPopupMenu(myMenu, TPM_RETURNCMD|TPM_NONOTIFY, cursorPos.x, cursorPos.y, 0, hwndDlg, 0);
                SendMessage(hwndDlg, WM_NULL, 0, 0);
                switch(MenuItemClicked)
                {
                case 1:
                    CopyToClipboard(var_name);
                    break;
                case 2:
                    CopyToClipboard(var_value);
                    break;
                case 3:
                    CopyToClipboard(line_text);
                    break;
                }
            }
            return TRUE;
            }
        }
        return TRUE;

        case IDC_BTN_DUMP:
        {
            char massive_string[32768]="", single_string[255]="Coded by Mr. eXoDia // T.P.o.D.T 2012\r\n\r\n";
            int total=SendDlgItemMessage(hwndDlg, IDC_LIST, LB_GETCOUNT, 0, 0);
            for(int i=0; i!=total; i++)
            {
                SendDlgItemMessage(hwndDlg, IDC_LIST, LB_GETTEXT, (WPARAM)i, (LPARAM)single_string);
                sprintf(massive_string, "%s%s\r\n", massive_string, single_string);
            }
            char log_filename[MAX_PATH]="";
            log_filename[0]=0;
            OPENFILENAME ofstruct;
            memset(&ofstruct, 0, sizeof(ofstruct));
            ofstruct.lStructSize=sizeof(ofstruct);
            ofstruct.hwndOwner=hwndDlg;
            ofstruct.hInstance=hInst;
            ofstruct.lpstrFilter="Log files (*.log)\0*.log\0\0";
            ofstruct.lpstrFile=log_filename;
            ofstruct.nMaxFile=MAX_PATH;
            ofstruct.lpstrInitialDir=EV_program_dir;
            ofstruct.lpstrTitle="Save file";
            ofstruct.lpstrDefExt="log";
            ofstruct.Flags=OFN_EXTENSIONDIFFERENT|OFN_HIDEREADONLY|OFN_NONETWORKBUTTON|OFN_OVERWRITEPROMPT;
            GetSaveFileName(&ofstruct);
            if(!log_filename[0])
                return TRUE;
            HANDLE hFile=CreateFileA(log_filename, GENERIC_ALL, 0, 0, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
            if(hFile==INVALID_HANDLE_VALUE)
            {
                MessageBoxA(hwndDlg, "Could not create the file, maybe it's in use...", "Error!", MB_ICONERROR);
                return TRUE;
            }
            DWORD written=0;
            if(!WriteFile(hFile, massive_string, strlen(massive_string), &written, 0))
            {
                CloseHandle(hFile);
                MessageBoxA(hwndDlg, "Could not write to the file, maybe it's in use...", "Error!", MB_ICONERROR);
                return TRUE;
            }
            CloseHandle(hFile);
        }
        return TRUE;
        }
    }
    return TRUE;
    }
    return FALSE;
}
Ejemplo n.º 28
0
//----------------------------------------------------------------
bool ofSerial::setup(string portName, int baud){
	bInited = false;

	#if defined( TARGET_OSX ) || defined( TARGET_LINUX )

		//lets account for the name being passed in instead of the device path
		if(portName.size() > 5 && portName.substr(0, 5) != "/dev/"){
			portName = "/dev/" + portName;
		}

		ofLogNotice("ofSerial") << "opening " << portName << " @ " << baud << " bps";
		fd = open(portName.c_str(), O_RDWR | O_NOCTTY | O_NONBLOCK);
		if(fd == -1){
			ofLogError("ofSerial") << "unable to open " << portName;
			return false;
		}

		struct termios options;
		tcgetattr(fd, &oldoptions);
		options = oldoptions;
		switch(baud){
			case 300:
			cfsetispeed(&options, B300);
				cfsetospeed(&options, B300);
				break;
		   case 1200:
			cfsetispeed(&options, B1200);
				cfsetospeed(&options, B1200);
				break;
		   case 2400:
			cfsetispeed(&options, B2400);
				cfsetospeed(&options, B2400);
				break;
		   case 4800:
			cfsetispeed(&options, B4800);
		cfsetospeed(&options, B4800);
		break;
		   case 9600:
			cfsetispeed(&options, B9600);
		cfsetospeed(&options, B9600);
		break;
		   case 14400:
			cfsetispeed(&options, B14400);
		cfsetospeed(&options, B14400);
		break;
		   case 19200:
			cfsetispeed(&options, B19200);
		cfsetospeed(&options, B19200);
		break;
		   case 28800:
			cfsetispeed(&options, B28800);
		cfsetospeed(&options, B28800);
		break;
		   case 38400:
			cfsetispeed(&options, B38400);
		cfsetospeed(&options, B38400);
		break;
		   case 57600:
			cfsetispeed(&options, B57600);
		cfsetospeed(&options, B57600);
		break;
		   case 115200:
			cfsetispeed(&options, B115200);
		cfsetospeed(&options, B115200);
		break;
		   case 230400:
			cfsetispeed(&options, B230400);
		cfsetospeed(&options, B230400);
		break;
		   default:
			cfsetispeed(&options, B9600);
		cfsetospeed(&options, B9600);
		ofLogError("ofSerial") << "setup(): cannot set " << baud << " bps, setting to 9600";
		break;
		}

		options.c_cflag |= (CLOCAL | CREAD);
		options.c_cflag &= ~PARENB;
		options.c_cflag &= ~CSTOPB;
		options.c_cflag &= ~CSIZE;
		options.c_iflag &= (tcflag_t) ~(INLCR | IGNCR | ICRNL | IGNBRK);
		options.c_oflag &= (tcflag_t) ~(OPOST);
		options.c_cflag |= CS8;
		#if defined( TARGET_LINUX )
			options.c_cflag |= CRTSCTS;
			options.c_lflag &= ~(ICANON | ECHO | ISIG);
		#endif
		tcsetattr(fd, TCSANOW, &options);
		#ifdef TARGET_LINUX
			struct serial_struct kernel_serial_settings;
			if (ioctl(fd, TIOCGSERIAL, &kernel_serial_settings) == 0) {
				kernel_serial_settings.flags |= ASYNC_LOW_LATENCY;
				ioctl(fd, TIOCSSERIAL, &kernel_serial_settings);
			}
		#endif
		bInited = true;
		ofLogNotice("ofSerial") << "opened " << portName << " sucessfully @ " << baud << " bps";

		return true;

	#elif defined( TARGET_WIN32 )

		char pn[sizeof(portName)];
		int num;
		if(sscanf(portName.c_str(), "COM%d", &num) == 1){
			// Microsoft KB115831 a.k.a if COM > COM9 you have to use a different
			// syntax
			sprintf(pn, "\\\\.\\COM%d", num);
		} else {
			strncpy(pn, (const char *)portName.c_str(), sizeof(portName)-1);
		}

		// open the serial port:
		// "COM4", etc...

		hComm = CreateFileA(pn, GENERIC_READ|GENERIC_WRITE, 0, 0,
							OPEN_EXISTING, 0, 0);

		if(hComm == INVALID_HANDLE_VALUE){
			ofLogError("ofSerial") << "setup(): unable to open " << portName;
			return false;
		}


		// now try the settings:
		COMMCONFIG cfg;
		DWORD cfgSize;
		WCHAR buf[80];

		cfgSize = sizeof(cfg);
		GetCommConfig(hComm, &cfg, &cfgSize);
		int bps = baud;
		swprintf(buf, L"baud=%d parity=N data=8 stop=1", bps);

		if(!BuildCommDCBW(buf, &cfg.dcb)){
			ofLogError("ofSerial") << "setup(): unable to build comm dcb, (" << buf << ")";
		}

		// Set baudrate and bits etc.
		// Note that BuildCommDCB() clears XON/XOFF and hardware control by default

		if(!SetCommState(hComm, &cfg.dcb)){
			ofLogError("ofSerial") << "setup(): couldn't set comm state: " << cfg.dcb.BaudRate << " bps, xio " << cfg.dcb.fInX << "/" << cfg.dcb.fOutX;
		}
		//ofLogNotice("ofSerial") << "bps=" << cfg.dcb.BaudRate << ", xio=" << cfg.dcb.fInX << "/" << cfg.dcb.fOutX;

		// Set communication timeouts (NT)
		COMMTIMEOUTS tOut;
		GetCommTimeouts(hComm, &oldTimeout);
		tOut = oldTimeout;
		// Make timeout so that:
		// - return immediately with buffered characters
		tOut.ReadIntervalTimeout = MAXDWORD;
		tOut.ReadTotalTimeoutMultiplier = 0;
		tOut.ReadTotalTimeoutConstant = 0;
		SetCommTimeouts(hComm, &tOut);

		bInited = true;
		return true;

	#else

		ofLogError("ofSerial") << "not implemented in this platform";
		return false;

	#endif
}
Ejemplo n.º 29
0
static void test_urlcacheA(void)
{
    static char ok_header[] = "HTTP/1.0 200 OK\r\n\r\n";
    BOOL ret;
    HANDLE hFile;
    BYTE zero_byte = 0;
    LPINTERNET_CACHE_ENTRY_INFO lpCacheEntryInfo;
    DWORD cbCacheEntryInfo;
    static const FILETIME filetime_zero;
    FILETIME now;

    ret = CreateUrlCacheEntry(TEST_URL, 0, "html", filenameA, 0);
    ok(ret, "CreateUrlCacheEntry failed with error %d\n", GetLastError());

    ret = CreateUrlCacheEntry(TEST_URL, 0, "html", filenameA1, 0);
    ok(ret, "CreateUrlCacheEntry failed with error %d\n", GetLastError());

    ok(lstrcmpiA(filenameA, filenameA1), "expected a different file name\n");

    create_and_write_file(filenameA, &zero_byte, sizeof(zero_byte));

    ret = CommitUrlCacheEntry(TEST_URL1, NULL, filetime_zero, filetime_zero, NORMAL_CACHE_ENTRY|URLHISTORY_CACHE_ENTRY, NULL, 0, NULL, NULL);
    ok(ret, "CommitUrlCacheEntry failed with error %d\n", GetLastError());
    cbCacheEntryInfo = 0;
    ret = GetUrlCacheEntryInfo(TEST_URL1, NULL, &cbCacheEntryInfo);
    ok(!ret, "GetUrlCacheEntryInfo should have failed\n");
    ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
       "GetUrlCacheEntryInfo should have set last error to ERROR_INSUFFICIENT_BUFFER instead of %d\n", GetLastError());
    lpCacheEntryInfo = HeapAlloc(GetProcessHeap(), 0, cbCacheEntryInfo);
    ret = GetUrlCacheEntryInfo(TEST_URL1, lpCacheEntryInfo, &cbCacheEntryInfo);
    ok(ret, "GetUrlCacheEntryInfo failed with error %d\n", GetLastError());
    ok(!memcmp(&lpCacheEntryInfo->ExpireTime, &filetime_zero, sizeof(FILETIME)),
       "expected zero ExpireTime\n");
    ok(!memcmp(&lpCacheEntryInfo->LastModifiedTime, &filetime_zero, sizeof(FILETIME)),
       "expected zero LastModifiedTime\n");
    ok(lpCacheEntryInfo->CacheEntryType == (NORMAL_CACHE_ENTRY|URLHISTORY_CACHE_ENTRY) ||
       broken(lpCacheEntryInfo->CacheEntryType == NORMAL_CACHE_ENTRY /* NT4/W2k */),
       "expected type NORMAL_CACHE_ENTRY|URLHISTORY_CACHE_ENTRY, got %08x\n",
       lpCacheEntryInfo->CacheEntryType);
    ok(!U(*lpCacheEntryInfo).dwExemptDelta, "expected dwExemptDelta 0, got %d\n",
       U(*lpCacheEntryInfo).dwExemptDelta);
    HeapFree(GetProcessHeap(), 0, lpCacheEntryInfo);

    /* A subsequent commit with a different time/type doesn't change the type */
    GetSystemTimeAsFileTime(&now);
    ret = CommitUrlCacheEntry(TEST_URL1, NULL, now, now, NORMAL_CACHE_ENTRY,
            (LPBYTE)ok_header, strlen(ok_header), NULL, NULL);
    ok(ret, "CommitUrlCacheEntry failed with error %d\n", GetLastError());
    cbCacheEntryInfo = 0;
    ret = GetUrlCacheEntryInfo(TEST_URL1, NULL, &cbCacheEntryInfo);
    ok(!ret, "GetUrlCacheEntryInfo should have failed\n");
    ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
       "expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());
    lpCacheEntryInfo = HeapAlloc(GetProcessHeap(), 0, cbCacheEntryInfo);
    ret = GetUrlCacheEntryInfo(TEST_URL1, lpCacheEntryInfo, &cbCacheEntryInfo);
    ok(ret, "GetUrlCacheEntryInfo failed with error %d\n", GetLastError());
    /* but it does change the time.. */
    todo_wine
    ok(memcmp(&lpCacheEntryInfo->ExpireTime, &filetime_zero, sizeof(FILETIME)),
       "expected positive ExpireTime\n");
    todo_wine
    ok(memcmp(&lpCacheEntryInfo->LastModifiedTime, &filetime_zero, sizeof(FILETIME)),
       "expected positive LastModifiedTime\n");
    ok(lpCacheEntryInfo->CacheEntryType == (NORMAL_CACHE_ENTRY|URLHISTORY_CACHE_ENTRY) ||
       broken(lpCacheEntryInfo->CacheEntryType == NORMAL_CACHE_ENTRY /* NT4/W2k */),
       "expected type NORMAL_CACHE_ENTRY|URLHISTORY_CACHE_ENTRY, got %08x\n",
       lpCacheEntryInfo->CacheEntryType);
    /* and set the headers. */
    todo_wine
    ok(lpCacheEntryInfo->dwHeaderInfoSize == 19,
       "expected headers size 19, got %d\n",
       lpCacheEntryInfo->dwHeaderInfoSize);
    HeapFree(GetProcessHeap(), 0, lpCacheEntryInfo);

    ret = CommitUrlCacheEntry(TEST_URL, filenameA, filetime_zero, filetime_zero, NORMAL_CACHE_ENTRY, NULL, 0, "html", NULL);
    ok(ret, "CommitUrlCacheEntry failed with error %d\n", GetLastError());

    cbCacheEntryInfo = 0;
    SetLastError(0xdeadbeef);
    ret = RetrieveUrlCacheEntryFile(TEST_URL, NULL, &cbCacheEntryInfo, 0);
    ok(!ret, "RetrieveUrlCacheEntryFile should have failed\n");
    ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
       "RetrieveUrlCacheEntryFile should have set last error to ERROR_INSUFFICIENT_BUFFER instead of %d\n", GetLastError());

    lpCacheEntryInfo = HeapAlloc(GetProcessHeap(), 0, cbCacheEntryInfo);
    ret = RetrieveUrlCacheEntryFile(TEST_URL, lpCacheEntryInfo, &cbCacheEntryInfo, 0);
    ok(ret, "RetrieveUrlCacheEntryFile failed with error %d\n", GetLastError());

    check_cache_entry_infoA("RetrieveUrlCacheEntryFile", lpCacheEntryInfo);

    HeapFree(GetProcessHeap(), 0, lpCacheEntryInfo);

    cbCacheEntryInfo = 0;
    SetLastError(0xdeadbeef);
    ret = RetrieveUrlCacheEntryFile(TEST_URL1, NULL, &cbCacheEntryInfo, 0);
    ok(!ret, "RetrieveUrlCacheEntryFile should have failed\n");
    ok(GetLastError() == ERROR_INVALID_DATA,
       "RetrieveUrlCacheEntryFile should have set last error to ERROR_INVALID_DATA instead of %d\n", GetLastError());

    if (pUnlockUrlCacheEntryFileA)
    {
        ret = pUnlockUrlCacheEntryFileA(TEST_URL, 0);
        ok(ret, "UnlockUrlCacheEntryFileA failed with error %d\n", GetLastError());
    }

    /* test Find*UrlCacheEntry functions */
    test_find_url_cache_entriesA();

    test_GetUrlCacheEntryInfoExA();
    test_RetrieveUrlCacheEntryA();
    test_IsUrlCacheEntryExpiredA();

    if (pDeleteUrlCacheEntryA)
    {
        ret = pDeleteUrlCacheEntryA(TEST_URL);
        ok(ret, "DeleteUrlCacheEntryA failed with error %d\n", GetLastError());
        ret = pDeleteUrlCacheEntryA(TEST_URL1);
        ok(ret, "DeleteUrlCacheEntryA failed with error %d\n", GetLastError());
    }

    SetLastError(0xdeadbeef);
    ret = DeleteFile(filenameA);
    todo_wine
    ok(!ret && GetLastError() == ERROR_FILE_NOT_FOUND, "local file should no longer exist\n");

    /* Creating two entries with the same URL */
    ret = CreateUrlCacheEntry(TEST_URL, 0, "html", filenameA, 0);
    ok(ret, "CreateUrlCacheEntry failed with error %d\n", GetLastError());

    ret = CreateUrlCacheEntry(TEST_URL, 0, "html", filenameA1, 0);
    ok(ret, "CreateUrlCacheEntry failed with error %d\n", GetLastError());

    ok(lstrcmpiA(filenameA, filenameA1), "expected a different file name\n");

    create_and_write_file(filenameA, &zero_byte, sizeof(zero_byte));
    create_and_write_file(filenameA1, &zero_byte, sizeof(zero_byte));
    check_file_exists(filenameA);
    check_file_exists(filenameA1);

    ret = CommitUrlCacheEntry(TEST_URL, filenameA, filetime_zero,
            filetime_zero, NORMAL_CACHE_ENTRY, (LPBYTE)ok_header,
            strlen(ok_header), "html", NULL);
    ok(ret, "CommitUrlCacheEntry failed with error %d\n", GetLastError());
    check_file_exists(filenameA);
    check_file_exists(filenameA1);
    ret = CommitUrlCacheEntry(TEST_URL, filenameA1, filetime_zero,
            filetime_zero, COOKIE_CACHE_ENTRY, NULL, 0, "html", NULL);
    ok(ret, "CommitUrlCacheEntry failed with error %d\n", GetLastError());
    /* By committing the same URL a second time, the prior entry is
     * overwritten...
     */
    cbCacheEntryInfo = 0;
    SetLastError(0xdeadbeef);
    ret = GetUrlCacheEntryInfo(TEST_URL, NULL, &cbCacheEntryInfo);
    ok(!ret, "RetrieveUrlCacheEntryFile should have failed\n");
    ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
       "expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());
    lpCacheEntryInfo = HeapAlloc(GetProcessHeap(), 0, cbCacheEntryInfo);
    ret = GetUrlCacheEntryInfo(TEST_URL, lpCacheEntryInfo, &cbCacheEntryInfo);
    ok(ret, "GetUrlCacheEntryInfo failed with error %d\n", GetLastError());
    /* with the previous entry type retained.. */
    ok(lpCacheEntryInfo->CacheEntryType & NORMAL_CACHE_ENTRY,
       "expected cache entry type NORMAL_CACHE_ENTRY, got %d (0x%08x)\n",
       lpCacheEntryInfo->CacheEntryType, lpCacheEntryInfo->CacheEntryType);
    /* and the headers overwritten.. */
    todo_wine
    ok(!lpCacheEntryInfo->dwHeaderInfoSize, "expected headers size 0, got %d\n",
       lpCacheEntryInfo->dwHeaderInfoSize);
    HeapFree(GetProcessHeap(), 0, lpCacheEntryInfo);
    /* and the previous filename shouldn't exist. */
    todo_wine
    check_file_not_exists(filenameA);
    check_file_exists(filenameA1);

    if (pDeleteUrlCacheEntryA)
    {
        ret = pDeleteUrlCacheEntryA(TEST_URL);
        ok(ret, "DeleteUrlCacheEntryA failed with error %d\n", GetLastError());
        todo_wine
        check_file_not_exists(filenameA);
        todo_wine
        check_file_not_exists(filenameA1);
        /* Just in case, clean up files */
        DeleteFileA(filenameA1);
        DeleteFileA(filenameA);
    }

    /* Check whether a retrieved cache entry can be deleted before it's
     * unlocked:
     */
    ret = CreateUrlCacheEntry(TEST_URL, 0, "html", filenameA, 0);
    ok(ret, "CreateUrlCacheEntry failed with error %d\n", GetLastError());
    ret = CommitUrlCacheEntry(TEST_URL, filenameA, filetime_zero, filetime_zero,
            NORMAL_CACHE_ENTRY, NULL, 0, "html", NULL);
    ok(ret, "CommitUrlCacheEntry failed with error %d\n", GetLastError());

    cbCacheEntryInfo = 0;
    SetLastError(0xdeadbeef);
    ret = RetrieveUrlCacheEntryFile(TEST_URL, NULL, &cbCacheEntryInfo, 0);
    ok(!ret, "RetrieveUrlCacheEntryFile should have failed\n");
    ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
       "expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());

    lpCacheEntryInfo = HeapAlloc(GetProcessHeap(), 0, cbCacheEntryInfo);
    ret = RetrieveUrlCacheEntryFile(TEST_URL, lpCacheEntryInfo,
            &cbCacheEntryInfo, 0);
    ok(ret, "RetrieveUrlCacheEntryFile failed with error %d\n", GetLastError());

    HeapFree(GetProcessHeap(), 0, lpCacheEntryInfo);

    if (pDeleteUrlCacheEntryA)
    {
        ret = pDeleteUrlCacheEntryA(TEST_URL);
        todo_wine
        ok(!ret, "Expected failure\n");
        todo_wine
        ok(GetLastError() == ERROR_SHARING_VIOLATION,
           "Expected ERROR_SHARING_VIOLATION, got %d\n", GetLastError());
        check_file_exists(filenameA);
    }
    if (pUnlockUrlCacheEntryFileA)
    {
        check_file_exists(filenameA);
        ret = pUnlockUrlCacheEntryFileA(TEST_URL, 0);
        todo_wine
        ok(ret, "UnlockUrlCacheEntryFileA failed: %d\n", GetLastError());
        /* By unlocking the already-deleted cache entry, the file associated
         * with it is deleted..
         */
        todo_wine
        check_file_not_exists(filenameA);
        /* (just in case, delete file) */
        DeleteFileA(filenameA);
    }
    if (pDeleteUrlCacheEntryA)
    {
        /* and a subsequent deletion should fail. */
        ret = pDeleteUrlCacheEntryA(TEST_URL);
        ok(!ret, "Expected failure\n");
        ok(GetLastError() == ERROR_FILE_NOT_FOUND,
           "expected ERROR_FILE_NOT_FOUND, got %d\n", GetLastError());
    }

    /* Test whether preventing a file from being deleted causes
     * DeleteUrlCacheEntryA to fail.
     */
    ret = CreateUrlCacheEntry(TEST_URL, 0, "html", filenameA, 0);
    ok(ret, "CreateUrlCacheEntry failed with error %d\n", GetLastError());

    create_and_write_file(filenameA, &zero_byte, sizeof(zero_byte));
    check_file_exists(filenameA);

    ret = CommitUrlCacheEntry(TEST_URL, filenameA, filetime_zero,
            filetime_zero, NORMAL_CACHE_ENTRY, (LPBYTE)ok_header,
            strlen(ok_header), "html", NULL);
    ok(ret, "CommitUrlCacheEntry failed with error %d\n", GetLastError());
    check_file_exists(filenameA);
    hFile = CreateFileA(filenameA, GENERIC_READ, 0, NULL, OPEN_EXISTING,
            FILE_ATTRIBUTE_NORMAL, NULL);
    ok(hFile != INVALID_HANDLE_VALUE, "CreateFileA failed: %d\n",
       GetLastError());
    if (pDeleteUrlCacheEntryA)
    {
        /* DeleteUrlCacheEntryA should succeed.. */
        ret = pDeleteUrlCacheEntryA(TEST_URL);
        ok(ret, "DeleteUrlCacheEntryA failed with error %d\n", GetLastError());
    }
    CloseHandle(hFile);
    if (pDeleteUrlCacheEntryA)
    {
        /* and a subsequent deletion should fail.. */
        ret = pDeleteUrlCacheEntryA(TEST_URL);
        ok(!ret, "Expected failure\n");
        ok(GetLastError() == ERROR_FILE_NOT_FOUND,
           "expected ERROR_FILE_NOT_FOUND, got %d\n", GetLastError());
    }
    /* and the file should be untouched. */
    check_file_exists(filenameA);
    DeleteFileA(filenameA);

    /* Try creating a sticky entry.  Unlike non-sticky entries, the filename
     * must have been set already.
     */
    SetLastError(0xdeadbeef);
    ret = CommitUrlCacheEntry(TEST_URL, NULL, filetime_zero, filetime_zero,
            STICKY_CACHE_ENTRY, (LPBYTE)ok_header, strlen(ok_header), "html",
            NULL);
    ok(!ret, "expected failure\n");
    ok(GetLastError() == ERROR_INVALID_PARAMETER,
       "expected ERROR_INVALID_PARAMETER, got %d\n", GetLastError());
    SetLastError(0xdeadbeef);
    ret = CommitUrlCacheEntry(TEST_URL, NULL, filetime_zero, filetime_zero,
            NORMAL_CACHE_ENTRY|STICKY_CACHE_ENTRY,
            (LPBYTE)ok_header, strlen(ok_header), "html", NULL);
    ok(!ret, "expected failure\n");
    ok(GetLastError() == ERROR_INVALID_PARAMETER,
       "expected ERROR_INVALID_PARAMETER, got %d\n", GetLastError());
    ret = CreateUrlCacheEntry(TEST_URL, 0, "html", filenameA, 0);
    ok(ret, "CreateUrlCacheEntry failed with error %d\n", GetLastError());
    create_and_write_file(filenameA, &zero_byte, sizeof(zero_byte));
    ret = CommitUrlCacheEntry(TEST_URL, filenameA, filetime_zero, filetime_zero,
            NORMAL_CACHE_ENTRY|STICKY_CACHE_ENTRY,
            (LPBYTE)ok_header, strlen(ok_header), "html", NULL);
    ok(ret, "CommitUrlCacheEntry failed with error %d\n", GetLastError());
    cbCacheEntryInfo = 0;
    SetLastError(0xdeadbeef);
    ret = GetUrlCacheEntryInfo(TEST_URL, NULL, &cbCacheEntryInfo);
    ok(!ret, "RetrieveUrlCacheEntryFile should have failed\n");
    ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
       "expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());
    lpCacheEntryInfo = HeapAlloc(GetProcessHeap(), 0, cbCacheEntryInfo);
    ret = GetUrlCacheEntryInfo(TEST_URL, lpCacheEntryInfo, &cbCacheEntryInfo);
    ok(ret, "GetUrlCacheEntryInfo failed with error %d\n", GetLastError());
    ok(lpCacheEntryInfo->CacheEntryType & (NORMAL_CACHE_ENTRY|STICKY_CACHE_ENTRY),
       "expected cache entry type NORMAL_CACHE_ENTRY | STICKY_CACHE_ENTRY, got %d (0x%08x)\n",
       lpCacheEntryInfo->CacheEntryType, lpCacheEntryInfo->CacheEntryType);
    ok(U(*lpCacheEntryInfo).dwExemptDelta == 86400,
       "expected dwExemptDelta 864000, got %d\n",
       U(*lpCacheEntryInfo).dwExemptDelta);
    HeapFree(GetProcessHeap(), 0, lpCacheEntryInfo);
    if (pDeleteUrlCacheEntryA)
    {
        ret = pDeleteUrlCacheEntryA(TEST_URL);
        ok(ret, "DeleteUrlCacheEntryA failed with error %d\n", GetLastError());
        /* When explicitly deleting the cache entry, the file is also deleted */
        todo_wine
        check_file_not_exists(filenameA);
    }
    /* Test once again, setting the exempt delta via SetUrlCacheEntryInfo */
    ret = CreateUrlCacheEntry(TEST_URL, 0, "html", filenameA, 0);
    ok(ret, "CreateUrlCacheEntry failed with error %d\n", GetLastError());
    create_and_write_file(filenameA, &zero_byte, sizeof(zero_byte));
    ret = CommitUrlCacheEntry(TEST_URL, filenameA, filetime_zero, filetime_zero,
            NORMAL_CACHE_ENTRY|STICKY_CACHE_ENTRY,
            (LPBYTE)ok_header, strlen(ok_header), "html", NULL);
    ok(ret, "CommitUrlCacheEntry failed with error %d\n", GetLastError());
    cbCacheEntryInfo = 0;
    SetLastError(0xdeadbeef);
    ret = GetUrlCacheEntryInfo(TEST_URL, NULL, &cbCacheEntryInfo);
    ok(!ret, "RetrieveUrlCacheEntryFile should have failed\n");
    ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER,
       "expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError());
    lpCacheEntryInfo = HeapAlloc(GetProcessHeap(), 0, cbCacheEntryInfo);
    ret = GetUrlCacheEntryInfo(TEST_URL, lpCacheEntryInfo, &cbCacheEntryInfo);
    ok(ret, "GetUrlCacheEntryInfo failed with error %d\n", GetLastError());
    ok(lpCacheEntryInfo->CacheEntryType & (NORMAL_CACHE_ENTRY|STICKY_CACHE_ENTRY),
       "expected cache entry type NORMAL_CACHE_ENTRY | STICKY_CACHE_ENTRY, got %d (0x%08x)\n",
       lpCacheEntryInfo->CacheEntryType, lpCacheEntryInfo->CacheEntryType);
    ok(U(*lpCacheEntryInfo).dwExemptDelta == 86400,
       "expected dwExemptDelta 864000, got %d\n",
       U(*lpCacheEntryInfo).dwExemptDelta);
    U(*lpCacheEntryInfo).dwExemptDelta = 0;
    ret = SetUrlCacheEntryInfoA(TEST_URL, lpCacheEntryInfo,
            CACHE_ENTRY_EXEMPT_DELTA_FC);
    ok(ret, "SetUrlCacheEntryInfo failed: %d\n", GetLastError());
    ret = GetUrlCacheEntryInfo(TEST_URL, lpCacheEntryInfo, &cbCacheEntryInfo);
    ok(ret, "GetUrlCacheEntryInfo failed with error %d\n", GetLastError());
    ok(!U(*lpCacheEntryInfo).dwExemptDelta, "expected dwExemptDelta 0, got %d\n",
       U(*lpCacheEntryInfo).dwExemptDelta);
    /* See whether a sticky cache entry has the flag cleared once the exempt
     * delta is meaningless.
     */
    ok(lpCacheEntryInfo->CacheEntryType & (NORMAL_CACHE_ENTRY|STICKY_CACHE_ENTRY),
       "expected cache entry type NORMAL_CACHE_ENTRY | STICKY_CACHE_ENTRY, got %d (0x%08x)\n",
       lpCacheEntryInfo->CacheEntryType, lpCacheEntryInfo->CacheEntryType);
    HeapFree(GetProcessHeap(), 0, lpCacheEntryInfo);
    if (pDeleteUrlCacheEntryA)
    {
        ret = pDeleteUrlCacheEntryA(TEST_URL);
        ok(ret, "DeleteUrlCacheEntryA failed with error %d\n", GetLastError());
        todo_wine
        check_file_not_exists(filenameA);
    }
}
Ejemplo n.º 30
0
Archivo: file.c Proyecto: NativeAPI/dmd
int File::write()
{
#if POSIX
    int fd;
    ssize_t numwritten;
    char *name;

    name = this->name->toChars();
    fd = open(name, O_CREAT | O_WRONLY | O_TRUNC, (6 << 6) | (4 << 3) | 4);
    if (fd == -1)
        goto err;

    numwritten = ::write(fd, buffer, len);
    if (len != numwritten)
        goto err2;

    if (close(fd) == -1)
        goto err;

    if (touchtime)
    {   struct utimbuf ubuf;

        ubuf.actime = ((struct stat *)touchtime)->st_atime;
        ubuf.modtime = ((struct stat *)touchtime)->st_mtime;
        if (utime(name, &ubuf))
            goto err;
    }
    return 0;

err2:
    close(fd);
    ::remove(name);
err:
    return 1;
#elif _WIN32
    HANDLE h;
    DWORD numwritten;
    char *name;

    name = this->name->toChars();
    h = CreateFileA(name,GENERIC_WRITE,0,NULL,CREATE_ALWAYS,
        FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN,NULL);
    if (h == INVALID_HANDLE_VALUE)
        goto err;

    if (WriteFile(h,buffer,len,&numwritten,NULL) != TRUE)
        goto err2;

    if (len != numwritten)
        goto err2;

    if (touchtime) {
        SetFileTime(h, NULL, NULL, &((WIN32_FIND_DATAA *)touchtime)->ftLastWriteTime);
    }
    if (!CloseHandle(h))
        goto err;
    return 0;

err2:
    CloseHandle(h);
    DeleteFileA(name);
err:
    return 1;
#else
    assert(0);
#endif
}