Exemplo n.º 1
1
int __cdecl main(int argc, char *argv[])
{

    HANDLE  hFile;
    char    buf[] = "this is a test string";
    char    ch[2048];
    WCHAR   lpFileName[] = {'t','e','s','t','.','t','m','p','\0'};
    HANDLE  hFileMapping;
    LPVOID  lpMapViewAddress;
    int     RetVal = PASS;
    int     err;
    DWORD   dwBytesWritten;


    /* Initialize the PAL environment.
     */
    if(0 != PAL_Initialize(argc, argv))
    {
        return FAIL;
    }

    /* Create a file handle with CreateFile.
     */
    hFile = CreateFile( lpFileName,
                        GENERIC_WRITE|GENERIC_READ,
                        FILE_SHARE_READ|FILE_SHARE_WRITE,
                        NULL,
                        CREATE_ALWAYS,
                        FILE_ATTRIBUTE_NORMAL,
                        NULL);

    if (hFile == INVALID_HANDLE_VALUE)
    {
        Fail("ERROR: %u :unable to create file \"%s\".\n",
             GetLastError(),
             lpFileName);
    }

    /* Write to the File handle.
     */ 
    err = WriteFile(hFile,
                    buf,
                    strlen(buf),
                    &dwBytesWritten,
                    NULL);

    if (err == FALSE)
    {
        Trace("ERROR: %u :unable to write to file handle "
                "hFile=0x%lx\n",
                GetLastError(),
                hFile);
        RetVal = FAIL;
        goto CleanUpOne;
    }
    
    /* Flush to the hard-drive.
      */
    FlushFileBuffers(hFile);

    /* Initialize the buffers.
     */
    memset(ch,  0, MAPPINGSIZE);

    /* Create a unnamed file-mapping object with file handle FileHandle
     * and with PAGE_WRITECOPY protection.
     */
    hFileMapping = CreateFileMapping(
                            hFile,
                            NULL,               /*not inherited*/
                            PAGE_WRITECOPY,     /*write copy*/
                            0,                  /*high-order size*/
                            0,                  /*low-order size*/
                            NULL);              /*unnamed object*/

    if(NULL == hFileMapping)
    {
        Trace("ERROR:%u: Failed to create File Mapping.\n", 
              GetLastError());
        RetVal = FAIL;
        goto CleanUpOne;
    }

    /* maps a view of a file into the address space of the calling process.
     */
    lpMapViewAddress = MapViewOfFile(
                            hFileMapping,
                            FILE_MAP_COPY,       /* access code */
                            0,                   /* high order offset*/
                            0,                   /* low order offset*/
                            0);                  /* number of bytes for map */

    if(NULL == lpMapViewAddress)
    {
        Trace("ERROR:%u: Failed to call MapViewOfFile "
              "API to map a view of file!\n", 
              GetLastError());
        RetVal = FAIL;
        goto CleanUpTwo;
    }
    
    /* Write to the Map view.3
     */ 
    memcpy(lpMapViewAddress, buf, strlen(buf));

    /* Read from the Map view.
     */ 
    memcpy(ch, (LPCSTR)lpMapViewAddress, MAPPINGSIZE);
    
    /* Copy the MapViewOfFile to buffer, so we can
     * compare with value read from file directly.
     */
    if (memcmp(ch, buf, strlen(buf))!= 0)
    {
        Trace("ERROR: MapViewOfFile not equal to file contents "
              "retrieved \"%s\", expected \"%s\".\n",
              ch, buf);
        RetVal = FAIL;
        goto CleanUpThree;
    }

CleanUpThree:
        
    /* Unmap the view of file.
        */
    if ( UnmapViewOfFile(lpMapViewAddress) == FALSE )
    {
        Trace("ERROR:%u: Failed to UnmapViewOfFile of \"%0x%lx\".\n",
                GetLastError(),
                lpMapViewAddress);
        RetVal = FAIL;
    }

CleanUpTwo:

    /* Close Handle to opend file mapping.
        */
    if ( CloseHandle(hFileMapping) == FALSE )
    {
        Trace("ERROR:%u: Failed to CloseHandle \"0x%lx\".\n",
                GetLastError(),
                hFileMapping);
        RetVal = FAIL;
    }

CleanUpOne:
        
    /* Close Handle to create file mapping.
        */
    if ( CloseHandle(hFile) == FALSE )
    {
        Trace("ERROR:%u: Failed to CloseHandle \"0x%lx\".\n",
                GetLastError(),
                hFile);
        RetVal = FAIL;
    }

    /* Terminate the PAL.
     */ 
    PAL_Terminate();
    return RetVal;
}
Exemplo n.º 2
1
/**
* @brief
* @param
* @see
* @remarks
* @code
* @endcode
* @return
**/
bool read_file_using_memory_map()
{
	// current directory 를 구한다.
	wchar_t *buf = NULL;
	uint32_t buflen = 0;
	buflen = GetCurrentDirectoryW(buflen, buf);
	if (0 == buflen)
	{
		print("err ] GetCurrentDirectoryW() failed. gle = 0x%08x", GetLastError());
		return false;
	}

	buf = (PWSTR)malloc(sizeof(WCHAR)* buflen);
	if (0 == GetCurrentDirectoryW(buflen, buf))
	{
		print("err ] GetCurrentDirectoryW() failed. gle = 0x%08x", GetLastError());
		free(buf);
		return false;
	}

	// current dir \\ test.txt 파일명 생성
	wchar_t file_name[260];
	if (!SUCCEEDED(StringCbPrintfW(
		file_name,
		sizeof(file_name),
		L"%ws\\test.txt",
		buf)))
	{
		print("err ] can not create file name");
		free(buf);
		return false;
	}
	free(buf); buf = NULL;

	if (true != is_file_existsW(file_name))
	{
		print("err ] no file exists. file = %ws", file_name);
		return false;
	}

	HANDLE file_handle = CreateFileW(
		(LPCWSTR)file_name,
		GENERIC_READ,
		NULL,
		NULL,
		OPEN_EXISTING,
		FILE_ATTRIBUTE_NORMAL,
		NULL
		);
	if (INVALID_HANDLE_VALUE == file_handle)
	{
		print("err ] CreateFile(%ws) failed, gle = %u", file_name, GetLastError());
		return false;
	}

	// check file size
	//
	LARGE_INTEGER fileSize;
	if (TRUE != GetFileSizeEx(file_handle, &fileSize))
	{
		print("err ] GetFileSizeEx(%ws) failed, gle = %u", file_name, GetLastError());
		CloseHandle(file_handle);
		return false;
	}

	// [ WARN ]
	//
	// 4Gb 이상의 파일의 경우 MapViewOfFile()에서 오류가 나거나
	// 파일 포인터 이동이 문제가 됨
	// FilIoHelperClass 모듈을 이용해야 함
	//
	_ASSERTE(fileSize.HighPart == 0);
	if (fileSize.HighPart > 0)
	{
		print("file size = %I64d (over 4GB) can not handle. use FileIoHelperClass",
			fileSize.QuadPart);
		CloseHandle(file_handle);
		return false;
	}

	DWORD file_size = (DWORD)fileSize.QuadPart;
	HANDLE file_map = CreateFileMapping(
		file_handle,
		NULL,
		PAGE_READONLY,
		0,
		0,
		NULL
		);
	if (NULL == file_map)
	{
		print("err ] CreateFileMapping(%ws) failed, gle = %u", file_name, GetLastError());
		CloseHandle(file_handle);
		return false;
	}

	PCHAR file_view = (PCHAR)MapViewOfFile(
		file_map,
		FILE_MAP_READ,
		0,
		0,
		0
		);
	if (file_view == NULL)
	{
		print("err ] MapViewOfFile(%ws) failed, gle = %u", file_name, GetLastError());

		CloseHandle(file_map);
		CloseHandle(file_handle);
		return false;
	}

	// do some io
	char a = file_view[0];  // 0x d9
	char b = file_view[1];  // 0xb3



	// close all
	UnmapViewOfFile(file_view);
	CloseHandle(file_map);
	CloseHandle(file_handle);
	return true;
}
Exemplo n.º 3
0
/**
* @brief
* @param
* @see
* @remarks
* @code
* @endcode
* @return
**/
pmap_context create_map_context(_In_ const wchar_t* file_path, _In_ uint32_t file_size)
{
	_ASSERTE(NULL != file_path);
	if (NULL == file_path) return false;
	if (is_file_existsW(file_path))
	{
		DeleteFileW(file_path);
	}

	pmap_context ctx = (pmap_context)malloc(sizeof(map_context));
	RtlZeroMemory(ctx, sizeof(map_context));

	bool ret = false;

#pragma warning(disable: 4127)
	do
	{
		ctx->handle = CreateFileW(
			(LPCWSTR)file_path,
			GENERIC_READ | GENERIC_WRITE,
			NULL,
			NULL,
			CREATE_NEW,
			FILE_ATTRIBUTE_NORMAL,
			NULL
			);
		if (INVALID_HANDLE_VALUE == ctx->handle)
		{
			print("err ] CreateFile( %ws ) failed. gle = %u", file_path, GetLastError());
			break;
		}

		ctx->size = file_size;
		ctx->map = CreateFileMapping(
			ctx->handle,
			NULL,
			PAGE_READWRITE,
			0,
			ctx->size,
			NULL
			);
		if (NULL == ctx->map)
		{
			print("err ] CreateFileMapping( %ws ) failed. gle = %u", file_path, GetLastError());
			break;
		}

		ctx->view = (PCHAR)MapViewOfFile(
			ctx->map,
			FILE_MAP_WRITE,
			0,
			0,
			ctx->size
			);
		if (ctx->view == NULL)
		{
			print("err ] MapViewOfFile( %ws ) failed. gle = %u", file_path, GetLastError());
			break;
		}

		ret = true;
	} while (FALSE);
#pragma warning(default: 4127)

	if (!ret)
	{
		if (NULL != ctx->view) UnmapViewOfFile(ctx->view);
		if (NULL != ctx->map) CloseHandle(ctx->map);
		if (INVALID_HANDLE_VALUE != ctx->handle) CloseHandle(ctx->handle);

		free(ctx); ctx = NULL;
	}

	return ctx;
}
Exemplo n.º 4
0
/**
* @brief
* @param
* @see
* @remarks
* @code
* @endcode
* @return
**/
pmap_context open_map_context(_In_ const wchar_t* file_path)
{
	_ASSERTE(NULL != file_path);
	if (NULL == file_path) return false;
	if (!is_file_existsW(file_path)) return false;;

	pmap_context ctx = (pmap_context)malloc(sizeof(map_context));
	RtlZeroMemory(ctx, sizeof(map_context));

	bool ret = false;

#pragma warning(disable: 4127)
	do
	{
		ctx->handle = CreateFileW(
			(LPCWSTR)file_path,
			GENERIC_READ,
			NULL,
			NULL,
			OPEN_EXISTING,
			FILE_ATTRIBUTE_NORMAL,
			NULL
			);
		if (INVALID_HANDLE_VALUE == ctx->handle)
		{
			print("err ] CreateFile( %ws ) failed. gle = %u", file_path, GetLastError());
			break;
		}

		// check file size
		//
		LARGE_INTEGER fileSize;
		if (TRUE != GetFileSizeEx(ctx->handle, &fileSize))
		{
			print("err ] GetFileSizeEx( %ws ) failed. gle = %u", file_path, GetLastError());
			break;
		}

		// [ WARN ]
		//
		// 4Gb 이상의 파일의 경우 MapViewOfFile()에서 오류가 나거나
		// 파일 포인터 이동이 문제가 됨
		// FilIoHelperClass 모듈을 이용해야 함
		//
		_ASSERTE(fileSize.HighPart == 0);
		if (fileSize.HighPart > 0)
		{
			print("err ] file is too large to map. file = %ws, size = %llu", file_path, fileSize.QuadPart);
			break;
		}

		ctx->size = (DWORD)fileSize.QuadPart;
		ctx->map = CreateFileMapping(
			ctx->handle,
			NULL,
			PAGE_READONLY,
			0,
			0,
			NULL
			);
		if (NULL == ctx->map)
		{
			print("err ] CreateFileMapping( %ws ) failed. gle = %u", file_path, GetLastError());
			break;
		}

		ctx->view = (PCHAR)MapViewOfFile(
			ctx->map,
			FILE_MAP_READ,
			0,
			0,
			0
			);
		if (ctx->view == NULL)
		{
			print("err ] MapViewOfFile( %ws ) failed. gle = %u", file_path, GetLastError());
			break;
		}

		ret = true;
	} while (FALSE);
#pragma warning(default: 4127)

	if (!ret)
	{
		if (NULL != ctx->view) UnmapViewOfFile(ctx->view);
		if (NULL != ctx->map) CloseHandle(ctx->map);
		if (INVALID_HANDLE_VALUE != ctx->handle) CloseHandle(ctx->handle);

		free(ctx); ctx = NULL;
	}

	return ctx;
}
Exemplo n.º 5
0
/*
 * Map a cache file into memory
 */
static FcCache *
FcDirCacheMapFd (FcConfig *config, int fd, struct stat *fd_stat, struct stat *dir_stat)
{
    FcCache	*cache;
    FcBool	allocated = FcFalse;

    if (fd_stat->st_size < (int) sizeof (FcCache))
	return NULL;
    cache = FcCacheFindByStat (fd_stat);
    if (cache)
    {
	if (FcCacheTimeValid (config, cache, dir_stat) &&
	    FcCacheDirsValid (config, cache))
	    return cache;
	FcDirCacheUnload (cache);
	cache = NULL;
    }

    /*
     * Large cache files are mmap'ed, smaller cache files are read. This
     * balances the system cost of mmap against per-process memory usage.
     */
    if (FcCacheIsMmapSafe (fd) && fd_stat->st_size >= FC_CACHE_MIN_MMAP)
    {
#if defined(HAVE_MMAP) || defined(__CYGWIN__)
	cache = mmap (0, fd_stat->st_size, PROT_READ, MAP_SHARED, fd, 0);
#if (HAVE_POSIX_FADVISE) && defined(POSIX_FADV_WILLNEED)
	posix_fadvise (fd, 0, fd_stat->st_size, POSIX_FADV_WILLNEED);
#endif
	if (cache == MAP_FAILED)
	    cache = NULL;
#elif defined(_WIN32)
	{
	    HANDLE hFileMap;

	    cache = NULL;
	    hFileMap = CreateFileMapping((HANDLE) _get_osfhandle(fd), NULL,
					 PAGE_READONLY, 0, 0, NULL);
	    if (hFileMap != NULL)
	    {
		cache = MapViewOfFile (hFileMap, FILE_MAP_READ, 0, 0,
				       fd_stat->st_size);
		CloseHandle (hFileMap);
	    }
	}
#endif
    }
    if (!cache)
    {
	cache = malloc (fd_stat->st_size);
	if (!cache)
	    return NULL;

	if (read (fd, cache, fd_stat->st_size) != fd_stat->st_size)
	{
	    free (cache);
	    return NULL;
	}
	allocated = FcTrue;
    }
    if (cache->magic != FC_CACHE_MAGIC_MMAP ||
	cache->version < FC_CACHE_VERSION_NUMBER ||
	cache->size != (intptr_t) fd_stat->st_size ||
	!FcCacheTimeValid (config, cache, dir_stat) ||
	!FcCacheDirsValid (config, cache) ||
	!FcCacheInsert (cache, fd_stat))
    {
	if (allocated)
	    free (cache);
	else
	{
#if defined(HAVE_MMAP) || defined(__CYGWIN__)
	    munmap (cache, fd_stat->st_size);
#elif defined(_WIN32)
	    UnmapViewOfFile (cache);
#endif
	}
	return NULL;
    }

    /* Mark allocated caches so they're freed rather than unmapped */
    if (allocated)
	cache->magic = FC_CACHE_MAGIC_ALLOC;
	
    return cache;
}
Exemplo n.º 6
0
char doHandshake( bool isD3DCalling, Handshake** handshake )
{
    const unsigned char partState = isD3DCalling ? 1 : 2;
    if ( isD3DCalling )
        logg( "Doing Handshake from D3D side..." );
    else
        logg( "Doing Handshake from Plugin side..." );
    
    HANDLE hmmf = CreateFileMapping( (HANDLE)0xFFFFFFFF, NULL, PAGE_READWRITE, 0, 1024, MEM_KEY );
    
    if ( hmmf == NULL )
    {
        logg( "ERROR: Handshake failed. Unable to create PAGEFILE Memory Mapped File." );
        return ( -1 );
    }
    
    unsigned char* mem0 = (unsigned char*)MapViewOfFile( hmmf, FILE_MAP_WRITE, 0, 0, 0 );
    unsigned char* mem = mem0;
    
    if ( mem == NULL )
    {
        logg( "ERROR: Handshake failed. Unable to get a pointer to memory of PAGEFILE Memory Mapped File." );
        return ( -1 );
    }
    
    logg( "    Successfully created a pointer to a PAGEFILE Memory Mapped File." );
    
    DWORD procId = GetCurrentProcessId();
    
    unsigned char initializeMem = 0;
    if ( !checkMemKey( (char*)mem ) )
        initializeMem = 1;
    else if ( *(DWORD*)( mem + 8 ) != procId )
        initializeMem = 2;
    
    if ( initializeMem != 0 )
    {
        if ( initializeMem == 1 )
            logg( "    Found virgin memory." );
        else if ( initializeMem == 2 )
            logg( "    Found outdated memory." );
        
        memcpy( mem, MEM_KEY, 8 );
        mem += 8;
        *(DWORD*)mem = procId;
        mem += sizeof( DWORD );
        *mem = partState;
        mem += 1;
        
        *handshake = new Handshake();
        (*handshake)->isPluginEnabled = true;
        (*handshake)->state = HANDSHAKE_STATE_WAITING_FOR_OTHER_SIDE;
        *(unsigned long long*)mem = (unsigned long long)*handshake;
        
        UnmapViewOfFile( mem0 );
        
        logg( "First part of Handshake successful." );
        
        return ( 0 ); // Handshake incomplete
    }
    
    mem += 8 + sizeof( DWORD );
    
    unsigned char state = *mem;
    
    if ( ( state & partState ) != 0 )
    {
        UnmapViewOfFile( mem0 );
        
        logg( "Handshake repeat detected for unknown reason. This tends to happen in windowed mode, where two D3D contexts seem to be created. Skipping!" );
        
        return ( 2 );
    }
    
    *mem = state | partState;
    
    mem += 1;
    
    logg( "    Found first part of handshake. Doing second part..." );
    
    *handshake = (Handshake*)(*(unsigned long long*)mem);
    (*handshake)->state = HANDSHAKE_STATE_COMPLETE;
    
    UnmapViewOfFile( mem0 );
    
    logg( "Second part of Handshake successful. Handshake complete." );
    
    return ( 1 );
}
/**----------------------------------------------------------------------------
\brief		FileSize 바이트 짜리 파일을 생성한다.

\param
\return
\code

\endcode
-----------------------------------------------------------------------------*/
DTSTATUS
FileIoHelper::FIOCreateFile(
IN std::wstring FilePath,
IN LARGE_INTEGER FileSize
)
{
	if (TRUE == Initialized()) { FIOClose(); }
	if (FileSize.QuadPart == 0) return DTS_INVALID_PARAMETER;

	mReadOnly = FALSE;

#pragma warning(disable: 4127)
	DTSTATUS status = DTS_WINAPI_FAILED;
	do
	{
		mFileSize = FileSize;

		mFileHandle = CreateFileW(
			FilePath.c_str(),
			GENERIC_READ | GENERIC_WRITE,
			FILE_SHARE_READ,		// write 도중 다른 프로세스에서 읽기가 가능
			NULL,
			CREATE_ALWAYS,
			FILE_ATTRIBUTE_NORMAL,
			NULL
			);
		if (INVALID_HANDLE_VALUE == mFileHandle)
		{
				break;
		}

		// increase file size
		// 
		if (TRUE != SetFilePointerEx(mFileHandle, mFileSize, NULL, FILE_BEGIN))
		{
				break;
		}

		if (TRUE != SetEndOfFile(mFileHandle))
		{
				break;
		}

		mFileMap = CreateFileMapping(
			mFileHandle,
			NULL,
			PAGE_READWRITE,
			0,
			0,
			NULL
			);
		if (NULL == mFileMap)
		{
				break;
		}

		status = DTS_SUCCESS;
	} while (FALSE);
#pragma warning(default: 4127)

	if (TRUE != DT_SUCCEEDED(status))
	{
		if (INVALID_HANDLE_VALUE != mFileHandle)
		{
			CloseHandle(mFileHandle);
			mFileHandle = INVALID_HANDLE_VALUE;
		}
		if (NULL != mFileMap) CloseHandle(mFileMap);
	}

	return status;
}
Exemplo n.º 8
0
void* mmap(void *addr, size_t len, int prot, int flags, int fildes, off_t off)
{
    HANDLE fm, h;
    
    void * map = MAP_FAILED;
    
    const DWORD dwFileOffsetLow = (sizeof(off_t) <= sizeof(DWORD)) ? 
                    (DWORD)off : (DWORD)(off & 0xFFFFFFFFL);
    const DWORD dwFileOffsetHigh = (sizeof(off_t) <= sizeof(DWORD)) ?
                    (DWORD)0 : (DWORD)((off >> 32) & 0xFFFFFFFFL);
    const DWORD protect = __map_mmap_prot_page(prot);
    const DWORD desiredAccess = __map_mmap_prot_file(prot);

    errno = 0;
    
    if (len == 0 
        /* Unsupported flag combinations */
        || (flags & MAP_FIXED) != 0
        /* Usupported protection combinations */
        || prot == PROT_EXEC)
    {
        errno = EINVAL;
        return MAP_FAILED;
    }
    
    h = ((flags & MAP_ANONYMOUS) == 0) ? 
                    (HANDLE)_get_osfhandle(fildes) : INVALID_HANDLE_VALUE;

    if ((flags & MAP_ANONYMOUS) == 0 && h == INVALID_HANDLE_VALUE)
    {
        errno = EBADF;
        return MAP_FAILED;
    }

    const off_t maxSize = off + (off_t)len;
    
    const DWORD dwMaxSizeLow = (sizeof(off_t) <= sizeof(DWORD)) ? 
                    (DWORD)maxSize : (DWORD)(maxSize & 0xFFFFFFFFL);
    const DWORD dwMaxSizeHigh = (sizeof(off_t) <= sizeof(DWORD)) ?
                    (DWORD)0 : (DWORD)((maxSize >> 32) & 0xFFFFFFFFL);
    
    fm = CreateFileMapping(h, NULL, protect, dwMaxSizeHigh, dwMaxSizeLow, NULL);

    if (fm == NULL)
    {
        errno = __map_mman_error(GetLastError(), EPERM);
        return MAP_FAILED;
    }
  
    map = MapViewOfFile(fm, desiredAccess, dwFileOffsetHigh, dwFileOffsetLow, len);

    CloseHandle(fm);
  
    if (map == NULL)
    {
        errno = __map_mman_error(GetLastError(), EPERM);
        return MAP_FAILED;
    }

    return map;
}
Exemplo n.º 9
0
int shmget(key_t key, int size, int shmflg)
{
    PtrHandleChain dummy;
    HANDLE hFile = (HANDLE)0xFFFFFFFF;
    DWORD flProtect;
    char name[100];
    
    if ((key == IPC_PRIVATE) || ((IPC_CREAT & shmflg) == IPC_CREAT))
    {
	if ((shmflg & O_RDONLY) == O_RDONLY)
	    flProtect = PAGE_READONLY;
	else 
	    flProtect = PAGE_READWRITE;
	
	if (key == IPC_PRIVATE)
	{
	    do {
		key++;
		_itoa(key, name, 10);
		if ((hFile != (HANDLE)0xFFFFFFFF) && (hFile != NULL))
		    CloseHandle(hFile);
		hFile = CreateFileMapping((HANDLE)0xFFFFFFFF, NULL, flProtect, 0, size, name);
	    } while (GetLastError() != 0);
	} else {
	    _itoa(key, name, 10);
	    hFile = CreateFileMapping(hFile, NULL, flProtect, 0, size, name);
	}
	
	if (hFile == NULL)
	{
	    errno = GetLastError();
	    return(-1);
	}
    } else {
	if ((shmflg & O_RDONLY) == O_RDONLY)
	    flProtect = FILE_MAP_READ;
	else
	    flProtect = FILE_MAP_WRITE;
	
	_itoa(key, name, 10);
	hFile = OpenFileMapping(flProtect, TRUE, name);
	if (hFile == NULL)
	{
	    errno = GetLastError();
	    return(-1);
	}
    }
    
    if (start == NULL)
    {
	start = (PtrHandleChain) malloc(sizeof(HandleChain));
	if (start == NULL)
	    return(-1);
	dummy = start;
    } else
    {
	dummy = start;
	while(dummy->next != NULL)
	    dummy = dummy->next;
	dummy->next = (PtrHandleChain) malloc(sizeof(HandleChain));
	if (dummy == NULL)
	    return(-1);
	dummy = dummy->next;
	
    }
    dummy->next = NULL;
    dummy->handle = hFile;
    dummy->key = key;
    dummy->address = NULL;
    dummy->size = size;
    
    return((int) key);
}
Exemplo n.º 10
0
static struct shmTime *
getShmTime (
	int unit
	)
{
#ifndef SYS_WINNT
	int shmid=shmget (0x4e545030+unit, sizeof (struct shmTime), IPC_CREAT|0777);
	if (shmid==-1) {
		perror ("shmget");
		exit (1);
	}
	else {
		struct shmTime *p=(struct shmTime *)shmat (shmid, 0, 0);
		if ((int)(long)p==-1) {
			perror ("shmat");
			p=0;
		}
		assert (p!=0);
		return p;
	}
#else
	char buf[10];
	LPSECURITY_ATTRIBUTES psec=0;
	snprintf (buf, sizeof(buf), "NTP%d", unit);
	SECURITY_DESCRIPTOR sd;
	SECURITY_ATTRIBUTES sa;
	HANDLE shmid;

	assert (InitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION));
	assert (SetSecurityDescriptorDacl(&sd,1,0,0));
	sa.nLength=sizeof (SECURITY_ATTRIBUTES);
	sa.lpSecurityDescriptor=&sd;
	sa.bInheritHandle=0;
	shmid=CreateFileMapping ((HANDLE)0xffffffff, 0, PAGE_READWRITE,
				 psec, sizeof (struct shmTime),buf);
	if (!shmid) {
		shmid=CreateFileMapping ((HANDLE)0xffffffff, 0, PAGE_READWRITE,
					 0, sizeof (struct shmTime),buf);
		cout <<"CreateFileMapping with psec!=0 failed"<<endl;
	}

	if (!shmid) {
		char mbuf[1000];
		FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM,
			       0, GetLastError (), 0, mbuf, sizeof (mbuf), 0);
		int x=GetLastError ();
		cout <<"CreateFileMapping "<<buf<<":"<<mbuf<<endl;
		exit (1);
	}
	else {
		struct shmTime *p=(struct shmTime *) MapViewOfFile (shmid, 
								    FILE_MAP_WRITE, 0, 0, sizeof (struct shmTime));
		if (p==0) {
			char mbuf[1000];
			FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM,
				       0, GetLastError (), 0, mbuf, sizeof (mbuf), 0);
			cout <<"MapViewOfFile "<<buf<<":"<<mbuf<<endl;
			exit (1);
		}
		return p;
	}
	return 0;
#endif
}
Exemplo n.º 11
0
/*******************************************************************************
*
*   函 数 名 : GetPEFileBit
*  功能描述 : 取得可执行文件的位数
*  参数列表 : pPEFilePath  --     pe文件路径
*   说      明 : 读pe文件的头进内存,再调用GetBitByPEHeader去判断
*  返回结果 :  返回当前进程位数
*
*******************************************************************************/
ULONG   GetPEFileBit(__in_z CONST PTCHAR pPEFilePath)
{
        ULONG uResult(0) ;
        HANDLE hFile(INVALID_HANDLE_VALUE) ;
        HANDLE hFileMap(NULL) ;
        LPVOID pAddr(NULL) ;

        __try
        {
                if (NULL == pPEFilePath)
                {
                        OutputDebugString(TEXT("GetPEFileBit pPEFilePath can't NULL!\r\n")) ;
                        __leave ;
                }
                
                if(FALSE == PathFileExists(pPEFilePath))
                {
                        OutputDebugString(TEXT("The file does not exist!\r\n")) ;
                        __leave ;
                }

                hFile = CreateFile(pPEFilePath, 
                                             GENERIC_READ,
                                             FILE_SHARE_READ,
                                             NULL,
                                             OPEN_EXISTING,
                                             FILE_ATTRIBUTE_NORMAL,
                                             NULL) ;
                if (INVALID_HANDLE_VALUE == hFile)
                {
                        OutputErrorInformation(TEXT("GetPEFileBit"), TEXT("CreateFile")) ;
                        __leave ;
                }

                hFileMap = CreateFileMapping(hFile,
                                                                     NULL,
                                                                     PAGE_READONLY,
                                                                     0,
                                                                     0,
                                                                     NULL) ;
                if (NULL == hFile)
                {
                        OutputErrorInformation(TEXT("GetPEFileBit"), TEXT("CreateFileMapping")) ;
                        __leave ;
                }

                pAddr = MapViewOfFile(hFileMap,
                                                        FILE_MAP_READ,
                                                        0,
                                                        0,
                                                        0) ;

                if (NULL == pAddr)
                {
                        OutputErrorInformation(TEXT("GetPEFileBit"), TEXT("MapViewOfFile")) ;
                        __leave ;
                }

                uResult = GetBitByPEHeader(pAddr, GetFileSize(hFile, NULL)) ;
        }

        __finally
        {
                if (NULL != pAddr)
                {
                        UnmapViewOfFile(pAddr) ;
                        pAddr = NULL ;
                }

                if (NULL != hFileMap)
                {
                        CloseHandle(hFileMap) ;
                        hFileMap = NULL ;
                }

                if (INVALID_HANDLE_VALUE != hFile)
                {
                        CloseHandle(hFile) ;
                        hFile = INVALID_HANDLE_VALUE ;
                }
        }
        return uResult ;
}
Exemplo n.º 12
0
char *get_file_contents (const char *filename) {
#ifdef USE_MEMORY_MAPPED_FILES
	HANDLE hFile = CreateFile(
		filename,
		GENERIC_READ,
		FILE_SHARE_READ,
		NULL,
		OPEN_EXISTING,
		FILE_ATTRIBUTE_NORMAL,
		NULL);
	if (hFile == INVALID_HANDLE_VALUE)
	{
		return NULL;
	}

	HANDLE hMapFile = CreateFileMapping(
		hFile,
		NULL,
		PAGE_READONLY,
		0L,
		0L,
		NULL);

	LPBYTE lpData = (LPBYTE) MapViewOfFile(hMapFile, FILE_MAP_READ, 0, 0, 0);
	return (char *) lpData;
#else
	FILE *file;
	char *buffer, *p;
	size_t size, read_size;

	// first try to open it
	file = fopen (filename, "rb");

	if (!file)
		return NULL;

	// find file size (Spencer says it's not a hack)
	fseek (file, 0, SEEK_END);
	size = ftell (file);
	rewind (file);


	// now allocate the memory and read in the contents
	buffer = (char *) malloc (size + 1);

	const unsigned char utf8_endian_mark[] = {0xEF, 0xBB, 0xBF};
	fread(buffer, 1, sizeof(utf8_endian_mark), file);
	if (memcmp(buffer, &utf8_endian_mark, sizeof(utf8_endian_mark)) == 0) {
		size -= sizeof(utf8_endian_mark);
		p = (char *) malloc (size + 1);
		memcpy(p, buffer + sizeof(utf8_endian_mark), size);
		free(buffer);
	} else {
		p = buffer;
		rewind(file);
	}

	read_size = fread (p, 1, size, file);
	fclose (file);

	if (read_size != size) {
		free (buffer);
		return NULL;
	}

	p[size] = '\0';
	return p;
#endif
}
Exemplo n.º 13
0
WDL_SHM_Connection::WDL_SHM_Connection(bool whichChan,
                      const char *uniquestring, // identify 
                      int shmsize, // bytes, whoever opens first decides
                      int timeout_sec,
                      int extra_flags // unused on win32

                    )
{
  m_timeout_cnt=0;
  m_timeout_sec=timeout_sec;
  m_last_recvt=time(NULL)+2; // grace period
  { // make shmsize the next power of two
    int a = shmsize;
    shmsize=2;
    while (shmsize < SHM_MINSIZE || shmsize<a) shmsize*=2;
  }

  m_file=INVALID_HANDLE_VALUE;
  m_filemap=NULL;
  m_mem=NULL;
  m_lockmutex=m_events[0]=m_events[1]=NULL;

  m_whichChan=whichChan ? 1 : 0;

  char buf[512];
  GetTempPath(sizeof(buf)-4,buf);
  if (!buf[0]) lstrcpyn(buf,"C:\\",32);
  if (buf[strlen(buf)-1] != '/' && buf[strlen(buf)-1] != '\\') strcat(buf,"\\");
  m_tempfn.Set(buf);
  m_tempfn.Append("WDL_SHM_");
  m_tempfn.Append(uniquestring);
  m_tempfn.Append(".tmp");

  WDL_String tmp;
  if (!(GetVersion()&0x80000000)) tmp.Set("Global\\WDL_SHM_");
  else tmp.Set("WDL_SHM_");
  tmp.Append(uniquestring);
  int tmp_l = strlen(tmp.Get());

  tmp.Append(".m");
  HANDLE mutex = CreateMutex(NULL,FALSE,tmp.Get());

  if (mutex) WaitForSingleObject(mutex,INFINITE);

  tmp.Get()[tmp_l]=0;
  tmp.Append(whichChan?".l1":".l0");
  m_lockmutex = CreateMutex(NULL,FALSE,tmp.Get());
  if (m_lockmutex)
  {
    if (WaitForSingleObject(m_lockmutex,100) == WAIT_OBJECT_0)
    {
      DeleteFile(m_tempfn.Get()); // this is designed to fail if another process has it locked

      m_file=CreateFile(m_tempfn.Get(),GENERIC_READ|GENERIC_WRITE,
                        FILE_SHARE_READ|FILE_SHARE_WRITE ,
                        NULL,whichChan ? OPEN_EXISTING : OPEN_ALWAYS,FILE_ATTRIBUTE_TEMPORARY,NULL);
    }
    else
    {
      CloseHandle(m_lockmutex);
      m_lockmutex=0;
    }
  }
  
  int mapsize;
  if (m_file != INVALID_HANDLE_VALUE && 
        ((mapsize=GetFileSize(m_file,NULL)) < SHM_HDRSIZE+SHM_MINSIZE*2 || 
          mapsize == 0xFFFFFFFF))
  {
    char buf[4096];
    memset(buf,0,sizeof(buf));
    *(int *)buf=shmsize;

    int sz=shmsize*2 + SHM_HDRSIZE;
    while (sz>0)
    {
      DWORD d;
      int a = sz;
      if (a>sizeof(buf))a=sizeof(buf);
      WriteFile(m_file,buf,a,&d,NULL);
      sz-=a;
      *(int *)buf = 0;
    }
  }

  if (m_file!=INVALID_HANDLE_VALUE)
    m_filemap=CreateFileMapping(m_file,NULL,PAGE_READWRITE,0,0,NULL);

  if (m_filemap)
  {
    m_mem=(unsigned char *)MapViewOfFile(m_filemap,FILE_MAP_WRITE,0,0,0);

    tmp.Get()[tmp_l]=0;
    tmp.Append(".1");
    m_events[0]=CreateEvent(NULL,false,false,tmp.Get());
    tmp.Get()[strlen(tmp.Get())-1]++; 
    m_events[1]=CreateEvent(NULL,false,false,tmp.Get());
  }

  if (mutex) 
  {
    ReleaseMutex(mutex);
    CloseHandle(mutex);
  }

}
Exemplo n.º 14
0
//=============================================================================
// initialize
// This function does the following:
//      1. Initialize XACT by calling xactEngine->Initialize 
//      2. Create the XACT wave bank(s) you want to use
//      3. Create the XACT sound bank(s) you want to use
//      4. Store indices to the XACT cue(s) your game uses
//=============================================================================
HRESULT Audio::initialize()
{
    HRESULT result = E_FAIL;
    HANDLE hFile;
    DWORD fileSize;
    DWORD bytesRead;
    HANDLE hMapFile;

    if( coInitialized == false)
        return E_FAIL;

    result = XACT3CreateEngine( 0, &xactEngine );
    if( FAILED( result ) || xactEngine == NULL )
        return E_FAIL;

    // Initialize & create the XACT runtime 
    XACT_RUNTIME_PARAMETERS xactParams = {0};
    xactParams.lookAheadTime = XACT_ENGINE_LOOKAHEAD_DEFAULT;
    result = xactEngine->Initialize( &xactParams );
    if( FAILED( result ) )
        return result;

    // Create an "in memory" XACT wave bank file using memory mapped file IO
    result = E_FAIL; // default to failure code, replaced on success
	//create file is not working properly
	auto temp = WAVE_BANK;
    hFile = CreateFileA( WAVE_BANK, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL );
    if( hFile != INVALID_HANDLE_VALUE )
    {
        fileSize = GetFileSize( hFile, NULL );
        if( fileSize != -1 )
        {
            hMapFile = CreateFileMapping( hFile, NULL, PAGE_READONLY, 0, fileSize, NULL );
            if( hMapFile )
            {
                mapWaveBank = MapViewOfFile( hMapFile, FILE_MAP_READ, 0, 0, 0 );
                if( mapWaveBank )
                    result = xactEngine->CreateInMemoryWaveBank( mapWaveBank, fileSize, 0, 0, &waveBank );

                CloseHandle( hMapFile );    // mapWaveBank maintains a handle on the file so close this unneeded handle
            }
        }
        CloseHandle( hFile );    // mapWaveBank maintains a handle on the file so close this unneeded handle
    }
    if( FAILED( result ) )
        return HRESULT_FROM_WIN32( ERROR_FILE_NOT_FOUND );

    // Read and register the sound bank file with XACT.
    result = E_FAIL;    // default to failure code, replaced on success
    hFile = CreateFileA( SOUND_BANK, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL );
    if( hFile != INVALID_HANDLE_VALUE )
    {
        fileSize = GetFileSize( hFile, NULL );
        if( fileSize != -1 )
        {
            soundBankData = new BYTE[fileSize];    // reserve memory for sound bank
            if( soundBankData )
            {
                if( 0 != ReadFile( hFile, soundBankData, fileSize, &bytesRead, NULL ) )
                    result = xactEngine->CreateSoundBank( soundBankData, fileSize, 0, 0, &soundBank );
            }
        }
        CloseHandle( hFile );
    }
    if( FAILED( result ) )
        return HRESULT_FROM_WIN32( ERROR_FILE_NOT_FOUND );

    return S_OK;
}
Exemplo n.º 15
0
/**----------------------------------------------------------------------------
\brief  파일 IO 를 위해 파일을 오픈한다.

\param
\return
\code

\endcode
-----------------------------------------------------------------------------*/
DTSTATUS
FileIoHelper::FIOpenForRead(
IN std::wstring FilePath
)
{
	if (TRUE == Initialized()) { FIOClose(); }

	mReadOnly = TRUE;
	if (TRUE != is_file_existsW(FilePath.c_str()))
	{
			return DTS_NO_FILE_EXIST;
	}

#pragma warning(disable: 4127)
	DTSTATUS status = DTS_WINAPI_FAILED;
	do
	{
		mFileHandle = CreateFileW(
			FilePath.c_str(),
			GENERIC_READ,
			NULL,
			NULL,
			OPEN_EXISTING,
			FILE_ATTRIBUTE_NORMAL,
			NULL
			);
		if (INVALID_HANDLE_VALUE == mFileHandle)
		{
				break;
		}

		// check file size 
		// 
		if (TRUE != GetFileSizeEx(mFileHandle, &mFileSize))
		{
				break;
		}

		mFileMap = CreateFileMapping(
			mFileHandle,
			NULL,
			PAGE_READONLY,
			0,
			0,
			NULL
			);
		if (NULL == mFileMap)
		{
				break;
		}

		status = DTS_SUCCESS;
	} while (FALSE);
#pragma warning(default: 4127)

	if (TRUE != DT_SUCCEEDED(status))
	{
		if (INVALID_HANDLE_VALUE != mFileHandle)
		{
			CloseHandle(mFileHandle);
			mFileHandle = INVALID_HANDLE_VALUE;
		}
		if (NULL != mFileMap) CloseHandle(mFileMap);
	}

	return status;
}
Exemplo n.º 16
0
bool ShareMemory::Create()
{
#ifdef WIN32
	m_hFile = (HANDLE)0xFFFFFFFF;// system
	if ("" != m_mapFilePath)
	{
		string strFile = m_mapFilePath + "/" + m_shareName;
		// file
		m_hFile = CreateFile(
			strFile.c_str(),
			GENERIC_READ|GENERIC_WRITE,
			FILE_SHARE_READ|FILE_SHARE_WRITE,
			NULL,
			OPEN_ALWAYS,//OPEN_EXISTING,
			FILE_ATTRIBUTE_NORMAL,
			NULL
			);
		if ( INVALID_HANDLE_VALUE == m_hFile ) 
		{
			m_lastError = "open file error:" + strFile;
			return false;
		}
	}
	m_hFileMap = CreateFileMapping( m_hFile, NULL, PAGE_READWRITE, 
									0, m_dwSize, m_shareName.c_str() );
	if (NULL == m_hFileMap) 
	{
		m_lastError = "create file mapping error";
		return false;
	}
#else
	if ( -1 == m_digName ) 
	{
		if ( "" == m_shareName ) 
		{
			m_lastError = "key is null";
			return false;
		}
		m_digName = atoi( m_shareName.c_str() );
		if ( 0 >= m_digName ) 
		{
			m_lastError = "key havo to bigger than 0";
			return false;
		}
	}
	m_shmid = shmget( m_digName, m_dwSize, IPC_CREAT|IPC_EXCL );
	if ( -1 == m_shmid )
	{
		if ( EEXIST == errno ) 
		{
			m_shmid = shmget( m_digName, m_dwSize, 0666 );
		}
		if ( -1 == m_shmid ) 
		{
			m_lastError = "open error:";
			if ( EINVAL == errno )
			{
				m_lastError += "size < SHMMIN or size > SHM-MAX";
				m_lastError += ", or segment is exist, but size is small than the new size";
			}
			if ( EIDRM == errno ) m_lastError += "segment is delete";
			if ( ENOSPC == errno ) m_lastError += "requested size would cause the  system  to exceed the system-wide limit on shared memory (SHMALL)";
			if ( ENOENT == errno ) m_lastError += "No segment exists";
			if ( EACCES == errno ) m_lastError += "not have permission to access";
			if ( ENOMEM == errno ) m_lastError += "No memory could be allocated for segment overhead";
			if ( ENFILE == errno ) m_lastError += "open too many file";
			return false;
		}
	}
#endif
	return true;
}
int    main(int argc, char **argv){
       int    numsec, i, size, shit;
       unsigned int    entrypoint;
       unsigned short * gg;
       HANDLE fd, temp;
       void *memptr;
       char *start, *blabla;

       printf("+-----------------------------------------------+\n");
       printf("|runtime crypter v1.0                           |\n");
       printf("|      coded by deroko                          |\n");
       printf("+-----------------------------------------------+\n\n");
       if (argc != 2){
              printf("Usage : \n%s <file_to_encrypt>\n",argv[0]);
              return 0;
       }

       fd = CreateFileA(argv[1], GENERIC_READ | GENERIC_WRITE, null, null, OPEN_EXISTING, null, null);
       if     ((int)fd == -1){
              printf("[X] Cann't open file %s",argv[1]);
              return 0;
       }

       temp = CreateFileMapping(fd, null, PAGE_READWRITE, null, null, null);
       if (temp == 0)
              return 0;
       memptr = MapViewOfFile(temp, FILE_MAP_ALL_ACCESS, null,null, null);
       if ((int)memptr == 0)
              return 0;
       start = (char *) memptr;
       size = GetFileSize(fd, 0);
       shit = 0;
       for (i=0; i<size; i++){
             if (!strcmp(start, "START")){
                   printf ("[*] Found matching start string\n");
                   //delete f*****g string
                   memset(start, 0xFF, 6);
                   start+=(strlen("START")+1); //skip singlestep trap + ENCRYPTED string
                   shit++;
                   break;
             }else
                 start++;
       }
       if (!shit){
              printf("[X] Cann't find matching start string\n");
              printf("[X] Aborting...\n");
              goto ende;
       }
       blabla = start;

       shit = 0;
       for (i=0; i<size; i++){
              if ( !strcmp(blabla, "END")){
                     printf("[*] Found matching end string\n");
                     //delete f*****g string
                     memset(blabla, 0x90, 4);
                     shit++;
                     break;
              }else
                 blabla++;
       }
       if (!shit){
              printf("[X] Cann't find matching end string\n");
              printf("[X] Aborting...\n");
              goto ende;
       }
       size = (int)blabla-(int)start;

       printf ("[/] Encrypting...\n");
       while (size){
                   *start^=XOR_KEY;
                   start++;
                   size--;
              }

       printf("[*] File ENCRYPTED, f**k AVs\n");
ende:  UnmapViewOfFile(memptr);
       CloseHandle(temp);
       CloseHandle(fd);

       return 0;
}
Exemplo n.º 18
0
static void *_map_alloc(void* ctx_, ptrdiff_t size)
{
  if (size == 0)
    return NULL;

  THMapAllocatorContext *ctx = ctx_;
  void *data = NULL;

#ifdef _WIN32
  if (ctx->flags & TH_ALLOCATOR_MAPPED_SHAREDMEM)
  {
    char *filename;
    LARGE_INTEGER hfilesz;

    if (ctx->filename[0] == '/')
      filename = ctx->filename + 1;
    else
      filename = ctx->filename;

    hfilesz.QuadPart = size;

    if (ctx->flags & TH_ALLOCATOR_MAPPED_EXCLUSIVE)
    {
      ctx->handle = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, hfilesz.HighPart, hfilesz.LowPart, filename);
    }
    else if (ctx->flags & TH_ALLOCATOR_MAPPED_NOCREATE)
    {
      ctx->handle = OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, filename);
    }
    else
    {
      THError("Excpected either TH_ALLOCATOR_MAPPED_EXCLUSIVE or TH_ALLOCATOR_MAPPED_NOCREATE");
    }

    if (ctx->handle == NULL)
      THError("Couldn't open shared file mapping: <%s>, error code: <%d>", filename, GetLastError());

    ctx->size = size;
    data = MapViewOfFile(ctx->handle, FILE_MAP_ALL_ACCESS, 0, 0, size);
    if (!data)
      THError("Couldn't map view of shared file <%s>, error code: <%d>", filename, GetLastError());
  }
  else
  {

    HANDLE hfile;
    HANDLE hmfile;
    LARGE_INTEGER hfilesz;

    if (ctx->flags & TH_ALLOCATOR_MAPPED_EXCLUSIVE)
      THError("exclusive file mapping is not supported on Windows");
    if (ctx->flags & TH_ALLOCATOR_MAPPED_NOCREATE)
      THError("file mapping without creation is not supported on Windows");
    if (ctx->flags & TH_ALLOCATOR_MAPPED_KEEPFD)
      THError("TH_ALLOCATOR_MAPPED_KEEPFD not supported on Windows");
    if (ctx->flags & TH_ALLOCATOR_MAPPED_FROMFD)
      THError("TH_ALLOCATOR_MAPPED_FROMFD not supported on Windows");

    /* open file */
    /* FILE_FLAG_RANDOM_ACCESS ? */
    if(ctx->flags)
    {
      hfile = CreateFileA(ctx->filename, GENERIC_READ|GENERIC_WRITE, FILE_SHARE_WRITE|FILE_SHARE_READ, 0, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
      if (hfile == INVALID_HANDLE_VALUE)
        THError("could not open file <%s> in read-write mode; error code: <%d>", ctx->filename, GetLastError());
    }
    else
    {
      hfile = CreateFileA(ctx->filename, GENERIC_READ, FILE_SHARE_WRITE|FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
      if (hfile == INVALID_HANDLE_VALUE)
        THError("could not open file <%s> in read-only mode; error code: <%d>", ctx->filename, GetLastError());
    }

    if (GetFileSizeEx(hfile, &hfilesz) == 0)
      THError("could not get file size: <%s>; error code: <%d>", ctx->filename, GetLastError());

    if(size > 0)
    {
      if(size > hfilesz.QuadPart)
      {
        if(ctx->flags)
        {
          hfilesz.QuadPart = size;
          if(SetFilePointerEx(hfile, hfilesz, NULL, FILE_BEGIN) == 0)
          {
            CloseHandle(hfile);
            THError("unable to stretch file <%s> to the right size; error code: <%d>", ctx->filename, GetLastError());
          }
          if(SetEndOfFile(hfile) == 0)
          {
            CloseHandle(hfile);
            THError("unable to write to file <%s>; error code: <%d>", ctx->filename, GetLastError());
          }
        }
        else
        {
          CloseHandle(hfile);
          THError("file <%s> size is smaller than the required mapping size <%ld>; error code: <%d>", ctx->filename, size, GetLastError());
        }
      }
    }
    else
      size = hfilesz.QuadPart;

    ctx->size = size; /* if we are here, it must be the right size */

    hfilesz.QuadPart = ctx->size;

    /* get map handle */
    if(ctx->flags)
    {
      if( (hmfile = CreateFileMapping(hfile, NULL, PAGE_READWRITE, hfilesz.HighPart, hfilesz.LowPart, NULL)) == NULL )
        THError("could not create a map on file <%s>; error code: <%d>", ctx->filename, GetLastError());
    }
    else
    {
      if( (hmfile = CreateFileMapping(hfile, NULL, PAGE_WRITECOPY, hfilesz.HighPart, hfilesz.LowPart, NULL)) == NULL )
        THError("could not create a map on file <%s>; error code: <%d>", ctx->filename, GetLastError());
    }

    /* map the stuff */
    if(ctx->flags)
      data = MapViewOfFile(hmfile, FILE_MAP_ALL_ACCESS, 0, 0, 0);
    else
      data = MapViewOfFile(hmfile, FILE_MAP_COPY, 0, 0, 0);

    CloseHandle(hfile);
    CloseHandle(hmfile);
  }
#else /* _WIN32 */
  {
    /* open file */
    int fd;
    int flags;
    struct stat file_stat;

    if (ctx->flags & (TH_ALLOCATOR_MAPPED_SHARED | TH_ALLOCATOR_MAPPED_SHAREDMEM))
      flags = O_RDWR | O_CREAT;
    else
      flags = O_RDONLY;

    if (ctx->flags & TH_ALLOCATOR_MAPPED_EXCLUSIVE)
      flags |= O_EXCL;
    if (ctx->flags & TH_ALLOCATOR_MAPPED_NOCREATE)
      flags &= ~O_CREAT;

    if (!(ctx->flags & TH_ALLOCATOR_MAPPED_FROMFD)) {
      if(ctx->flags & TH_ALLOCATOR_MAPPED_SHARED)
      {
        if((fd = open(ctx->filename, flags, (mode_t)0600)) == -1)
          THError("unable to open file <%s> in read-write mode", ctx->filename);
      }
      else if (ctx->flags & TH_ALLOCATOR_MAPPED_SHAREDMEM)
      {
#ifdef HAVE_SHM_OPEN
        if((fd = shm_open(ctx->filename, flags, (mode_t)0600)) == -1)
          THError("unable to open shared memory object <%s> in read-write mode", ctx->filename);
#else
        THError("unable to open file <%s> in sharedmem mode, shm_open unavailable on this platform", ctx->filename);
#endif
      }
      else
      {
        if((fd = open(ctx->filename, O_RDONLY)) == -1)
          THError("unable to open file <%s> in read-only mode", ctx->filename);
      }
    } else {
      fd = ctx->fd;
    }

    if(fstat(fd, &file_stat) == -1)
    {
      if (!(ctx->flags & TH_ALLOCATOR_MAPPED_FROMFD))
        close(fd);
      THError("unable to stat the file <%s>", ctx->filename);
    }

    if(size > 0)
    {
      if(size > file_stat.st_size)
      {
        if(ctx->flags)
        {
          if(ftruncate(fd, size) == -1)
            THError("unable to resize file <%s> to the right size", ctx->filename);
          if(fstat(fd, &file_stat) == -1 || file_stat.st_size < size)
          {
            close(fd);
            THError("unable to stretch file <%s> to the right size", ctx->filename);
          }
/* on OS X write returns with errno 45 (Opperation not supported) when used
 * with a file descriptor obtained via shm_open
 */
#ifndef __APPLE__
          if((write(fd, "", 1)) != 1) /* note that the string "" contains the '\0' byte ... */
          {
            close(fd);
            THError("unable to write to file <%s>", ctx->filename);
          }
#endif
        }
        else
        {
          close(fd);
          THError("file <%s> size is smaller than the required mapping size <%ld>", ctx->filename, size);
        }
      }
    }
    else
      size = file_stat.st_size;

    ctx->size = size; /* if we are here, it must be the right size */

    /* map it */
    if (ctx->flags & (TH_ALLOCATOR_MAPPED_SHARED | TH_ALLOCATOR_MAPPED_SHAREDMEM))
      data = mmap(NULL, ctx->size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
    else
      data = mmap(NULL, ctx->size, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0);

    if (ctx->flags & TH_ALLOCATOR_MAPPED_KEEPFD) {
      ctx->fd = fd;
    } else {
      if(close(fd) == -1)
        THError("Error closing file <%s>", ctx->filename);
      ctx->fd = -1;
    }

    if (ctx->flags & TH_ALLOCATOR_MAPPED_UNLINK) {
      if (ctx->flags & TH_ALLOCATOR_MAPPED_SHAREDMEM)
      {
#ifdef HAVE_SHM_UNLINK
        if (shm_unlink(ctx->filename) == -1)
          THError("could not unlink the shared memory file %s", ctx->filename);
#else
        THError("could not unlink the shared memory file %s, shm_unlink not available on platform", ctx->filename);
#endif
      }
      else
      {
        if (unlink(ctx->filename) == -1)
          THError("could not unlink file %s", ctx->filename);
      }
    }

    if(data == MAP_FAILED)
    {
      data = NULL; /* let's be sure it is NULL */
      THError("$ Torch: unable to mmap memory: you tried to mmap %dGB.", ctx->size/1073741824);
    }
  }
#endif

  return data;
}
Exemplo n.º 19
0
int CMiniDumpReader::Open(CString sFileName, CString sSymSearchPath)
{  
    static DWORD dwProcessID = 0;

    if(m_bLoaded)
    {
		// Already loaded
        return 0;
    }

    m_sFileName = sFileName;
    m_sSymSearchPath = sSymSearchPath;

    m_hFileMiniDump = CreateFile(
        sFileName, 
        FILE_GENERIC_READ, 
        0, 
        NULL, 
        OPEN_EXISTING, 
        NULL, 
        NULL);

    if(m_hFileMiniDump==INVALID_HANDLE_VALUE)
    {
        Close();
        return 1;
    }

    m_hFileMapping = CreateFileMapping(
        m_hFileMiniDump, 
        NULL, 
        PAGE_READONLY, 
        0, 
        0, 
        0);

    if(m_hFileMapping==NULL)
    {
        Close();
        return 2;
    }

    m_pMiniDumpStartPtr = MapViewOfFile(
        m_hFileMapping, 
        FILE_MAP_READ, 
        0, 
        0, 
        0);

    if(m_pMiniDumpStartPtr==NULL)
    {    
        Close();
        return 3;
    }

    m_DumpData.m_hProcess = (HANDLE)(++dwProcessID);  

    DWORD dwOptions = 0;
    //dwOptions |= SYMOPT_DEFERRED_LOADS; // Symbols are not loaded until a reference is made requiring the symbols be loaded.
    dwOptions |= SYMOPT_EXACT_SYMBOLS; // Do not load an unmatched .pdb file. 
    dwOptions |= SYMOPT_FAIL_CRITICAL_ERRORS; // Do not display system dialog boxes when there is a media failure such as no media in a drive.
    dwOptions |= SYMOPT_UNDNAME; // All symbols are presented in undecorated form.   
    SymSetOptions(dwOptions);

    strconv_t strconv;
    BOOL bSymInit = SymInitializeW(
        m_DumpData.m_hProcess,
        strconv.t2w(sSymSearchPath), 
        FALSE);

    if(!bSymInit)
    {
        m_DumpData.m_hProcess = NULL;
        Close();
        return 5;
    }

    /*SymRegisterCallbackW64(
    m_DumpData.m_hProcess, 
    SymRegisterCallbackProc64,
    (ULONG64)this);*/

    m_bReadSysInfoStream = !ReadSysInfoStream();  
    m_bReadModuleListStream = !ReadModuleListStream();
    m_bReadThreadListStream = !ReadThreadListStream();
    m_bReadMemoryListStream = !ReadMemoryListStream();    
    m_bReadExceptionStream = !ReadExceptionStream();    

    m_bLoaded = true;
    return 0;
}
Exemplo n.º 20
0
SharedMenuBuffer::SharedMenuBuffer(unsigned int length)
{
   m_hFileMapping = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, length, NULL);
   m_hViewPtr = NULL;
}
Exemplo n.º 21
0
//
// Open up a file, memory map it, and call the appropriate dumping routine
//
void DumpFile(LPSTR filename)
{
    HANDLE hFile;
    HANDLE hFileMapping;
    LPVOID lpFileBase;
    PIMAGE_DOS_HEADER dosHeader;
    
    hFile = CreateFile(filename, GENERIC_READ, FILE_SHARE_READ, NULL,
                        OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
                    
    if ( hFile == INVALID_HANDLE_VALUE )
    {
        printf("Couldn't open file with CreateFile()\n");
        return;
    }

    hFileMapping = CreateFileMapping(hFile, NULL, PAGE_READONLY, 0, 0, NULL);
    if ( hFileMapping == 0 )
    {
        CloseHandle(hFile);
        printf("Couldn't open file mapping with CreateFileMapping()\n");
        return;
    }

    lpFileBase = MapViewOfFile(hFileMapping, FILE_MAP_READ, 0, 0, 0);
    if ( lpFileBase == 0 )
    {
        CloseHandle(hFileMapping);
        CloseHandle(hFile);
        printf("Couldn't map view of file with MapViewOfFile()\n");
        return;
    }

    printf("Dump of file %s\n\n", filename);
    
    dosHeader = (PIMAGE_DOS_HEADER)lpFileBase;
	PIMAGE_FILE_HEADER pImgFileHdr = (PIMAGE_FILE_HEADER)lpFileBase;

    if ( dosHeader->e_magic == IMAGE_DOS_SIGNATURE )
    {
        DumpExeFile( dosHeader );
    }
    else if ( dosHeader->e_magic == IMAGE_SEPARATE_DEBUG_SIGNATURE )
    {
        DumpDbgFile( (PIMAGE_SEPARATE_DEBUG_HEADER)lpFileBase );
    }
    else if ( (pImgFileHdr->Machine == IMAGE_FILE_MACHINE_I386)	// FIX THIS!!!
    		||(pImgFileHdr->Machine == IMAGE_FILE_MACHINE_ALPHA) )
    {
		if ( 0 == pImgFileHdr->SizeOfOptionalHeader )	// 0 optional header
	        DumpObjFile( pImgFileHdr );					// means it's an OBJ

		else if ( 	pImgFileHdr->SizeOfOptionalHeader
					== IMAGE_SIZEOF_ROM_OPTIONAL_HEADER )
		{
			DumpROMImage( (PIMAGE_ROM_HEADERS)pImgFileHdr );
		}
    }
    else if ( 0 == strncmp((char *)lpFileBase, 	IMAGE_ARCHIVE_START,
                                       			IMAGE_ARCHIVE_START_SIZE ) )
    {
        DumpLibFile( lpFileBase );
    }
    else
        printf("unrecognized file format\n");

    UnmapViewOfFile(lpFileBase);
    CloseHandle(hFileMapping);
    CloseHandle(hFile);
}
Exemplo n.º 22
0
int32_t drn_open(drn_t * cache, const char * filename, int mode)
{
    int fd = OPEN(filename, OPEN_MODE);
    if (fd <=0)
    {
        return -1;
    }
    cache->fd = fd;
    cache->mmap_size = drn_fsize(fd);
    cache->mode = mode;
    if (mode == DRN_READ_NOLOAD)
    {
        uint64_t i;
        size_t bytes;
        drn_desc_t hashes_desc;
        drn_map_container_t * map_containers;

        cache->mmap_start = 0;
        cache->data = 0;
        cache->header = ALLOCATE(sizeof(drn_header_container_t));
        bytes = READ(fd, cache->header, sizeof(drn_header_container_t));
        assert(bytes == sizeof(drn_header_container_t));
        if (drn_get_version(cache) != DRN_WRITER_VERSION)
            return 1;
        cache->descriptors = ALLOCATE(cache->header->chunk_count * sizeof(drn_desc_t));
        LSEEK(fd, cache->header->index_offset, SEEK_SET);
        bytes = READ(fd, cache->descriptors, READ_COUNT_CAST ((size_t) cache->header->chunk_count) * sizeof(drn_desc_t));
        assert(bytes == cache->header->chunk_count * sizeof(drn_desc_t));

        hashes_desc =  drn_get_desc(cache, cache->header->maps_chunk_id);
        cache->map_count = hashes_desc.size / sizeof(drn_map_container_t);
        cache->maps = ALLOCATE(sizeof(drn_map_t) * (size_t) cache->map_count);
        map_containers = ALLOCATE(hashes_desc.size);
        drn_read_chunk(cache, cache->header->maps_chunk_id, map_containers);
        for (i = 0; i < cache->map_count; ++i)
        {
            drn_desc_t d;
            const drn_map_container_t * c = map_containers + i;
            drn_map_t * h = cache->maps + i;

            h->hash = ALLOCATE(drn_get_desc(cache, c->hash_chunk_id).size);
            drn_read_chunk(cache, c->hash_chunk_id, (void *) h->hash);
            h->name = ALLOCATE(drn_get_desc(cache, c->name_chunk_id).size);
            drn_read_chunk(cache, c->name_chunk_id, (void *) h->name);
            d = drn_get_desc(cache, c->descriptors_chunk_id);
            h->chunk_count = d.size / sizeof(drn_hash_desc_t);
            h->descriptors = ALLOCATE(d.size);
            drn_read_chunk(cache, c->descriptors_chunk_id, (void *) h->descriptors);
            h->value_strings = ALLOCATE(drn_get_desc(cache, c->value_strings_chunk_id).size);
            drn_read_chunk(cache, c->value_strings_chunk_id, (void *)h->value_strings);
        }
        FREE(map_containers);
    }
    else
    {
        uint64_t i;
        drn_desc_t maps_desc;
        drn_map_container_t * map_containers;

        if (mode == DRN_READ_MMAP)
        {
#ifdef _MSC_VER
			wchar_t * w_filename;
			size_t bytes;

			CLOSE(fd);
			w_filename = ALLOCATE((strlen(filename)+1) * sizeof(wchar_t));
			bytes = mbstowcs(w_filename, filename, strlen(filename)+1);
			//cache->w_fhandle = CreateFile(L"test.drn", GENERIC_READ, 0, 0, OPEN_EXISTING, 0, 0);
			cache->w_fhandle = CreateFile(w_filename, GENERIC_READ, 0, 0, OPEN_EXISTING, 0, 0);
			FREE(w_filename);
			if ((int) cache->w_fhandle  == HFILE_ERROR)
			{
				DWORD err = GetLastError();
				printf("ERROR %Ld\n", err);
				return -1;
			}
			cache->w_mhandle = CreateFileMapping(cache->w_fhandle, NULL, PAGE_READONLY, 0, 0, NULL);
			if (cache->w_mhandle  == NULL)
			{
				DWORD err = GetLastError();
				return -1;
			}
			cache->mmap_start = MapViewOfFile(cache->w_mhandle, FILE_MAP_READ, 0, 0, (size_t) cache->mmap_size);
			if (cache->mmap_start  == NULL)
			{
				DWORD err = GetLastError();
				return -1;
			}
#else
            cache->mmap_start = mmap(0, cache->mmap_size, PROT_READ, MAP_PRIVATE, fd, 0);
			CLOSE(fd);
#endif
        }
        else if (mode == DRN_READ_LOAD)
        {
            size_t bytes;

            cache->mmap_start = ALLOCATE(cache->mmap_size);
            bytes = READ(fd, cache->mmap_start, READ_COUNT_CAST (size_t) cache->mmap_size);
            assert(bytes == cache->mmap_size);
			CLOSE(fd);
        }
        cache->data = (char *) cache->mmap_start + sizeof(drn_header_container_t);
        cache->header = (drn_header_container_t *) cache->mmap_start;
        if (drn_get_version(cache) != DRN_WRITER_VERSION)
            return 1;
        cache->descriptors = (drn_desc_t *) ((char *)cache->mmap_start + cache->header->index_offset);
        maps_desc =  drn_get_desc(cache, cache->header->maps_chunk_id);
        cache->map_count = maps_desc.size / sizeof(drn_map_container_t);
        map_containers = (drn_map_container_t *) drn_get_chunk(cache, cache->header->maps_chunk_id);
        cache->maps = ALLOCATE(sizeof(drn_map_t) * (size_t) cache->map_count);
        for (i = 0; i < cache->map_count; ++i)
        {
            drn_desc_t d;
            const drn_map_container_t * c = map_containers + i;
            drn_map_t * h = cache->maps + i;

            h->hash =  drn_get_chunk(cache, c->hash_chunk_id);
            h->name =  drn_get_chunk(cache, c->name_chunk_id);
            d = drn_get_desc(cache, c->descriptors_chunk_id);
            h->chunk_count = d.size / sizeof(drn_hash_desc_t);
            h->descriptors =  drn_get_chunk(cache, c->descriptors_chunk_id);
            h->value_strings =  drn_get_chunk(cache, c->value_strings_chunk_id);
        }
    }
    return 0;
}
Exemplo n.º 23
0
static PyObject *
mmap_resize_method(mmap_object *self,
                   PyObject *args)
{
    Py_ssize_t new_size;
    CHECK_VALID(NULL);
    if (!PyArg_ParseTuple(args, "n:resize", &new_size) ||
        !is_resizeable(self)) {
        return NULL;
#ifdef MS_WINDOWS
    } else {
        DWORD dwErrCode = 0;
        DWORD off_hi, off_lo, newSizeLow, newSizeHigh;
        /* First, unmap the file view */
        UnmapViewOfFile(self->data);
        self->data = NULL;
        /* Close the mapping object */
        CloseHandle(self->map_handle);
        self->map_handle = NULL;
        /* Move to the desired EOF position */
        newSizeHigh = (DWORD)((self->offset + new_size) >> 32);
        newSizeLow = (DWORD)((self->offset + new_size) & 0xFFFFFFFF);
        off_hi = (DWORD)(self->offset >> 32);
        off_lo = (DWORD)(self->offset & 0xFFFFFFFF);
        SetFilePointer(self->file_handle,
                       newSizeLow, &newSizeHigh, FILE_BEGIN);
        /* Change the size of the file */
        SetEndOfFile(self->file_handle);
        /* Create another mapping object and remap the file view */
        self->map_handle = CreateFileMapping(
            self->file_handle,
            NULL,
            PAGE_READWRITE,
            0,
            0,
            self->tagname);
        if (self->map_handle != NULL) {
            self->data = (char *) MapViewOfFile(self->map_handle,
                                                FILE_MAP_WRITE,
                                                off_hi,
                                                off_lo,
                                                new_size);
            if (self->data != NULL) {
                self->size = new_size;
                Py_INCREF(Py_None);
                return Py_None;
            } else {
                dwErrCode = GetLastError();
                CloseHandle(self->map_handle);
                self->map_handle = NULL;
            }
        } else {
            dwErrCode = GetLastError();
        }
        PyErr_SetFromWindowsErr(dwErrCode);
        return NULL;
#endif /* MS_WINDOWS */

#ifdef UNIX
#ifndef HAVE_MREMAP
    } else {
Exemplo n.º 24
0
DWORD
TpDiffOpenLogFiles(
    VOID
    )

/*++

Routine Description:

    This routine opens the file names stored in the global variables
    LogFileName and KnownLogFile name, creates a buffer for each and
    reads the file contents into the respective buffer.

Arguments:

    None

Return Value:

    DWORD - If NO_ERROR the files were opened and read into the buffers.
            otherwise there was a failure that will cause the application
            to un-initialize and exit.

--*/

{
    DWORD Status;
    HANDLE LogFileHandle = NULL;
    HANDLE LogFileMapHandle = NULL;
    HANDLE KnownLogFileHandle = NULL;
    HANDLE KnownLogFileMapHandle = NULL;

    //
    // First open the LOG_FILE file.
    //

    if (( LogFileName[0] == '\0' ) || ( KnownLogFileName[0] == '\0' )) {
        return ERROR_NO_MORE_FILES;
    }

    LogFileHandle = CreateFile(
                        LogFileName,
                        GENERIC_READ,
                        FILE_SHARE_READ,
                        NULL,
                        OPEN_EXISTING,
                        FILE_ATTRIBUTE_NORMAL,
                        NULL
                        );

    if ( LogFileHandle == (HANDLE)-1 ) {
        Status = GetLastError();

        if ( Status == ERROR_FILE_NOT_FOUND ) {
            TpDiffWriteErrorToDiffFile( "Tpdiff: WARNING - Failed to open LOG_FILE \"" );
            TpDiffWriteErrorToDiffFile( LogFileName );
            TpDiffWriteErrorToDiffFile( "\".\n");
        }

        printf("\n\tTpDiff: Failed to open LOG_FILE \"%s\", returned %ld.\n",
            LogFileName,Status);
        return Status;
    }

    //
    // then find its size.
    //

    LogFileSize = GetFileSize( LogFileHandle,NULL );

    if ( LogFileSize == -1 ) {
        Status = GetLastError();
        printf("\n\tTpDiff: failed find LOG_FILE size - returned %ld.\n",Status);
        CloseHandle( LogFileHandle );
        return Status;
    } else if ( LogFileSize == 0 ) {
        printf("\n\tTpDiff: LOG_FILE \"%s\" is empty, nothing to compare.\n",LogFileName);
        CloseHandle( LogFileHandle );
        return ERROR_NO_MORE_FILES;

    }

    //
    // and create a file mapping.
    //

    LogFileMapHandle = CreateFileMapping(
                           LogFileHandle,
                           NULL,
                           PAGE_READONLY,
                           0,
                           LogFileSize,
                           NULL
                           );

    if ( LogFileMapHandle == NULL ) {
        Status = GetLastError();
        printf("\n\tTpDiff: Unable to map LOG_FILE \"%s\", returned %d",
            LogFileName,Status);
        CloseHandle( LogFileHandle );
        return Status;
    }

    //
    // We're done with the file handle so close it now.
    //

    CloseHandle( LogFileHandle );

    //
    // Now create a View of the mapped file.
    //

    LogFileBuffer = MapViewOfFile(
                        LogFileMapHandle,
                        FILE_MAP_READ,
                        0,
                        0,
                        LogFileSize
                        );

    if ( LogFileBuffer == NULL ) {
        Status = GetLastError();
        printf("\n\tTpDiff: Unable to map view of LOG_FILE \"%s\", returned %d",
            LogFileName,Status);
        CloseHandle( LogFileMapHandle );
        return Status;
    }

    //
    // We're done with the map handle so close it now.
    //

    CloseHandle( LogFileMapHandle );

    //
    // Now reset the offset into the LogFilebuffer and the line number
    // counter to zero.
    //

    LogFileOffset = 0;
    LogFileLineNumber = 1;

    //
    // Then open the KNOWN_LOG_FILE file.
    //

    KnownLogFileHandle = CreateFile(
                             KnownLogFileName,
                             GENERIC_READ,
                             FILE_SHARE_READ,
                             NULL,
                             OPEN_EXISTING,
                             FILE_ATTRIBUTE_NORMAL,
                             NULL
                             );

    if ( KnownLogFileHandle == (HANDLE)-1 ) {
        Status = GetLastError();

        if ( Status == ERROR_FILE_NOT_FOUND ) {
            TpDiffWriteErrorToDiffFile("TpDiff: WARNING Failed to open KNOWN_LOG_FILE \"");
            TpDiffWriteErrorToDiffFile(KnownLogFileName);
            TpDiffWriteErrorToDiffFile("\".\n");
        }

        printf("\n\tTpDiff: Failed to open KNOWN_LOG_FILE \"%s\", returned %ld.\n",
            KnownLogFileName,Status);
        return Status;
    }

    //
    // then find its size.
    //

    KnownLogFileSize = GetFileSize( KnownLogFileHandle,NULL );

    if ( KnownLogFileSize == -1 ) {
        Status = GetLastError();
        printf("\n\tTpDiff: failed find KNOWN_LOG_FILE size - returned %ld.\n",Status);
        CloseHandle( KnownLogFileHandle );
        return Status;
    } else if ( KnownLogFileSize == 0 ) {
        printf("\n\tTpDiff: KNOWN_LOG_FILE \"%s\" is empty, nothing to compare.\n",KnownLogFileName);
        CloseHandle( KnownLogFileHandle );
        return ERROR_NO_MORE_FILES;
    }

    //
    // and create a file mapping.
    //

    KnownLogFileMapHandle = CreateFileMapping(
                                KnownLogFileHandle,
                                NULL,
                                PAGE_READONLY,
                                0,
                                KnownLogFileSize,
                                NULL
                                );

    if ( KnownLogFileMapHandle == NULL ) {
        Status = GetLastError();
        printf("\n\tTpDiff: Unable to map KNOWN_LOG_FILE \"%s\", returned %d",
            KnownLogFileName,Status);
        CloseHandle( KnownLogFileHandle );
        return Status;
    }

    //
    // We're done with the file handle so close it now.
    //

    CloseHandle( KnownLogFileHandle );

    //
    // Now create a View of the mapped file.
    //

    KnownLogFileBuffer = MapViewOfFile(
                             KnownLogFileMapHandle,
                             FILE_MAP_READ,
                             0,
                             0,
                             KnownLogFileSize
                             );

    if ( KnownLogFileBuffer == NULL ) {
        Status = GetLastError();
        printf("\n\tTpDiff: Unable to map view of KNOWN_LOG_FILE \"%s\", returned %d",
            KnownLogFileName,Status);
        CloseHandle( KnownLogFileMapHandle );
        return Status;
    }

    //
    // We're done with the map handle so close it now.
    //

    CloseHandle( KnownLogFileMapHandle );

    //
    // Now reset the offset into the KnownLogFilebuffer to zero.
    // and return.
    //

    KnownLogFileOffset = 0;
    KnownLogFileLineNumber = 1;

    return NO_ERROR;
}
Exemplo n.º 25
0
static int create_segments(size_t requested_size, zend_shared_segment ***shared_segments_p, int *shared_segments_count, char **error_in)
{
	int err, ret;
	zend_shared_segment *shared_segment;
	int map_retries = 0;
	void *default_mapping_base_set[] = { 0, 0 };
	/* TODO:
	  improve fixed addresses on x64. It still makes no sense to do it as Windows addresses are virtual per se and can or should be randomized anyway
	  through Address Space Layout Radomization (ASLR). We can still let the OS do its job and be sure that each process gets the same address if
	  desired. Not done yet, @zend refused but did not remember the exact reason, pls add info here if one of you know why :)
	*/
#if defined(_WIN64)
	void *vista_mapping_base_set[] = { (void *) 0x0000100000000000, (void *) 0x0000200000000000, (void *) 0x0000300000000000, (void *) 0x0000700000000000, 0 };
#else
	void *vista_mapping_base_set[] = { (void *) 0x20000000, (void *) 0x21000000, (void *) 0x30000000, (void *) 0x31000000, (void *) 0x50000000, 0 };
#endif
	void **wanted_mapping_base = default_mapping_base_set;

	zend_shared_alloc_lock_win32();
	/* Mapping retries: When Apache2 restarts, the parent process startup routine
	   can be called before the child process is killed. In this case, the map will fail
	   and we have to sleep some time (until the child releases the mapping object) and retry.*/
	do {
		memfile = OpenFileMapping(FILE_MAP_WRITE, 0, create_name_with_username(ACCEL_FILEMAP_NAME));
		err = GetLastError();
		if (memfile == NULL) {
			break;
		}

		ret =  zend_shared_alloc_reattach(requested_size, error_in);
		err = GetLastError();
		if (ret == ALLOC_FAIL_MAPPING) {
			/* Mapping failed, wait for mapping object to get freed and retry */
            CloseHandle(memfile);
			memfile = NULL;
			if (++map_retries >= MAX_MAP_RETRIES) {
				break;
			}
			zend_shared_alloc_unlock_win32();
			Sleep(1000 * (map_retries + 1));
			zend_shared_alloc_lock_win32();
		} else {
			zend_shared_alloc_unlock_win32();
			return ret;
		}
	} while (1);

	if (map_retries == MAX_MAP_RETRIES) {
		zend_shared_alloc_unlock_win32();
		zend_win_error_message(ACCEL_LOG_FATAL, "Unable to open file mapping", err);
		*error_in = "OpenFileMapping";
		return ALLOC_FAILURE;
	}

	/* creating segment here */
	*shared_segments_count = 1;
	*shared_segments_p = (zend_shared_segment **) calloc(1, sizeof(zend_shared_segment)+sizeof(void *));
	if (!*shared_segments_p) {
		zend_shared_alloc_unlock_win32();
		zend_win_error_message(ACCEL_LOG_FATAL, "calloc() failed", GetLastError());
		*error_in = "calloc";
		return ALLOC_FAILURE;
	}
	shared_segment = (zend_shared_segment *)((char *)(*shared_segments_p) + sizeof(void *));
	(*shared_segments_p)[0] = shared_segment;

	memfile	= CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, requested_size,
								create_name_with_username(ACCEL_FILEMAP_NAME));
	err = GetLastError();
	if (memfile == NULL) {
		zend_shared_alloc_unlock_win32();
		zend_win_error_message(ACCEL_LOG_FATAL, "Unable to create file mapping", err);
		*error_in = "CreateFileMapping";
		return ALLOC_FAILURE;
	}

	/* Starting from windows Vista, heap randomization occurs which might cause our mapping base to
	   be taken (fail to map). So under Vista, we try to map into a hard coded predefined addresses
	   in high memory. */
	if (!ZCG(accel_directives).mmap_base || !*ZCG(accel_directives).mmap_base) {
		do {
			OSVERSIONINFOEX osvi;
			SYSTEM_INFO si;

			ZeroMemory(&si, sizeof(SYSTEM_INFO));
			ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX));

			osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);

			if (! GetVersionEx ((OSVERSIONINFO *) &osvi)) {
				osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
				if (!GetVersionEx((OSVERSIONINFO *)&osvi)) {
					break;
				}
			}

			GetSystemInfo(&si);

			/* Are we running Vista ? */
			if (osvi.dwPlatformId == VER_PLATFORM_WIN32_NT && osvi.dwMajorVersion == 6) {
				wanted_mapping_base = vista_mapping_base_set;
			}
		} while (0);
	} else {
		char *s = ZCG(accel_directives).mmap_base;

		/* skip leading 0x, %p assumes hexdeciaml format anyway */
		if (*s == '0' && *(s + 1) == 'x') {
			s += 2;
		}
		if (sscanf(s, "%p", &default_mapping_base_set[0]) != 1) {
			zend_shared_alloc_unlock_win32();
			zend_win_error_message(ACCEL_LOG_FATAL, "Bad mapping address specified in opcache.mmap_base", err);
			return ALLOC_FAILURE;
		}
	}

	do {
		shared_segment->p = mapping_base = MapViewOfFileEx(memfile, FILE_MAP_ALL_ACCESS, 0, 0, 0, *wanted_mapping_base);
		if (*wanted_mapping_base == NULL) { /* Auto address (NULL) is the last option on the array */
			break;
		}
		wanted_mapping_base++;
	} while (!mapping_base);

	err = GetLastError();
	if (mapping_base == NULL) {
		zend_shared_alloc_unlock_win32();
		zend_win_error_message(ACCEL_LOG_FATAL, "Unable to create view for file mapping", err);
		*error_in = "MapViewOfFile";
		return ALLOC_FAILURE;
	} else {
		char *mmap_base_file = get_mmap_base_file();
		FILE *fp = fopen(mmap_base_file, "w");
		err = GetLastError();
		if (!fp) {
			zend_shared_alloc_unlock_win32();
			zend_win_error_message(ACCEL_LOG_WARNING, mmap_base_file, err);
			zend_win_error_message(ACCEL_LOG_FATAL, "Unable to write base address", err);
			return ALLOC_FAILURE;
		}
		fprintf(fp, "%p\n", mapping_base);
		fclose(fp);
	}

	shared_segment->pos = 0;
	shared_segment->size = requested_size;

	zend_shared_alloc_unlock_win32();

	return ALLOC_SUCCESS;
}
Exemplo n.º 26
0
DWORD
TpDiffInitLogFileList(
    IN LPSTR LogFileList
    )

/*++

Routine Description:

    This routine opens and reads the LOG_FILE_LIST file into a newly
    allocated buffer.  The handle, buffer and filename are all attached
    to global LOG_FILE_LIST variables.

Arguments:

    IN LPSTR LogFileList - Supplies the name of the LOG_FILE_LIST file
                           to open.

Return Value:

    DWORD - If NO_ERROR the file was opened and read into the buffer.
            otherwise there was a failure that will cause the application
            to un-initialize and exit.

--*/

{
    DWORD Status;
    HANDLE LogFileListHandle = NULL;
    HANDLE LogFileListMapHandle = NULL;

    //
    // First Open the LOG_FILE_LIST file.
    //

    strcpy( LogFileListName,LogFileList );

    LogFileListHandle = CreateFile(
                            LogFileListName,
                            GENERIC_READ,
                            FILE_SHARE_READ,
                            NULL,
                            OPEN_EXISTING,
                            FILE_ATTRIBUTE_NORMAL,
                            NULL
                            );

    if ( LogFileListHandle == (HANDLE)-1 ) {
        Status = GetLastError();
        printf("\n\tTpDiff: Failed to open LOG_FILE_LIST \"%s\", returned %ld.\n",
            LogFileListName,Status);
        return Status;
    }

    //
    // then find its size.
    //

    LogFileListSize = GetFileSize( LogFileListHandle,NULL );

    if ( LogFileListSize == -1 ) {
        Status = GetLastError();
        printf("\n\tTpDiff: failed find LOG_FILE_LIST size, returned %ld.\n",Status);
        CloseHandle( LogFileListHandle );
        return Status;
    } else if ( LogFileListSize == 0 ) {
        printf("\n\tTpDiff: LOG_FILE_LIST is empty, nothing to compare.\n");
        CloseHandle( LogFileListHandle );
        return ERROR_FILE_NOT_FOUND;
    }

    //
    // and create a file mapping.
    //

    LogFileListMapHandle = CreateFileMapping(
                               LogFileListHandle,
                               NULL,
                               PAGE_READONLY,
                               0,
                               LogFileListSize,
                               NULL
                               );

    if ( LogFileListMapHandle == NULL ) {
        Status = GetLastError();
        printf("\n\tTpDiff: Unable to map LOG_FILE_LIST \"%s\", returned %d",
            LogFileListName,Status);
        CloseHandle( LogFileListHandle );
        return Status;
    }

    //
    // We're done with the file handle so close it now.
    //

    CloseHandle( LogFileListHandle );

    //
    // Now create a View of the mapped file.
    //

    LogFileListBuffer = MapViewOfFile(
                            LogFileListMapHandle,
                            FILE_MAP_READ,
                            0,
                            0,
                            LogFileListSize
                            );

    if ( LogFileListBuffer == NULL ) {
        Status = GetLastError();
        printf("\n\tTpDiff: Unable to map view of LOG_FILE_LIST \"%s\", returned %d",
            LogFileListName,Status);
        CloseHandle( LogFileListMapHandle );
        return Status;
    }

    //
    // We're done with the map handle so close it now.
    //

    CloseHandle( LogFileListMapHandle );

    return NO_ERROR;
}
Exemplo n.º 27
0
BOOL FileReverse(PCTSTR pszPathname, PBOOL pbIsTextUnicode) {

   *pbIsTextUnicode = FALSE;  // Assume text is Unicode

   // Open the file for reading and writing.
   HANDLE hFile = CreateFile(pszPathname, GENERIC_WRITE | GENERIC_READ, 0, 
      NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);

   if (hFile == INVALID_HANDLE_VALUE) {
      chMB("File could not be opened.");
      return(FALSE);
   }

   // Get the size of the file (I assume the whole file can be mapped).
   DWORD dwFileSize = GetFileSize(hFile, NULL);

   // Create the file-mapping object. The file-mapping object is 1 character 
   // bigger than the file size so that a zero character can be placed at the 
   // end of the file to terminate the string (file). Because I don't yet know
   // if the file contains ANSI or Unicode characters, I assume worst case
   // and add the size of a WCHAR instead of CHAR.
   HANDLE hFileMap = CreateFileMapping(hFile, NULL, PAGE_READWRITE, 
      0, dwFileSize + sizeof(WCHAR), NULL);

   if (hFileMap == NULL) {
      chMB("File map could not be opened.");
      CloseHandle(hFile);
      return(FALSE);
   }

   // Get the address where the first byte of the file is mapped into memory.
   PVOID pvFile = MapViewOfFile(hFileMap, FILE_MAP_WRITE, 0, 0, 0);

   if (pvFile == NULL) {
      chMB("Could not map view of file.");
      CloseHandle(hFileMap);
      CloseHandle(hFile);
      return(FALSE);
   }

   // Does the buffer contain ANSI or Unicode?
   int iUnicodeTestFlags = -1;   // Try all tests
   *pbIsTextUnicode = IsTextUnicode(pvFile, dwFileSize, &iUnicodeTestFlags);

   if (!*pbIsTextUnicode) {
      // For all the file manipulations below, we explicitly use ANSI 
      // functions because we are processing an ANSI file.

      // Put a zero character at the very end of the file.
      PSTR pchANSI = (PSTR) pvFile;
      pchANSI[dwFileSize / sizeof(CHAR)] = 0;

      // Reverse the contents of the file.
      _strrev(pchANSI);

      // Convert all "\n\r" combinations back to "\r\n" to 
      // preserve the normal end-of-line sequence.
      pchANSI = strstr(pchANSI, "\n\r"); // Find first "\r\n".

      while (pchANSI != NULL) {
         // We have found an occurrence....
         *pchANSI++ = '\r';   // Change '\n' to '\r'.
         *pchANSI++ = '\n';   // Change '\r' to '\n'.
         pchANSI = strstr(pchANSI, "\n\r"); // Find the next occurrence.
      }

   } else {
      // For all the file manipulations below, we explicitly use Unicode
      // functions because we are processing a Unicode file.

      // Put a zero character at the very end of the file.
      PWSTR pchUnicode = (PWSTR) pvFile;
      pchUnicode[dwFileSize / sizeof(WCHAR)] = 0;

      if ((iUnicodeTestFlags & IS_TEXT_UNICODE_SIGNATURE) != 0) {
         // If the first character is the Unicode BOM (byte-order-mark), 
         // 0xFEFF, keep this character at the beginning of the file.
         pchUnicode++;
      }

      // Reverse the contents of the file.
      _wcsrev(pchUnicode);

      // Convert all "\n\r" combinations back to "\r\n" to 
      // preserve the normal end-of-line sequence.
      pchUnicode = wcsstr(pchUnicode, L"\n\r"); // Find first '\n\r'.

      while (pchUnicode != NULL) {
         // We have found an occurrence....
         *pchUnicode++ = L'\r';   // Change '\n' to '\r'.
         *pchUnicode++ = L'\n';   // Change '\r' to '\n'.
         pchUnicode = wcsstr(pchUnicode, L"\n\r"); // Find the next occurrence.
      }
   }

   // Clean up everything before exiting.
   UnmapViewOfFile(pvFile);
   CloseHandle(hFileMap);

   // Remove trailing zero character added earlier.
   SetFilePointer(hFile, dwFileSize, NULL, FILE_BEGIN);
   SetEndOfFile(hFile);
   CloseHandle(hFile);

   return(TRUE);
}
Exemplo n.º 28
0
BOOL WINAPI DllMain( 
					 HINSTANCE hinstDLL,	// handle to DLL module
					 DWORD fdwReason,		// reason for calling function
					 LPVOID lpReserved		// reserved
				   )  
{
	BOOL	fInit = FALSE;
	WORD	wVersionRequested;
	WSADATA wsaData;

    // Perform actions based on the reason for calling.
    switch( fdwReason ) 
    { 
        case DLL_PROCESS_ATTACH:

			OutputDebugString("--> dll_entry.c - oRTP.dll - DLL_PROCESS_ATTACH()\n");
		 
			wVersionRequested = MAKEWORD( 1, 0 );

			if (WSAStartup(wVersionRequested,&wsaData)!=0) 
			{
				return FALSE;
			}

            // Create a named file mapping object. 
            hMapObject = CreateFileMapping( INVALID_HANDLE_VALUE,	// use paging file
											NULL,					// default security attributes
											PAGE_READWRITE,			// read/write access
											0,						// size: high 32-bits
											SHMEMSIZE,				// size: low 32-bits
											"oRTPSharedMemory");  // name of map object

            if (hMapObject == NULL) 
                return FALSE; 
 
            // The first process to attach initializes memory. 
            fInit = (GetLastError() != ERROR_ALREADY_EXISTS); 
 
            // Get a pointer to the file-mapped shared memory.
 
            lpSharedData = (LPSHARED_DATA) MapViewOfFile(   hMapObject,     // object to map view of
														   	FILE_MAP_WRITE, // read/write access
															0,              // high offset:  map from
															0,              // low offset:   beginning
															0);             // default: map entire file
            if (lpSharedData == NULL) 
                return FALSE; 
 
            // Initialize memory if this is the first process.
 
            if (fInit) 
			{
				OutputDebugString("--> dll_entry.c - oRTP.dll - Initializing module\n");

				lpSharedData->m_dwStartTime	= GetTickCount();
				lpSharedData->m_nReference	= 1;
				lpSharedData->m_bInitialize = FALSE;

				// Register the log
				RegisterLog(&dwoRTPLogLevel, "LOG_ORTP");
			}
			else
			{
				OutputDebugString("--> dll_entry.c - oRTP.dll - Binding\n");
				lpSharedData->m_nReference++;
			}
            break;

        case DLL_THREAD_ATTACH:

			if (lpSharedData != NULL)
			{
				if (lpSharedData->m_bInitialize == FALSE)
				{
					// Initialize oRTP
					ortp_init();

					// Start the scheduler
					//ortp_scheduler_init();

					lpSharedData->m_bInitialize = TRUE;
				}
			}
            break;

        case DLL_THREAD_DETACH:
			break;

        case DLL_PROCESS_DETACH:

			if (lpSharedData != NULL)
			{			
				OutputDebugString("--> dll_entry.c - oRTP.dll - Binding\n");
				lpSharedData->m_nReference--;

				if (lpSharedData->m_nReference == 0)
				{
					OutputDebugString("--> dll_entry.c - oRTP.dll - Detaching\n");

					ortp_exit();
					UnregisterLog(&dwoRTPLogLevel, "LOG_ORTP");


					// Unmap shared memory from the process's address space. 
					UnmapViewOfFile(lpSharedData);
					lpSharedData = NULL;
	 
					// Close the process's handle to the file-mapping object.
					CloseHandle(hMapObject); 
					hMapObject = INVALID_HANDLE_VALUE;
				}
			}
            break;
    }

    return TRUE;  // Successful DLL_PROCESS_ATTACH.
}
Exemplo n.º 29
0
Arquivo: mmap.c Projeto: lihnux/plibc
/**
 * @brief map files into memory
 * @author Cygwin team
 * @author Nils Durner
 */
void *_win_mmap(void *start, size_t len, int access, int flags, int fd,
                unsigned long long off) {
  DWORD protect, high, low, access_param;
  HANDLE h, hFile;
  SECURITY_ATTRIBUTES sec_none;
  void *base;
  BOOL bFound = FALSE;
  unsigned int uiIndex;

  errno = 0;

  switch(access)
  {
    case PROT_WRITE:
      protect = PAGE_READWRITE;
      access_param = FILE_MAP_WRITE;
      break;
    case PROT_READ:
      protect = PAGE_READONLY;
      access_param = FILE_MAP_READ;
      break;
    default:
      protect = PAGE_WRITECOPY;
      access_param = FILE_MAP_COPY;
      break;
  }

  sec_none.nLength = sizeof(SECURITY_ATTRIBUTES);
  sec_none.bInheritHandle = TRUE;
  sec_none.lpSecurityDescriptor = NULL;

  hFile = (HANDLE) _get_osfhandle(fd);

  h = CreateFileMapping(hFile, &sec_none, protect, 0, 0, NULL);

  if (! h)
  {
    SetErrnoFromWinError(GetLastError());
    return MAP_FAILED;
  }

  high = off >> 32;
  low = off & ULONG_MAX;
  base = NULL;

  /* If a non-zero start is given, try mapping using the given address first.
     If it fails and flags is not MAP_FIXED, try again with NULL address. */
  if (start)
    base = MapViewOfFileEx(h, access_param, high, low, len, start);
  if (!base && !(flags & MAP_FIXED))
    base = MapViewOfFileEx(h, access_param, high, low, len, NULL);

  if (!base || ((flags & MAP_FIXED) && base != start))
  {
    if (!base)
      SetErrnoFromWinError(GetLastError());
    else
      errno = EINVAL;

    CloseHandle(h);
    return MAP_FAILED;
  }

  /* Save mapping handle */
  WaitForSingleObject(hMappingsLock, INFINITE);

  for(uiIndex = 0; uiIndex <= uiMappingsCount; uiIndex++)
  {
    if (pMappings[uiIndex].pStart == base)
    {
      bFound = 1;
      break;
    }
  }

  if (! bFound)
  {
    int inserted = 0;
    HANDLE hOwnFile;

    if (!DuplicateHandle (GetCurrentProcess (), hFile, GetCurrentProcess (),
        &hOwnFile, 0, FALSE, DUPLICATE_SAME_ACCESS))
    {
      ReleaseMutex(hMappingsLock);
      SetErrnoFromWinError(GetLastError());
      CloseHandle(h);
      return MAP_FAILED;
    }
    
    uiIndex = 0;

    while(!inserted)
    {
      if (pMappings[uiIndex].pStart == NULL)
      {
        pMappings[uiIndex].pStart = base;
        pMappings[uiIndex].hMapping = h;
        pMappings[uiIndex].hFile = hOwnFile;
        inserted = 1;
      }
      if (uiIndex == uiMappingsCount)
      {
        uiMappingsCount++;
        pMappings = (TMapping *) realloc(pMappings, (uiMappingsCount + 1) * sizeof(TMapping));
        pMappings[uiMappingsCount].pStart = NULL;
      }
      uiIndex++;
    }
  }
  ReleaseMutex(hMappingsLock);

  return base;
}
Exemplo n.º 30
-1
void search_file(const char *file_full_path) {
    int fd;
    off_t f_len = 0;
    char *buf = NULL;
    struct stat statbuf;
    int rv = 0;
    FILE *pipe = NULL;

    fd = open(file_full_path, O_RDONLY);
    if (fd < 0) {
        log_err("Error opening file %s: %s Skipping...", file_full_path, strerror(errno));
        goto cleanup;
    }

    rv = fstat(fd, &statbuf);
    if (rv != 0) {
        log_err("Error fstat()ing file %s. Skipping...", file_full_path);
        goto cleanup;
    }

    if (opts.stdout_inode != 0 && opts.stdout_inode == statbuf.st_ino) {
        log_debug("Skipping %s because stdout is redirected to it", file_full_path);
        goto cleanup;
    }

    if ((statbuf.st_mode & S_IFMT) == 0) {
        log_err("%s is not a file. Mode %u. Skipping...", file_full_path, statbuf.st_mode);
        goto cleanup;
    }

    if (statbuf.st_mode & S_IFIFO) {
        log_debug("%s is a named pipe. stream searching", file_full_path);
        pipe = fdopen(fd, "r");
        search_stream(pipe, file_full_path);
        fclose(pipe);
    } else {
        f_len = statbuf.st_size;

        if (f_len == 0) {
            log_debug("File %s is empty, skipping.", file_full_path);
            goto cleanup;
        }

#ifdef _WIN32
        {
            HANDLE hmmap = CreateFileMapping(
                (HANDLE)_get_osfhandle(fd), 0, PAGE_READONLY, 0, f_len, NULL);
            buf = (char*) MapViewOfFile(hmmap, FILE_SHARE_READ, 0, 0, f_len);
            if (hmmap != NULL)
              CloseHandle(hmmap);
        }
        if (buf == NULL) {
            FormatMessageA(
                FORMAT_MESSAGE_ALLOCATE_BUFFER |
                FORMAT_MESSAGE_FROM_SYSTEM |
                FORMAT_MESSAGE_IGNORE_INSERTS,
                NULL, GetLastError(), 0, (void*) &buf, 0, NULL);
            log_err("File %s failed to load: %s.", file_full_path, buf);
            LocalFree((void*)buf);
            goto cleanup;
        }
#else
        buf = mmap(0, f_len, PROT_READ, MAP_SHARED, fd, 0);
        if (buf == MAP_FAILED) {
            log_err("File %s failed to load: %s.", file_full_path, strerror(errno));
            goto cleanup;
        }
#endif

        if (opts.search_zip_files) {
            ag_compression_type zip_type = is_zipped(buf, f_len);
            if (zip_type != AG_NO_COMPRESSION) {
                int _buf_len = (int)f_len;
                char *_buf = decompress(zip_type, buf, f_len, file_full_path, &_buf_len);
                if (_buf == NULL || _buf_len == 0) {
                    log_err("Cannot decompress zipped file %s", file_full_path);
                    goto cleanup;
                }
                search_buf(_buf, _buf_len, file_full_path);
                free(_buf);
                goto cleanup;
            }
        }

        search_buf(buf, (int)f_len, file_full_path);
    }

    cleanup:;
    if (fd != -1) {
#ifdef _WIN32
        UnmapViewOfFile(buf);
#else
        munmap(buf, f_len);
#endif
        close(fd);
    }
}