Esempio n. 1
0
static int
_lzget(struct lzstate *lzs,BYTE *b) {
	if (lzs->getcur<lzs->getlen) {
		*b		= lzs->get[lzs->getcur++];
		return		1;
	} else {
		int ret = _lread(lzs->realfd,lzs->get,GETLEN);
		if (ret==HFILE_ERROR)
			return HFILE_ERROR;
		if (ret==0)
			return 0;
		lzs->getlen	= ret;
		lzs->getcur	= 1;
		*b		= *(lzs->get);
		return 1;
	}
}
Esempio n. 2
0
static BOOL GRPFILE_ReadFileToBuffer(LPCSTR path, HLOCAL *phBuffer,
				     INT *piSize)
{
  UINT    len, size;
  LPSTR  buffer;
  HLOCAL hBuffer, hNewBuffer;
  HFILE  file;

  file=_lopen(path, OF_READ);
  if (file == HFILE_ERROR) return FALSE;

  size = 0;
  hBuffer = LocalAlloc(LMEM_FIXED, MALLOCHUNK + 1);
  if (!hBuffer) return FALSE;
  buffer = LocalLock(hBuffer);

  while ((len = _lread(file, buffer + size, MALLOCHUNK))
	 == MALLOCHUNK)
    {
      size += len;
      hNewBuffer = LocalReAlloc(hBuffer, size + MALLOCHUNK + 1,
				LMEM_MOVEABLE);
      if (!hNewBuffer)
	{
	  LocalFree(hBuffer);
	  return FALSE;
	}
      hBuffer = hNewBuffer;
      buffer = LocalLock(hBuffer);
    }

  _lclose(file);

  if (len == (UINT)HFILE_ERROR)
    {
      LocalFree(hBuffer);
      return FALSE;
    }

  size += len;
  buffer[size] = 0;

  *phBuffer = hBuffer;
  *piSize   = size;
  return TRUE;
}
Esempio n. 3
0
void RecordsList_Populate_fn(char * fn, int i) {
	char filename[2000];
	wsprintf(filename, ".\\records\\%s", fn);
	
	CreateDirectory(".\\records", 0);

	OFSTRUCT of;
	HFILE in = OpenFile(filename, &of, OF_READ);
	if (in == HFILE_ERROR) {
		RecordsListDlg_list.AddRow(fn, i);
		RecordsListDlg_list.FillRow("Error", 1, i);
		return;
	}
	DWORD len = GetFileSize((HANDLE)in, 0);
	if (len < 300) {
		RecordsListDlg_list.AddRow(fn, i);
		RecordsListDlg_list.FillRow("File too short", 1, i);
		return;
	}
	PlayBackBuffer.buffer = filename;
	_lread(in, PlayBackBuffer.buffer, 300);
	PlayBackBuffer.ptr = PlayBackBuffer.buffer + 4;
	PlayBackBuffer.end = PlayBackBuffer.buffer + len;
	_lclose(in);
	char APPC[128];
	PlayBackBuffer.load_str(APPC, 128);
	PlayBackBuffer.ptr = PlayBackBuffer.buffer + 132;	
	PlayBackBuffer.load_str(GAME,128);
	PlayBackBuffer.ptr = PlayBackBuffer.buffer + 260;
	time_t timee = PlayBackBuffer.load_unsigned_int();
	playerno = PlayBackBuffer.load_int();
	numplayers = PlayBackBuffer.load_int();
	RecordsListDlg_list.AddRow(GAME,i);
	RecordsListDlg_list.FillRow(APPC,1,i);
	///**/time((time_t *)&timee);
	tm * ecx = localtime(&timee);
	if(!ecx) 
	{
		MessageBox(0,"Failed to read a replay file!","Failure!",0);
		return;
	}
	wsprintf(filename, "%02d:%02d on %02d/%02d/%02d",ecx->tm_hour,ecx->tm_min, ecx->tm_mon +1, ecx->tm_mday, ecx->tm_year +1900);
	RecordsListDlg_list.FillRow(filename,2,i);
	RecordsListDlg_list.FillRow(fn,3,i);
}
Esempio n. 4
0
/*************************************************************************

  Function:  ReadDIBFile (int)

   Purpose:  Reads in the specified DIB file into a global chunk of
             memory.

   Returns:  A handle to a dib (hDIB) if successful.
             NULL if an error occurs.

  Comments:  BITMAPFILEHEADER is stripped off of the DIB.  Everything
             from the end of the BITMAPFILEHEADER structure on is
             returned in the global memory handle.

   History:   Date      Author      Reason

             6/1/91    Created
             6/27/91   Removed PM bitmap conversion routines.
             6/31/91   Removed logic which overallocated memory
                       (to account for bad display drivers).
            11/08/91   Again removed logic which overallocated
                       memory (it had creeped back in!)

*************************************************************************/
static HANDLE ReadDIBFile (int hFile,int dwBitsSize)
{
   BITMAPFILEHEADER   bmfHeader;
   HANDLE             hDIB;
   LPSTR              pDIB;



   // Go read the DIB file header and check if it's valid.

   if ((_lread (hFile, (LPSTR) &bmfHeader, sizeof (bmfHeader)) != sizeof (bmfHeader)) ||
        (bmfHeader.bfType != DIB_HEADER_MARKER))
      {
        //              ShowDbgMsg("Not a DIB file!");
                return NULL;
      }

   // Allocate memory for DIB

   hDIB = GlobalAlloc (GMEM_SHARE|GMEM_MOVEABLE | GMEM_ZEROINIT, dwBitsSize - sizeof(BITMAPFILEHEADER));

   if (hDIB == 0)
     {
       //       ShowDbgMsg("Couldn't allocate memory!");
                return NULL;
     }

   pDIB = GlobalLock (hDIB);

   // Go read the bits.

   if (!MyRead (hFile, pDIB, dwBitsSize - sizeof(BITMAPFILEHEADER)))
      {
      GlobalUnlock (hDIB);
      GlobalFree   (hDIB);
      //  ShowDbgMsg("Error reading file!");
      return NULL;
      }


   GlobalUnlock (hDIB);
   return hDIB;
}
Esempio n. 5
0
static BOOL FileIsPlaceable( LPCSTR szFileName )
{
  HFILE		hInFile;
  APMFILEHEADER	apmh;

  if( (hInFile = _lopen( szFileName, OF_READ ) ) == HFILE_ERROR )
    return FALSE;

  if( _lread( hInFile, &apmh, sizeof(APMFILEHEADER) )
      != sizeof(APMFILEHEADER) )
    {
      _lclose( hInFile );
      return FALSE;
    }
  _lclose( hInFile );

  /* Is it placeable? */
  return (apmh.key == APMHEADER_KEY);
}
Esempio n. 6
0
/*************************************************************************

  Function:  MyRead (int, LPSTR, DWORD)

   Purpose:  Routine to read files greater than 64K in size.

   Returns:  TRUE if successful.
             FALSE if an error occurs.

  Comments:

   History:   Date     Reason

             6/1/91    Created

*************************************************************************/
static BOOL MyRead (int hFile, LPSTR lpBuffer, DWORD dwSize)
{
   char *lpInBuf = (char *) lpBuffer;
   int       nBytes;


   while (dwSize)
      {
      nBytes = (int) (dwSize > (DWORD) BYTES_PER_READ ? BYTES_PER_READ :
                                                        LOWORD (dwSize));

      if (_lread (hFile, (LPSTR) lpInBuf, nBytes) != (WORD) nBytes)
         return FALSE;

      dwSize  -= nBytes;
      lpInBuf += nBytes;
      }

   return TRUE;
}
Esempio n. 7
0
UINT
DIAMONDAPI
SpdFdiRead(
    IN  int   Handle,
    OUT PVOID pv,
    IN  UINT  ByteCount
    )

/*++

Routine Description:

    Callback used by FDICopy to read from a file.

Arguments:

    Handle - supplies handle to open file to be read from.

    pv - supplies pointer to buffer to receive bytes we read.

    ByteCount - supplies number of bytes to read.

Return Value:

    Number of bytes read (ByteCount) or -1 if an error occurs.

--*/

{
    UINT rc;

    rc = _lread((HFILE)Handle,pv,ByteCount);

    if(rc == HFILE_ERROR) {
        rc = (UINT)(-1);
        DiamondLastIoError = LZERROR_READ;
    }

    return(rc);
}
Esempio n. 8
0
BOOL CDDB::ConstructDDBFromFile(		// build a CDDB object from a DIB in a file
	LPCSTR lpszFileName,						// name of file containing DIB data
	HDC hDC,										// device context to use for call to CreateDIBitmap()
	BOOL fUseDIBPalette,						// flag indicating if DIB bitmap should be used for conversion
	HPALETTE hPalette)
{
	/*
	// Attempt to open the file and read in the BITMAPFILEHEADER structure.
	*/
		
	OFSTRUCT of;
	HFILE hfDIB;
		
	if ((hfDIB = OpenFile(lpszFileName, &of, OF_READ|OF_SHARE_DENY_WRITE)) != HFILE_ERROR)
	{
		BITMAPFILEHEADER BitmapFileHeader;
			
		if (_lread(hfDIB, &BitmapFileHeader, sizeof(BitmapFileHeader)) == sizeof(BitmapFileHeader))
		{
			/*
			// Validate the header.
			*/
				
			if (BitmapFileHeader.bfType == 0x4d42)
			{
				/*
				// Read in the rest of the file.
				*/
					
				HGLOBAL hDIB;
				long dwDIBSize;
					
				dwDIBSize = BitmapFileHeader.bfSize-sizeof(BitmapFileHeader);
					
				if ((hDIB = GlobalAlloc(GMEM_MOVEABLE, dwDIBSize)) != NULL)
				{
					LPBITMAPINFOHEADER lpHeader;
			
					if ((lpHeader = (LPBITMAPINFOHEADER)GlobalLock(hDIB)) != NULL)
					{
						if (_hread(hfDIB, lpHeader, dwDIBSize) == dwDIBSize)
						{
							/*
							// Validate the header size.
							*/
								
							if (lpHeader->biSize == sizeof(BITMAPINFOHEADER))
							{
								/*
								// Create the DDB.
								*/
									
								ConstructDDB(			// construct a DDB from the DIB data
									lpHeader,				// pointer to BITMAPINFOHEADER structure
									hDC,						// device context to use for call to CreateDIBitmap()
									fUseDIBPalette,		// flag indicating if DIB bitmap should be used for conversion
									hPalette);
							}
						}
							
						GlobalUnlock(hDIB);
						lpHeader = NULL;
					}
						
					GlobalFree(hDIB);
					hDIB = NULL;
				}
			}
		}
			
		_lclose(hfDIB);
		hfDIB = HFILE_ERROR;
	}
	
	return IsValid();
}
Esempio n. 9
0
//=============================================================================
//  This routine loads a 256 color PCX file. The file can be a standalone
// PCX file or it can be combined with a resource. If the data is part
// of a resource, the rshandle flag will be set. The bitmap data is read
// into a buffer that is the size of the bitmap + 4 bytes. The first 4
// bytes in the buffer contain the width and height of the bitmap.
//=============================================================================
unsigned char *AckReadPCX(char *filename)
{
    int32_t i;
    int mode=NORMAL,nbytes;
    char abyte,*p;
    short   handle;
    PcxFile *pcx;

pcx = &pcxGlobal;
// Open the file since no resource is open.
if (!rsHandle)
    {
    handle = _lopen(filename,OF_READ); // Open the file for reading
    if (handle == HFILE_ERROR) // Make sure file is opened
        {
        ErrorCode = ERR_BADFILE;
        return NULL;
        }
    }
else // Use the resource instead
    {
    handle = rsHandle; // Use the handle to the resource file
    // Move to the location in the resource where the data is stored
    _llseek(handle,(int)(rbaTable[(int64_t)filename]),SEEK_SET);
    }


_lread(handle,&pcx->hdr,sizeof(PcxHeader)); // Read in the header data
pcx->width=1+pcx->hdr.xmax-pcx->hdr.xmin;   // Store width and height
pcx->height=1+pcx->hdr.ymax-pcx->hdr.ymin;
// Store number of bytes used for image
pcx->imagebytes=(unsigned int)(pcx->width*pcx->height);

// Make sure bitmap is correct size
if (pcx->imagebytes > PCX_MAX_SIZE)
    {
    if (!rsHandle)
        _lclose(handle);
    ErrorCode = ERR_INVALIDFORM;
    return(NULL);
    }

// Allocate size for bitmap. 4 extra bytes are included to give
// room to store bitmap width and height info.
pcx->bitmap=(UCHAR*)AckMalloc(pcx->imagebytes+4);

if (pcx->bitmap == NULL)    // Make sure memory is allocated
    {
    if (!rsHandle)
        _lclose(handle);
    ErrorCode = ERR_NOMEMORY;
    return(NULL);
    }
p=(char*)(&pcx->bitmap[4]);      // Get address of data area

// Loop and read in pixel data for bitmap
// Uses RLE decompression
for (i=0;i<pcx->imagebytes;i++)
    {
    if (mode == NORMAL)     // Normal color read mode
        {
        _lread(handle,&abyte,1);    // Read in pixel value from file
        if ((unsigned char)abyte > 0xbf) // Value read > 191
            {
            nbytes=abyte & 0x3f;    // Get the RLE counter
            _lread(handle,&abyte,1);
            if (--nbytes > 0)       // Is counter greater than 1?
                mode=RLE;           // Yes, we're in RLE mode
            }
        }
    else if (--nbytes == 0)         // When counter down to 0
            mode=NORMAL;            // return to color read mode
    *p++=abyte;                     // Store pixel value
    }

// Get palette from PCX file, 256 color palette store 768 bytes from
// end of file. For a resource file we need to find the position where
// the next file starts and then backup 768 bytes
if (rsHandle)
    _llseek(handle,(int)(rbaTable[(int64_t)(filename + 1)])-768,SEEK_CUR);
else
    _llseek(handle,-768,SEEK_END);

// Store the palette data in our global colordat array
_lread(handle,colordat,768);
p=(char*)colordat;
for (i=0;i<768;i++)            // bit shift palette
    *p++ = *p >> 2;

if (!rsHandle)                  // Close pcx file if not using a resource
    _lclose(handle);

// Add in bitmap width and height to first 4 bytes of buffer
p = (char*)pcx->bitmap;
(*(short *)p) = pcx->width;
p += sizeof(short);
(*(short *)p) = pcx->height;

return(pcx->bitmap);         // return bitmap buffer
}
Esempio n. 10
0
/*
	ExpandVolume

	Sets the volume size in the volume header (and backup header) to a larger value,
	and resizes the filesystem within the volume (only NTFS supported)

	Parameters:

		hwndDlg : HWND
			[in] handle to progress dialog

		lpszVolume : char *
			[in] Pointer to a string that contains the path to the truecrypt volume

		pVolumePassword : Password *
			[in] Pointer to the volume password

		newHostSize : uint64
			[in] new value of the volume host size (can be zero for devices,
			     which means the volume should use all space of the host device)

		initFreeSpace : BOOL
			[in] if true, the new volume space will be initalized with random data

	Return value:

		int with Truecrypt error code (ERR_SUCCESS on success)

	Remarks: a lot of code is from TrueCrypt 'Common\Password.c' :: ChangePwd()

*/
static int ExpandVolume (HWND hwndDlg, wchar_t *lpszVolume, Password *pVolumePassword, int VolumePkcs5, int VolumePim, uint64 newHostSize, BOOL initFreeSpace)
{
    int nDosLinkCreated = 1, nStatus = ERR_OS_ERROR;
    wchar_t szDiskFile[TC_MAX_PATH], szCFDevice[TC_MAX_PATH];
    wchar_t szDosDevice[TC_MAX_PATH];
    char buffer[TC_VOLUME_HEADER_EFFECTIVE_SIZE];
    PCRYPTO_INFO cryptoInfo = NULL, ci = NULL;
    void *dev = INVALID_HANDLE_VALUE;
    DWORD dwError;
    BOOL bDevice;
    uint64 hostSize=0, newDataAreaSize, currentVolSize;
    DWORD HostSectorSize;
    FILETIME ftCreationTime;
    FILETIME ftLastWriteTime;
    FILETIME ftLastAccessTime;
    BOOL bTimeStampValid = FALSE;
    LARGE_INTEGER headerOffset;
    BOOL backupHeader;
    byte *wipeBuffer = NULL;
    uint32 workChunkSize = TC_VOLUME_HEADER_GROUP_SIZE;

    if (pVolumePassword->Length == 0) return -1;

    WaitCursor ();

    CreateFullVolumePath (szDiskFile, sizeof(szDiskFile), lpszVolume, &bDevice);

    if (bDevice == FALSE)
    {
        wcscpy (szCFDevice, szDiskFile);
    }
    else
    {
        nDosLinkCreated = FakeDosNameForDevice (szDiskFile, szDosDevice, sizeof(szDosDevice), szCFDevice, sizeof(szCFDevice), FALSE);

        if (nDosLinkCreated != 0) // note: nStatus == ERR_OS_ERROR
            goto error;
    }

    dev = CreateFile (szCFDevice, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);

    if (dev == INVALID_HANDLE_VALUE)
        goto error;

    if (bDevice)
    {
        /* This is necessary to determine the hidden volume header offset */

        if (dev == INVALID_HANDLE_VALUE)
        {
            goto error;
        }
        else
        {
            PARTITION_INFORMATION diskInfo;
            DWORD dwResult;
            BOOL bResult;

            bResult = GetPartitionInfo (lpszVolume, &diskInfo);

            if (bResult)
            {
                hostSize = diskInfo.PartitionLength.QuadPart;
                HostSectorSize = TC_SECTOR_SIZE_FILE_HOSTED_VOLUME; //TO DO: get the real host disk sector size
            }
            else
            {
                DISK_GEOMETRY driveInfo;

                bResult = DeviceIoControl (dev, IOCTL_DISK_GET_DRIVE_GEOMETRY, NULL, 0,
                                           &driveInfo, sizeof (driveInfo), &dwResult, NULL);

                if (!bResult)
                    goto error;

                hostSize = driveInfo.Cylinders.QuadPart * driveInfo.BytesPerSector *
                           driveInfo.SectorsPerTrack * driveInfo.TracksPerCylinder;

                HostSectorSize = driveInfo.BytesPerSector;
            }

            if (hostSize == 0)
            {
                nStatus = ERR_VOL_SIZE_WRONG;
                goto error;
            }
        }
    }
    else
    {
        LARGE_INTEGER fileSize;
        if (!GetFileSizeEx (dev, &fileSize))
        {
            nStatus = ERR_OS_ERROR;
            goto error;
        }

        hostSize = fileSize.QuadPart;
        HostSectorSize = TC_SECTOR_SIZE_FILE_HOSTED_VOLUME; //TO DO: get the real host disk sector size
    }

    if (Randinit ())
    {
        if (CryptoAPILastError == ERROR_SUCCESS)
            nStatus = ERR_RAND_INIT_FAILED;
        else
            nStatus = ERR_CAPI_INIT_FAILED;
        goto error;
    }

    if (!bDevice && bPreserveTimestamp)
    {
        /* Remember the container modification/creation date and time, (used to reset file date and time of
        file-hosted volumes after password change (or attempt to), in order to preserve plausible deniability
        of hidden volumes (last password change time is stored in the volume header). */

        if (GetFileTime ((HANDLE) dev, &ftCreationTime, &ftLastAccessTime, &ftLastWriteTime) == 0)
        {
            bTimeStampValid = FALSE;
            MessageBoxW (hwndDlg, GetString ("GETFILETIME_FAILED_PW"), lpszTitle, MB_OK | MB_ICONEXCLAMATION);
        }
        else
            bTimeStampValid = TRUE;
    }

    // Seek the volume header
    headerOffset.QuadPart = TC_VOLUME_HEADER_OFFSET;

    if (!SetFilePointerEx ((HANDLE) dev, headerOffset, NULL, FILE_BEGIN))
    {
        nStatus = ERR_OS_ERROR;
        goto error;
    }

    /* Read in volume header */
    nStatus = _lread ((HFILE) dev, buffer, sizeof (buffer));
    if (nStatus != sizeof (buffer))
    {
        // Windows may report EOF when reading sectors from the last cluster of a device formatted as NTFS
        memset (buffer, 0, sizeof (buffer));
    }

    /* Try to decrypt the header */

    nStatus = ReadVolumeHeader (FALSE, buffer, pVolumePassword, VolumePkcs5, VolumePim, FALSE, &cryptoInfo, NULL);
    if (nStatus == ERR_CIPHER_INIT_WEAK_KEY)
        nStatus = 0;	// We can ignore this error here

    if (nStatus != 0)
    {
        cryptoInfo = NULL;
        goto error;
    }

    if (cryptoInfo->HeaderFlags & TC_HEADER_FLAG_ENCRYPTED_SYSTEM)
    {
        nStatus = ERR_SYS_HIDVOL_HEAD_REENC_MODE_WRONG;
        goto error;
    }

    if (bDevice && newHostSize == 0)
    {
        // this means we shall take all host space as new volume size
        newHostSize = hostSize;
    }

    if ( newHostSize % cryptoInfo->SectorSize != 0  || newHostSize > TC_MAX_VOLUME_SIZE || (bDevice && newHostSize > hostSize) )
    {
        // 1. must be multiple of sector size
        // 2. truecrypt volume size limit
        // 3. for devices volume size can't be larger than host size
        cryptoInfo = NULL;
        nStatus = ERR_PARAMETER_INCORRECT;
        goto error;
    }

    newDataAreaSize = GetVolumeDataAreaSize (newHostSize, cryptoInfo->LegacyVolume);

    if (cryptoInfo->LegacyVolume)
    {
        if (bDevice)
        {
            if (initFreeSpace)
            {
                // unsupported
                cryptoInfo = NULL;
                nStatus = ERR_PARAMETER_INCORRECT;
                goto error;
            }
            else
            {
                // note: dummy value (only used for parameter checks)
                cryptoInfo->VolumeSize.Value = newDataAreaSize - TC_MINVAL_FS_EXPAND;
            }
        }
        else
        {
            cryptoInfo->VolumeSize.Value = GetVolumeDataAreaSize (hostSize, TRUE);
        }
    }

    currentVolSize = GetVolumeSizeByDataAreaSize (cryptoInfo->VolumeSize.Value, cryptoInfo->LegacyVolume);

    if ( newDataAreaSize < cryptoInfo->VolumeSize.Value + TC_MINVAL_FS_EXPAND )
    {
        // shrinking a volume or enlarging by less then TC_MINVAL_FS_EXPAND is not allowed
        cryptoInfo = NULL;
        nStatus = ERR_PARAMETER_INCORRECT;
        goto error;
    }

    InitProgressBar ( newHostSize, currentVolSize, FALSE, FALSE, FALSE, TRUE);

    if (bVolTransformThreadCancel)
    {
        SetLastError(0);
        nStatus = ERR_USER_ABORT;
        goto error;
    }

    if (!bDevice) {
        LARGE_INTEGER liNewSize;

        liNewSize.QuadPart=(LONGLONG)newHostSize;

        // Preallocate the file
        if (!SetFilePointerEx (dev, liNewSize, NULL, FILE_BEGIN)
                || !SetEndOfFile (dev)
                || SetFilePointer (dev, 0, NULL, FILE_BEGIN) != 0)
        {
            nStatus = ERR_OS_ERROR;
            goto error;
        }
    }

    if (initFreeSpace)
    {
        uint64 startSector;
        int64 num_sectors;

        // fill new space with random data
        startSector = currentVolSize/HostSectorSize ;
        num_sectors = (newHostSize/HostSectorSize) - startSector;

        if (bDevice && !StartFormatWriteThread())
        {
            nStatus = ERR_OS_ERROR;
            goto error;
        }

        DebugAddProgressDlgStatus(hwndDlg, L"Writing random data to new space ...\r\n");

        SetFormatSectorSize(HostSectorSize);
        nStatus = FormatNoFs (hwndDlg, startSector, num_sectors, dev, cryptoInfo, FALSE);

        dwError = GetLastError();
        StopFormatWriteThread();
        SetLastError (dwError);
    }
    else
    {
        UpdateProgressBar(newHostSize);
    }

    if (nStatus != ERR_SUCCESS)
    {
        dwError = GetLastError();
        DebugAddProgressDlgStatus(hwndDlg, L"Error: failed to write random data ...\r\n");
        if ( !bDevice ) {
            // restore original size of the container file
            LARGE_INTEGER liOldSize;
            liOldSize.QuadPart=(LONGLONG)hostSize;
            if (!SetFilePointerEx (dev, liOldSize, NULL, FILE_BEGIN) || !SetEndOfFile (dev))
            {
                DebugAddProgressDlgStatus(hwndDlg, L"Warning: failed to restore original size of the container file\r\n");
            }
        }
        SetLastError (dwError);
        goto error;
    }

    RandSetHashFunction (cryptoInfo->pkcs5);

    // Re-encrypt the volume header forn non-legacy volumes: backup header first
    backupHeader = TRUE;
    headerOffset.QuadPart = TC_VOLUME_HEADER_OFFSET + newHostSize - TC_VOLUME_HEADER_GROUP_SIZE;

    /* note: updating the header is not neccessary for legay volumes */
    while ( !cryptoInfo->LegacyVolume )
    {
        if (backupHeader)
            DebugAddProgressDlgStatus(hwndDlg, L"Writing re-encrypted backup header ...\r\n");
        else
            DebugAddProgressDlgStatus(hwndDlg, L"Writing re-encrypted primary header ...\r\n");

        // Prepare new volume header
        nStatus = CreateVolumeHeaderInMemory (hwndDlg, FALSE,
                                              buffer,
                                              cryptoInfo->ea,
                                              cryptoInfo->mode,
                                              pVolumePassword,
                                              cryptoInfo->pkcs5,
                                              VolumePim,
                                              (char*)(cryptoInfo->master_keydata),
                                              &ci,
                                              newDataAreaSize,
                                              0, // hiddenVolumeSize
                                              cryptoInfo->EncryptedAreaStart.Value,
                                              newDataAreaSize,
                                              cryptoInfo->RequiredProgramVersion,
                                              cryptoInfo->HeaderFlags,
                                              cryptoInfo->SectorSize,
                                              TRUE ); // use slow poll

        if (ci != NULL)
            crypto_close (ci);

        if (nStatus != 0)
            goto error;

        if (!SetFilePointerEx ((HANDLE) dev, headerOffset, NULL, FILE_BEGIN))
        {
            nStatus = ERR_OS_ERROR;
            goto error;
        }

        nStatus = _lwrite ((HFILE) dev, buffer, TC_VOLUME_HEADER_EFFECTIVE_SIZE);
        if (nStatus != TC_VOLUME_HEADER_EFFECTIVE_SIZE)
        {
            nStatus = ERR_OS_ERROR;
            goto error;
        }

        if ( ( backupHeader && !initFreeSpace )
                || ( bDevice
                     && !cryptoInfo->LegacyVolume
                     && !cryptoInfo->hiddenVolume
                     && cryptoInfo->HeaderVersion == 4	// BUG in TrueCrypt: doing this only for v4 make no sense
                     && (cryptoInfo->HeaderFlags & TC_HEADER_FLAG_NONSYS_INPLACE_ENC) != 0
                     && (cryptoInfo->HeaderFlags & ~TC_HEADER_FLAG_NONSYS_INPLACE_ENC) == 0 )
           )
        {
            //DebugAddProgressDlgStatus(hwndDlg, L"WriteRandomDataToReservedHeaderAreas() ...\r\n");
            nStatus = WriteRandomDataToReservedHeaderAreas (hwndDlg, dev, cryptoInfo, newDataAreaSize, !backupHeader, backupHeader);
            if (nStatus != ERR_SUCCESS)
                goto error;
        }

        FlushFileBuffers (dev);

        if (!backupHeader)
            break;

        backupHeader = FALSE;
        headerOffset.QuadPart = TC_VOLUME_HEADER_OFFSET; // offset for main header
    }

    /* header successfully updated */
    nStatus = ERR_SUCCESS;

    if (bVolTransformThreadCancel)
    {
        nStatus = ERR_USER_ABORT;
        goto error;
    }

    /* wipe old backup header */
    if ( !cryptoInfo->LegacyVolume )
    {
        byte wipeRandChars [TC_WIPE_RAND_CHAR_COUNT];
        byte wipeRandCharsUpdate [TC_WIPE_RAND_CHAR_COUNT];
        byte wipePass;
        UINT64_STRUCT unitNo;
        LARGE_INTEGER offset;
        WipeAlgorithmId wipeAlgorithm = TC_WIPE_35_GUTMANN;

        if (	!RandgetBytes (hwndDlg, wipeRandChars, TC_WIPE_RAND_CHAR_COUNT, TRUE)
                || !RandgetBytes (hwndDlg, wipeRandCharsUpdate, TC_WIPE_RAND_CHAR_COUNT, TRUE)
           )
        {
            nStatus = ERR_OS_ERROR;
            goto error;
        }

        DebugAddProgressDlgStatus(hwndDlg, L"Wiping old backup header ...\r\n");

        wipeBuffer = (byte *) TCalloc (workChunkSize);
        if (!wipeBuffer)
        {
            nStatus = ERR_OUTOFMEMORY;
            goto error;
        }

        offset.QuadPart = currentVolSize - TC_VOLUME_HEADER_GROUP_SIZE;
        unitNo.Value = offset.QuadPart;

        for (wipePass = 1; wipePass <= GetWipePassCount (wipeAlgorithm); ++wipePass)
        {
            if (!WipeBuffer (wipeAlgorithm, wipeRandChars, wipePass, wipeBuffer, workChunkSize))
            {
                ULONG i;
                for (i = 0; i < workChunkSize; ++i)
                {
                    wipeBuffer[i] = wipePass;
                }

                EncryptDataUnits (wipeBuffer, &unitNo, workChunkSize / ENCRYPTION_DATA_UNIT_SIZE, cryptoInfo);
                memcpy (wipeRandCharsUpdate, wipeBuffer, sizeof (wipeRandCharsUpdate));
            }

            if ( !SetFilePointerEx (dev, offset, NULL, FILE_BEGIN)
                    || _lwrite ((HFILE)dev, (LPCSTR)wipeBuffer, workChunkSize) == HFILE_ERROR
               )
            {
                // Write error
                DebugAddProgressDlgStatus(hwndDlg, L"Warning: Failed to wipe old backup header\r\n");
                MessageBoxW (hwndDlg, L"WARNING: Failed to wipe old backup header!\n\nIt may be possible to use the current volume password to decrypt the old backup header even after a future password change.\n", lpszTitle, MB_OK | MB_ICONEXCLAMATION);
                if (wipePass == 1)
                    continue; // retry once
                // non-critical error - it's better to continue
                nStatus = ERR_SUCCESS;
                goto error;
            }
            FlushFileBuffers(dev);
            // we don't check FlushFileBuffers() return code, because it fails for devices
            // (same implementation in password.c - a bug or not ???)
        }

        burn (wipeRandChars, TC_WIPE_RAND_CHAR_COUNT);
        burn (wipeRandCharsUpdate, TC_WIPE_RAND_CHAR_COUNT);
    }

error:
    dwError = GetLastError ();

    if (wipeBuffer)
    {
        burn (wipeBuffer, workChunkSize);
        TCfree (wipeBuffer);
        wipeBuffer = NULL;
    }

    burn (buffer, sizeof (buffer));

    if (cryptoInfo != NULL)
        crypto_close (cryptoInfo);

    if (bTimeStampValid)
    {
        // Restore the container timestamp (to preserve plausible deniability of possible hidden volume).
        if (SetFileTime (dev, &ftCreationTime, &ftLastAccessTime, &ftLastWriteTime) == 0)
            MessageBoxW (hwndDlg, GetString ("SETFILETIME_FAILED_PW"), lpszTitle, MB_OK | MB_ICONEXCLAMATION);
    }

    if (dev != INVALID_HANDLE_VALUE)
        CloseHandle ((HANDLE) dev);

    if (nDosLinkCreated == 0)
        RemoveFakeDosName (szDiskFile, szDosDevice);

    RandStop (FALSE);

    if (bVolTransformThreadCancel)
        nStatus = ERR_USER_ABORT;

    SetLastError (dwError);

    if (nStatus == ERR_SUCCESS)
    {
        nStatus = ExtendFileSystem (hwndDlg, lpszVolume, pVolumePassword, VolumePkcs5, VolumePim, newDataAreaSize);
    }

    return nStatus;
}
Esempio n. 11
0
//	Will read a file in DIB format and return a global HANDLE to its
//	BITMAPINFO.	 This function will work with both "old" and "new"
//	bitmap formats, but will always return a "new" BITMAPINFO
//************************************************************************
BOOL CDib::ReadBitmapInfo( HFILE fh )
//************************************************************************
{
	DWORD off, size;
	HANDLE hbi = NULL;
	int i, nNumColors;
	LPRGBQUAD pRgb;
	BITMAPINFOHEADER bi;
	BITMAPCOREHEADER bc;
	BITMAPFILEHEADER bf;

	if ( fh < 0 )
		return FALSE;

	off = _llseek(fh,0L,SEEK_CUR);

	if (sizeof(bf) != _lread(fh,(LPSTR)&bf,sizeof(bf)))
		return FALSE;

	// do we have a RC HEADER?
	if (bf.bfType != BFT_BITMAP)
		{
		bf.bfOffBits = 0L;
		_llseek(fh,off,SEEK_SET);
		}

	if (sizeof(bi) != _lread(fh,(LPSTR)&bi,sizeof(bi)))
		return FALSE;

	// what type of bitmap info is this?
	if ( (size = bi.biSize) == sizeof(BITMAPCOREHEADER) )
		{
			bc = *(LPBITMAPCOREHEADER)&bi;
			bi.biSize				= sizeof(BITMAPINFOHEADER);
			bi.biWidth				= (DWORD)bc.bcWidth;
			bi.biHeight				= (DWORD)bc.bcHeight;
			bi.biPlanes				= (UINT)bc.bcPlanes;
			bi.biBitCount			= (UINT)bc.bcBitCount;
			bi.biCompression		= BI_RGB;
			bi.biSizeImage			= 0;
			bi.biXPelsPerMeter		= 0;
			bi.biYPelsPerMeter		= 0;
			bi.biClrUsed			= 0;
			bi.biClrImportant		= 0;
			_llseek(fh,(long)sizeof(BITMAPCOREHEADER)-sizeof(BITMAPINFOHEADER),SEEK_CUR);
		}

	//!!! hack for BI_BITFIELDS
	if ( bi.biCompression == BI_BITFIELDS && !bi.biClrUsed )
		bi.biClrUsed = 3;

	// Copy in the bitmap info header
	m_bmiHeader = bi;
	FixHeader();
	nNumColors = GetNumColors();
	pRgb = GetColors();

	if (nNumColors)
		{
		if (size == sizeof(BITMAPCOREHEADER))
			{
			// convert old color table (3 byte entries) to new (4 byte entries)
			_lread(fh,(LPVOID)pRgb,nNumColors * sizeof(RGBTRIPLE));

			for (i=nNumColors-1; i>=0; i--)
				{
				RGBQUAD rgb;

				rgb.rgbRed		= ((LPRGBTRIPLE)pRgb)[i].rgbtRed;
				rgb.rgbBlue		= ((LPRGBTRIPLE)pRgb)[i].rgbtBlue;
				rgb.rgbGreen	= ((LPRGBTRIPLE)pRgb)[i].rgbtGreen;
				rgb.rgbReserved = (BYTE)0;

				pRgb[i] = rgb;
				}
			}
		else
			{
			_lread(fh,(LPVOID)pRgb,nNumColors * sizeof(RGBQUAD));
			}
		}

	if (bf.bfOffBits)
		_llseek(fh,off + bf.bfOffBits,SEEK_SET);

	return TRUE;
}
Esempio n. 12
0
/***********************************************************************
 *           LZRead   (LZEXPAND.5)
 */
INT16 WINAPI LZRead16( HFILE16 fd, LPVOID buf, UINT16 toread )
{
    if (IS_LZ_HANDLE(fd)) return LZRead( fd, buf, toread );
    return _lread( (HFILE)DosFileHandleToWin32Handle(fd), buf, toread );
}
Esempio n. 13
0
/*-------------------------------------------
  add item to tcmenu*.txt
---------------------------------------------*/
void OnRequestMenu(HWND hwnd, BOOL bClear)
{
	char tcmenutxt[MAX_PATH];
	WIN32_FIND_DATA fd;
	HANDLE hfind;
	HFILE hf;
	int size;
	char *buf;
	const char *p, *np;
	static BOOL bWrite = FALSE;
	
	if(!bClear && m_pTimerRun == NULL) return;
	
	if(bClear && !bWrite) return;
	
	// ../common/tclang.c
	FindFileWithLangCode(tcmenutxt, GetUserDefaultLangID(), TCMENUTXT);
	
	hfind = FindFirstFile(tcmenutxt, &fd);
	if(hfind == INVALID_HANDLE_VALUE) return;
	
	FindClose(hfind);
	size = (int)fd.nFileSizeLow;
	buf = malloc(size+1);
	if(!buf) return;
	
	hf = _lopen(tcmenutxt, OF_READWRITE);
	if(hf == HFILE_ERROR) { free(buf); return; }
	_lread(hf, buf, size);
	*(buf + size) = 0;
	
	_llseek(hf, 0, 0);
	
	p = buf;
	while(*p)
	{
		if(strncmp(p, "#Timer Begin", 12) == 0)
		{
			PTIMERSTRUCT pitem;
			DWORD tick;
			char s[160];
			
			np = nextline(p);
			_lwrite(hf, p, (int)(np - p));
			p = np;
			
			tick = GetTickCount();
			
			pitem = m_pTimerRun;
			while(pitem)
			{
				int remaining =
					pitem->interval - (tick - pitem->tickonstart)/1000 - 1;
				
				wsprintf(s, "\"%s %s %02d:%02d\" post %s %d 0 %d\r\n",
					MyString(IDS_STOP, "Stop"),
					pitem->name, remaining/60, remaining%60,
					CLASS_TCLOCKTIMER, TIMERM_STOP, pitem->id);
				_lwrite(hf, s, (int)strlen(s));
				
				pitem = pitem->next;
			}
			
			while(*p)
			{
				if(strncmp(p, "#Timer End", 10) == 0)
					break;
				p = nextline(p);
			}
		}
		else
		{
			np = nextline(p);
			_lwrite(hf, p, (int)(np - p));
			p = np;
		}
	}
	
	_lwrite(hf, NULL, 0); // truncate
	
	_lclose(hf);
	free(buf);
	
	bWrite = TRUE;
}
Esempio n. 14
0
File: Text.c Progetto: atrniv/CLIPS
BOOL text_Revert(
  HWND hwnd,
  char *fileName,
  HWND hEditWnd)
  {
   int hFile;
   OFSTRUCT OfStruct;
   long text_length;
   char *pEditBuffer;
   HICON hSaveCursor;
   unsigned ioStatus;
   char szTemp[128];
   struct textWindowData *theData;
   
   theData = (struct textWindowData *) GetWindowLong(hEditWnd,GWL_USERDATA);
 
   
   /*===================================*/
   /* Open the file and get its handle. */
   /*===================================*/
   
   /* TBD Replace OpenFile with CreateFile. */
   
   if (theData == NULL)
     {
      hFile = OpenFile((LPSTR) fileName,
                       (LPOFSTRUCT) &OfStruct,
                       OF_READ);
     }
   else
     {
      hFile = OpenFile((LPSTR) (char *) &theData->fileName,
                       (LPOFSTRUCT) &OfStruct,
                       OF_READ);
     }
     
   if (hFile == HFILE_ERROR)
     { return (FALSE); }
 
   /*=====================*/
   /* Update window data. */
   /*=====================*/
   
   if (theData == NULL)
     { 
      theData = (struct textWindowData *) malloc(sizeof(struct textWindowData));
      if (theData == NULL) return(FALSE);
      
      strcpy((char *) &theData->fileName,(char *) fileName);
      SetWindowLong(hEditWnd,GWL_USERDATA,(long) theData);
     }
   
   /*===================================================*/
   /* Allocate edit buffer to the size of the file + 1. */
   /*===================================================*/
   
   text_length = _llseek(hFile,0,2); 
   _llseek(hFile,0,0); 

   if (text_length > 65534L) 
     {
      MessageBox(hwnd, "Can't load files larger than 65,534 bytes long !",
                 "FILE READ ERROR", MB_OK | MB_ICONEXCLAMATION);
      _lclose(hFile);
      return (FALSE);
     }

   pEditBuffer = (char *) malloc((size_t) text_length+1);

   if (pEditBuffer == NULL)
     {
      MessageBox(hwnd,"Not enough memory.",
                 NULL,MB_OK | MB_ICONEXCLAMATION);
      _lclose(hFile);
      return (FALSE);
     }

   hSaveCursor = SetCursor(hHourGlass);
        
   ioStatus = _lread(hFile,pEditBuffer,(UINT) text_length);
   pEditBuffer[text_length] = '\0';
   _lclose(hFile); 

   /*====================================*/
   /* # bytes read must equal file size. */
   /*====================================*/

   if (((long) ioStatus) != text_length)
	 {
      sprintf(szTemp,"Error reading %s tl %ld IO %ld.",
	          fileName,text_length,ioStatus);
      SetCursor(hSaveCursor);      
      MessageBox(hwnd,szTemp,NULL,MB_OK | MB_ICONEXCLAMATION);
     }
   else
     { 
      hEditWnd = GetDlgItem(hEditWnd,ID_EDIT_CONTROL);
      SendMessage(hEditWnd,WM_SETTEXT,0,(LPARAM) pEditBuffer);
      FixTextLineEndings(hEditWnd);
     }

   free(pEditBuffer);
    
   /*=======================================*/
   /* Set up a new buffer and window title. */
   /*=======================================*/	 
     
   //sprintf(szTemp, "Edit File - (%s)", szFileTitle);
   //SetNewBuffer(hWnd,(LPSTR)&szTemp);
   SetCursor(hSaveCursor);
   
   return(TRUE);
  }
Esempio n. 15
0
void WINAPI VXD_Win32s( CONTEXT86 *context )
{
    switch (AX_reg(context))
    {
    case 0x0000: /* Get Version */
        /*
         * Input:   None
         *
         * Output:  EAX: LoWord: Win32s Version (1.30)
         *               HiWord: VxD Version (200)
         *
         *          EBX: Build (172)
         *
         *          ECX: ???   (1)
         *
         *          EDX: Debugging Flags
         *
         *          EDI: Error Flag
         *               0 if OK,
         *               1 if VMCPD VxD not found
         */

        TRACE("GetVersion()\n");

	context->Eax = VXD_WinVersion() | (200 << 16);
        context->Ebx = 0;
        context->Ecx = 0;
        context->Edx = 0;
        context->Edi = 0;

        /*
         * If this is the first time we are called for this process,
         * hack the memory image of WIN32S16 so that it doesn't try
         * to access the GDT directly ...
         *
         * The first code segment of WIN32S16 (version 1.30) contains
         * an unexported function somewhere between the exported functions
         * SetFS and StackLinearToSegmented that tries to find a selector
         * in the LDT that maps to the memory image of the LDT itself.
         * If it succeeds, it stores this selector into a global variable
         * which will be used to speed up execution by using this selector
         * to modify the LDT directly instead of using the DPMI calls.
         *
         * To perform this search of the LDT, this function uses the
         * sgdt and sldt instructions to find the linear address of
         * the (GDT and then) LDT. While those instructions themselves
         * execute without problem, the linear address that sgdt returns
         * points (at least under Linux) to the kernel address space, so
         * that any subsequent access leads to a segfault.
         *
         * Fortunately, WIN32S16 still contains as a fallback option the
         * mechanism of using DPMI calls to modify LDT selectors instead
         * of direct writes to the LDT. Thus we can circumvent the problem
         * by simply replacing the first byte of the offending function
         * with an 'retf' instruction. This means that the global variable
         * supposed to contain the LDT alias selector will remain zero,
         * and hence WIN32S16 will fall back to using DPMI calls.
         *
         * The heuristic we employ to _find_ that function is as follows:
         * We search between the addresses of the exported symbols SetFS
         * and StackLinearToSegmented for the byte sequence '0F 01 04'
         * (this is the opcode of 'sgdt [si]'). We then search backwards
         * from this address for the last occurrence of 'CB' (retf) that marks
         * the end of the preceeding function. The following byte (which
         * should now be the first byte of the function we are looking for)
         * will be replaced by 'CB' (retf).
         *
         * This heuristic works for the retail as well as the debug version
         * of Win32s version 1.30. For versions earlier than that this
         * hack should not be necessary at all, since the whole mechanism
         * ('PERF130') was introduced only in 1.30 to improve the overall
         * performance of Win32s.
         */

        if (!W32S_offset)
        {
            HMODULE16 hModule = GetModuleHandle16("win32s16");
            SEGPTR func1 = (SEGPTR)GetProcAddress16(hModule, "SetFS");
            SEGPTR func2 = (SEGPTR)GetProcAddress16(hModule, "StackLinearToSegmented");

            if (   hModule && func1 && func2
                && SELECTOROF(func1) == SELECTOROF(func2))
            {
                BYTE *start = MapSL(func1);
                BYTE *end   = MapSL(func2);
                BYTE *p, *retv = NULL;
                int found = 0;

                for (p = start; p < end; p++)
                    if (*p == 0xCB) found = 0, retv = p;
                    else if (*p == 0x0F) found = 1;
                    else if (*p == 0x01 && found == 1) found = 2;
                    else if (*p == 0x04 && found == 2) { found = 3; break; }
                    else found = 0;

                if (found == 3 && retv)
                {
                    TRACE("PERF130 hack: "
                               "Replacing byte %02X at offset %04X:%04X\n",
                               *(retv+1), SELECTOROF(func1),
                                          OFFSETOF(func1) + retv+1-start);

                    *(retv+1) = (BYTE)0xCB;
                }
            }
        }

        /*
         * Mark process as Win32s, so that subsequent DPMI calls
         * will perform the W32S_APP2WINE/W32S_WINE2APP address shift.
         */
        W32S_offset = 0x10000;
        break;


    case 0x0001: /* Install Exception Handling */
        /*
         * Input:   EBX: Flat address of W32SKRNL Exception Data
         *
         *          ECX: LoWord: Flat Code Selector
         *               HiWord: Flat Data Selector
         *
         *          EDX: Flat address of W32SKRNL Exception Handler
         *               (this is equal to W32S_BackTo32 + 0x40)
         *
         *          ESI: SEGPTR KERNEL.HASGPHANDLER
         *
         *          EDI: SEGPTR phCurrentTask (KERNEL.THHOOK + 0x10)
         *
         * Output:  EAX: 0 if OK
         */

        TRACE("[0001] EBX=%lx ECX=%lx EDX=%lx ESI=%lx EDI=%lx\n",
                   context->Ebx, context->Ecx, context->Edx,
                   context->Esi, context->Edi);

        /* FIXME */

        context->Eax = 0;
        break;


    case 0x0002: /* Set Page Access Flags */
        /*
         * Input:   EBX: New access flags
         *               Bit 2: User Page if set, Supervisor Page if clear
         *               Bit 1: Read-Write if set, Read-Only if clear
         *
         *          ECX: Size of memory area to change
         *
         *          EDX: Flat start address of memory area
         *
         * Output:  EAX: Size of area changed
         */

        TRACE("[0002] EBX=%lx ECX=%lx EDX=%lx\n",
                   context->Ebx, context->Ecx, context->Edx);

        /* FIXME */

        context->Eax = context->Ecx;
        break;


    case 0x0003: /* Get Page Access Flags */
        /*
         * Input:   EDX: Flat address of page to query
         *
         * Output:  EAX: Page access flags
         *               Bit 2: User Page if set, Supervisor Page if clear
         *               Bit 1: Read-Write if set, Read-Only if clear
         */

        TRACE("[0003] EDX=%lx\n", context->Edx);

        /* FIXME */

        context->Eax = 6;
        break;


    case 0x0004: /* Map Module */
        /*
         * Input:   ECX: IMTE (offset in Module Table) of new module
         *
         *          EDX: Flat address of Win32s Module Table
         *
         * Output:  EAX: 0 if OK
         */

    if (!context->Edx || CX_reg(context) == 0xFFFF)
    {
        TRACE("MapModule: Initialization call\n");
        context->Eax = 0;
    }
    else
    {
        /*
         * Structure of a Win32s Module Table Entry:
         */
        struct Win32sModule
        {
            DWORD  flags;
            DWORD  flatBaseAddr;
            LPCSTR moduleName;
            LPCSTR pathName;
            LPCSTR unknown;
            LPBYTE baseAddr;
            DWORD  hModule;
            DWORD  relocDelta;
        };

        /*
         * Note: This function should set up a demand-paged memory image
         *       of the given module. Since mmap does not allow file offsets
         *       not aligned at 1024 bytes, we simply load the image fully
         *       into memory.
         */

        struct Win32sModule *moduleTable =
                            (struct Win32sModule *)W32S_APP2WINE(context->Edx);
        struct Win32sModule *module = moduleTable + context->Ecx;

        IMAGE_NT_HEADERS *nt_header = PE_HEADER(module->baseAddr);
        IMAGE_SECTION_HEADER *pe_seg = PE_SECTIONS(module->baseAddr);

        HFILE image = _lopen(module->pathName, OF_READ);
        BOOL error = (image == HFILE_ERROR);
        UINT i;

        TRACE("MapModule: Loading %s\n", module->pathName);

        for (i = 0;
             !error && i < nt_header->FileHeader.NumberOfSections;
             i++, pe_seg++)
            if(!(pe_seg->Characteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA))
            {
                DWORD  off  = pe_seg->PointerToRawData;
                DWORD  len  = pe_seg->SizeOfRawData;
                LPBYTE addr = module->baseAddr + pe_seg->VirtualAddress;

                TRACE("MapModule: "
                           "Section %d at %08lx from %08lx len %08lx\n",
                           i, (DWORD)addr, off, len);

                if (   _llseek(image, off, SEEK_SET) != off
                    || _lread(image, addr, len) != len)
                    error = TRUE;
            }

        _lclose(image);

        if (error)
            ERR("MapModule: Unable to load %s\n", module->pathName);

        else if (module->relocDelta != 0)
        {
            IMAGE_DATA_DIRECTORY *dir = nt_header->OptionalHeader.DataDirectory
                                      + IMAGE_DIRECTORY_ENTRY_BASERELOC;
            IMAGE_BASE_RELOCATION *r = (IMAGE_BASE_RELOCATION *)
                (dir->Size? module->baseAddr + dir->VirtualAddress : 0);

            TRACE("MapModule: Reloc delta %08lx\n", module->relocDelta);

            while (r && r->VirtualAddress)
            {
                LPBYTE page  = module->baseAddr + r->VirtualAddress;
                WORD *TypeOffset = (WORD *)(r + 1);
                int count = (r->SizeOfBlock - sizeof(*r)) / sizeof(*TypeOffset);

                TRACE("MapModule: %d relocations for page %08lx\n",
                           count, (DWORD)page);

                for(i = 0; i < count; i++)
                {
                    int offset = TypeOffset[i] & 0xFFF;
                    int type   = TypeOffset[i] >> 12;
                    switch(type)
                    {
                    case IMAGE_REL_BASED_ABSOLUTE:
                        break;
                    case IMAGE_REL_BASED_HIGH:
                        *(WORD *)(page+offset) += HIWORD(module->relocDelta);
                        break;
                    case IMAGE_REL_BASED_LOW:
                        *(WORD *)(page+offset) += LOWORD(module->relocDelta);
                        break;
                    case IMAGE_REL_BASED_HIGHLOW:
                        *(DWORD*)(page+offset) += module->relocDelta;
                        break;
                    default:
                        WARN("MapModule: Unsupported fixup type\n");
                        break;
                    }
                }

                r = (IMAGE_BASE_RELOCATION *)((LPBYTE)r + r->SizeOfBlock);
            }
        }

        context->Eax = 0;
        RESET_CFLAG(context);
    }
    break;


    case 0x0005: /* UnMap Module */
        /*
         * Input:   EDX: Flat address of module image
         *
         * Output:  EAX: 1 if OK
         */

        TRACE("UnMapModule: %lx\n", (DWORD)W32S_APP2WINE(context->Edx));

        /* As we didn't map anything, there's nothing to unmap ... */

        context->Eax = 1;
        break;


    case 0x0006: /* VirtualAlloc */
        /*
         * Input:   ECX: Current Process
         *
         *          EDX: Flat address of arguments on stack
         *
         *   DWORD *retv     [out] Flat base address of allocated region
         *   LPVOID base     [in]  Flat address of region to reserve/commit
         *   DWORD  size     [in]  Size of region
         *   DWORD  type     [in]  Type of allocation
         *   DWORD  prot     [in]  Type of access protection
         *
         * Output:  EAX: NtStatus
         */
    {
        DWORD *stack  = (DWORD *)W32S_APP2WINE(context->Edx);
        DWORD *retv   = (DWORD *)W32S_APP2WINE(stack[0]);
        LPVOID base   = (LPVOID) W32S_APP2WINE(stack[1]);
        DWORD  size   = stack[2];
        DWORD  type   = stack[3];
        DWORD  prot   = stack[4];
        DWORD  result;

        TRACE("VirtualAlloc(%lx, %lx, %lx, %lx, %lx)\n",
                   (DWORD)retv, (DWORD)base, size, type, prot);

        if (type & 0x80000000)
        {
            WARN("VirtualAlloc: strange type %lx\n", type);
            type &= 0x7fffffff;
        }

        if (!base && (type & MEM_COMMIT) && prot == PAGE_READONLY)
        {
            WARN("VirtualAlloc: NLS hack, allowing write access!\n");
            prot = PAGE_READWRITE;
        }

        result = (DWORD)VirtualAlloc(base, size, type, prot);

        if (W32S_WINE2APP(result))
            *retv            = W32S_WINE2APP(result),
            context->Eax = STATUS_SUCCESS;
        else
            *retv            = 0,
            context->Eax = STATUS_NO_MEMORY;  /* FIXME */
    }
    break;


    case 0x0007: /* VirtualFree */
        /*
         * Input:   ECX: Current Process
         *
         *          EDX: Flat address of arguments on stack
         *
         *   DWORD *retv     [out] TRUE if success, FALSE if failure
         *   LPVOID base     [in]  Flat address of region
         *   DWORD  size     [in]  Size of region
         *   DWORD  type     [in]  Type of operation
         *
         * Output:  EAX: NtStatus
         */
    {
        DWORD *stack  = (DWORD *)W32S_APP2WINE(context->Edx);
        DWORD *retv   = (DWORD *)W32S_APP2WINE(stack[0]);
        LPVOID base   = (LPVOID) W32S_APP2WINE(stack[1]);
        DWORD  size   = stack[2];
        DWORD  type   = stack[3];
        DWORD  result;

        TRACE("VirtualFree(%lx, %lx, %lx, %lx)\n",
                   (DWORD)retv, (DWORD)base, size, type);

        result = VirtualFree(base, size, type);

        if (result)
            *retv            = TRUE,
            context->Eax = STATUS_SUCCESS;
        else
            *retv            = FALSE,
            context->Eax = STATUS_NO_MEMORY;  /* FIXME */
    }
    break;


    case 0x0008: /* VirtualProtect */
        /*
         * Input:   ECX: Current Process
         *
         *          EDX: Flat address of arguments on stack
         *
         *   DWORD *retv     [out] TRUE if success, FALSE if failure
         *   LPVOID base     [in]  Flat address of region
         *   DWORD  size     [in]  Size of region
         *   DWORD  new_prot [in]  Desired access protection
         *   DWORD *old_prot [out] Previous access protection
         *
         * Output:  EAX: NtStatus
         */
    {
        DWORD *stack    = (DWORD *)W32S_APP2WINE(context->Edx);
        DWORD *retv     = (DWORD *)W32S_APP2WINE(stack[0]);
        LPVOID base     = (LPVOID) W32S_APP2WINE(stack[1]);
        DWORD  size     = stack[2];
        DWORD  new_prot = stack[3];
        DWORD *old_prot = (DWORD *)W32S_APP2WINE(stack[4]);
        DWORD  result;

        TRACE("VirtualProtect(%lx, %lx, %lx, %lx, %lx)\n",
                   (DWORD)retv, (DWORD)base, size, new_prot, (DWORD)old_prot);

        result = VirtualProtect(base, size, new_prot, old_prot);

        if (result)
            *retv            = TRUE,
            context->Eax = STATUS_SUCCESS;
        else
            *retv            = FALSE,
            context->Eax = STATUS_NO_MEMORY;  /* FIXME */
    }
    break;


    case 0x0009: /* VirtualQuery */
        /*
         * Input:   ECX: Current Process
         *
         *          EDX: Flat address of arguments on stack
         *
         *   DWORD *retv                     [out] Nr. bytes returned
         *   LPVOID base                     [in]  Flat address of region
         *   LPMEMORY_BASIC_INFORMATION info [out] Info buffer
         *   DWORD  len                      [in]  Size of buffer
         *
         * Output:  EAX: NtStatus
         */
    {
        DWORD *stack  = (DWORD *)W32S_APP2WINE(context->Edx);
        DWORD *retv   = (DWORD *)W32S_APP2WINE(stack[0]);
        LPVOID base   = (LPVOID) W32S_APP2WINE(stack[1]);
        LPMEMORY_BASIC_INFORMATION info =
                        (LPMEMORY_BASIC_INFORMATION)W32S_APP2WINE(stack[2]);
        DWORD  len    = stack[3];
        DWORD  result;

        TRACE("VirtualQuery(%lx, %lx, %lx, %lx)\n",
                   (DWORD)retv, (DWORD)base, (DWORD)info, len);

        result = VirtualQuery(base, info, len);

        *retv            = result;
        context->Eax = STATUS_SUCCESS;
    }
    break;


    case 0x000A: /* SetVirtMemProcess */
        /*
         * Input:   ECX: Process Handle
         *
         *          EDX: Flat address of region
         *
         * Output:  EAX: NtStatus
         */

        TRACE("[000a] ECX=%lx EDX=%lx\n",
                   context->Ecx, context->Edx);

        /* FIXME */

        context->Eax = STATUS_SUCCESS;
        break;


    case 0x000B: /* ??? some kind of cleanup */
        /*
         * Input:   ECX: Process Handle
         *
         * Output:  EAX: NtStatus
         */

        TRACE("[000b] ECX=%lx\n", context->Ecx);

        /* FIXME */

        context->Eax = STATUS_SUCCESS;
        break;


    case 0x000C: /* Set Debug Flags */
        /*
         * Input:   EDX: Debug Flags
         *
         * Output:  EDX: Previous Debug Flags
         */

        FIXME("[000c] EDX=%lx\n", context->Edx);

        /* FIXME */

        context->Edx = 0;
        break;


    case 0x000D: /* NtCreateSection */
        /*
         * Input:   EDX: Flat address of arguments on stack
         *
         *   HANDLE32 *retv      [out] Handle of Section created
         *   DWORD  flags1       [in]  (?? unknown ??)
         *   DWORD  atom         [in]  Name of Section to create
         *   LARGE_INTEGER *size [in]  Size of Section
         *   DWORD  protect      [in]  Access protection
         *   DWORD  flags2       [in]  (?? unknown ??)
         *   HFILE32 hFile       [in]  Handle of file to map
         *   DWORD  psp          [in]  (Win32s: PSP that hFile belongs to)
         *
         * Output:  EAX: NtStatus
         */
    {
        DWORD *stack    = (DWORD *)   W32S_APP2WINE(context->Edx);
        HANDLE *retv  = (HANDLE *)W32S_APP2WINE(stack[0]);
        DWORD  flags1   = stack[1];
        DWORD  atom     = stack[2];
        LARGE_INTEGER *size = (LARGE_INTEGER *)W32S_APP2WINE(stack[3]);
        DWORD  protect  = stack[4];
        DWORD  flags2   = stack[5];
        HANDLE hFile    = DosFileHandleToWin32Handle(stack[6]);
        DWORD  psp      = stack[7];

        HANDLE result = INVALID_HANDLE_VALUE;
        char name[128];

        TRACE("NtCreateSection(%lx, %lx, %lx, %lx, %lx, %lx, %lx, %lx)\n",
                   (DWORD)retv, flags1, atom, (DWORD)size, protect, flags2,
                   (DWORD)hFile, psp);

        if (!atom || GlobalGetAtomNameA(atom, name, sizeof(name)))
        {
            TRACE("NtCreateSection: name=%s\n", atom? name : NULL);

            result = CreateFileMappingA(hFile, NULL, protect,
                                          size? size->s.HighPart : 0,
                                          size? size->s.LowPart  : 0,
                                          atom? name : NULL);
        }

        if (result == INVALID_HANDLE_VALUE)
            WARN("NtCreateSection: failed!\n");
        else
            TRACE("NtCreateSection: returned %lx\n", (DWORD)result);

        if (result != INVALID_HANDLE_VALUE)
            *retv            = result,
            context->Eax = STATUS_SUCCESS;
        else
            *retv            = result,
            context->Eax = STATUS_NO_MEMORY;   /* FIXME */
    }
    break;


    case 0x000E: /* NtOpenSection */
        /*
         * Input:   EDX: Flat address of arguments on stack
         *
         *   HANDLE32 *retv  [out] Handle of Section opened
         *   DWORD  protect  [in]  Access protection
         *   DWORD  atom     [in]  Name of Section to create
         *
         * Output:  EAX: NtStatus
         */
    {
        DWORD *stack    = (DWORD *)W32S_APP2WINE(context->Edx);
        HANDLE *retv  = (HANDLE *)W32S_APP2WINE(stack[0]);
        DWORD  protect  = stack[1];
        DWORD  atom     = stack[2];

        HANDLE result = INVALID_HANDLE_VALUE;
        char name[128];

        TRACE("NtOpenSection(%lx, %lx, %lx)\n",
                   (DWORD)retv, protect, atom);

        if (atom && GlobalGetAtomNameA(atom, name, sizeof(name)))
        {
            TRACE("NtOpenSection: name=%s\n", name);

            result = OpenFileMappingA(protect, FALSE, name);
        }

        if (result == INVALID_HANDLE_VALUE)
            WARN("NtOpenSection: failed!\n");
        else
            TRACE("NtOpenSection: returned %lx\n", (DWORD)result);

        if (result != INVALID_HANDLE_VALUE)
            *retv            = result,
            context->Eax = STATUS_SUCCESS;
        else
            *retv            = result,
            context->Eax = STATUS_NO_MEMORY;   /* FIXME */
    }
    break;


    case 0x000F: /* NtCloseSection */
        /*
         * Input:   EDX: Flat address of arguments on stack
         *
         *   HANDLE32 handle  [in]  Handle of Section to close
         *   DWORD *id        [out] Unique ID  (?? unclear ??)
         *
         * Output:  EAX: NtStatus
         */
    {
        DWORD *stack    = (DWORD *)W32S_APP2WINE(context->Edx);
        HANDLE handle = stack[0];
        DWORD *id       = (DWORD *)W32S_APP2WINE(stack[1]);

        TRACE("NtCloseSection(%lx, %lx)\n", (DWORD)handle, (DWORD)id);

        CloseHandle(handle);
        if (id) *id = 0; /* FIXME */

        context->Eax = STATUS_SUCCESS;
    }
    break;


    case 0x0010: /* NtDupSection */
        /*
         * Input:   EDX: Flat address of arguments on stack
         *
         *   HANDLE32 handle  [in]  Handle of Section to duplicate
         *
         * Output:  EAX: NtStatus
         */
    {
        DWORD *stack    = (DWORD *)W32S_APP2WINE(context->Edx);
        HANDLE handle = stack[0];
        HANDLE new_handle;

        TRACE("NtDupSection(%lx)\n", (DWORD)handle);

        DuplicateHandle( GetCurrentProcess(), handle,
                         GetCurrentProcess(), &new_handle,
                         0, FALSE, DUPLICATE_SAME_ACCESS );
        context->Eax = STATUS_SUCCESS;
    }
    break;


    case 0x0011: /* NtMapViewOfSection */
        /*
         * Input:   EDX: Flat address of arguments on stack
         *
         *   HANDLE32 SectionHandle       [in]     Section to be mapped
         *   DWORD    ProcessHandle       [in]     Process to be mapped into
         *   DWORD *  BaseAddress         [in/out] Address to be mapped at
         *   DWORD    ZeroBits            [in]     (?? unclear ??)
         *   DWORD    CommitSize          [in]     (?? unclear ??)
         *   LARGE_INTEGER *SectionOffset [in]     Offset within section
         *   DWORD *  ViewSize            [in]     Size of view
         *   DWORD    InheritDisposition  [in]     (?? unclear ??)
         *   DWORD    AllocationType      [in]     (?? unclear ??)
         *   DWORD    Protect             [in]     Access protection
         *
         * Output:  EAX: NtStatus
         */
    {
        DWORD *  stack          = (DWORD *)W32S_APP2WINE(context->Edx);
        HANDLE SectionHandle  = stack[0];
        DWORD    ProcessHandle  = stack[1]; /* ignored */
        DWORD *  BaseAddress    = (DWORD *)W32S_APP2WINE(stack[2]);
        DWORD    ZeroBits       = stack[3];
        DWORD    CommitSize     = stack[4];
        LARGE_INTEGER *SectionOffset = (LARGE_INTEGER *)W32S_APP2WINE(stack[5]);
        DWORD *  ViewSize       = (DWORD *)W32S_APP2WINE(stack[6]);
        DWORD    InheritDisposition = stack[7];
        DWORD    AllocationType = stack[8];
        DWORD    Protect        = stack[9];

        LPBYTE address = (LPBYTE)(BaseAddress?
			W32S_APP2WINE(*BaseAddress) : 0);
        DWORD  access = 0, result;

        switch (Protect & ~(PAGE_GUARD|PAGE_NOCACHE))
        {
            case PAGE_READONLY:           access = FILE_MAP_READ;  break;
            case PAGE_READWRITE:          access = FILE_MAP_WRITE; break;
            case PAGE_WRITECOPY:          access = FILE_MAP_COPY;  break;

            case PAGE_EXECUTE_READ:       access = FILE_MAP_READ;  break;
            case PAGE_EXECUTE_READWRITE:  access = FILE_MAP_WRITE; break;
            case PAGE_EXECUTE_WRITECOPY:  access = FILE_MAP_COPY;  break;
        }

        TRACE("NtMapViewOfSection"
                   "(%lx, %lx, %lx, %lx, %lx, %lx, %lx, %lx, %lx, %lx)\n",
                   (DWORD)SectionHandle, ProcessHandle, (DWORD)BaseAddress,
                   ZeroBits, CommitSize, (DWORD)SectionOffset, (DWORD)ViewSize,
                   InheritDisposition, AllocationType, Protect);
        TRACE("NtMapViewOfSection: "
                   "base=%lx, offset=%lx, size=%lx, access=%lx\n",
                   (DWORD)address, SectionOffset? SectionOffset->s.LowPart : 0,
                   ViewSize? *ViewSize : 0, access);

        result = (DWORD)MapViewOfFileEx(SectionHandle, access,
                            SectionOffset? SectionOffset->s.HighPart : 0,
                            SectionOffset? SectionOffset->s.LowPart  : 0,
                            ViewSize? *ViewSize : 0, address);

        TRACE("NtMapViewOfSection: result=%lx\n", result);

        if (W32S_WINE2APP(result))
        {
            if (BaseAddress) *BaseAddress = W32S_WINE2APP(result);
            context->Eax = STATUS_SUCCESS;
        }
        else
            context->Eax = STATUS_NO_MEMORY; /* FIXME */
    }
    break;


    case 0x0012: /* NtUnmapViewOfSection */
        /*
         * Input:   EDX: Flat address of arguments on stack
         *
         *   DWORD  ProcessHandle  [in]  Process (defining address space)
         *   LPBYTE BaseAddress    [in]  Base address of view to be unmapped
         *
         * Output:  EAX: NtStatus
         */
    {
        DWORD *stack          = (DWORD *)W32S_APP2WINE(context->Edx);
        DWORD  ProcessHandle  = stack[0]; /* ignored */
        LPBYTE BaseAddress    = (LPBYTE)W32S_APP2WINE(stack[1]);

        TRACE("NtUnmapViewOfSection(%lx, %lx)\n",
                   ProcessHandle, (DWORD)BaseAddress);

        UnmapViewOfFile(BaseAddress);

        context->Eax = STATUS_SUCCESS;
    }
    break;


    case 0x0013: /* NtFlushVirtualMemory */
        /*
         * Input:   EDX: Flat address of arguments on stack
         *
         *   DWORD   ProcessHandle  [in]  Process (defining address space)
         *   LPBYTE *BaseAddress    [in?] Base address of range to be flushed
         *   DWORD  *ViewSize       [in?] Number of bytes to be flushed
         *   DWORD  *unknown        [???] (?? unknown ??)
         *
         * Output:  EAX: NtStatus
         */
    {
        DWORD *stack          = (DWORD *)W32S_APP2WINE(context->Edx);
        DWORD  ProcessHandle  = stack[0]; /* ignored */
        DWORD *BaseAddress    = (DWORD *)W32S_APP2WINE(stack[1]);
        DWORD *ViewSize       = (DWORD *)W32S_APP2WINE(stack[2]);
        DWORD *unknown        = (DWORD *)W32S_APP2WINE(stack[3]);

        LPBYTE address = (LPBYTE)(BaseAddress? W32S_APP2WINE(*BaseAddress) : 0);
        DWORD  size    = ViewSize? *ViewSize : 0;

        TRACE("NtFlushVirtualMemory(%lx, %lx, %lx, %lx)\n",
                   ProcessHandle, (DWORD)BaseAddress, (DWORD)ViewSize,
                   (DWORD)unknown);
        TRACE("NtFlushVirtualMemory: base=%lx, size=%lx\n",
                   (DWORD)address, size);

        FlushViewOfFile(address, size);

        context->Eax = STATUS_SUCCESS;
    }
    break;


    case 0x0014: /* Get/Set Debug Registers */
        /*
         * Input:   ECX: 0 if Get, 1 if Set
         *
         *          EDX: Get: Flat address of buffer to receive values of
         *                    debug registers DR0 .. DR7
         *               Set: Flat address of buffer containing values of
         *                    debug registers DR0 .. DR7 to be set
         * Output:  None
         */

        FIXME("[0014] ECX=%lx EDX=%lx\n",
                   context->Ecx, context->Edx);

        /* FIXME */
        break;


    case 0x0015: /* Set Coprocessor Emulation Flag */
        /*
         * Input:   EDX: 0 to deactivate, 1 to activate coprocessor emulation
         *
         * Output:  None
         */

        TRACE("[0015] EDX=%lx\n", context->Edx);

        /* We don't care, as we always have a coprocessor anyway */
        break;


    case 0x0016: /* Init Win32S VxD PSP */
        /*
         * If called to query required PSP size:
         *
         *     Input:  EBX: 0
         *     Output: EDX: Required size of Win32s VxD PSP
         *
         * If called to initialize allocated PSP:
         *
         *     Input:  EBX: LoWord: Selector of Win32s VxD PSP
         *                  HiWord: Paragraph of Win32s VxD PSP (DOSMEM)
         *     Output: None
         */

        if (context->Ebx == 0)
            context->Edx = 0x80;
        else
        {
            PDB16 *psp = MapSL( MAKESEGPTR( BX_reg(context), 0 ));
            psp->nbFiles = 32;
            psp->fileHandlesPtr = MAKELONG(HIWORD(context->Ebx), 0x5c);
            memset((LPBYTE)psp + 0x5c, '\xFF', 32);
        }
        break;


    case 0x0017: /* Set Break Point */
        /*
         * Input:   EBX: Offset of Break Point
         *          CX:  Selector of Break Point
         *
         * Output:  None
         */

        FIXME("[0017] EBX=%lx CX=%x\n",
                   context->Ebx, CX_reg(context));

        /* FIXME */
        break;


    case 0x0018: /* VirtualLock */
        /*
         * Input:   ECX: Current Process
         *
         *          EDX: Flat address of arguments on stack
         *
         *   DWORD *retv     [out] TRUE if success, FALSE if failure
         *   LPVOID base     [in]  Flat address of range to lock
         *   DWORD  size     [in]  Size of range
         *
         * Output:  EAX: NtStatus
         */
    {
        DWORD *stack  = (DWORD *)W32S_APP2WINE(context->Edx);
        DWORD *retv   = (DWORD *)W32S_APP2WINE(stack[0]);
        LPVOID base   = (LPVOID) W32S_APP2WINE(stack[1]);
        DWORD  size   = stack[2];
        DWORD  result;

        TRACE("VirtualLock(%lx, %lx, %lx)\n",
                   (DWORD)retv, (DWORD)base, size);

        result = VirtualLock(base, size);

        if (result)
            *retv            = TRUE,
            context->Eax = STATUS_SUCCESS;
        else
            *retv            = FALSE,
            context->Eax = STATUS_NO_MEMORY;  /* FIXME */
    }
    break;


    case 0x0019: /* VirtualUnlock */
        /*
         * Input:   ECX: Current Process
         *
         *          EDX: Flat address of arguments on stack
         *
         *   DWORD *retv     [out] TRUE if success, FALSE if failure
         *   LPVOID base     [in]  Flat address of range to unlock
         *   DWORD  size     [in]  Size of range
         *
         * Output:  EAX: NtStatus
         */
    {
        DWORD *stack  = (DWORD *)W32S_APP2WINE(context->Edx);
        DWORD *retv   = (DWORD *)W32S_APP2WINE(stack[0]);
        LPVOID base   = (LPVOID) W32S_APP2WINE(stack[1]);
        DWORD  size   = stack[2];
        DWORD  result;

        TRACE("VirtualUnlock(%lx, %lx, %lx)\n",
                   (DWORD)retv, (DWORD)base, size);

        result = VirtualUnlock(base, size);

        if (result)
            *retv            = TRUE,
            context->Eax = STATUS_SUCCESS;
        else
            *retv            = FALSE,
            context->Eax = STATUS_NO_MEMORY;  /* FIXME */
    }
    break;


    case 0x001A: /* KGetSystemInfo */
        /*
         * Input:   None
         *
         * Output:  ECX:  Start of sparse memory arena
         *          EDX:  End of sparse memory arena
         */

        TRACE("KGetSystemInfo()\n");

        /*
         * Note: Win32s reserves 0GB - 2GB for Win 3.1 and uses 2GB - 4GB as
         *       sparse memory arena. We do it the other way around, since
         *       we have to reserve 3GB - 4GB for Linux, and thus use
         *       0GB - 3GB as sparse memory arena.
         *
         *       FIXME: What about other OSes ?
         */

        context->Ecx = W32S_WINE2APP(0x00000000);
        context->Edx = W32S_WINE2APP(0xbfffffff);
        break;


    case 0x001B: /* KGlobalMemStat */
        /*
         * Input:   ESI: Flat address of buffer to receive memory info
         *
         * Output:  None
         */
    {
        struct Win32sMemoryInfo
        {
            DWORD DIPhys_Count;       /* Total physical pages */
            DWORD DIFree_Count;       /* Free physical pages */
            DWORD DILin_Total_Count;  /* Total virtual pages (private arena) */
            DWORD DILin_Total_Free;   /* Free virtual pages (private arena) */

            DWORD SparseTotal;        /* Total size of sparse arena (bytes ?) */
            DWORD SparseFree;         /* Free size of sparse arena (bytes ?) */
        };

        struct Win32sMemoryInfo *info =
                       (struct Win32sMemoryInfo *)W32S_APP2WINE(context->Esi);

        FIXME("KGlobalMemStat(%lx)\n", (DWORD)info);

        /* FIXME */
    }
    break;


    case 0x001C: /* Enable/Disable Exceptions */
        /*
         * Input:   ECX: 0 to disable, 1 to enable exception handling
         *
         * Output:  None
         */

        TRACE("[001c] ECX=%lx\n", context->Ecx);

        /* FIXME */
        break;


    case 0x001D: /* VirtualAlloc called from 16-bit code */
        /*
         * Input:   EDX: Segmented address of arguments on stack
         *
         *   LPVOID base     [in]  Flat address of region to reserve/commit
         *   DWORD  size     [in]  Size of region
         *   DWORD  type     [in]  Type of allocation
         *   DWORD  prot     [in]  Type of access protection
         *
         * Output:  EAX: NtStatus
         *          EDX: Flat base address of allocated region
         */
    {
        DWORD *stack  = MapSL( MAKESEGPTR( LOWORD(context->Edx), HIWORD(context->Edx) ));
        LPVOID base   = (LPVOID)W32S_APP2WINE(stack[0]);
        DWORD  size   = stack[1];
        DWORD  type   = stack[2];
        DWORD  prot   = stack[3];
        DWORD  result;

        TRACE("VirtualAlloc16(%lx, %lx, %lx, %lx)\n",
                   (DWORD)base, size, type, prot);

        if (type & 0x80000000)
        {
            WARN("VirtualAlloc16: strange type %lx\n", type);
            type &= 0x7fffffff;
        }

        result = (DWORD)VirtualAlloc(base, size, type, prot);

        if (W32S_WINE2APP(result))
            context->Edx = W32S_WINE2APP(result),
            context->Eax = STATUS_SUCCESS;
        else
            context->Edx = 0,
            context->Eax = STATUS_NO_MEMORY;  /* FIXME */
	TRACE("VirtualAlloc16: returning base %lx\n", context->Edx);
    }
    break;


    case 0x001E: /* VirtualFree called from 16-bit code */
        /*
         * Input:   EDX: Segmented address of arguments on stack
         *
         *   LPVOID base     [in]  Flat address of region
         *   DWORD  size     [in]  Size of region
         *   DWORD  type     [in]  Type of operation
         *
         * Output:  EAX: NtStatus
         *          EDX: TRUE if success, FALSE if failure
         */
    {
        DWORD *stack  = MapSL( MAKESEGPTR( LOWORD(context->Edx), HIWORD(context->Edx) ));
        LPVOID base   = (LPVOID)W32S_APP2WINE(stack[0]);
        DWORD  size   = stack[1];
        DWORD  type   = stack[2];
        DWORD  result;

        TRACE("VirtualFree16(%lx, %lx, %lx)\n",
                   (DWORD)base, size, type);

        result = VirtualFree(base, size, type);

        if (result)
            context->Edx = TRUE,
            context->Eax = STATUS_SUCCESS;
        else
            context->Edx = FALSE,
            context->Eax = STATUS_NO_MEMORY;  /* FIXME */
    }
    break;


    case 0x001F: /* FWorkingSetSize */
        /*
         * Input:   EDX: 0 if Get, 1 if Set
         *
         *          ECX: Get: Buffer to receive Working Set Size
         *               Set: Buffer containing Working Set Size
         *
         * Output:  NtStatus
         */
    {
        DWORD *ptr = (DWORD *)W32S_APP2WINE(context->Ecx);
        BOOL set = context->Edx;

        TRACE("FWorkingSetSize(%lx, %lx)\n", (DWORD)ptr, (DWORD)set);

        if (set)
            /* We do it differently ... */;
        else
            *ptr = 0x100;

        context->Eax = STATUS_SUCCESS;
    }
    break;


    default:
	VXD_BARF( context, "W32S" );
    }
Esempio n. 16
0
///////////////////////////////////////
// read in the DIB file format (256 color BMP)
///////////////////////////////////////
BOOL CDib::ReadFile(LPSTR lpszFilename)
{
	BITMAPINFOHEADER   bih;
	OFSTRUCT           of;
	HFILE              fh;
	DWORD              dwFileStart;
	BITMAPFILEHEADER   bif;
	UINT               rgbQuadTableSize;
	UINT               lpbitsSize;
	UINT               nPalEntries;
    
	// open the DIB file to initialize OFSTRUCT
	fh = OpenFile(lpszFilename, &of, OF_READ);
	if (fh == -1)
	{ 
	  SetCDibState(FAIL_DIB_OPEN);
	  return FALSE;
	}

    // find the beginning of the DIB file	
 	dwFileStart = _llseek(fh, 0L, FILE_BEGIN);

	// BITMAPFILEHEADER

	// read in the BITMAPFILEHEADER
    if ((_lread(fh,&bif, sizeof(bif))) != sizeof(bif)) 
    {
		SetCDibState(FAIL_FHDR_READ);
		_lclose(fh);
		return FALSE;
    }

    // is the BITMAPFILEHEADER field bfType = 'BM' ?
    if (bif.bfType != 0x4D42) 
    {
		SetCDibState(FAIL_BFTYPE_INVALID);
		_lclose(fh);
		return FALSE;
    }
	

	// BITMAPINFOHEADER

	// read in the BITMAPINFOHEADER
    if ((_lread(fh, &bih, sizeof(bih))) != sizeof(bih)) 
    {
		SetCDibState(FAIL_IHDR_READ);
		_lclose(fh);
		return FALSE;
    }

    // BITMAPINFO

    CreateBITMAPINFO();      

	if (lpbinfo == NULL)
	{
	  _lclose(fh);
	  return FALSE;
	}

    // Copy the header we already have.
    memcpy(lpbinfo, &bih, sizeof(BITMAPINFOHEADER));

	// RGBQUAD

	// determine the RGBQUAD array size
    nPalEntries = NumberOfColorEntries((LPBITMAPINFO) &bih);
    rgbQuadTableSize = nPalEntries * sizeof(RGBQUAD);

    // Read the color table from the file.
    if ((_lread(fh,((LPBYTE) lpbinfo) + sizeof(BITMAPINFOHEADER),rgbQuadTableSize)) != rgbQuadTableSize) 
    {			   // 
        SetCDibState(FAIL_FORMAT_INVALID);
		_lclose(fh);
		return FALSE;
    }

	// assign the LPRGBQUAD pointer to the RGBQUAD array
	lprgb = GetLPRGBPtr();

	// Image Bits

    // Free any previous garbage
	if (lpBits != NULL) 
       GlobalFreePtr(lpBits);

	// determine the size of the image in the file
	lpbitsSize = bif.bfSize - bif.bfOffBits;

	// allocate memory to hold the image
    lpBits = (LPBYTE) GlobalAllocPtr(GMEM_MOVEABLE,lpbitsSize);
    if (lpBits == NULL) 
    {
		SetCDibState(FAIL_BITS_ALLOC);
		_lclose(fh);
		return FALSE;
    }

    // move the file handle to the start of the image
	_llseek(fh, dwFileStart + bif.bfOffBits, FILE_BEGIN);
	
    // read the image into memory
    if ((_lread(fh, lpBits, lpbitsSize)) != lpbitsSize) 
    {
		SetCDibState(FAIL_BITS_READ);
		_lclose(fh);
		return FALSE;
    }

	// all done, close the file
	_lclose(fh);
    return TRUE;
}
Esempio n. 17
0
/*
 * Reads a DIB from a file, obtains a handle to its BITMAPINFO struct, and
 * loads the DIB.  Once the DIB is loaded, the function also creates a bitmap
 * and palette out of the DIB for a device-dependent form.
 *
 * Returns TRUE if the DIB is loaded and the bitmap/palette created, in which
 * case, the DIBINIT structure pointed to by pInfo is filled with the appropriate
 * handles, and FALSE if something went wrong.
 */
BOOL ReadDIB(HWND hWnd, LPSTR lpFileName, DIBINIT *pInfo)
{
    HFILE fh;
    LPBITMAPINFOHEADER lpbi;
    OFSTRUCT of;
    BITMAPFILEHEADER bf;
    WORD nNumColors;
    BOOL result = FALSE;
    DWORD offBits;
    HDC hDC;
    BOOL bCoreHead = FALSE;

    /* Open the file and get a handle to it's BITMAPINFO */
    fh = OpenFile(lpFileName, &of, OF_READ);
    if (fh == -1)
        return (FALSE);

    pInfo->hDIB = GlobalAlloc(GHND, (DWORD)(sizeof(BITMAPINFOHEADER) +
                                            256 * sizeof(RGBQUAD)));

    if (!pInfo->hDIB)
        return (FALSE);

    lpbi = (LPBITMAPINFOHEADER)GlobalLock(pInfo->hDIB);

    /* read the BITMAPFILEHEADER */
    if (sizeof (bf) != _lread(fh, (LPSTR)&bf, sizeof(bf)))
        goto ErrExit;

    /* 'BM' */
    if (bf.bfType != 0x4d42)
        goto ErrExit;

    if (sizeof(BITMAPCOREHEADER) != _lread(fh, (LPSTR)lpbi, sizeof(BITMAPCOREHEADER)))
        goto ErrExit;

    if (lpbi->biSize == sizeof(BITMAPCOREHEADER))
    {
        lpbi->biSize = sizeof(BITMAPINFOHEADER);
        lpbi->biBitCount = ((LPBITMAPCOREHEADER)lpbi)->bcBitCount;
        lpbi->biPlanes = ((LPBITMAPCOREHEADER)lpbi)->bcPlanes;
        lpbi->biHeight = ((LPBITMAPCOREHEADER)lpbi)->bcHeight;
        lpbi->biWidth = ((LPBITMAPCOREHEADER)lpbi)->bcWidth;
        bCoreHead = TRUE;
    }
    else
    {
        /* get to the start of the header and read INFOHEADER */
        _llseek(fh, sizeof(BITMAPFILEHEADER), SEEK_SET);
        if (sizeof(BITMAPINFOHEADER) != _lread(fh, (LPSTR)lpbi, sizeof(BITMAPINFOHEADER)))
            goto ErrExit;
    }

    if (!(nNumColors = (WORD)lpbi->biClrUsed))
    {
        /* no color table for 24-bit, default size otherwise */
        if (lpbi->biBitCount != 24)
            nNumColors = 1 << lpbi->biBitCount;
    }

    /* fill in some default values if they are zero */
    if (lpbi->biClrUsed == 0)
        lpbi->biClrUsed = nNumColors;

    if (lpbi->biSizeImage == 0)
    {
        lpbi->biSizeImage = (((((lpbi->biWidth * (DWORD)lpbi->biBitCount) + 31) & ~31) >> 3)
                             * lpbi->biHeight);
    }
Esempio n. 18
0
BOOL XSendPacket(PFileVar fv, PXVar xv, PComVar cv)
{
	BYTE b;
	int i;
	BOOL SendFlag;
	WORD Check;

	SendFlag = FALSE;
	if (xv->PktBufCount == 0) {
		i = XRead1Byte(fv, xv, cv, &b);
		do {
			if (i == 0)
				return TRUE;
			switch (b) {
			case ACK:
				if (!fv->FileOpen) {
					fv->Success = TRUE;
					return FALSE;
				} else if (xv->PktNumSent == (BYTE) (xv->PktNum + 1)) {
					xv->PktNum = xv->PktNumSent;
					if (xv->PktNum == 0)
						xv->PktNumOffset = xv->PktNumOffset + 256;
					SendFlag = TRUE;
				}
				break;
			case NAK:
				if (xv->PktNum == 0 && xv->XOpt == Xopt1K) {
					/* we wanted 1k with CRC, but the other end specified checksum */
					/* keep the 1k block, but move back to checksum mode.          */
					xv->XOpt = XoptCheck;
					xv->CheckLen = 1;
				}
				SendFlag = TRUE;
				break;
			case CAN:
				break;
			case 0x43:
				if ((xv->PktNum == 0) && (xv->PktNumOffset == 0) && (xv->PktNumSent == 0)) {
					 if ((xv->XOpt == XoptCheck))
						XSetOpt(fv, xv, XoptCRC);
					SendFlag = TRUE;
				}
				break;
			}
			if (!SendFlag)
				i = XRead1Byte(fv, xv, cv, &b);
		} while (!SendFlag);
		// reset timeout timer
		FTSetTimeOut(fv, TimeOutVeryLong);

		do {
			i = XRead1Byte(fv, xv, cv, &b);
		} while (i != 0);

		if (xv->PktNumSent == xv->PktNum) {	/* make a new packet */
			xv->PktNumSent++;
			if (xv->DataLen == 128)
				xv->PktOut[0] = SOH;
			else
				xv->PktOut[0] = STX;
			xv->PktOut[1] = xv->PktNumSent;
			xv->PktOut[2] = ~xv->PktNumSent;

			i = 1;
			while ((i <= xv->DataLen) && fv->FileOpen &&
				   (_lread(fv->FileHandle, &b, 1) == 1)) {
				xv->PktOut[2 + i] = b;
				i++;
				fv->ByteCount++;
			}

			if (i > 1) {
				while (i <= xv->DataLen) {
					xv->PktOut[2 + i] = 0x1A;
					i++;
				}

				Check = XCalcCheck(xv, xv->PktOut);
				if (xv->CheckLen == 1)	/* Checksum */
					xv->PktOut[xv->DataLen + 3] = (BYTE) Check;
				else {
					xv->PktOut[xv->DataLen + 3] = HIBYTE(Check);
					xv->PktOut[xv->DataLen + 4] = LOBYTE(Check);
				}
				xv->PktBufCount = 3 + xv->DataLen + xv->CheckLen;
			} else {			/* send EOT */
				if (fv->FileOpen) {
					_lclose(fv->FileHandle);
					fv->FileHandle = 0;
					fv->FileOpen = FALSE;
				}
				xv->PktOut[0] = EOT;
				xv->PktBufCount = 1;
			}
		} else {				/* resend packet */
			if (xv->PktOut[0] == EOT) {
				xv->PktBufCount = 1;
			} else {
				xv->PktBufCount = 3 + xv->DataLen + xv->CheckLen;
			}
		}
		xv->PktBufPtr = 0;
	}
	/* a NAK or C could have arrived while we were buffering.  Consume it. */
	do {
		i = XRead1Byte(fv, xv, cv, &b);
	} while (i != 0);

	i = 1;
	while ((xv->PktBufCount > 0) && (i > 0)) {
		b = xv->PktOut[xv->PktBufPtr];
		i = XWrite(fv, xv, cv, &b, 1);
		if (i > 0) {
			xv->PktBufCount--;
			xv->PktBufPtr++;
		}
	}

	if (xv->PktBufCount == 0) {
		if (xv->PktNumSent == 0) {
			SetDlgNum(fv->HWin, IDC_PROTOPKTNUM, xv->PktNumOffset + 256);
		}
		else {
			SetDlgNum(fv->HWin, IDC_PROTOPKTNUM, xv->PktNumOffset + xv->PktNumSent);
		}
		SetDlgNum(fv->HWin, IDC_PROTOBYTECOUNT, fv->ByteCount);
		SetDlgPercent(fv->HWin, IDC_PROTOPERCENT, IDC_PROTOPROGRESS,
		              fv->ByteCount, fv->FileSize, &fv->ProgStat);
		SetDlgTime(fv->HWin, IDC_PROTOELAPSEDTIME, fv->StartTime, fv->ByteCount);
	}

	return TRUE;
}
Esempio n. 19
0
File: file.c Progetto: bilboed/wine
/***********************************************************************
 *           _lread16   (KERNEL.82)
 */
UINT16 WINAPI _lread16( HFILE16 hFile, LPVOID buffer, UINT16 count )
{
    return (UINT16)_lread((HFILE)DosFileHandleToWin32Handle(hFile), buffer, (LONG)count );
}
Esempio n. 20
0
/**************************************************************************
 *               	mmioDosIOProc           		[internal]
 */
static LRESULT CALLBACK mmioDosIOProc(LPMMIOINFO lpmmioinfo, UINT uMessage,
				      LPARAM lParam1, LPARAM lParam2)
{
    LRESULT	ret = MMSYSERR_NOERROR;

    TRACE("(%p, %X, 0x%lx, 0x%lx);\n", lpmmioinfo, uMessage, lParam1, lParam2);

    switch (uMessage) {
    case MMIOM_OPEN:
	{
	    /* Parameters:
	     * lParam1 = szFileName parameter from mmioOpen
	     * lParam2 = reserved
	     * Returns: zero on success, error code on error
	     * NOTE: lDiskOffset automatically set to zero
	     */
	    LPCSTR      szFileName = (LPCSTR)lParam1;

	    if (lpmmioinfo->dwFlags & MMIO_GETTEMP) {
		FIXME("MMIO_GETTEMP not implemented\n");
		return MMIOERR_CANNOTOPEN;
	    }

	    /* if filename NULL, assume open file handle in adwInfo[0] */
	    if (szFileName) {
                OFSTRUCT    ofs;
                lpmmioinfo->adwInfo[0] = (DWORD)OpenFile(szFileName, &ofs, lpmmioinfo->dwFlags & 0xFFFF);
            }
	    if (lpmmioinfo->adwInfo[0] == (DWORD)HFILE_ERROR)
		ret = MMIOERR_CANNOTOPEN;
	}
	break;

    case MMIOM_CLOSE:
	/* Parameters:
	 * lParam1 = wFlags parameter from mmioClose
	 * lParam2 = unused
	 * Returns: zero on success, error code on error
	 */
	if (!(lParam1 & MMIO_FHOPEN))
	    _lclose((HFILE)lpmmioinfo->adwInfo[0]);
	break;

    case MMIOM_READ:
	/* Parameters:
	 * lParam1 = huge pointer to read buffer
	 * lParam2 = number of bytes to read
	 * Returns: number of bytes read, 0 for EOF, -1 for error (error code
	 *	   in wErrorRet)
	 */
	ret = _lread((HFILE)lpmmioinfo->adwInfo[0], (HPSTR)lParam1, (LONG)lParam2);
	if (ret != -1)
	    lpmmioinfo->lDiskOffset += ret;

	break;

    case MMIOM_WRITE:
    case MMIOM_WRITEFLUSH:
	/* no internal buffering, so WRITEFLUSH handled same as WRITE */

	/* Parameters:
	 * lParam1 = huge pointer to write buffer
	 * lParam2 = number of bytes to write
	 * Returns: number of bytes written, -1 for error (error code in
	 *		wErrorRet)
	 */
	ret = _hwrite((HFILE)lpmmioinfo->adwInfo[0], (HPSTR)lParam1, (LONG)lParam2);
	if (ret != -1)
	    lpmmioinfo->lDiskOffset += ret;
	break;

    case MMIOM_SEEK:
	/* Parameters:
	 * lParam1 = new position
	 * lParam2 = from whence to seek (SEEK_SET, SEEK_CUR, SEEK_END)
	 * Returns: new file postion, -1 on error
	 */
	ret = _llseek((HFILE)lpmmioinfo->adwInfo[0], (LONG)lParam1, (LONG)lParam2);
	if (ret != -1)
	    lpmmioinfo->lDiskOffset = ret;
	return ret;

    case MMIOM_RENAME:
	/* Parameters:
	 * lParam1 = old name
	 * lParam2 = new name
	 * Returns: zero on success, non-zero on failure
	 */
 	 if (!MoveFileA((const char*)lParam1, (const char*)lParam2))
	     ret = MMIOERR_FILENOTFOUND;
	 break;

    default:
	FIXME("unexpected message %u\n", uMessage);
	return 0;
    }

    return ret;
}
Esempio n. 21
0
/***********************************************************************
 *           LZRead   (KERNEL32.@)
 */
INT WINAPI LZRead( HFILE fd, LPSTR vbuf, INT toread )
{
	int	howmuch;
	BYTE	b,*buf;
	struct	lzstate	*lzs;

	buf=(LPBYTE)vbuf;
	TRACE("(%d,%p,%d)\n",fd,buf,toread);
	howmuch=toread;
	if (!(lzs = GET_LZ_STATE(fd))) return _lread(fd,buf,toread);

/* The decompressor itself is in a define, cause we need it twice
 * in this function. (the decompressed byte will be in b)
 */
#define DECOMPRESS_ONE_BYTE 						\
		if (lzs->stringlen) {					\
			b		= lzs->table[lzs->stringpos];	\
			lzs->stringpos	= (lzs->stringpos+1)&0xFFF;	\
			lzs->stringlen--;				\
		} else {						\
			if (!(lzs->bytetype&0x100)) {			\
				if (1!=GET(lzs,b)) 			\
					return toread-howmuch;		\
				lzs->bytetype = b|0xFF00;		\
			}						\
			if (lzs->bytetype & 1) {			\
				if (1!=GET(lzs,b))			\
					return toread-howmuch;		\
			} else {					\
				BYTE	b1,b2;				\
									\
				if (1!=GET(lzs,b1))			\
					return toread-howmuch;		\
				if (1!=GET(lzs,b2))			\
					return toread-howmuch;		\
				/* Format:				\
				 * b1 b2				\
				 * AB CD 				\
				 * where CAB is the stringoffset in the table\
				 * and D+3 is the len of the string	\
				 */					\
				lzs->stringpos	= b1|((b2&0xf0)<<4);	\
				lzs->stringlen	= (b2&0xf)+2; 		\
				/* 3, but we use a  byte already below ... */\
				b		= lzs->table[lzs->stringpos];\
				lzs->stringpos	= (lzs->stringpos+1)&0xFFF;\
			}						\
			lzs->bytetype>>=1;				\
		}							\
		/* store b in table */					\
		lzs->table[lzs->curtabent++]= b;			\
		lzs->curtabent	&= 0xFFF;				\
		lzs->realcurrent++;

	/* if someone has seeked, we have to bring the decompressor
	 * to that position
	 */
	if (lzs->realcurrent!=lzs->realwanted) {
		/* if the wanted position is before the current position
		 * I see no easy way to unroll ... We have to restart at
		 * the beginning. *sigh*
		 */
		if (lzs->realcurrent>lzs->realwanted) {
			/* flush decompressor state */
			_llseek(lzs->realfd,LZ_HEADER_LEN,SEEK_SET);
			GET_FLUSH(lzs);
			lzs->realcurrent= 0;
			lzs->bytetype	= 0;
			lzs->stringlen	= 0;
			memset(lzs->table,' ',LZ_TABLE_SIZE);
			lzs->curtabent	= 0xFF0;
		}
		while (lzs->realcurrent<lzs->realwanted) {
			DECOMPRESS_ONE_BYTE;
		}
	}

	while (howmuch) {
		DECOMPRESS_ONE_BYTE;
		lzs->realwanted++;
		*buf++		= b;
		howmuch--;
	}
	return 	toread;
#undef DECOMPRESS_ONE_BYTE
}
Esempio n. 22
0
BOOL EXTERN ValidColorSpace(LPPDEVICE lppd, LPICMINFO lpICMI, LPCSIG lpDevCS )
{
    icHeader    CPHeader;
    HFILE       hFile;
    SINT        Res;
    CSIG        CPColorSpaceTag;

    if (NULL == lpICMI)
    {
        return(FALSE);
    }
    hFile = _lopen(lpICMI->lcsDestFilename, READ);
    if( hFile == HFILE_ERROR )
    {
        return(FALSE);
    }

    Res = _lread(hFile, (LPVOID) &CPHeader, sizeof(CPHeader));
    _lclose(hFile);
    if( (Res == HFILE_ERROR) || (Res != sizeof(CPHeader)) )
    {
        return(FALSE);
    }

    // Make the initial check for validity of the profile
    if( SigtoCSIG(CPHeader.magic) != icMagicNumber )
    {
        return(FALSE);
    }
    // Make sure the profile is 'prtr'
    // SRGB98
    // if( SigtoCSIG(CPHeader.deviceClass) != icSigOutputClass )
    // {
    //     return(FALSE);
    // }
    CPColorSpaceTag = SigtoCSIG(CPHeader.colorSpace);
    *lpDevCS = CPColorSpaceTag;             // 247974

    switch ( lppd->lpPSExtDevmode->dm.iColorMatchingMethod )
    {
        case COLOR_MATCHING_ON_HOST:
            if ((CPColorSpaceTag == icSigCmyData))
//                (CPColorSpaceTag == icSigRgbData))
//                (CPColorSpaceTag == icSigGrayData))
            {
                return(FALSE);
            }
            break;
            case COLOR_MATCHING_ON_PRINTER:
            if ((CPColorSpaceTag == icSigCmyData))
//                (CPColorSpaceTag == icSigGrayData))
            {
                return(FALSE);
            }
            break;
        case COLOR_MATCHING_PRINTER_CALIBRATION:
        default:
            break;
    }
    return (TRUE);
}
Esempio n. 23
0
MODULE_HEADERS *
ExecPE(char *lpszName)
{
	static void *BaseAddress;

	IMAGE_DOS_HEADER DosHeader;
 	PIMAGE_SECTION_HEADER pSectionHeaders;
	PIMAGE_NT_HEADERS pNTHeader;
	static int nNTHeader;
	int i,len;
	int index = nNTHeader;
	char *bp;
	int ret;
	HFILE hFile;

	bp = lpszName;
	while(*bp) {
		*bp = tolower(*bp);
		bp++;
	}
	for(i=0;i<nNTHeader;i++) {
		if(strcmp(NTModules[i].modulename,lpszName) == 0) {
			return &NTModules[i];
		}
	}

    	hFile = _lopen(lpszName,READ);
	if(hFile == -1) {
		char lpszFileName[256];

		strcpy(lpszFileName,dirname);	
		strcat(lpszFileName,"/");	
		strcat(lpszFileName,lpszName);	

		hFile = _lopen(lpszFileName,READ);

		if(hFile == -1) {
			logstr(LF_ERROR,"cannot open file %s\n",lpszFileName);
			return 0;
		}		
	}

	/* read the dos image header first */
        ret = _lread(hFile,&DosHeader,sizeof(IMAGE_DOS_HEADER));

	if(DosHeader.e_magic == IMAGE_DOS_SIGNATURE)	{

		/* now read in the nt header */
    		_llseek(hFile,DosHeader.e_lfanew,0);

		pNTHeader = &NTHeader[nNTHeader];

		ret = _lread(hFile,pNTHeader, sizeof(IMAGE_NT_HEADERS));

		/* yes, it is a win32 header */
		if (pNTHeader->Signature != IMAGE_NT_SIGNATURE) {
			_lclose(hFile);
			return 0;
		}
		

		bp = strrchr(lpszName,'/');
		if(bp)
			bp++;
		else 
			bp = lpszName;

		BaseAddress = VirtualAlloc(
			(void *) pNTHeader->OptionalHeader.ImageBase,
			pNTHeader->OptionalHeader.SizeOfImage,
			MEM_COMMIT,
			PAGE_EXECUTE_READWRITE);

		logstr(lf_console,"Load File: %s %p\n",lpszName,BaseAddress);

		NTModules[nNTHeader].modulename = bp; 		
		NTModules[nNTHeader].pNTHeader = pNTHeader; 		
		NTModules[nNTHeader].BaseAddress = BaseAddress; 		
		nNTHeader++;

		if (nNTHeader == 1 && usebuiltins) {
			NTModules[nNTHeader++].modulename = "user32.dll";
			NTModules[nNTHeader++].modulename = "gdi32.dll";
			NTModules[nNTHeader++].modulename = "kernel32.dll";
			NTModules[nNTHeader++].modulename = "shell32.dll";
			NTModules[nNTHeader++].modulename = "comctl32.dll";
			NTModules[nNTHeader++].modulename = "comdlg32.dll";
			NTModules[nNTHeader++].modulename = "rpcrt4.dll";
			NTModules[nNTHeader++].modulename = "advapi32.dll";
		}

		/* show the NT header */
	 	//if (index == 0)
		   DumpHeader(&pNTHeader->FileHeader);

		/* show the Optional header */
	 	//if (index == 0)
		   DumpOptionalHeader((PIMAGE_OPTIONAL_HEADER) 
			&pNTHeader->OptionalHeader);

		pSectionHeaders = (PIMAGE_SECTION_HEADER)((void *)BaseAddress + sizeof(IMAGE_NT_HEADERS));

		/* now read the section headers */
		ret = _lread( hFile, pSectionHeaders, sizeof(IMAGE_SECTION_HEADER)*
			pNTHeader->FileHeader.NumberOfSections);

		for(i=0; i < pNTHeader->FileHeader.NumberOfSections; i++) {
			void *LoadAddress;

			LoadAddress = 
				RVA(BaseAddress,pSectionHeaders->VirtualAddress);
			//if (index == 0) 
			{
			   DumpSectionTable( LoadAddress,pSectionHeaders,i);
			}

			/* load only non-BSS segments */
			if(!(pSectionHeaders->Characteristics &
				IMAGE_SCN_CNT_UNINITIALIZED_DATA)) 
		        {
			    _llseek(hFile,pSectionHeaders->PointerToRawData,SEEK_SET);
			    len = _lread(hFile,(char*) LoadAddress, 
				pSectionHeaders->SizeOfRawData);

			    if( len != pSectionHeaders->SizeOfRawData)
			    {
				logstr(LF_ERROR,"Failed to load section %x %x\n", i,len);
				exit(0);
			    }
			    pSectionHeaders++;
			}
			
			/* not needed, memory is zero */
			if(strcmp(pSectionHeaders[i].Name, ".bss") == 0)
			    memset((void *)LoadAddress, 0,
				   pSectionHeaders[i].Misc.VirtualSize ?
				   pSectionHeaders[i].Misc.VirtualSize :
				   pSectionHeaders[i].SizeOfRawData);
		}

		_lclose(hFile);

		// we are dependent on other modules, go get and load those
		//if (index == 0)
		   LoadImportsSection(BaseAddress, pNTHeader,lpszName);

		if (index == 0) 
		{
			logstr(lf_header,"   %32s   PE Header  BaseAddress\n",
				"FileName");
			for(i=0;i<nNTHeader;i++) {
			   logstr(lf_header,"%.4d: %32s %p %p\n",
				i,
				NTModules[i].modulename,
				NTModules[i].pNTHeader,
				NTModules[i].BaseAddress);
			}	
        		
		}

		if (index == 0)
		   LoadExportsTable(&NTModules[0],pNTHeader,lpszName);

		if (index == 0)
		   ExecEntryPoint(
			NTModules[0].BaseAddress, 
			NTModules[0].pNTHeader, 
			lpszName);

		return &NTModules[index]; 		
	}
	return 0;
}
Esempio n. 24
0
/*--------------------------------------------------
  read BMP file and return bitmap handle
----------------------------------------------------*/
HBITMAP ReadBitmap(HWND hwnd, const char* fname, BOOL bTrans)
{
	BITMAPFILEHEADER bmfh;
	BYTE* pDib;
	DWORD size;
	HFILE hf;
	BITMAPINFOHEADER* pbmih;
	BYTE* pDIBits;
	HDC hdc;
	int index;
	HBITMAP hBmp;
	
	hf = _lopen(fname, OF_READ);
	if(hf == HFILE_ERROR) return NULL;
	
	size = _llseek(hf, 0, 2) - sizeof(BITMAPFILEHEADER);
	_llseek(hf, 0, 0);
	
	if(_lread(hf, (LPSTR)&bmfh, sizeof(BITMAPFILEHEADER)) !=
		sizeof(BITMAPFILEHEADER))
	{
		_lclose(hf); return NULL;
	}
	
	if(bmfh.bfType != *(WORD *)"BM")
	{
		_lclose(hf); return NULL;
	}
	
	pDib = malloc(size);
	if(pDib == NULL)
	{
		_lclose (hf); return NULL;
	}
	
	if(_lread(hf, pDib, size) != size)
	{
		_lclose(hf); free(pDib);
		return NULL;
	}
	_lclose(hf);
	
	pbmih = (BITMAPINFOHEADER*)pDib;
	// don't support OS/2 format
	if(pbmih->biSize != sizeof(BITMAPINFOHEADER))
	{
		free(pDib); return NULL;
	}
	// don't support RLE compression
	if(pbmih->biCompression != BI_RGB &&
		pbmih->biCompression != BI_BITFIELDS)
	{
		free(pDib); return NULL;
	}
	
	if(pbmih->biCompression == BI_RGB)
		pDIBits = GetDibBitsAddr(pDib);
	else
		pDIBits = pDib + sizeof(BITMAPINFOHEADER) + 3 * sizeof(DWORD);
	
	if(bTrans) // pseudo transparency
	{
		if(pbmih->biBitCount == 1)
			index = (*pDIBits & 0x80) >> 7;
		else if(pbmih->biBitCount == 4)
			index = (*pDIBits & 0xF0) >> 4;
		else if(pbmih->biBitCount == 8)
Esempio n. 25
0
/************************************************************************************************
*																								*
*   读取24位真彩色位图像素数据函数,每个像素用3个字节RGB表示                                    *
*   打开图像文件,解析位图文件结构,分解出位图文件头、位图信息头,像素数据						*
*   输入参数:imgFileName - 文件名                                                              *
*   返回值  :              存放24位真彩色位图像素RGB数据及尺寸为320*240位图结构指针            *
*																								*
************************************************************************************************/
BmpImage* ReadBmpFile(LPSTR imgFileName)
{
	OFSTRUCT of;
	HFILE Image_fp;
	BITMAPFILEHEADER bfImage;
	BITMAPINFOHEADER biImage;
	BmpImage *pImage;


	if( strlen(imgFileName) == 0 )
		return NULL;
	
	Image_fp = OpenFile(imgFileName, &of, OF_READ);
	if (Image_fp == HFILE_ERROR) 
	{
		MessageBox(NULL, "打开读bmp图像文件出错", "打开文件出错信息", MB_OK);
		return NULL;
	}

	// 定位及读取位图文件头
	_llseek(Image_fp, 0, 0);
	_lread(Image_fp, &bfImage, sizeof(BITMAPFILEHEADER));

	// "BM" (0x4d42):表示位图BMP
	if ((bfImage.bfType != 0x4d42)) 
	{
		MessageBox(NULL, "非bmp文件", "打开bmp文件出错信息", MB_OK);
		_lclose(Image_fp);
		return NULL;
	}

	// 读取位图信息头
	_lread(Image_fp, &biImage, sizeof(BITMAPINFOHEADER));

	if (biImage.biBitCount != 24)
	{
		MessageBox(NULL, "非24位真彩色位图", "读取bmp文件出错信息", MB_OK);
		_lclose(Image_fp);
		return NULL;
	}

	// 分配临时存储像素数据空间
	pImage = MallocBmpImage(biImage.biWidth, biImage.biHeight);
	if( pImage == NULL )
	{
		MessageBox(NULL, "系统没有足够内存空间以分配存储位图", "读取bmp文件出错信息", MB_OK);
		_lclose(Image_fp);
		return NULL;
	}

	// 定位及读取位图像素阵列数据
	_llseek(Image_fp, bfImage.bfOffBits, 0);
	_lread(Image_fp, pImage->data, biImage.biSizeImage);

	// 丢掉bmp像素数据中补齐每行像素字节数4倍的无效数据0,得RGB真实像素数据
	ExtractImageData(pImage);
	
	// bmp图片像素从下到上,从左到右,倒转为从上到下,从左到右
	ReverseImageData(pImage);

	//图像缩放归一化,限定输出图像尺寸:320*240
	NormalizeImageSize(pImage, 320, 240);
						
	_lclose(Image_fp);

	return pImage;
}
Esempio n. 26
0
HANDLE ReadDIBFile(int hFile)
{
   BITMAPFILEHEADER bmfHeader;
   DWORD dwBitsSize;
   UINT nNumColors;   // Number of colors in table
   HANDLE hDIB;        
   HANDLE hDIBtmp;    // Used for GlobalRealloc() //MPB
   LPBITMAPINFOHEADER lpbi;
   DWORD offBits;

   /*
    * get length of DIB in bytes for use when reading
    */

   dwBitsSize = filelength(hFile);

   // Allocate memory for header & color table.	We'll enlarge this
   // memory as needed.

   hDIB = GlobalAlloc(GMEM_MOVEABLE,
       (DWORD)(sizeof(BITMAPINFOHEADER) + 256 * sizeof(RGBQUAD)));
   
   if (!hDIB) return NULL;

   lpbi = (LPBITMAPINFOHEADER)GlobalLock(hDIB);
   if (!lpbi) 
   {
     GlobalFree(hDIB);
     return NULL;
   }

   // read the BITMAPFILEHEADER from our file

   if (sizeof (BITMAPFILEHEADER) != _lread (hFile, (LPSTR)&bmfHeader, sizeof (BITMAPFILEHEADER)))
     goto ErrExit;

   if (bmfHeader.bfType != 0x4d42)	/* 'BM' */
     goto ErrExit;

   // read the BITMAPINFOHEADER

   if (sizeof(BITMAPINFOHEADER) != _lread (hFile, (LPSTR)lpbi, sizeof(BITMAPINFOHEADER)))
     goto ErrExit;

   // Check to see that it's a Windows DIB -- an OS/2 DIB would cause
   // strange problems with the rest of the DIB API since the fields
   // in the header are different and the color table entries are
   // smaller.
   //
   // If it's not a Windows DIB (e.g. if biSize is wrong), return NULL.

   if (lpbi->biSize == sizeof(BITMAPCOREHEADER))
     goto ErrExit;

   // Now determine the size of the color table and read it.  Since the
   // bitmap bits are offset in the file by bfOffBits, we need to do some
   // special processing here to make sure the bits directly follow
   // the color table (because that's the format we are susposed to pass
   // back)

   if (!(nNumColors = (UINT)lpbi->biClrUsed))
    {
      // no color table for 24-bit, default size otherwise
      if (lpbi->biBitCount != 24)
        nNumColors = 1 << lpbi->biBitCount; /* standard size table */
    }

   // fill in some default values if they are zero
   if (lpbi->biClrUsed == 0)
     lpbi->biClrUsed = nNumColors;

   if (lpbi->biSizeImage == 0)
   {
     lpbi->biSizeImage = ((((lpbi->biWidth * (DWORD)lpbi->biBitCount) + 31) & ~31) >> 3)
			 * lpbi->biHeight;
   }
Esempio n. 27
0
BOOL    EXTERN LoadCP(LPCSTR filename, HGLOBAL FAR *phMem, LPCHANDLE lpCP)
{
    icHeader    CPHeader;
    HFILE       hFile;
    SINT        Res, CPSize;
    MEMPTR      mpCP;

    *phMem = 0;
    if (lpCP == NULL)
    {
        SetCPLastError(CP_NULL_POINTER_ERR);
        return(FALSE);
    }

    hFile = _lopen(filename, READ );
    if( hFile == HFILE_ERROR )
    {
        SetCPLastError(CP_FILE_OPEN_ERR);
        return(FALSE);
    }
 
    Res = _lread(hFile, (LPVOID) &CPHeader, sizeof(CPHeader));
    if( (Res == HFILE_ERROR) ||
        (Res != sizeof(CPHeader)) )
    {
        _lclose(hFile);
        SetCPLastError(CP_FILE_READ_ERR);
        return(FALSE);
    }

    // Make the initial check for validity of the profile
    if( SigtoCSIG(CPHeader.magic) != icMagicNumber )
    {
        _lclose(hFile);
        SetCPLastError(CP_FORMAT_ERR);
        return(FALSE);
    }

    CPSize = ui32toSINT(CPHeader.size);
    if( MemAlloc(CPSize, phMem, (LPMEMPTR) &mpCP) )
    {

        *lpCP = (CHANDLE) mpCP;  // Put the memory pointer as  handle
        // Read profile into  memory
         _lseek(hFile, 0L, SEEK_SET);

        while(CPSize)
        {
            Res = _lread(hFile, (LPVOID) mpCP, 4096);
            if (Res == HFILE_ERROR) 
            {
                _lclose(hFile);
                SetCPLastError(CP_FILE_READ_ERR);
                return(FALSE);
            }
            mpCP    += Res;
            CPSize  -= Res;
        }
    }else
    {
        *phMem = 0;
        _lclose(hFile);
        return(FALSE);
    }
    _lclose(hFile);
    return (TRUE);
}
Esempio n. 28
0
int Load_Bitmap_File(BITMAP_FILE_PTR bitmap, char *filename)
{
// this function opens a bitmap file and loads the data into bitmap

int file_handle,  // the file handle
    index;        // looping index


UCHAR   *temp_buffer = NULL; // used to convert 24 bit images to 16 bit
OFSTRUCT file_data;          // the file data information

// open the file if it exists
if ((file_handle = OpenFile(filename,&file_data,OF_READ))==-1)
   return(0);


// now load the bitmap file header
_lread(file_handle, &bitmap->bitmapfileheader,sizeof(BITMAPFILEHEADER));

// test if this is a bitmap file
if (bitmap->bitmapfileheader.bfType!=0x4D42)
   {
   // close the file
   _lclose(file_handle);

   // return error
   return(0);

   } // end if

// now we know this is a bitmap, so read in all the sections

// first the bitmap infoheader

// now load the bitmap file header
_lread(file_handle, &bitmap->bitmapinfoheader,sizeof(BITMAPINFOHEADER));

// now load the color palette if there is one
if (bitmap->bitmapinfoheader.biBitCount == 8)
   {
   _lread(file_handle, &bitmap->palette,256*sizeof(PALETTEENTRY));

   // now set all the flags in the palette correctly and fix the reversed 
   // BGR RGBQUAD data format
   for (index=0; index < 256; index++)
       {
       // reverse the red and green fields
       int temp_color                = bitmap->palette[index].peRed;
       bitmap->palette[index].peRed  = bitmap->palette[index].peBlue;
       bitmap->palette[index].peBlue = temp_color;
       
       // always set the flags word to this
       bitmap->palette[index].peFlags = PC_NOCOLLAPSE;
       } // end for index

    } // end if

// finally the image data itself
_lseek(file_handle,-(int)(bitmap->bitmapinfoheader.biSizeImage),SEEK_END);

// now read in the image, if the image is 8 or 16 bit then simply read it
// but if its 24 bit then read it into a temporary area and then convert
// it to a 16 bit image

if (bitmap->bitmapinfoheader.biBitCount==8 || bitmap->bitmapinfoheader.biBitCount==16 || 
    bitmap->bitmapinfoheader.biBitCount==24)
   {
   // delete the last image if there was one
   if (bitmap->buffer)
       free(bitmap->buffer);

   // allocate the memory for the image
   if (!(bitmap->buffer = (UCHAR *)malloc(bitmap->bitmapinfoheader.biSizeImage)))
      {
      // close the file
      _lclose(file_handle);

      // return error
      return(0);
      } // end if

   // now read it in
   _lread(file_handle,bitmap->buffer,bitmap->bitmapinfoheader.biSizeImage);

   } // end if
else
   {
   // serious problem
   return(0);

   } // end else

#if 0
// write the file info out 
printf("\nfilename:%s \nsize=%d \nwidth=%d \nheight=%d \nbitsperpixel=%d \ncolors=%d \nimpcolors=%d",
        filename,
        bitmap->bitmapinfoheader.biSizeImage,
        bitmap->bitmapinfoheader.biWidth,
        bitmap->bitmapinfoheader.biHeight,
		bitmap->bitmapinfoheader.biBitCount,
        bitmap->bitmapinfoheader.biClrUsed,
        bitmap->bitmapinfoheader.biClrImportant);

#endif

// close the file
_lclose(file_handle);

// flip the bitmap
Flip_Bitmap(bitmap->buffer, 
            bitmap->bitmapinfoheader.biWidth*(bitmap->bitmapinfoheader.biBitCount/8), 
            bitmap->bitmapinfoheader.biHeight);

// return success

return(1);

} // end Load_Bitmap_File
Esempio n. 29
0
//---------------------------------------------------------------------------
// MainWndProc
//
// Main window procedure
//
// RETURNS:     Per Windows Convention....
//---------------------------------------------------------------------------
LONG  APIENTRY MainWndProc (HWND hwnd, WORD message,
                             WPARAM wParam, LPARAM lParam)
{
    FARPROC lpProcAbout;

    switch (message)
        {
        case WM_CREATE:
            {
            RECT    r;

            // Create an edit window for the client area
            //---------------------------------------------------------------
            GetClientRect (hwnd, &r);
            hwndEdit = CreateWindow ("RBEdit", NULL,
            //hwndEdit = CreateWindow ("edit", NULL,
            //                         ES_MULTILINE |
                                     WS_BORDER |
                                     WS_CHILD | WS_CLIPCHILDREN |
                                     WS_VSCROLL | WS_HSCROLL,
                                     0,
                                     20,
                                     r.right,
                                     r.bottom-20,
                                     hwnd,
                                     0xCAC,
                                     hInst,
                                     NULL);
            ShowWindow (hwndEdit, SW_SHOWNORMAL);
            fNotify = FALSE;
            break;
            }

        case WM_SIZE:
            // Move the edit window to fit the new client area
            //---------------------------------------------------------------
            if (IsWindow (hwndEdit))
                MoveWindow (hwndEdit, 0, 20,
                                      LOWORD(lParam), HIWORD(lParam)-20, 1);
            break;

        case WM_PAINT:
            {
            HDC         hdc;
            PAINTSTRUCT ps;

            hdc = BeginPaint (hwnd, &ps);
            PaintStatus (hwnd, hdc);
            EndPaint (hwnd, &ps);
            break;
            }

        case WM_SETFOCUS:
            if (IsWindow (hwndEdit))
                SetFocus (hwndEdit);
            break;

        case WM_SYSCOLORCHANGE:
            SendMessage (hwndEdit, message, wParam, lParam);
            break;

        case WM_COMMAND:
            switch (GET_WM_COMMAND_ID (wParam, lParam))
                {
                case IDM_ABOUT:
                    lpProcAbout = MakeProcInstance ((FARPROC)About, hInst);
                    DialogBox (hInst, "AboutBox", hwnd, (WNDPROC)lpProcAbout);
                    FreeProcInstance (lpProcAbout);
                    break;

                case IDM_CRASH:
                    {
                    INT     l;

                    l = (INT)SendMessage (hwndEdit, EM_LINELENGTH, 0, -1L);
                    SendMessage (hwndEdit, EM_SETSELXY, -1,
                                 MAKELONG (l, l+3));
                    break;
                    }

                case IDM_UNDO:
                    if (!SendMessage (hwndEdit, EM_UNDO, 0, 0L))
                        MessageBeep (0);
                    break;

                case IDM_SETRO:
                    SendMessage (hwndEdit, EM_SETREADONLY, 1, 0L);
                    break;

                case IDM_SETRW:
                    SendMessage (hwndEdit, EM_SETREADONLY, 0, 0L);
                    break;

                case IDM_SETFONT:
                    SendMessage (hwndEdit, EM_SETFONT,
                                 (WORD)GetStockObject (ANSI_FIXED_FONT), 0L);
                    break;

                case IDM_CHGATTR:
                    SendMessage (hwndEdit, EM_SETLINEATTR, -1, oldattr++);

                    if (oldattr == 4)
                        oldattr = 0;
                    break;

                case IDM_NOTIFY:
                    fNotify = !fNotify;
                    SendMessage (hwndEdit, EM_SETNOTIFY, fNotify, 0L);
                    CheckMenuItem (GetMenu (hwnd), IDM_NOTIFY,
                                   fNotify ? MF_CHECKED : MF_UNCHECKED);
                    break;

                case IDM_LOADFILE:
                    {
                    HANDLE  hText;
                    LPSTR   lpText;
                    INT     file;
                    LONG    size;
                    DWORD   l1, l2;
                    CHAR    buf[80];

                    l1 = GetWindowLong (hwndEdit, 0);
                    l2 = GetWindowLong (hwndEdit, 4);
                    wsprintf (buf, "HSTATE: %X  LPSTATE: %x\r\n", l1, l2);
                    Out (buf);

                    hText = GlobalAlloc (GHND, 65536);
                    if (!hText)
                        break;
                    lpText = GlobalLock (hText);

                    l1 = GetWindowLong (hwndEdit, 0);
                    l2 = GetWindowLong (hwndEdit, 4);
                    wsprintf (buf, "HSTATE: %X  LPSTATE: %x\r\n", l1, l2);
                    Out (buf);

                    file = _lopen ("edittest.txt", OF_READ);
                    if (file != -1)
                        {
                        size = _llseek (file, 0, 2);
                        if (size > 0x0000ffff)
                            {
                            size = 0xfe00;
                            Alert (hwnd, "File truncated!");
                            }
                        _llseek(file, 0, 0);
                        lpText[_lread(file, lpText, (UINT)size)] = 0;

                    l1 = GetWindowLong (hwndEdit, 0);
                    l2 = GetWindowLong (hwndEdit, 4);
                    wsprintf (buf, "HSTATE: %X  LPSTATE: %x\r\n", l1, l2);
                    Out (buf);

                        _lclose(file);
                        Out ("Sending SETTEXT... ");

                    l1 = GetWindowLong (hwndEdit, 0);
                    l2 = GetWindowLong (hwndEdit, 4);
                    wsprintf (buf, "HSTATE: %X  LPSTATE: %x\r\n", l1, l2);
                    Out (buf);

                        file = (INT)SendMessage (hwndEdit, EM_RBSETTEXT, 0,
                                                 (LONG)lpText);
                        wsprintf (buf, "file = %d\r\n", file);
                        Out (buf);
                        if (!file)
                            Alert (hwnd, "SETTEXT Failed!");
                        }
                    else
                        Alert (hwnd, "EDITTEST.TXT not found...");
                    GlobalUnlock (hText);
                    GlobalFree (hText);
                    break;
                    }

                case 0xCAC:
                    // These (had better be) notification codes for the
                    // edit window
                    //-------------------------------------------------------
                    switch (HIWORD (lParam))
                        {
                        case EN_ERRSPACE:
                            Alert (hwnd, "Out of edit spce");
                            break;
                        case EN_LINETOOLONG:
                            Alert (hwnd, "Line too long");
                            break;
                        case EN_LINEWRAPPED:
                            Alert (hwnd, "Line too long -- CR inserted");
                            break;
                        case EN_SETCURSOR:
                            {
                            HDC     hdc;

                            hdc = GetDC (hwnd);
                            PaintStatus (hwnd, hdc);
                            ReleaseDC (hwnd, hdc);
                            break;
                            }
                        default:
                            break;
                            //Alert (hwnd, "Unknown notification code");
                        }
                    break;


                default:
                    return (DefWindowProc(hwnd, message, wParam, lParam));
                }
            break;

        case WM_DESTROY:
	    PostQuitMessage(0);
	    break;

        default:
            return (DefWindowProc (hwnd, message, wParam, lParam));
        }
    return (NULL);
}
Esempio n. 30
0
int SaveScreen() {

	// String buffers for the filenames
	
	char test[] = "anim\\pic";
	char format[] = ".bmp";

	char file[40];
	char file2[40];
	char file3[40];

	// Create the correct file paths and names in the buffers

	sprintf(file, "anim\\pic%d.bmp", frame++);
	sprintf(file3, "Work___Win32_Release\\anim\\pic%d.bmp", frame );
	sprintf(file2, "Work___Win32_Release\\%s", file);

	// Create a pointer to a screen buffer

	UCHAR *screen_buffer = NULL;

	// Assign the pointer to the display

	screen_buffer = (UCHAR *) ddsd.lpSurface;

	// Set the pixel position to the lower left corner

	screen_buffer += (SCREEN_WIDTH * (SCREEN_HEIGHT - 1));


	// Open pic0.bmp for writing

	#define BITMAP_ID        0x4D42				// this is the universal id for a bitmap

	int      file_handle;						// the file handle
	bitmap_file_ptr bitmap = new bitmap_file;	// the bitmap header structure


	OFSTRUCT file_data;							// the file data information

	// open the file if it exists

	if ((file_handle = OpenFile(file,&file_data,OF_READWRITE))==-1)
		return(0);
 
	// Now load the bitmap file header
	
	_lread(file_handle, &bitmap->bitmapfileheader,sizeof(BITMAPFILEHEADER));

	// Test if this is a bitmap file
	if (bitmap->bitmapfileheader.bfType!=BITMAP_ID) {
	
		// close the file
		_lclose(file_handle);
 
		// return error
		return(0);

	} // end if


	// Load the bitmap file header
	
	_lread(file_handle, &bitmap->bitmapinfoheader,sizeof(BITMAPINFOHEADER));


	// Write the palette to the file
	_lwrite(file_handle, (char*) colour_palette,256*sizeof(PALETTEENTRY));
	
	
	// Find the start of the image data
	_lseek(file_handle,-(int)(bitmap->bitmapinfoheader.biSizeImage),SEEK_END);


	// Overwrite the image data in the file

	for (int i=0; i<SCREEN_HEIGHT; i++) {

		_lwrite(file_handle,(char*) screen_buffer,SCREEN_WIDTH * sizeof(UCHAR));
		screen_buffer -= SCREEN_WIDTH;
	
	}


	// Deallocate bitmap header
	delete bitmap;

	// close the file
	_lclose(file_handle);

	// Copy the file to another ( for animation frames )

	CopyFile(file2, file3,TRUE);

	return 1;

}